code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react'
import { Col, Row } from 'react-bootstrap'
import WorkPageLayout from '../../components/work-page-layout'
import './index.scss'
export default class WorkPage extends Component {
static title = 'walknote'
static image = '/works/walknote_eyecatch.png'
static description = 'Free music discovery player for iOS'
render() {
return (
<WorkPageLayout
title={WorkPage.title}
eyecatch="/works/walknote_eyecatch.png"
>
<Row>
<Col sm={6}>
<div>
<img
src="/works/walknote_01.png"
className="image-screenshot"
alt="image screenshot"
/>
</div>
</Col>
<Col sm={6}>
<div>
<img
src="/works/walknote_02.png"
className="image-screenshot"
alt="image screenshot"
/>
</div>
</Col>
</Row>
<div>
<img
src="/works/walknote_05.png"
className="image-screenshot"
alt="image screenshot"
/>
</div>
<div>
<img
src="/works/walknote_03.png"
className="image-screenshot"
alt="image screenshot"
/>
</div>
<div>
<img
src="/works/walknote_04.png"
className="image-screenshot"
alt="image screenshot"
/>
</div>
<h3>walknote (2011-2016)</h3>
<div className="work-description">
<div>好みを理解して推薦する無料で聴き放題な音楽プレーヤー</div>
<div>Free music discovery player for iOS</div>
</div>
<div className="work-long-description">
<p>
13万人超が使う音楽アプリ。
あなたのiPhoneに入っている曲から好みを理解して、新しい曲を提示。
まるでラジオのように推薦曲を聴いて楽しめる!
</p>
<p>
※本サービスは終了しました。 詳細は
<a href="http://blog.odoruinu.net/2016/09/06/farewell-from-walknote/">
こちら
</a>
。
</p>
</div>
<div className="work-long-description">
<p>
walknote recommends new music you may like based on your music
preferences by recognizing your favorite songs stored in your
device. You can listen to recommended music just like a radio!
</p>
<p>
This service has been closed. Thank you for over 130,000 registered
users!
</p>
</div>
<h3>掲載実績</h3>
<div className="work-description">
<ul>
<li>
<a
href="http://renewal49.hateblo.jp/entry/20120710/1341925681"
target="_blank"
rel="noopener noreferrer"
>
強力すぎて紹介しそびれていた音楽好きのための神アプリ『walknote』
- リニューアル式様
</a>
</li>
<li>
<a
href="http://www.appbank.net/2011/10/15/iphone-application/309349.php"
target="_blank"
rel="noopener noreferrer"
>
walknote:
CD屋の試聴機が、自分向けになって手元に到着。そんな曲探しアプリ。無料。
- appbank様
</a>
</li>
<li>
<a
href="http://www.danshihack.com/2012/07/18/junp/iphoneapp-walknote.html"
target="_blank"
rel="noopener noreferrer"
>
おすすめの音楽をレコメンド!ストリーミング再生してくれるiPhoneアプリ「walknote」が素敵。
- 男子ハック様
</a>
</li>
<li>
<a
href="http://www.tabroid.jp/app/multimedia/2013/05/app.walknote.html"
target="_blank"
rel="noopener noreferrer"
>
「YOU、これ聴いちゃいなよ」自分好みの曲が勝手に集まる音楽プレーヤー『walknote』
- タブロイド様
</a>
</li>
<li>その他、多数</li>
</ul>
</div>
</WorkPageLayout>
)
}
}
| odoruinu/odoruinu.net-pug | pages/works/walknote.js | JavaScript | mit | 4,792 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { CSSNavigation } from './cssNavigation.js';
import * as nodes from '../parser/cssNodes.js';
import { URI } from './../../vscode-uri/index.js';
import { startsWith } from '../utils/strings.js';
var SCSSNavigation = /** @class */ (function (_super) {
__extends(SCSSNavigation, _super);
function SCSSNavigation(fileSystemProvider) {
return _super.call(this, fileSystemProvider) || this;
}
SCSSNavigation.prototype.isRawStringDocumentLinkNode = function (node) {
return (_super.prototype.isRawStringDocumentLinkNode.call(this, node) ||
node.type === nodes.NodeType.Use ||
node.type === nodes.NodeType.Forward);
};
SCSSNavigation.prototype.resolveRelativeReference = function (ref, documentUri, documentContext, isRawLink) {
return __awaiter(this, void 0, void 0, function () {
function toPathVariations(uri) {
// No valid path
if (uri.path === '') {
return undefined;
}
// No variation for links that ends with suffix
if (uri.path.endsWith('.scss') || uri.path.endsWith('.css')) {
return undefined;
}
// If a link is like a/, try resolving a/index.scss and a/_index.scss
if (uri.path.endsWith('/')) {
return [
uri.with({ path: uri.path + 'index.scss' }).toString(),
uri.with({ path: uri.path + '_index.scss' }).toString()
];
}
// Use `uri.path` since it's normalized to use `/` in all platforms
var pathFragments = uri.path.split('/');
var basename = pathFragments[pathFragments.length - 1];
var pathWithoutBasename = uri.path.slice(0, -basename.length);
// No variation for links such as _a
if (basename.startsWith('_')) {
if (uri.path.endsWith('.scss')) {
return undefined;
}
else {
return [uri.with({ path: uri.path + '.scss' }).toString()];
}
}
var normalizedBasename = basename + '.scss';
var documentUriWithBasename = function (newBasename) {
return uri.with({ path: pathWithoutBasename + newBasename }).toString();
};
var normalizedPath = documentUriWithBasename(normalizedBasename);
var underScorePath = documentUriWithBasename('_' + normalizedBasename);
var indexPath = documentUriWithBasename(normalizedBasename.slice(0, -5) + '/index.scss');
var indexUnderscoreUri = documentUriWithBasename(normalizedBasename.slice(0, -5) + '/_index.scss');
var cssPath = documentUriWithBasename(normalizedBasename.slice(0, -5) + '.css');
return [normalizedPath, underScorePath, indexPath, indexUnderscoreUri, cssPath];
}
var target, parsedUri, pathVariations, j, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (startsWith(ref, 'sass:')) {
return [2 /*return*/, undefined]; // sass library
}
return [4 /*yield*/, _super.prototype.resolveRelativeReference.call(this, ref, documentUri, documentContext, isRawLink)];
case 1:
target = _a.sent();
if (!(this.fileSystemProvider && target && isRawLink)) return [3 /*break*/, 8];
parsedUri = URI.parse(target);
_a.label = 2;
case 2:
_a.trys.push([2, 7, , 8]);
pathVariations = toPathVariations(parsedUri);
if (!pathVariations) return [3 /*break*/, 6];
j = 0;
_a.label = 3;
case 3:
if (!(j < pathVariations.length)) return [3 /*break*/, 6];
return [4 /*yield*/, this.fileExists(pathVariations[j])];
case 4:
if (_a.sent()) {
return [2 /*return*/, pathVariations[j]];
}
_a.label = 5;
case 5:
j++;
return [3 /*break*/, 3];
case 6: return [3 /*break*/, 8];
case 7:
e_1 = _a.sent();
return [3 /*break*/, 8];
case 8: return [2 /*return*/, target];
}
});
});
};
return SCSSNavigation;
}(CSSNavigation));
export { SCSSNavigation };
| TeamSPoon/logicmoo_workspace | packs_web/swish/web/node_modules/monaco-editor/esm/vs/language/css/_deps/vscode-css-languageservice/services/scssNavigation.js | JavaScript | mit | 8,591 |
angular.module('fishTank')
.controller('PostsCtrl', [
'$scope',
'postsFactory',
'post',
function($scope, postsFactory, post){
$("input.tags").tagsinput('items')
// $("input.form-control").show()
$scope.post = post;
$scope.incrementUpvotes = function(comment) {
postsFactory.upvoteComment(post, comment);
};
$scope.decrementUpvotes = function(comment) {
postsFactory.downvoteComment(post, comment);
};
$scope.addComment = function(){
errors();
if($scope.body === ''){return;}
postsFactory.addComment(post.id, {
body: $scope.body,
author: 'user'
}).success(function(comment) {
$scope.post.comments.push(comment)
});
$scope.body = '';
};
var errors = function() {
$scope.$on('devise:unauthorized', function(event, xhr, deferred) {
$scope.error = xhr.data.error
});
}
}]); | the-widget/fish-tank | app/assets/javascripts/posts/postsCtrl.js | JavaScript | mit | 974 |
export default [
{
name: 'Types',
examples: [
{
name: 'List',
description: 'A list groups related content',
file: 'List',
},
{
description: 'You can also pass an array of items as props',
file: 'ListShorthand',
},
{
file: 'ListIcon',
},
{
file: 'ListDivided',
},
{
file: 'ListTree',
},
{
name: 'Bulleted',
description: 'A list can mark items with a bullet.',
file: 'Bulleted',
},
{
file: 'BulletedHorizontal',
},
{
name: 'Ordered',
description: 'A list can be ordered numerically.',
file: 'Ordered',
},
{
description:
'You can also use an `ol` and `li` to render an ordered list.',
file: 'OrderedNumber',
},
{
name: 'Link',
description: 'A list can be specially formatted for navigation links.',
file: 'Link',
},
],
},
{
name: 'Content',
examples: [
{
name: 'Item',
description: 'A list item can contain a set of items.',
file: 'Item',
},
{
name: 'Icon',
description: 'A list item can contain an icon.',
file: 'Icon',
},
{
name: 'Image',
description: 'A list item can contain an image.',
file: 'Image',
},
{
name: 'Link',
description: 'A list can contain links.',
file: 'LinkContent',
},
{
file: 'LinkDescription',
},
{
name: 'Header',
description: 'A list item can contain a header.',
file: 'Header',
},
{
name: 'Description',
description: 'A list item can contain a description.',
file: 'Description',
},
],
},
{
name: 'Variations',
examples: [
{
name: 'Inverted',
description: 'A list can be inverted to appear on a dark background.',
file: 'ListInverted',
},
],
},
];
| Semantic-UI-Vue/Semantic-UI-Vue | docs/definitions/elements/List/index.js | JavaScript | mit | 2,082 |
/*
* docs-mixin: used by any page under /docs path
*/
import { updateMetaTOC, scrollTo, offsetTop } from '~/utils'
import { bvDescription, nav } from '~/content'
const TOC_CACHE = {}
// @vue/component
export default {
head() {
return {
title: this.headTitle,
meta: this.headMeta
}
},
computed: {
headTitle() {
const routeName = this.$route.name
let title = ''
let section = ''
if (this.meta && this.meta.title) {
title = this.meta.title
}
if (/^docs-components/.test(routeName)) {
section = 'Components'
} else if (/^docs-directives/.test(routeName)) {
section = 'Directives'
} else if (/^docs-reference/.test(routeName)) {
section = 'Reference'
}
return [title, section, 'BootstrapVue'].filter(Boolean).join(' | ')
},
headMeta() {
const section = this.$route.name.split('-')[1]
const sectionMeta = section ? nav.find(n => n.base === `${section}/`) : null
const description =
this.meta && this.meta.description
? this.meta.description
: sectionMeta && sectionMeta.description
? sectionMeta.description
: bvDescription
const meta = [
{
hid: 'og:title',
name: 'og:title',
property: 'og:title',
content: this.headTitle
}
]
if (description) {
meta.push({
hid: 'description',
name: 'description',
content: description
})
meta.push({
hid: 'og:description',
name: 'og:description',
property: 'og:description',
content: description
})
}
return meta
}
},
created() {
// Create private non-reactive props
this.$_filterTimer = null
// In a `$nextTick()` to ensure `toc.vue` is created first
this.$nextTick(() => {
const key = `${this.$route.name}_${this.$route.params.slug || ''}`
const toc =
TOC_CACHE[key] || (TOC_CACHE[key] = updateMetaTOC(this.baseTOC || {}, this.meta || null))
this.$root.$emit('docs-set-toc', toc)
})
},
mounted() {
this.clearScrollTimeout()
this.focusScroll()
},
updated() {
this.clearScrollTimeout()
this.focusScroll()
},
beforeDestroy() {
this.clearScrollTimeout()
},
methods: {
clearScrollTimeout() {
clearTimeout(this.$_scrollTimeout)
this.$_scrollTimeout = null
},
focusScroll() {
const hash = this.$route.hash
this.$nextTick(() => {
let el
if (hash) {
// We use an attribute `querySelector()` rather than `getElementByID()`,
// as some auto-generated ID's are invalid or not unique
el = this.$el.querySelector(`[id="${hash.replace('#', '')}"]`)
this.scrollIntoView(el)
}
if (!el) {
el = this.$el.querySelector('h1')
}
if (el) {
el.tabIndex = -1
el.focus()
}
})
},
scrollIntoView(el) {
if (el) {
// Get the document scrolling element
const scroller = document.scrollingElement || document.documentElement || document.body
this.clearScrollTimeout()
// Allow time for v-play to finish rendering
this.$_scrollTimeout = setTimeout(() => {
// Scroll heading into view (minus offset to account for nav top height)
scrollTo(scroller, offsetTop(el) - 70, 100)
}, 100)
}
}
}
}
| bootstrap-vue/bootstrap-vue | docs/plugins/docs-mixin.js | JavaScript | mit | 3,531 |
/**
* Data that contains a string.
* @param {string} value
* @param {boolean} [isValid=true]
* @constructor
*/
function StringData(value, isValid) {
Data.call(this, Data.types.string, value, isValid);
}
StringData.prototype = Object.create(Data.prototype);
StringData.prototype.constructor = StringData;
/**
* If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned
* @return {NumData}
*/
StringData.prototype.asNum = function() {
if (this.isNumber()) {
return new NumData(parseFloat(this.getValue()), this.isValid);
} else {
return new NumData(0, false);
}
};
/**
* The string is a valid boolean if it is "true" or "false" (any casing)
* @return {BoolData}
*/
StringData.prototype.asBool = function() {
if (this.getValue().toUpperCase() === "TRUE") {
return new BoolData(true, this.isValid);
} else if (this.getValue().toUpperCase() === "FALSE") {
return new BoolData(false, this.isValid);
}
return new BoolData(false, false);
};
/**
* @return {StringData}
*/
StringData.prototype.asString = function() {
return this;
};
/**
* Checks to see if the number can be converted to a valid number
* @return {boolean}
*/
StringData.prototype.isNumber = function() {
//from https://en.wikipedia.org/wiki/Regular_expression
const numberRE = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;
return numberRE.test(this.getValue());
};
/**
* Imports StringData from XML
* @param {Node} dataNode
* @return {StringData|null}
*/
StringData.importXml = function(dataNode) {
const value = XmlWriter.getTextNode(dataNode, "value");
if (value == null) return null;
return new StringData(value);
}; | BirdBrainTechnologies/HummingbirdDragAndDrop- | Data/StringData.js | JavaScript | mit | 1,681 |
$(document).ready(function(){
///Declare variables
var unitSwap = true;
var latitude = $('#latitude');
var longitude = $('#longitude');
var location = $('#location');
var temperature = $('#temperature');
var weather = $('#weather');
var weatherIcon;
var clock = $('#clock');
var day = $('#day');
///Geolocation
//Find the geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
///Weather API
//Setup for weather app
var key = 'd160d975b9920be65fcf14313e95afb4';
var weatherNow = 'http://api.openweathermap.org/data/2.5/weather?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude + '&APPID=' + key + '&units=metric';
//Get the weather
$.getJSON(weatherNow, function(data) {
location.html(data.name + ', ' + data.sys.country);
temperature.html(data.main.temp + '<sup>o</sup>C');
weather.html(data.weather[0].main);
//Weather icons https://openweathermap.org/weather-conditions
if(data.weather[0].icon === '01d') {
document.getElementById('weatherIcon').src = 'img/sun.png';
$('body').css("background-image", "url(img/02.jpeg)");
} else if (data.weather[0].icon === '01n') {
document.getElementById('weatherIcon').src = 'img/moon.png';
$('body').css("background-image", "url(img/04.jpeg)");
} else if(data.weather[0].icon === '02d') {
document.getElementById('weatherIcon').src = 'img/cloud.png';
$('body').css("background-image", "url(img/01.jpeg)");
} else if(data.weather[0].icon === '02n') {
document.getElementById('weatherIcon').src = 'img/night.png';
$('body').css("background-image", "url(img/05.jpeg)");
} else if(data.weather[0].icon === '03d' || data.weather[0].icon === '03n') {
document.getElementById('weatherIcon').src = 'img/cloud2.png';
$('body').css("background-image", "url(img/06.jpeg)");
} else if(data.weather[0].icon === '04d' || data.weather[0].icon === '04n') {
document.getElementById('weatherIcon').src = 'img/cloudy.png';
$('body').css("background-image", "url(img/07.jpeg)");
} else if(data.weather[0].icon === '09d' || data.weather[0].icon === '90n' || data.weather[0].icon === '10d' || data.weather[0].icon === '10n') {
document.getElementById('weatherIcon').src = 'img/rain.png';
$('body').css("background-image", "url(img/03.jpeg)");
} else if(data.weather[0].icon === '11d' || data.weather[0].icon === '11n') {
document.getElementById('weatherIcon').src = 'img/flash.png';
$('body').css("background-image", "url(img/08.jpeg)");
} else if(data.weather[0].icon === '13d' || data.weather[0].icon === '13n') {
document.getElementById('weatherIcon').src = 'img/snowflake.png';
$('body').css("background-image", "url(img/09.jpeg)");
} else if(data.weather[0].icon === '50d' || data.weather[0].icon === '50n') {
document.getElementById('weatherIcon').src = 'img/fog.png';
$('body').css("background-image", "url(img/10.jpeg)");
} else {
console.log('photo didn\'t load');
}
//button to change between fahrenheit and celcius
temperature.click(function() {
if (unitSwap === true) {
temperature.html(data.main.temp*9/5+32 + '<sup>o</sup>F');
unitSwap = false;
}else {
temperature.html(data.main.temp + '<sup>o</sup>C');
unitSwap = true;
}
});
});
//Get current time
function time() {
var currentTime = new Date ();
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
//Formatting it to a nice string using ternary operators
currentMinutes = ( currentMinutes < 10 ? '0' : '' ) + currentMinutes;
//Formatting it to 12 hours and adding AM and PM
var timeOfDay = ( currentHours < 12 ) ? 'AM' : 'PM';
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours === 0 ) ? 12 : currentHours;
//The last part to make the finished formatted string
var currentTimeString = currentHours + ':' + currentMinutes + ' ' + timeOfDay;
day.html(weekday[currentTime.getDay()]);
clock.html(currentTimeString);
}
time();
});
} else {
location.html('Geolocation is not supported by this browser');
}
});
| TheGameFreak720/Weather-App | js/app.js | JavaScript | mit | 5,395 |
app.controller('ThumbnailCtrl', function($http, Upload, $timeout, $location, $anchorScroll, $stateParams, $cookies){
thumbnailCtrl = this;
thumbnailCtrl.sendEmail = function(){
$http.get('/api/sendEmail').success(function(response){
console.log('Ok')
}).catch(function(err){
console.log(err)
});
};
thumbnailCtrl.getThumbnails = function(){
thumbnailCtrl.loading=true;
$http.get('/api/thumbnails').success(function(response){
thumbnailCtrl.thumbnailData = response.thumbnailsFound;
thumbnailCtrl.actualPage = response.actualPage;
articleLoader();
paginatorCalculator(response);
getLastPosts();
thumbnailCtrl.loading = false;
}).catch(function(response){
thumbnailCtrl.loading = false;
thumbnailCtrl.responseError = response;
});
};
thumbnailCtrl.postThumbnail = function(myFile){
thumbnailCtrl.loading=true;
if(myFile){
Upload.upload({
url: '/api/thumbnails',
method: 'POST',
data: {
file: Upload.dataUrltoBlob(myFile),
thumbnailTitle: thumbnailCtrl.thumbnailTitle,
thumbnailBody: thumbnailCtrl.thumbnailBody,
articleTitle: thumbnailCtrl.articleTitle,
articleBody: thumbnailCtrl.articleBody
}
}).then(function(response){
$timeout(function(){
myFile.result = response.data;
thumbnailCtrl.loading = false;
thumbnailCtrl.response = response.data.message;
thumbnailCtrl.credentials = response.data.credentials;
});
}, function(responseError){
if(responseError) thumbnailCtrl.responseError = responseError;
});
}
};
thumbnailCtrl.removeThumbnail = function(myTitle){
$http.delete('/api/thumbnails/'+myTitle).success(function(response){
thumbnailCtrl.getThumbnails();
}).catch(function(response){
thumbnailCtrl.responseError = 'Something went wrong';
});
};
thumbnailCtrl.editThumbnail = function(myTitle, editTitle, editBody){
$http.put('/api/thumbnails/'+myTitle, {
thumbnailTitle: editTitle,
thumbnailBody: editBody
}).success(function(response){
thumbnailCtrl.getThumbnails();
}).catch(function(response){
console.log(response);
thumbnailCtrl.responseError = 'Something went wrong';
});
};
thumbnailCtrl.getPage = function(pageQuery){
$http.get('/api/thumbnails?page='+pageQuery).success(function(response){
thumbnailCtrl.loading = false;
thumbnailCtrl.thumbnailData = response.thumbnailsFound;
thumbnailCtrl.actualPage = response.actualPage;
}).catch(function(response){
alert('Something went wrong');
});
};
thumbnailCtrl.selectIndex = function(index){
thumbnailCtrl.loading = true;
for (var i = 0; i < thumbnailCtrl.thumbnailData.length; i++) {
if(thumbnailCtrl.thumbnailData[i] == thumbnailCtrl.thumbnailData[index]){
thumbnailCtrl.articleFound = thumbnailCtrl.thumbnailData[i];
thumbnailCtrl.loading = false;
return thumbnailCtrl.thumbnailData[i];
}
}
};
thumbnailCtrl.editArticle = function(editedTitle, editedBody){
thumbnailCtrl.loading = true;
var myTitle = thumbnailCtrl.thumbnailData[$stateParams.id].thumbnailTitle;
$http.put('/api/article/'+myTitle, {
articleTitle: editedTitle,
articleBody: editedBody
}).success(function(response){
console.log(response)
thumbnailCtrl.getThumbnails();
thumbnailCtrl.loading = false;
}).catch(function(error){
console.log(error)
});
};
thumbnailCtrl.getThumbnailsLimit = function(limitQuery, pageQuery){
thumbnailCtrl.loading=true;
if(pageQuery){
$http.get('/api/thumbnails/search?limit='+limitQuery+'&page='+pageQuery).success(function(response){
thumbnailCtrl.loading = false;
thumbnailCtrl.thumbnailData = response.thumbnailsFound;
}).catch(function(response){
alert('Something went wrong');
});
}else{
$http.get('/api/thumbnails/search?limit='+limitQuery).success(function(response){
thumbnailCtrl.loading = false;
thumbnailCtrl.thumbnailData = response.thumbnailsFound;
}).catch(function(response){
alert('Something went wrong');
});
}
};
thumbnailCtrl.scrollToTop = function(){
$location.hash('scrollTop');
$anchorScroll();
};
thumbnailCtrl.currentParamsId = function(){
return $stateParams.id;
};
thumbnailCtrl.isLogged = function(){
if($cookies.get('username')){
return true;
}else{
return false;
}
}
function paginatorCalculator(response){
//Paginator calculation
var totalPages = Math.ceil(response.totalPages/18);
var range = [];
for (var i = 1; i <= totalPages; i++) {
range.push(i);
}
thumbnailCtrl.pagesArray = range;
}
function articleLoader(){
if(Object.keys($stateParams).length != 0){
//the id object is defined in the routes app.js
thumbnailCtrl.selectIndex($stateParams.id);
}
};
function getLastPosts(){
$http.get('/api/thumbnails?lastPosts=10').success(function(response){
thumbnailCtrl.loading = false;
thumbnailCtrl.lastPosts = response.thumbnailsFound;
}).catch(function(response){
console.log('error'+response.error);
});
};
});
| merlox/thetoptenweb-blog | public/js/controllers/Thumbnail.client.controller.js | JavaScript | mit | 5,363 |
import Component from '@ember/component';
import layout from '../templates/components/google-docs';
import { computed, get } from '@ember/object';
import { capitalize } from '@ember/string';
const GoogleDocs = Component.extend({
layout,
tagName: 'a',
attributeBindings: ['href', 'rel', 'target'],
type: 'reference',
referenceUrl: 'https://developers.google.com/maps/documentation/javascript/reference#',
guideUrl: 'https://developers.google.com/maps/documentation/javascript/',
rel: 'noopener',
target: '_blank',
baseUrl: computed('type', function() {
return (this.type === 'reference') ? this.referenceUrl : this.guideUrl;
}),
displayType: computed('type', function() {
return capitalize(this.type);
}),
href: computed(function() {
return get(this, 'baseUrl') + get(this, 'section');
})
});
GoogleDocs.reopenClass({
positionalParams: ['section']
});
export default GoogleDocs;
| ryanholte/ember-google-maps | tests/dummy/app/components/google-docs.js | JavaScript | mit | 927 |
/*
* Exemplo de Readline (Input via console)
*
* @author André Ferreira <andrehrf@gmail.com>
*/
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Qual sua idade? ', (idade) => {
console.log('Sua idade é :', idade);
rl.close();
}); | brjsoficial/matrix-decode-exemplos | readline.js | JavaScript | mit | 345 |
// For info about this file refer to webpack and webpack-hot-middleware documentation
// For info on how we're generating bundles with hashed filenames for cache busting: https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.w99i89nsz
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import WebpackMd5Hash from 'webpack-md5-hash';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import autoprefixer from 'autoprefixer';
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('production'),
__DEV__: false
};
export default {
resolve: {
extensions: ['', '.js', '.jsx']
},
debug: true,
devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
entry: './src/index',
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: `${__dirname}/dist`,
publicPath: '/',
filename: '[name].[chunkhash].js'
},
plugins: [
// Hash the files using MD5 so that their names change when the content changes.
new WebpackMd5Hash(),
// Optimize the order that items are bundled. This assures the hash is deterministic.
new webpack.optimize.OccurenceOrderPlugin(),
// Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
new webpack.DefinePlugin(GLOBALS),
// Generate an external css file with a hash in the filename
new ExtractTextPlugin('[name].[contenthash].css'),
// Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage
new HtmlWebpackPlugin({
template: 'src/index.ejs',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
},
inject: true,
// Note that you can add custom options here if you need to handle other custom logic in index.html
// To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below.
trackJSToken: ''
}),
// Eliminate duplicate packages when generating bundle
new webpack.optimize.DedupePlugin(),
// Minify JS
new webpack.optimize.UglifyJsPlugin()
],
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'url?name=[name].[ext]' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff&name=[name].[ext]" },
{ test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=[name].[ext]' },
{ test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=[name].[ext]' },
{ test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]' },
{ test: /\.ico$/, loader: 'file?name=[name].[ext]' },
{ test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap') }
]
},
postcss: () => [autoprefixer]
};
| pisgrupo9/ash_web | webpack.config.prod.js | JavaScript | mit | 3,520 |
/* Set the width of the side navigation to 250px */
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
/* Set the width of the side navigation to 0 */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
| pvskand/addictionRemoval | js/homepage.js | JavaScript | mit | 273 |
var App = angular.module('validationApp', []);
App.controller('mainController', function ($scope) {
$scope.submitForm = function (isValid) {
if (isValid) {
alert('Our form is Amazing');
}
else {
alert('Please enter the values and click submit');
}
};
}); | sandy912/AngularJS | demo/Controller/Validation.js | JavaScript | mit | 337 |
var dikoServices = angular.module('diko.basic.service', []);
dikoServices.factory('dikoShareObject', [dikoServicesFunction]);
function dikoServicesFunction() {
var tabActive= "planets";
return {
setTabActive: function(name) {
if(typeof name !== 'undefined') tabActive = name;
return tabActive;
},
getTabActive: function() {
return tabActive;
}
};
}
| mazipan/angularjs-basic-tutorial | exercise/Fathurrahman Diko Raditya/AppService.js | JavaScript | mit | 444 |
/*global tarteaucitron */
tarteaucitron.lang = {
"adblock": "Benvenuto! Questo sito ti permette di attivare i servizi di terzi di tua scelta.",
"adblock_call": "Disabilita il tuo adblocker per iniziare la navigazione.",
"reload": "Aggiorna la pagina",
"alertBigScroll": "Continuando a scorrere,",
"alertBigClick": "Continuando a navigare nel sito,",
"alertBig": "autorizzi l’utilizzo dei cookies inviati da domini di terze parti",
"alertBigPrivacy": "Questo sito fa uso di cookies e ti consente di decidere se accettarli o rifiutarli",
"alertSmall": "Gestione dei servizi",
"acceptAll": "Ok, accetta tutto",
"personalize": "Personalizza",
"close": "Chiudi",
"all": "Preferenze per tutti i servizi",
"info": "Tutela della privacy",
"disclaimer": "Abilitando l'uso dei servizi di terze parti, accetti la ricezione dei cookies e l'uso delle tecnologie analitici necessarie al loro funzionamento.",
"allow": "Consenti",
"deny": "Blocca",
"noCookie": "Questo servizio non invia nessun cookie",
"useCookie": "Questo servizio puo' inviare",
"useCookieCurrent": "Questo servizio ha inviato",
"useNoCookie": "Questo servizio non ha inviato nessun cookie",
"more": "Saperne di più",
"source": "Vai al sito ufficiale",
"credit": "Gestione dei cookies da tarteaucitron.js",
"toggleInfoBox": "Show/hide informations about cookie storage",
"title": "Cookies management panel",
"cookieDetail": "Cookie detail for",
"ourSite": "on our site",
"newWindow": "(new window)",
"allowAll": "Allow all cookies",
"denyAll": "Deny all cookies",
"fallback": "è disattivato",
"ads": {
"title": "Regie pubblicitarie",
"details": "Le regie pubblicitarie producono redditi gestendo la commercializzazione degli spazi del sito dedicati alle campagne pubblicitarie"
},
"analytic": {
"title": "Misura del pubblico",
"details": "I servizi di misura del pubblico permettono di raccogliere le statistiche utili al miglioramento del sito"
},
"social": {
"title": "Reti sociali",
"details": "Le reti sociali permettono di migliorare l'aspetto conviviale del sito e di sviluppare la condivisione dei contenuti da parte degli utenti a fini promozionali."
},
"video": {
"title": "Video",
"details": "I servizi di condivisione di video permettono di arricchire il sito di contenuti multimediali e di aumentare la sua visibilità"
},
"comment": {
"title": "Commenti",
"details": "La gestione dei commenti utente aiuta a gestire la pubblicazione dei commenti e a lottare contro lo spamming"
},
"support": {
"title": "Supporto",
"details": "I servizi di supporto ti consentono di contattare la team del sito e di contribuire al suo miglioramento"
},
"api": {
"title": "API",
"details": "Le API permettono di implementare script diversi : geolocalizzazione, motori di ricerca, traduttori..."
},
"other": {
"title": "Altro",
"details": "Servizi per visualizzare contenuti web."
}
};
| eldk/tarteaucitron.js | lang/tarteaucitron.it.js | JavaScript | mit | 3,187 |
// index.js
import {
LocalStateForm,
SimpleValidation
} from 'immutable-react-form';
import Form from './form';
import validation from './validation';
import {GetData,UpdateData} from './data';
export default LocalStateForm(
props => (GetData()),
validation,
submit
)(Form);
async function submit(model,props){
await UpdateData(model);
}
| Trioxis/immutable-react-form | docs/src/examples/one/index.js | JavaScript | mit | 353 |
JsonRecordApp.contorller(getCtrl, ['$scope', '$http', function($scope, $http){
var testArray = new Array();
var errorChar = 1;
for (var i = 10001; i < 10101; i++) {
var query = jQuery.ajax({
url: jsonUrl + jsonName + i + ".json",
type: "GET",
async: false,
dataType: 'json',
success: function(result){
testArray.push(result);
$scope.jsonData = testArray;
}
});
if (query.status=="404") { break;}
// $http.get(jsonUrl + jsonName + i + ".json").then(function(data){
// testArray.push(data.data);
// $scope.jsonData = testArray;
// console.log(testArray);
// }).catch(function(){
// errorChar = 0;
// });
}
var testJson ={
"id" : 100010,
"Name" : "testsName"
}
// var postQuery=$http.post("http://localhost:8080" + jsonUrl + jsonName + "10001.json", testJson).then(function(data){
// // var postQuery=$http.post(jsonUrl + jsonName + "test.json", testJson).then(function(data){
// console.log(data);
// }).catch(err => console.log(err));
jQuery.ajax({
url: jsonUrl + jsonName + "10001.json",
type: "POST",
context: testJson,
contentType: "application/json",
async: false,
dataType: 'json',
success: function(result){
console.log(result);
}
})
}]); | xingchen19/angular-json | src/app/getRecords/get.js | JavaScript | mit | 1,327 |
import React, { Component } from 'react';
import { View, TextInput, Text } from 'react-native';
const Input = ({ label, securetxt, maxlen, keytype, value, onChangeText, placeHolder }) => {
return (
<View style={styles.containerStyle}>
<Text style={styles.labelStyle}>{label}</Text>
<TextInput
secureTextEntry={securetxt}
keyboardType={keytype}
maxLength={maxlen}
autoCorrect={false}
placeholder={placeHolder}
placeholderTextColor={'#e0e2e1'}
multiline={false}
value={value}
onChangeText={onChangeText}
style={styles.inputStyle}
/>
</View>
);
};
const styles = {
inputStyle: {
color: '#000',
paddingRight: 10,
paddingLeft: 5,
fontSize: 18,
lineHeight: 23,
flex: 2,
width: 150
},
labelStyle: {
paddingLeft: 5,
fontSize: 18,
flex: 2
},
containerStyle: {
height: 40,
flex: 1,
flexDirection: 'row',
alignItems: 'center'
}
};
export { Input } | Moshikol/DaiabetesJournal | app/Components/common/Input.js | JavaScript | mit | 1,197 |
import { RocketChat } from 'meteor/rocketchat:lib';
RocketChat.settings.addGroup('Logs', function() {
this.add('Log_Exceptions_to_Channel', '', { type: 'string' });
});
| pkgodara/Rocket.Chat | packages/rocketchat-error-handler/server/startup/settings.js | JavaScript | mit | 171 |
const EventEmitter = require("events");
const ssh2 = require("ssh2");
const Client = ssh2.Client;
class Connection extends EventEmitter {
constructor (connectOptions, dimensions) {
this.connectOptions = connectOptions;
this.dimensions = dimensions;
this.errorCallback = errorCallback;
if (!this.errorCallback) {
this.errorCallback = function () {};
}
this.stream = null;
this.connection = new Client();
}
ready () {
this.emit("info", "Client is ready");
connection.shell({
cols: this.dimensions.cols,
rows: this.dimensions.rows
}, this.onConnect);
}
connect (connectOptions = null) {
if (connectOptions)
this.connectOptions = connectOptions;
this.connection.connect(this.connectOptions);
}
resize (cols, rows) {
if (this.stream) {
// Height and width are set to the defaults because their values don't seem to actually matter
this.stream.setWindow(rows, cols, 480, 640);
}
else {
this.emit("info", "Connection not established! (resize)");
console.warn("Connection not established! (resize)");
}
}
write (data) {
if (this.stream !== null) {
this.stream.write(data);
}
else {
this.emit("info", "Connection not established! (write)");
console.warn("Connection not established! (write)");
}
}
// Events
onConnect (err, stream) {
if (err)
return errorCallback();
this.emit("info", "Connection successful");
this.stream = stream;
stream
.on("close", this.onClose.bind(this))
.on("data", this.onData.bind(this))
.stderr.on("data", onErrorData.bind(this));
}
onData (data) {
this.emit("data", data);
this.emit("stdout", data);
}
onErrorData (data) {
this.emit("data", data);
this.emit("stderr", data);
}
onClose () {
this.emit("info", "Connection stream closed");
this.connection.end();
this.stream = null;
}
}
module.exports = Connection; | petschekr/Chocolate-Shell | app/js/connection.js | JavaScript | mit | 1,862 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ramda_1 = require("ramda");
var render_instance_1 = require("./render-instance");
var types_1 = require("./types");
function deepResolver(mapper, renderer) {
return function (comp) {
var resolve = deepResolver(mapper, renderer);
var mapped = mapper(comp);
if (types_1.isShallow(mapped)) {
var newComp = renderer(mapped.instance);
// note that newComp might be shallow again, so we need to call
// deepResolver on it to resolve the whole the tree
return resolve(newComp);
}
if (types_1.isHtml(mapped))
return ramda_1.merge(mapped, {
children: mapped.children.map(resolve)
});
return mapped;
};
}
exports.deepResolver = deepResolver;
function shallowResolver(mapper, _) {
return function (comp) {
var resolve = shallowResolver(mapper, _);
var mapped = mapper(comp);
if (types_1.isShallow(mapped)) {
return render_instance_1.toArtificialHtml(mapped);
}
if (types_1.isHtml(mapped)) {
return ramda_1.merge(mapped, {
children: mapped.children.map(resolve)
});
}
return mapped;
};
}
exports.shallowResolver = shallowResolver;
function interleavedResolver(mapper, renderer, nonRoot) {
return function (comp) {
var resolve = interleavedResolver(mapper, renderer, true);
var mapped = mapper(comp);
if (types_1.isShallow(mapped)) {
var newComp = renderer(mapped.instance);
// note that newComp might be shallow again, so we need to call
// interleavedResolver on it to render the whole the tree
var renderedComp = resolve(newComp);
return render_instance_1.toArtificialHtml(mapped, renderedComp);
}
if (types_1.isHtml(mapped)) {
var mappedWithChildren = ramda_1.merge(mapped, {
children: mapped.children.map(resolve)
});
return nonRoot
? mappedWithChildren
: render_instance_1.toArtificialHtml(mappedWithChildren, mappedWithChildren);
}
return mapped;
};
}
exports.interleavedResolver = interleavedResolver;
| pzavolinsky/react-unit | dist/resolver.js | JavaScript | mit | 2,346 |
const express = require('express');
const mongodb = require('mongodb')
const request = require('request');
const app = express();
const server = require('http').createServer(app)
const io = require('socket.io').listen(server)
const mongo_url = 'mongodb://localhost:27017/rally'
const mongo = mongodb.MongoClient()
app.set("port", process.env.PORT || 3001);
// Express only serves static assets in production
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
let is_live = function(event) {
let today = new Date()
let yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
if ("start" in event) {
if(event.start >= today) {
let end = event.start
if ("end" in event) {
end = event.end
}
if(end <= yesterday) {
return true
}
}
}
return false
}
let events_data;
let updateEventsData = () => {
try {
mongo.connect(mongo_url, (err, db) => {
if (err) {
console.log('Unable to connect to database server', err);
} else {
let collection = db.collection('ra_events');
let results = collection.find({},{'sort': {'start':-1}});
results.toArray((err, data) => {
if (err) {
console.log('Unable to get events from database', err);
} else if (data) {
let parentEvents = {};
let years = new Set();
for (let event of data) {
if (event['type'] === 'parent') {
if (event.year in parentEvents) {
if (is_live(event)) {
event['live'] = 'LIVE event'
}
parentEvents[event.year].push(event)
} else {
parentEvents[event.year] = [event]
}
years.add(event.year)
}
}
years = Array.from(years).sort(function(a, b){return b-a});
events_data = {
"events": parentEvents,
"years": years
};
}
})
}
});
} catch (e) {
console.log('exception thrown by mongo.connect', e);
}
}
let updateRaEvent = (year, code) => {
let evt = year + code;
console.log(evt);
console.log(evt + ': requesting to start update')
// if (false) {
if (evt in jobs) {
return({
'year': year,
'code': code,
'jobid': jobs[evt]
});
console.log(evt + ': job already exists: ' + jobs[evt])
} else {
// send the request to start the job for scrapyd
request.post(
'http://localhost:6800/schedule.json',
{ form: {
project: 'timecontrol',
spider: 'ra_scores',
year: year,
event_code: code,
} },
function (err, response, data) {
if (!err && response.statusCode == 200) {
data = JSON.parse(data)
jobs[evt] = data.jobid
return({year: year, code: code, 'jobid': data.jobid})
console.log(evt + ': starting the update: ' + jobs[evt])
} else {
return({error: err})
}
}
);
}
}
app.get("/api/events", (req, res) => {
if (!events_data) {
updateEventsData();
}
res.send(events_data);
});
app.get('/api/ra/:year/:code', function(req, res, next) {
try {
var year = req.params.year
var code = req.params.code
mongo.connect(mongo_url, function(err, db) {
if (err) {
res.send({error: err});
console.log('Unable to connect to database server', err)
} else {
var collection = db.collection('ra_scores')
collection.findOne({
'year':year,
'event_code':code
}, function(err, data) {
if (err) {
res.send({error: err});
} else if (data) {
res.send(data);
} else {
res.send({no_data: 'There is no data for this event, please update.'});
}
});
}
});
} catch(e) {
next(e)
}
});
var jobs = {};
app.get('/api/ra/update/:year/:code', function(req, res, next) {
var year = req.params.year
var code = req.params.code
res.send(updateRaEvent(year,code));
});
var latestStatus = {};
var waitingClients = [];
var checkStatus = function() {
let srvSockets = io.sockets.sockets;
if (Object.keys(srvSockets).length > 0) {
request.get(
'http://localhost:6800/listjobs.json?project=timecontrol',
function (err, response, data) {
if (!err && response.statusCode == 200) {
data = JSON.parse(data);
latestStatus = data;
} else {
console.log(err)
}
}
);
}
const findInFinshed = (id, status) => {
for (let i in status.finished) {
if (id === status.finished[i].id) {
return true;
}
}
return false;
}
let finishedJobs = [];
for (let evt in jobs) {
if (jobs.hasOwnProperty(evt)) {
let jobid = jobs[evt];
if (latestStatus.finished && findInFinshed(jobid, latestStatus)) {
finishedJobs.push(evt);
console.log(evt);
}
}
}
for (let i in finishedJobs) {
let evt = finishedJobs[i];
console.log(evt + ': finished, removing from jobs');
delete jobs[evt];
}
}
// poll the status from scrapyd every 1 seconds
setInterval(checkStatus, 1000);
io.on('connection', function(client) {
let srvSockets = io.sockets.sockets;
console.log('number of connected clients: ' + Object.keys(srvSockets).length);
client.on('subscribeToStatus', (interval) => {
console.log('client is subscribing to status with interval ', interval);
setInterval(() => {
client.emit('status', latestStatus);
}, interval);
});
});
server.listen(app.get("port"), () => {
console.log(`Find the server at: http://localhost:${app.get("port")}/`); // eslint-disable-line no-console
});
| tylerjw/rallyscores | rallyboard-v2/server.js | JavaScript | mit | 5,883 |
import e3AnimatedChild from '../e3-animated-child';
export default e3AnimatedChild.extend({
shadowType: 'text',
enterState: {
x: 0,
y: 0,
text: ''
},
activeState: {
x: null,
y: null,
text: null
}
});
| sly7-7/e3 | addon/components/e3-shape/text.js | JavaScript | mit | 237 |
describe('my app', function() {
it('should redirect `index.html` to `index.html#!/countries/countries', function() {
browser.get('index.html');
expect(browser.getLocationAbsUrl()).toBe('/home');
});
describe('home', function() {
beforeEach(function() {
browser.get('index.html');
});
it('should filter the country list as a user types into the search box', function() {
var countryList = element.all(by.repeater('country in $ctrl.countries'));
var query = element(by.model('$ctrl.query'));
expect(countryList.count()).toBe(11);
query.sendKeys('vietnam');
expect(countryList.count()).toBe(1);
query.clear();
query.sendKeys('Brunei');
expect(countryList.count()).toBe(1);
query.clear();
query.sendKeys('Indien');
expect(countryList.count()).toBe(0);
});
it('should render country specific links', function() {
var query = element(by.model('$ctrl.query'));
query.sendKeys('Brunei');
element.all(by.css('.thumbDescription a')).first().click();
expect(browser.getLocationAbsUrl()).toBe('/countries/countries/BN');
});
});
describe('View: Country details', function() {
beforeEach(function() {
browser.get('index.html#!/countries/countries/BN');
});
it('should display country with title `translations.de`', function() {
expect(element(by.binding('$ctrl.country.translations.de')).getText()).toBe('Brunei');
});
});
});
| InaDoWo/suedostasien | e2e-tests/scenarios.js | JavaScript | mit | 1,482 |
var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.resolve(__dirname, 'react');
var BUILD_DIR = path.resolve(__dirname, 'project/static/js');
var config = {
entry: {
public: APP_DIR + '/public.main.jsx',
private: APP_DIR + '/private.main.jsx',
},
output: {
path: BUILD_DIR,
filename: "[name].bundle.js",
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('init.js'),
new webpack.EnvironmentPlugin(['NODE_ENV']),
],
resolve: {
extensions: ['', '.js', '.jsx'],
moduleDirectories: ['node_modules', 'react'],
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
cacheDirectory: false,
plugins: [
require.resolve('babel-plugin-transform-decorators-legacy'),
],
presets: [
require.resolve('babel-preset-react'),
require.resolve('babel-preset-es2015'),
require.resolve('babel-preset-stage-0'),
],
},
},
],
},
};
module.exports = config;
| iMerica/django-react-uncool | webpack.dev.config.js | JavaScript | mit | 1,124 |
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Task Schema
* @type {Object}
*/
var TaskSchema = new Schema({
title: {
type: String,
default: '',
trim: true
},
project: {
type: String,
default: '',
trim: true
},
date: {
type: Date
},
created: {
type: Date
},
user: {
type: String
}
});
/**
* Validations
*/
TaskSchema.path('title').validate(function(title) {
"use strict";
return title.length;
}, 'Titulo em branco');
TaskSchema.path('project').validate(function(project) {
"use strict";
return project.length;
}, 'Projeto em branco');
/**
* Statics
*/
TaskSchema.statics = {
load: function(id, cb) {
"use strict";
this.findOne({
_id: id
}).populate('user', 'name username').exec(cb);
}
};
mongoose.model('Task', TaskSchema);
| tonightsystems/taz-manager | app/models/task.js | JavaScript | mit | 935 |
'use strict';
var Promise = require('bluebird'),
git = require('../index');
describe('isClean command', function() {
var command = git.isClean;
it('should exists', function(){
expect(command).to.be.a('function');
});
it('should issue a git diff-index', function() {
return command()
.tap(function() {
var call = mockSpawn.calls.pop();
expect(call.args).to.be.eql([
'diff-index',
'--quiet',
'HEAD',
'.'
]);
});
});
it('should return true when is clean', function() {
mockSpawn.sequence.add(mockSpawn.simple(0));
return command()
.tap(function(isClean) {
expect(isClean).to.be.true;
});
});
it('should return true when is dirty', function() {
mockSpawn.sequence.add(mockSpawn.simple(1));
return command()
.tap(function(isClean) {
expect(isClean).to.be.false;
});
});
it('should fail when git does', function() {
mockSpawn.sequence.add(mockSpawn.simple(128));
return command()
.then(Promise.reject)
.catch(Promise.resolve);
});
});
| jmendiara/gitftw | test/command.isClean.spec.js | JavaScript | mit | 1,160 |
import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite';
import {fmt} from 'ember-runtime/system/string';
var suite = SuiteModuleBuilder.create();
suite.module('objectAt');
suite.test('should return object at specified index', function() {
var expected = this.newFixture(3);
var obj = this.newObject(expected);
var len = expected.length;
var idx;
for (idx=0;idx<len;idx++) {
equal(obj.objectAt(idx), expected[idx], fmt('obj.objectAt(%@) should match', [idx]));
}
});
suite.test('should return undefined when requesting objects beyond index', function() {
var obj;
obj = this.newObject(this.newFixture(3));
equal(obj.objectAt(5), undefined, 'should return undefined for obj.objectAt(5) when len = 3');
obj = this.newObject([]);
equal(obj.objectAt(0), undefined, 'should return undefined for obj.objectAt(0) when len = 0');
});
export default suite;
| ianstarz/ember.js | packages/ember-runtime/tests/suites/array/objectAt.js | JavaScript | mit | 904 |
export var meanDocs = {
name: 'mean',
category: 'Statistics',
syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dim)'],
description: 'Compute the arithmetic mean of a list of values.',
examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'],
seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance']
}; | Michayal/michayal.github.io | node_modules/mathjs/es/expression/embeddedDocs/function/statistics/mean.js | JavaScript | mit | 424 |
import InfiniteScroll from './directive';
import 'bh-mint-ui2/src/style/empty.css';
import Vue from 'vue';
const install = function(Vue) {
Vue.directive('InfiniteScroll', InfiniteScroll);
};
if (!Vue.prototype.$isServer && window.Vue) {
window.infiniteScroll = InfiniteScroll;
Vue.use(install); // eslint-disable-line
}
InfiniteScroll.install = install;
export default InfiniteScroll;
| wisedu/bh-mint-ui2 | packages/infinite-scroll/src/infinite-scroll.js | JavaScript | mit | 395 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = require("../models/config");
const version_1 = require("../upgrade/version");
const common_tags_1 = require("common-tags");
const Command = require('../ember-cli/lib/models/command');
const config = config_1.CliConfig.fromProject() || config_1.CliConfig.fromGlobal();
const pollDefault = config.config.defaults && config.config.defaults.poll;
// defaults for BuildOptions
exports.baseBuildCommandOptions = [
{
name: 'target',
type: String,
default: 'development',
aliases: ['t', { 'dev': 'development' }, { 'prod': 'production' }],
description: 'Defines the build target.'
},
{
name: 'environment',
type: String,
aliases: ['e'],
description: 'Defines the build environment.'
},
{
name: 'output-path',
type: 'Path',
aliases: ['op'],
description: 'Path where output will be placed.'
},
{
name: 'aot',
type: Boolean,
description: 'Build using Ahead of Time compilation.'
},
{
name: 'sourcemaps',
type: Boolean,
aliases: ['sm', 'sourcemap'],
description: 'Output sourcemaps.'
},
{
name: 'vendor-chunk',
type: Boolean,
default: true,
aliases: ['vc'],
description: 'Use a separate bundle containing only vendor libraries.'
},
{
name: 'base-href',
type: String,
aliases: ['bh'],
description: 'Base url for the application being built.'
},
{
name: 'deploy-url',
type: String,
aliases: ['d'],
description: 'URL where files will be deployed.'
},
{
name: 'verbose',
type: Boolean,
default: false,
aliases: ['v'],
description: 'Adds more details to output logging.'
},
{
name: 'progress',
type: Boolean,
default: true,
aliases: ['pr'],
description: 'Log progress to the console while building.'
},
{
name: 'i18n-file',
type: String,
description: 'Localization file to use for i18n.'
},
{
name: 'i18n-format',
type: String,
description: 'Format of the localization file specified with --i18n-file.'
},
{
name: 'locale',
type: String,
description: 'Locale to use for i18n.'
},
{
name: 'extract-css',
type: Boolean,
aliases: ['ec'],
description: 'Extract css from global styles onto css files instead of js ones.'
},
{
name: 'watch',
type: Boolean,
default: false,
aliases: ['w'],
description: 'Run build when files change.'
},
{
name: 'output-hashing',
type: String,
values: ['none', 'all', 'media', 'bundles'],
description: 'Define the output filename cache-busting hashing mode.',
aliases: ['oh']
},
{
name: 'poll',
type: Number,
default: pollDefault,
description: 'Enable and define the file watching poll time period (milliseconds).'
},
{
name: 'app',
type: String,
aliases: ['a'],
description: 'Specifies app name or index to use.'
},
{
name: 'delete-output-path',
type: Boolean,
default: true,
aliases: ['dop'],
description: 'Delete output path before build.'
},
{
name: 'preserve-symlinks',
type: Boolean,
default: false,
description: 'Do not use the real path when resolving modules.'
},
{
name: 'extract-licenses',
type: Boolean,
default: true,
description: 'Extract all licenses in a separate file, in the case of production builds only.'
}
];
const BuildCommand = Command.extend({
name: 'build',
description: 'Builds your app and places it into the output path (dist/ by default).',
aliases: ['b'],
availableOptions: exports.baseBuildCommandOptions.concat([
{
name: 'stats-json',
type: Boolean,
default: false,
description: common_tags_1.oneLine `Generates a \`stats.json\` file which can be analyzed using tools
such as: \`webpack-bundle-analyzer\` or https://webpack.github.io/analyse.`
}
]),
run: function (commandOptions) {
// Check angular version.
version_1.Version.assertAngularVersionIs2_3_1OrHigher(this.project.root);
const BuildTask = require('../tasks/build').default;
const buildTask = new BuildTask({
project: this.project,
ui: this.ui,
});
return buildTask.run(commandOptions);
}
});
BuildCommand.overrideCore = true;
exports.default = BuildCommand;
//# sourceMappingURL=/users/arick/angular-cli/commands/build.js.map | rtnews/rtsfnt | node_modules/@angular/cli/commands/build.js | JavaScript | mit | 4,958 |
/*
Add Fish Form
*/
import React from 'react';
import autobind from 'autobind-decorator';
class AddFishForm extends React.Component{
@autobind
createFish(event){
//1. Stop the form from submitting
event.preventDefault();
//2. Take the data from the form and create an object
var fish = {
name : this.refs.name.value,
price : this.refs.price.value,
status :this.refs.status.value,
desc : this.refs.desc.value,
image :this.refs.image.value
}
//3. Add the fish to the App State
this.props.addFish(fish); //asdf
this.refs.fishForm.reset();
}
render(){
return(
<form className="fish-edit" refs="fishForm" onSubmit={this.createFish}>
<input type="text" ref="name" placeholder="Fish Name"/>
<input type="text" ref="price" placeholder="Fish Price"/>
<select ref="status">
<option value="available">Fresh!</option>
<option value="unavailable">Sold Out!</option>
</select>
<textarea type="text" ref="desc" placeholder="Desc"></textarea>
<input type="text" ref="image" placeholder="URL to image"/>
<button type="submit">+ Add Item </button>
</form>
)
}
}
export default AddFishForm;
| BarukhOr/cuddly-giggle-reactjs | scripts/components/AddFishForm.js | JavaScript | mit | 1,248 |
import Ember from 'ember';
export default Ember.Route.extend({
appState: Ember.inject.service('app-state'),
actions: {
toggleLeftSidebar(){
this.set('appState.isLeftSidebarOpen', !this.get('appState.isLeftSidebarOpen'));
},
toggleRightSidebar(){
this.set('appState.isRightSidebarOpen', !this.get('appState.isRightSidebarOpen'));
},
toggleScrollingX(){
this.set('appState.scrollingX', !this.get('appState.scrollingX'));
},
toggleScrollingY(){
this.set('appState.scrollingY', !this.get('appState.scrollingY'));
},
toggleAnimating(){
this.set('appState.animating', !this.get('appState.animating'));
},
toggleBouncing(){
this.set('appState.bouncing', !this.get('appState.bouncing'));
},
toggleLocking(){
this.set('appState.locking', !this.get('appState.locking'));
},
togglePaging(){
this.set('appState.paging', !this.get('appState.paging'));
},
toggleZooming(){
this.set('appState.zooming', !this.get('appState.zooming'));
},
toggleUseNativeScroll(){
this.set('appState.useNativeScroll', !this.get('appState.useNativeScroll'));
},
onSelectOption(value){
this.set('appState.selectValue',value);
}
},
renderTemplate(){
this._super(...arguments);
/* this.render('dummy-sidebar', {
outlet: 'left-sidebar',
into: 'application'
});*/
this.render('content', {
outlet: 'content',
into: 'application'
});
this.render('header', {
outlet: "header-content",
into: 'application'
});
/*this.render('dummy-right-sidebar', {
outlet: 'right-sidebar',
into: 'application'
});
var self = this;
this.render('nested-header-content', {
outlet: "another-header-content",
into: 'dummy-content'
});
this.render('nested-right-sidebar-content', {
outlet: "right-sidebar",
into: 'dummy-content'
});
this.render('nested-left-sidebar-content', {
outlet: "left-sidebar",
into: 'dummy-content'
});
this.render('nested-content', {
outlet: "content",
into: 'dummy-content'
});*/
}
});
| nullrocket/nullbase-select | tests/dummy/app/application/route.js | JavaScript | mit | 2,185 |
const Webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const package = require('./package.json')
const { join } = require('path')
const externals = () => {
const dependencies = package.dependencies
return Object
.keys(dependencies)
.reduce((modules, module) =>
Object.assign({}, modules, { [module]: `commonjs ${module}` }),
{}
)
}
module.exports = {
context: join(__dirname, './build'),
entry: {
boleto: './resources/boleto/index.js',
database: './functions/database/index.js'
},
output: {
path: join(__dirname, './dist'),
libraryTarget: 'commonjs2',
filename: '[name].js'
},
devtool: 'inline-source-map',
target: 'node',
externals: externals(),
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['source-map-loader'],
enforce: 'pre'
}
]
},
plugins: [
new Webpack.DefinePlugin({
'process.env.ENV': JSON.stringify('production'),
'process.env.NODE_ENV': JSON.stringify('production'),
}),
new Webpack.BannerPlugin({
banner: `
require("source-map-support").install();
require("core-js");
`,
raw: true,
entryOnly: false
}),
new CopyWebpackPlugin([{
from: './database/migrations',
to: './migrations',
context: join(__dirname, './build')
}])
]
}
| vcapretz/superbowleto | webpackfile.js | JavaScript | mit | 1,414 |
/**
* todo service
*/
class Todo {
// id = 0;
// text = '';
// checked = false;
constructor(id, text, checked) {
this.id = id;
this.text = text;
this.checked = checked;
}
}
| codecounter/testable-todos | app/todo.js | JavaScript | mit | 189 |
var mongoose = require('mongoose');
var urlSchema = require('../schemas/UrlSchema');
var Url = mongoose.model('Url', urlSchema);
var insertUrl = function(url, urlMinifie) {
var link = new Url({
url,
urlMinifie
});
link.save(function(err) {
if (err) return handleError(err);
});
};
var getUrls = function() {
return Url.find().exec();
};
module.exports = {Url, insertUrl, getUrls};
| VincentCana/url-minifie | app/models/UrlEntity.js | JavaScript | mit | 427 |
Template.botanikaLogo.events({
'click .botanika-logo' (evt) {
evt.preventDefault();
Meteor.swiperV.slideTo(0);
}
});
| pomahtuk/meteor-dummy | client/scripts/logo.js | JavaScript | mit | 129 |
const event = {
on(element, type, listener, options) {
element.addEventListener(type, listener, options);
return () => event.off(element, type, listener, options);
},
off(element, type, listener, options) {
element.removeEventListener(type, listener, options);
},
once(element, type, listener) {
const fn = function (...args) {
listener.apply(this, args);
event.off(element, type, fn);
};
event.on(element, type, fn);
},
};
export default event;
| vusion/proto-ui | src/utils/event/index.js | JavaScript | mit | 543 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'iframe', 'bg', {
border: 'Показва рамка на карето',
noUrl: 'Моля въведете URL за iFrame',
scrolling: 'Активира прелистване',
title: 'IFrame настройки',
toolbar: 'IFrame'
} );
| otto-torino/gino | ckeditor/plugins/iframe/lang/bg.js | JavaScript | mit | 446 |
/*
* y
*
*
* Copyright (c) 2013 ssddi456
* Licensed under the MIT license.
*/
'use strict';
var iconvLite = require('iconv-lite');
var _ = require('underscore');
var path = require('path');
module.exports = function(grunt) {
function detectDestType (dest) {
if (grunt.util._.endsWith(dest, path.sep)) {
return 'directory';
} else {
return 'file';
}
};
function unixifyPath (filepath) {
if (process.platform === 'win32') {
return filepath.replace(/\\/g, '/');
} else {
return filepath;
}
};
grunt.registerMultiTask('grunt-iconv-lite', 'trans encoding', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
fromEncoding : 'utf8',
toEncoding : 'gb2312'
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
var isExpandedPair = f.orig.expand || false;
// Concat specified files.
f.src.filter(function(src) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(src)) {
grunt.log.warn('Source file "' + src + '" not found.');
return false;
} else {
return true;
}
}).forEach(function(src) {
var dest;
if (detectDestType(f.dest) === 'directory') {
dest = (isExpandedPair) ? f.dest : unixifyPath(path.join(f.dest, src));
} else {
dest = f.dest;
}
if (grunt.file.isDir(src)) {
// grunt.log.writeln('Creating ' + dest.cyan);
grunt.file.mkdir(dest);
} else {
// grunt.log.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan);
// Read file source.
grunt.file.copy(src, dest, {
encoding : options.fromEncoding,
process : function( content ){
return iconvLite.encode(new Buffer(content),options.toEncoding);
}
});
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" transed.');
}
});
});
});
};
| ssddi456/grunt-iconv-lite | tasks/grunt-iconv.js | JavaScript | mit | 2,154 |
var Bluebird = require('bluebird');
var connection = require('./connection');
var errors = require('./errors');
var mockOptions = {};
var offlineMode = false;
module.exports.errors = errors;
module.exports.connect = function connect(options) {
if (offlineMode) {
throw new Error('Real connections to ' + options.host + ' are not allowed in offline mode');
}
return new connection.Connection(options).connect();
};
module.exports.connectMock = function connectMock(options) {
return new connection.MockConnection(options, mockOptions).connect();
};
module.exports.setMockOptions = function setMockOptions(options) {
mockOptions = options;
};
module.exports.setOfflineMode = function setOfflineMode(value) {
offlineMode = !!value;
};
| relekang/promised-ssh | lib/ssh.js | JavaScript | mit | 755 |
"use strict";
const hamt = require('../hamt');
const assert = require('chai').assert;
describe('entries', () => {
it('should be empty for empty map', () => {
const h = hamt.make();
const it = hamt.entries(h);
let v = it.next();
assert.ok(v.done);
for (let x of h)
assert.isFalse(true);
});
it('should visit single child', () => {
const h = hamt.make().set('a', 3);
const it = hamt.entries(h);
let v = it.next();
assert.deepEqual(['a', 3], v.value);
assert.notOk(v.done);
v = it.next();
assert.ok(v.done);
assert.deepEqual([['a', 3]], Array.from(h));
});
it('should visit all children', () => {
const h = hamt.make()
.set('a', 3)
.set('b', 5)
.set('c', 7);
const expected = [['a', 3], ['b', 5], ['c', 7]];
{
const it = h.entries();
const results = [];
let v;
for (var i = 0; i < h.count(); ++i) {
v = it.next();
assert.notOk(v.done);
results.push(v.value)
}
v = it.next();
assert.isTrue(v.done);
assert.deepEqual(expected, results);
}
assert.deepEqual(expected, Array.from(h));
});
it('should handle collisions', () => {
const h = hamt.make()
.setHash(0, 'a', 3)
.setHash(0, 'b', 5)
.setHash(0, 'c', 7)
const expected = [['b', 5], ['a', 3], ['c', 7]];
{
const it = h.entries();
const results = [];
let v;
for (var i = 0; i < h.count(); ++i) {
v = it.next();
assert.notOk(v.done);
results.push(v.value)
}
v = it.next();
assert.isTrue(v.done);
assert.deepEqual(expected, results);
}
assert.deepEqual(expected, Array.from(h));
});
it('should handle large map correctly', () => {
let h = hamt.make();
let sum = 0;
for (let i = 0; i < 20000; ++i) {
h = h.set(i + '', i);
sum += i;
}
let foundSum = 0;
for (let x of h)
foundSum += x[1];
assert.strictEqual(sum, foundSum);
});
});
| mattbierner/hamt_plus | tests/entries.js | JavaScript | mit | 2,486 |
import { each } from "../helpers";
import TablesHandler from "../TablesHandler";
each("table", table => {
const tables = new TablesHandler(table);
tables.enable();
});
| madewithlove/why-cant-we-have-nice-things | resources/assets/js/components/tables.js | JavaScript | mit | 177 |
#!/usr/bin/env node
'use strict';
var program = require('commander');
var pluck = require('pluck-keys');
var credential = require('../credential');
var stdin = '';
program
.command('hash [password]')
.description('Hash password')
.option('-w --work <work>', 'relative work load (0.5 for half the work)', Number)
.option('-k --key-length <key-length>', 'length of salt', Number)
.action(function (password, options){
var pw = credential(pluck([
'keyLength',
'hashMethod',
'work'
], options));
pw.hash(stdin || password, function (err, result){
if (err){
return console.error(err);
}
console.log(result);
});
});
program
.command('verify [hash] <password>')
.description('Verify password')
.action(function (hash, password){
credential().verify(stdin || hash, password, function (err, valid){
if (err){
return console.error(err);
}
if (!valid){
throw new Error('Invalid');
}
console.log('Verified');
});
});
if (process.stdin.isTTY) {
program.parse(process.argv);
} else {
process.stdin.on('readable', function (){
stdin += this.read() || '';
});
process.stdin.on('end', function (){
program.parse(process.argv);
});
}
| koeppel/apocms | node_modules/credential/bin/cmd.js | JavaScript | mit | 1,203 |
var app = angular.module('app',[]);
app.controller('adderController', function($scope) {
$scope.firstNumber = 2;
$scope.secondNumber = 2;
$scope.lvalue = 2+2;
$scope.thirdNumber = function () {
if (!$scope.firstNumber || !$scope.secondNumber) {
return $scope.lvalue;
} else {
$scope.lvalue=parseInt($scope.firstNumber)+
parseInt($scope.secondNumber);
return $scope.lvalue;
}
};
});
| henfredemars/dbproject | public/controllers/adder.js | JavaScript | mit | 407 |
var expect = require('expect.js');
var request = require('supertest');
var app = require(process.cwd() + '/app.js');
describe('GET /api/artists', function() {
this.timeout(15000);
it('should return a single JSON artist object', function(done) {
request(app)
.get('/api/artists')
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res) {
if (err) throw err;
expect(res).to.be.an('object');
expect(res.body.status).to.be.equal('ok');
expect(res.body.artists).to.be.an('array');
expect(res.body.count).to.be.equal(res.body.artists.length);
done();
});
});
});
describe('GET /api/artists/:slug', function() {
this.timeout(15000);
it('should return a JSON array of artists', function(done) {
var slug = 'deserto-rosso';
request(app)
.get('/api/artists/' + slug)
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res) {
if (err) throw err;
expect(res).to.be.an('object');
expect(res.body.status).to.be.equal('ok');
expect(res.body.artist).to.be.an('object');
done();
});
});
});
describe('GET /api/artists/genre/:slug', function() {
this.timeout(15000);
it('should return a JSON array of artist within a specific genre', function(done) {
var slug = 'rock';
request(app)
.get('/api/artists/genre/' + slug)
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res) {
if (err) throw err;
expect(res).to.be.an('object');
expect(res.body.status).to.be.equal('ok');
expect(res.body.genre.slug).to.be.equal(slug);
expect(res.body.artists).to.be.an('array');
expect(res.body.count).to.be.equal(res.body.artists.length);
done();
});
});
});
describe('GET /api/artists/tag/:slug', function() {
this.timeout(15000);
it('should return a JSON array of artist within a specific tag', function(done) {
var slug = 'pop';
request(app)
.get('/api/artists/tag/' + slug)
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res) {
if (err) throw err;
expect(res).to.be.an('object');
expect(res.body.status).to.be.equal('ok');
expect(res.body.tag.slug).to.be.equal(slug);
expect(res.body.artists).to.be.an('array');
expect(res.body.count).to.be.equal(res.body.artists.length);
done();
});
});
});
describe('GET /api/genres/artists', function() {
this.timeout(15000);
it('should return a JSON array of all artists genre', function(done) {
request(app)
.get('/api/genres/artists')
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res) {
if (err) throw err;
done();
});
});
});
| ripliveit/riplive.it | test/spec/server/controllers/artists.js | JavaScript | mit | 3,336 |
/*
Copyright (c) 2012 Jacob Rus
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
File-like objects that read from or write to a string buffer.
A nearly direct port of Python’s StringIO module.
f = StringIO() # ready for writing
f = StringIO(buf) # ready for reading
f.close() # explicitly release resources held
pos = f.tell() # get current position
f.seek(pos) # set current position
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
buf = f.read() # read until EOF
buf = f.read(n) # read up to n bytes
buf = f.readline() # read until end of line ('\n') or EOF
list = f.readlines() # list of f.readline() results until EOF
f.truncate([size]) # truncate file to at most size (default: current pos)
f.write(buf) # write at current position
f.writelines(list) # for line in list: f.write(line)
f.getvalue() # return whole file's contents as a string
Notes:
- Seeking far beyond EOF and then writing will insert real null
bytes that occupy space in the buffer.
- There's a simple test set (see end of this file).
*/
var StringIO, _complain_ifclosed, _test, module_root;
_complain_ifclosed = function(closed) {
if (closed) {
throw new Error('I/O operation on closed file');
}
};
/* class StringIO([buffer])
When a StringIO object is created, it can be initialized to an existing
string by passing the string to the constructor. If no string is given,
the StringIO will start empty.
*/
StringIO = (function() {
function StringIO(buf) {
if (buf == null) {
buf = '';
}
this.buf = '' + buf;
this.length = this.buf.length;
this.buflist = [];
this.pos = 0;
this.closed = false;
}
/* Free the memory buffer. */
StringIO.prototype.close = function() {
if (!this.closed) {
this.closed = true;
delete this.buf;
delete this.pos;
}
};
StringIO.prototype._flush_buflist = function() {
this.buf += this.buflist.join('');
return this.buflist = [];
};
/* Set the file's current position.
The mode argument is optional and defaults to 0 (absolute file
positioning); other values are 1 (seek relative to the current
position) and 2 (seek relative to the file's end).
There is no return value.
*/
StringIO.prototype.seek = function(pos, mode) {
if (mode == null) {
mode = 0;
}
_complain_ifclosed(this.closed);
if (this.buflist.length) {
this._flush_buflist();
}
if (mode === 1) {
pos += this.pos;
} else if (mode === 2) {
pos += this.length;
}
this.pos = Math.max(0, pos);
};
/* Return the file's current position. */
StringIO.prototype.tell = function() {
_complain_ifclosed(this.closed);
return this.pos;
};
/* Read at most size bytes from the file
(less if the read hits EOF before obtaining size bytes).
If the size argument is negative or omitted, read all data until EOF
is reached. The bytes are returned as a string object. An empty
string is returned when EOF is encountered immediately.
*/
StringIO.prototype.read = function(n) {
var newpos, r;
if (n == null) {
n = -1;
}
_complain_ifclosed(this.closed);
if (this.buflist.length) {
this._flush_buflist();
}
if (n < 0) {
newpos = this.length;
} else {
newpos = Math.min(this.pos + n, this.length);
}
r = this.buf.slice(this.pos, newpos);
this.pos = newpos;
return r;
};
/* Read one entire line from the file.
A trailing newline character is kept in the string (but may be absent
when a file ends with an incomplete line). If the size argument is
present and non-negative, it is a maximum byte count (including the
trailing newline) and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.
*/
StringIO.prototype.readline = function(length) {
var i, newpos, r;
if (length == null) {
length = null;
}
_complain_ifclosed(this.closed);
if (this.buflist.length) {
this._flush_buflist();
}
i = this.buf.indexOf('\n', this.pos);
if (i < 0) {
newpos = this.length;
} else {
newpos = i + 1;
}
if ((length != null) && this.pos + length < newpos) {
newpos = this.pos + length;
}
r = this.buf.slice(this.pos, newpos);
this.pos = newpos;
return r;
};
/* Read until EOF using readline() and return a list containing the
lines thus read.
If the optional sizehint argument is present, instead of reading up
to EOF, whole lines totalling approximately sizehint bytes (or more
to accommodate a final whole line).
*/
StringIO.prototype.readlines = function(sizehint) {
var line, lines, total;
if (sizehint == null) {
sizehint = 0;
}
total = 0;
lines = [];
line = this.readline();
while (line) {
lines.push(line);
total += line.length;
if ((0 < sizehint && sizehint <= total)) {
break;
}
line = this.readline();
}
return lines;
};
/* Truncate the file's size.
If the optional size argument is present, the file is truncated to
(at most) that size. The size defaults to the current position.
The current file position is not changed unless the position
is beyond the new file size.
If the specified size exceeds the file's current size, the
file remains unchanged.
*/
StringIO.prototype.truncate = function(size) {
if (size == null) {
size = null;
}
_complain_ifclosed(this.closed);
if (size == null) {
size = this.pos;
} else if (size < 0) {
throw new Error('Negative size not allowed');
} else if (size < this.pos) {
this.pos = size;
}
this.buf = this.getvalue().slice(0, size);
this.length = size;
};
/* Write a string to the file.
There is no return value.
*/
StringIO.prototype.write = function(s) {
var newpos, null_bytes, slen, spos;
_complain_ifclosed(this.closed);
if (!s) {
return;
}
if (typeof s !== 'string') {
s = s.toString();
}
spos = this.pos;
slen = this.length;
if (spos === slen) {
this.buflist.push(s);
this.length = this.pos = spos + s.length;
return;
}
if (spos > slen) {
null_bytes = (Array(spos - slen + 1)).join('\x00');
this.buflist.push(null_bytes);
slen = spos;
}
newpos = spos + s.length;
if (spos < slen) {
if (this.buflist.length) {
this._flush_buflist();
}
this.buflist.push(this.buf.slice(0, spos), s, this.buf.slice(newpos));
this.buf = '';
if (newpos > slen) {
slen = newpos;
}
} else {
this.buflist.push(s);
slen = newpos;
}
this.length = slen;
this.pos = newpos;
};
/* Write a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings. There
is no return value.
(The name is intended to match readlines(); writelines() does not add
line separators.)
*/
StringIO.prototype.writelines = function(array) {
var j, len, line;
for (j = 0, len = array.length; j < len; j++) {
line = array[j];
this.write(line);
}
};
/* Flush the internal buffer */
StringIO.prototype.flush = function() {
_complain_ifclosed(this.closed);
};
/* Retrieve the entire contents of the "file" at any time
before the StringIO object's close() method is called.
*/
StringIO.prototype.getvalue = function() {
if (this.buflist.length) {
this._flush_buflist();
}
return this.buf;
};
return StringIO;
})();
module_root = typeof exports !== "undefined" && exports !== null ? exports : typeof window !== "undefined" && window !== null ? window : this;
module_root.StringIO = StringIO;
_test = function() {
var f, j, len, length, line, line2, lines, list, print, ref;
print = function() {
return console.log.apply(console, arguments);
};
lines = ['This is a test,\n', 'Blah blah blah,\n', 'Wow does this work?\n', 'Okay, here are some lines\n', 'of text.\n'];
f = new StringIO;
ref = lines.slice(0, -2);
for (j = 0, len = ref.length; j < len; j++) {
line = ref[j];
f.write(line);
}
f.writelines(lines.slice(-2));
if (f.getvalue() !== lines.join('')) {
throw new Error('write failed');
}
length = f.tell();
print('File length =', length);
f.seek(lines[0].length);
f.write(lines[1]);
f.seek(0);
print("First line = " + (f.readline()));
print("Position = " + (f.tell()));
line = f.readline();
print("Second line = " + line);
f.seek(-line.length, 1);
line2 = f.read(line.length);
if (line !== line2) {
throw new Error('bad result after seek back');
}
f.seek(-line2.length, 1);
list = f.readlines();
line = list[list.length - 1];
f.seek(f.tell() - line.length);
line2 = f.read();
if (line !== line2) {
throw new Error('bad result after seek back from EOF');
}
print("Read " + list.length + " more lines");
print("File length = " + (f.tell()));
if (f.tell() !== length) {
throw new Error('bad length');
}
f.truncate((length / 2) | 0);
f.seek(0, 2);
print("Truncated length = " + (f.tell()));
if (f.tell() !== ((length / 2) | 0)) {
throw new Error('truncate did not adjust length');
}
return f.close();
}; | joshuaferrara/node-csgo | helpers/stringio.js | JavaScript | mit | 10,405 |
var searchData=
[
['upmixtype',['UpmixType',['../struct_upmix_type.html',1,'']]]
];
| andresgonzalezfornell/TFM | doc/html/search/classes_c.js | JavaScript | mit | 86 |
import { suite, test, equal, isUndefined, isFalse, isTrue } from "../assert";
import CompositeContext from "di/CompositeContext";
import Context from "di/Context";
suite("CompositeContext", () => {
test("no contexts", () => {
const composite = new CompositeContext();
const hasFirst = composite.has("first");
const firstValue = composite.get("first");
isFalse(hasFirst);
isUndefined(firstValue);
});
test("single context", () => {
const context = new Context({ first: "first expected" });
const composite = new CompositeContext([context]);
const hasFirst = composite.has("first");
const firstValue = composite.get("first");
isTrue(hasFirst);
equal("first expected", firstValue);
});
test("multiple contexts", () => {
const primaryContext = new Context({ first: "first expected" });
const secondaryContext = new Context({
first: "nothing",
second: "second expected"
});
const composite = new CompositeContext([primaryContext, secondaryContext]);
const hasFirst = composite.has("first");
const firstValue = composite.get("first");
isTrue(hasFirst);
equal("first expected", firstValue);
const hasSecond = composite.has("second");
const secondValue = composite.get("second");
isTrue(hasSecond);
equal("second expected", secondValue);
});
});
| RikardLegge/modulin-di | tests/di/CompositeContextTest.js | JavaScript | mit | 1,364 |
var xue =xue || {};
xue.formCheck = xue.formCheck || {};
var fCheck = xue.formCheck;
/* 提示信息的css样式 */
fCheck.setTips = function(select, tips){
$(select).css({
'display': 'block',
}).html(tips);
};
/* 输入正确时,清除提醒 */
fCheck.clearTips = function(select){
$(select).css({
'display':'none'
}).html(null);
};
/* 边框样式 */
fCheck.bordercss = function(argument) {
if($(argument).val() !== ''){
$(argument).css('border','1px solid #68c04a');
}else{$(argument).css('border','1px solid #d2d2d2');}
}
/* 验证昵称 */
$(function(){
var nickname = $('.nickname');
$(nickname).on('focus',function(){
nickname.data('lastVal', $.trim(nickname.val()));
$('.prompt-empty').html('请输入不超过6个汉字、18个字母或18个数字').css({
color: '#999',
display: 'block'
});
$(".nickname-warning").css({
display: 'none',
});
});
$(nickname).on('blur',function(){
fCheck.clearTips(".prompt-empty");
if (nickname.val() == '') {
$(".nickname-warning").html('请输入昵称').css({
display: 'block',
});
}else{
if(nickname.data('lastVal') != $.trim(nickname.val())) {
$(".nickname").css('border','1px solid #d2d2d2');
fCheck.clearTips(".nickname-warning");
$.fn.nickname();
}else{
$(".nickname-warning").css({
display: 'block',
});
}
}
});
});
var boxs = {
nickname: '.nickname',
school:'.school'
}
$.fn.nickname = function(){
var box = $(boxs.nickname),
val = box.val();
if (val == '') {
fCheck.setTips(".nickname-warning",'请输入昵称');
}else {
var reg = /^[0-9a-zA-Z\u4e00-\u9fa5]{1,18}$/;
if(reg.test(val)){
$.fn.nicknameajax();
}else{
fCheck.setTips(".nickname-warning",'只能输入数字、汉字和字母');
}
}
};
$.fn.nicknameajax = function(){
var box = $(boxs.nickname),
val = box.val(),
d_val = $.trim(box.data('lastVal'));
if($.trim(val) != d_val){
$.ajax({
url : '/MyInfos/getNicknameUseful',
type : 'GET',
dataType : 'json',
data : 'nickname=' + $('.nickname').val(),
timeout: 7000,
async: true,
success : function(result){
if(result.sign == false){
fCheck.setTips(".nickname-warning",result.msg);
return false;
} else {
fCheck.clearTips(".nickname-warning");
fCheck.bordercss('.nickname');
$(box).data('lastVal',val);
return true;
}
if(result.sign === 2){
window.location.href = result.msg;
}
}
});
}
}
/* 学校格式验证 */
$.fn.school = function(){
var box = $(boxs.school),
val = box.val();
var text = box.next('.school-warning'),
block = text.addClass('success');
if (val == '') {
fCheck.clearTips(".school-warning");
}else {
var reg = /^[0-9a-zA-Z\u4e00-\u9fa5]{1,50}$/;
if(reg.test(val)){
fCheck.clearTips(".school-warning");
fCheck.bordercss('.school');
}else{
fCheck.setTips(".school-warning",'只能输入数字、汉字和字母');
$('.school').css('border','1px solid #d2d2d2');
return false;
}
}
};
$('.school').on('blur',function(){
$.fn.school();
});
/* 点击提交按钮验证 */
function inforCheckform () {
if ($(".nickname").val() == $(".nickname").data("nickname") && $(".school").val() == $(".school").data("school") && $("#year").find("option:selected").text() == $("#year").attr("rel") && $("#month").find("option:selected").text() == $("#month").attr("rel") && $("#day").find("option:selected").text() == $("#day").attr("rel")) {
alert('您没有修改或新增任何资料');
return false;
}else{
setTimeout($.fn.nickname(),200);
$.fn.school();
}
if ($('.nickname-warning').is(":empty") && $('.school-warning').is(":empty") && $('.date-warning').is(":empty")) {
}else{
return false;
};
}
var messageError = $(".message-error span").is(":empty");
if (messageError == '0') {
$('.message-error').css({
display: 'block'
});
setTimeout("$('.message-error').css({display: 'none'});",6000);
} | wujay/xue-project | source/widget/UM.Basic.information/basic-information.js | JavaScript | mit | 4,686 |
'use strict';
var chai = require('chai')
, Sequelize = require('../../../index')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../../lib/data-types')
, datetime = require('chai-datetime')
, async = require('async');
chai.use(datetime);
chai.config.includeStack = true;
var sortById = function(a, b) {
return a.id < b.id ? -1 : 1;
};
describe(Support.getTestDialectTeaser('Includes with schemas'), function() {
describe('findAll', function() {
this.timeout(30000);
beforeEach(function() {
var self = this;
this.fixtureA = function(done) {
self.sequelize.dropAllSchemas().success(function() {
self.sequelize.createSchema('account').success(function() {
var AccUser = self.sequelize.define('AccUser', {}, {schema: 'account'})
, Company = self.sequelize.define('Company', {
name: DataTypes.STRING
}, {schema: 'account'})
, Product = self.sequelize.define('Product', {
title: DataTypes.STRING
}, {schema: 'account'})
, Tag = self.sequelize.define('Tag', {
name: DataTypes.STRING
}, {schema: 'account'})
, Price = self.sequelize.define('Price', {
value: DataTypes.FLOAT
}, {schema: 'account'})
, Customer = self.sequelize.define('Customer', {
name: DataTypes.STRING
}, {schema: 'account'})
, Group = self.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'})
, GroupMember = self.sequelize.define('GroupMember', {
}, {schema: 'account'})
, Rank = self.sequelize.define('Rank', {
name: DataTypes.STRING,
canInvite: {
type: DataTypes.INTEGER,
defaultValue: 0
},
canRemove: {
type: DataTypes.INTEGER,
defaultValue: 0
},
canPost: {
type: DataTypes.INTEGER,
defaultValue: 0
}
}, {schema: 'account'});
self.models = {
AccUser: AccUser,
Company: Company,
Product: Product,
Tag: Tag,
Price: Price,
Customer: Customer,
Group: Group,
GroupMember: GroupMember,
Rank: Rank
};
AccUser.hasMany(Product);
Product.belongsTo(AccUser);
Product.hasMany(Tag);
Tag.hasMany(Product);
Product.belongsTo(Tag, {as: 'Category'});
Product.belongsTo(Company);
Product.hasMany(Price);
Price.belongsTo(Product);
AccUser.hasMany(GroupMember, {as: 'Memberships'});
GroupMember.belongsTo(AccUser);
GroupMember.belongsTo(Rank);
GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, {as: 'Memberships'});
self.sequelize.sync({force: true}).done(function() {
var count = 4
, i = -1;
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'Developers'},
{name: 'Designers'},
{name: 'Managers'}
]).done(function() {
Group.findAll().done(callback);
});
},
companies: function(callback) {
Company.bulkCreate([
{name: 'Sequelize'},
{name: 'Coca Cola'},
{name: 'Bonanza'},
{name: 'NYSE'},
{name: 'Coshopr'}
]).done(function(err) {
if (err) return callback(err);
Company.findAll().done(callback);
});
},
ranks: function(callback) {
Rank.bulkCreate([
{name: 'Admin', canInvite: 1, canRemove: 1, canPost: 1},
{name: 'Trustee', canInvite: 1, canRemove: 0, canPost: 1},
{name: 'Member', canInvite: 1, canRemove: 0, canPost: 0}
]).done(function() {
Rank.findAll().done(callback);
});
},
tags: function(callback) {
Tag.bulkCreate([
{name: 'A'},
{name: 'B'},
{name: 'C'},
{name: 'D'},
{name: 'E'}
]).done(function() {
Tag.findAll().done(callback);
});
},
loop: ['groups', 'ranks', 'tags', 'companies', function(done, results) {
var groups = results.groups
, ranks = results.ranks
, tags = results.tags
, companies = results.companies;
async.whilst(
function() { return i < count; },
function(callback) {
i++;
async.auto({
user: function(callback) {
AccUser.create().done(callback);
},
memberships: ['user', function(callback, results) {
var groupMembers = [
{AccUserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{AccUserId: results.user.id, GroupId: groups[1].id, RankId: ranks[2].id}
];
if (i < 3) {
groupMembers.push({AccUserId: results.user.id, GroupId: groups[2].id, RankId: ranks[1].id});
}
GroupMember.bulkCreate(groupMembers).done(callback);
}],
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'},
{title: 'Bed'},
{title: 'Pen'},
{title: 'Monitor'}
]).done(function(err) {
if (err) return callback(err);
Product.findAll().done(callback);
});
},
userProducts: ['user', 'products', function(callback, results) {
results.user.setProducts([
results.products[(i * 5) + 0],
results.products[(i * 5) + 1],
results.products[(i * 5) + 3]
]).done(callback);
}],
productTags: ['products', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[(i * 5) + 0].setTags([
tags[0],
tags[2]
]));
chainer.add(results.products[(i * 5) + 1].setTags([
tags[1]
]));
chainer.add(results.products[(i * 5) + 0].setCategory(tags[1]));
chainer.add(results.products[(i * 5) + 2].setTags([
tags[0]
]));
chainer.add(results.products[(i * 5) + 3].setTags([
tags[0]
]));
chainer.run().done(callback);
}],
companies: ['products', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.products[(i * 5) + 0].setCompany(companies[4]);
results.products[(i * 5) + 1].setCompany(companies[3]);
results.products[(i * 5) + 2].setCompany(companies[2]);
results.products[(i * 5) + 3].setCompany(companies[1]);
results.products[(i * 5) + 4].setCompany(companies[0]);
chainer.run().done(callback);
}],
prices: ['products', function(callback, results) {
Price.bulkCreate([
{ProductId: results.products[(i * 5) + 0].id, value: 5},
{ProductId: results.products[(i * 5) + 0].id, value: 10},
{ProductId: results.products[(i * 5) + 1].id, value: 5},
{ProductId: results.products[(i * 5) + 1].id, value: 10},
{ProductId: results.products[(i * 5) + 1].id, value: 15},
{ProductId: results.products[(i * 5) + 1].id, value: 20},
{ProductId: results.products[(i * 5) + 2].id, value: 20},
{ProductId: results.products[(i * 5) + 3].id, value: 20}
]).done(callback);
}]
}, callback);
},
function(err) {
expect(err).not.to.be.ok;
done();
}
);
}]
}, done.bind(this));
}).error(done);
});
});
};
});
it('should support an include with multiple different association types', function(done) {
var self = this;
self.sequelize.dropAllSchemas().success(function() {
self.sequelize.createSchema('account').success(function() {
var AccUser = self.sequelize.define('AccUser', {}, {schema: 'account'})
, Product = self.sequelize.define('Product', {
title: DataTypes.STRING
}, {schema: 'account'})
, Tag = self.sequelize.define('Tag', {
name: DataTypes.STRING
}, {schema: 'account'})
, Price = self.sequelize.define('Price', {
value: DataTypes.FLOAT
}, {schema: 'account'})
, Customer = self.sequelize.define('Customer', {
name: DataTypes.STRING
}, {schema: 'account'})
, Group = self.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'})
, GroupMember = self.sequelize.define('GroupMember', {
}, {schema: 'account'})
, Rank = self.sequelize.define('Rank', {
name: DataTypes.STRING,
canInvite: {
type: DataTypes.INTEGER,
defaultValue: 0
},
canRemove: {
type: DataTypes.INTEGER,
defaultValue: 0
}
}, {schema: 'account'});
AccUser.hasMany(Product);
Product.belongsTo(AccUser);
Product.hasMany(Tag);
Tag.hasMany(Product);
Product.belongsTo(Tag, {as: 'Category'});
Product.hasMany(Price);
Price.belongsTo(Product);
AccUser.hasMany(GroupMember, {as: 'Memberships'});
GroupMember.belongsTo(AccUser);
GroupMember.belongsTo(Rank);
GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, {as: 'Memberships'});
self.sequelize.sync({force: true}).done(function() {
var count = 4
, i = -1;
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'Developers'},
{name: 'Designers'}
]).done(function() {
Group.findAll().done(callback);
});
},
ranks: function(callback) {
Rank.bulkCreate([
{name: 'Admin', canInvite: 1, canRemove: 1},
{name: 'Member', canInvite: 1, canRemove: 0}
]).done(function() {
Rank.findAll().done(callback);
});
},
tags: function(callback) {
Tag.bulkCreate([
{name: 'A'},
{name: 'B'},
{name: 'C'}
]).done(function() {
Tag.findAll().done(callback);
});
},
loop: ['groups', 'ranks', 'tags', function(done, results) {
var groups = results.groups
, ranks = results.ranks
, tags = results.tags;
async.whilst(
function() { return i < count; },
function(callback) {
i++;
async.auto({
user: function(callback) {
AccUser.create().done(callback);
},
memberships: ['user', function(callback, results) {
GroupMember.bulkCreate([
{AccUserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{AccUserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]).done(callback);
}],
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'}
]).done(function() {
Product.findAll().done(callback);
});
},
userProducts: ['user', 'products', function(callback, results) {
results.user.setProducts([
results.products[(i * 2) + 0],
results.products[(i * 2) + 1]
]).done(callback);
}],
productTags: ['products', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[(i * 2) + 0].setTags([
tags[0],
tags[2]
]));
chainer.add(results.products[(i * 2) + 1].setTags([
tags[1]
]));
chainer.add(results.products[(i * 2) + 0].setCategory(tags[1]));
chainer.run().done(callback);
}],
prices: ['products', function(callback, results) {
Price.bulkCreate([
{ProductId: results.products[(i * 2) + 0].id, value: 5},
{ProductId: results.products[(i * 2) + 0].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 5},
{ProductId: results.products[(i * 2) + 1].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 15},
{ProductId: results.products[(i * 2) + 1].id, value: 20}
]).done(callback);
}]
}, callback);
},
function(err) {
expect(err).not.to.be.ok;
AccUser.findAll({
include: [
{model: GroupMember, as: 'Memberships', include: [
Group,
Rank
]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
Price
]}
],
order: [
[AccUser.rawAttributes.id, 'ASC']
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
users.forEach(function(user) {
expect(user.Memberships).to.be.ok;
user.Memberships.sort(sortById);
expect(user.Memberships.length).to.equal(2);
expect(user.Memberships[0].Group.name).to.equal('Developers');
expect(user.Memberships[0].Rank.canRemove).to.equal(1);
expect(user.Memberships[1].Group.name).to.equal('Designers');
expect(user.Memberships[1].Rank.canRemove).to.equal(0);
user.Products.sort(sortById);
expect(user.Products.length).to.equal(2);
expect(user.Products[0].Tags.length).to.equal(2);
expect(user.Products[1].Tags.length).to.equal(1);
expect(user.Products[0].Category).to.be.ok;
expect(user.Products[1].Category).not.to.be.ok;
expect(user.Products[0].Prices.length).to.equal(2);
expect(user.Products[1].Prices.length).to.equal(4);
done();
});
});
}
);
}]
}, done);
});
});
});
});
it('should support many levels of belongsTo', function(done) {
var A = this.sequelize.define('a', {}, {schema: 'account'})
, B = this.sequelize.define('b', {}, {schema: 'account'})
, C = this.sequelize.define('c', {}, {schema: 'account'})
, D = this.sequelize.define('d', {}, {schema: 'account'})
, E = this.sequelize.define('e', {}, {schema: 'account'})
, F = this.sequelize.define('f', {}, {schema: 'account'})
, G = this.sequelize.define('g', {}, {schema: 'account'})
, H = this.sequelize.define('h', {}, {schema: 'account'});
A.belongsTo(B);
B.belongsTo(C);
C.belongsTo(D);
D.belongsTo(E);
E.belongsTo(F);
F.belongsTo(G);
G.belongsTo(H);
var b, singles = [
B,
C,
D,
E,
F,
G,
H
];
this.sequelize.sync().done(function() {
async.auto({
as: function(callback) {
A.bulkCreate([
{},
{},
{},
{},
{},
{},
{},
{}
]).done(function() {
A.findAll().done(callback);
});
},
singleChain: function(callback) {
var previousInstance;
async.eachSeries(singles, function(model, callback) {
model.create({}).done(function(err, instance) {
if (previousInstance) {
previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function() {
previousInstance = instance;
callback();
});
} else {
previousInstance = b = instance;
callback();
}
});
}, callback);
},
abs: ['as', 'singleChain', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.as.forEach(function(a) {
chainer.add(a.setB(b));
});
chainer.run().done(callback);
}]
}, function() {
A.findAll({
include: [
{model: B, include: [
{model: C, include: [
{model: D, include: [
{model: E, include: [
{model: F, include: [
{model: G, include: [
{model: H}
]}
]}
]}
]}
]}
]}
]
}).done(function(err, as) {
expect(err).not.to.be.ok;
expect(as.length).to.be.ok;
as.forEach(function(a) {
expect(a.b.c.d.e.f.g.h).to.be.ok;
});
done();
});
});
});
});
it('should support ordering with only belongsTo includes', function(done) {
var User = this.sequelize.define('SpecialUser', {}, {schema: 'account'})
, Item = this.sequelize.define('Item', {'test': DataTypes.STRING}, {schema: 'account'})
, Order = this.sequelize.define('Order', {'position': DataTypes.INTEGER}, {schema: 'account'});
User.belongsTo(Item, {'as': 'itemA', foreignKey: 'itemA_id'});
User.belongsTo(Item, {'as': 'itemB', foreignKey: 'itemB_id'});
User.belongsTo(Order);
this.sequelize.sync().done(function() {
async.auto({
users: function(callback) {
User.bulkCreate([{}, {}, {}]).done(function() {
User.findAll().done(callback);
});
},
items: function(callback) {
Item.bulkCreate([
{'test': 'abc'},
{'test': 'def'},
{'test': 'ghi'},
{'test': 'jkl'}
]).done(function() {
Item.findAll({order: ['id']}).done(callback);
});
},
orders: function(callback) {
Order.bulkCreate([
{'position': 2},
{'position': 3},
{'position': 1}
]).done(function() {
Order.findAll({order: ['id']}).done(callback);
});
},
associate: ['users', 'items', 'orders', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
var user1 = results.users[0];
var user2 = results.users[1];
var user3 = results.users[2];
var item1 = results.items[0];
var item2 = results.items[1];
var item3 = results.items[2];
var item4 = results.items[3];
var order1 = results.orders[0];
var order2 = results.orders[1];
var order3 = results.orders[2];
chainer.add(user1.setItemA(item1));
chainer.add(user1.setItemB(item2));
chainer.add(user1.setOrder(order3));
chainer.add(user2.setItemA(item3));
chainer.add(user2.setItemB(item4));
chainer.add(user2.setOrder(order2));
chainer.add(user3.setItemA(item1));
chainer.add(user3.setItemB(item4));
chainer.add(user3.setOrder(order1));
chainer.run().done(callback);
}]
}, function() {
User.findAll({
'include': [
{'model': Item, 'as': 'itemA', where: {test: 'abc'}},
{'model': Item, 'as': 'itemB'},
Order],
'order': [
[Order, 'position']
]
}).done(function(err, as) {
expect(err).not.to.be.ok;
expect(as.length).to.eql(2);
expect(as[0].itemA.test).to.eql('abc');
expect(as[1].itemA.test).to.eql('abc');
expect(as[0].Order.position).to.eql(1);
expect(as[1].Order.position).to.eql(2);
done();
});
});
});
});
it('should include attributes from through models', function(done) {
var Product = this.sequelize.define('Product', {
title: DataTypes.STRING
}, {schema: 'account'})
, Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING
}, {schema: 'account'})
, ProductTag = this.sequelize.define('ProductTag', {
priority: DataTypes.INTEGER
}, {schema: 'account'});
Product.hasMany(Tag, {through: ProductTag});
Tag.hasMany(Product, {through: ProductTag});
this.sequelize.sync({force: true}).done(function() {
async.auto({
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'},
{title: 'Dress'}
]).done(function() {
Product.findAll().done(callback);
});
},
tags: function(callback) {
Tag.bulkCreate([
{name: 'A'},
{name: 'B'},
{name: 'C'}
]).done(function() {
Tag.findAll().done(callback);
});
},
productTags: ['products', 'tags', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[0].addTag(results.tags[0], {priority: 1}));
chainer.add(results.products[0].addTag(results.tags[1], {priority: 2}));
chainer.add(results.products[1].addTag(results.tags[1], {priority: 1}));
chainer.add(results.products[2].addTag(results.tags[0], {priority: 3}));
chainer.add(results.products[2].addTag(results.tags[1], {priority: 1}));
chainer.add(results.products[2].addTag(results.tags[2], {priority: 2}));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
Product.findAll({
include: [
{model: Tag}
],
order: [
['id', 'ASC'],
[Tag, 'id', 'ASC']
]
}).done(function(err, products) {
expect(err).not.to.be.ok;
expect(products[0].Tags[0].ProductTag.priority).to.equal(1);
expect(products[0].Tags[1].ProductTag.priority).to.equal(2);
expect(products[1].Tags[0].ProductTag.priority).to.equal(1);
expect(products[2].Tags[0].ProductTag.priority).to.equal(3);
expect(products[2].Tags[1].ProductTag.priority).to.equal(1);
expect(products[2].Tags[2].ProductTag.priority).to.equal(2);
done();
});
});
});
});
it('should support a required belongsTo include', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {}, {schema: 'account'});
User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([{}, {}]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}, {}]).done(function() {
User.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
results.users[2].setGroup(results.groups[1]).done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, required: true}
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1);
expect(users[0].Group).to.be.ok;
done();
});
});
});
});
it('should be possible to extend the on clause with a where option on a belongsTo include', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'});
User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'A'},
{name: 'B'}
]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}]).done(function() {
User.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[0].setGroup(results.groups[1]));
chainer.add(results.users[1].setGroup(results.groups[0]));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, where: {name: 'A'}}
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1);
expect(users[0].Group).to.be.ok;
expect(users[0].Group.name).to.equal('A');
done();
});
});
});
});
it('should be possible to extend the on clause with a where option on a belongsTo include', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'});
User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'A'},
{name: 'B'}
]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}]).done(function() {
User.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[0].setGroup(results.groups[1]));
chainer.add(results.users[1].setGroup(results.groups[0]));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, required: true}
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
users.forEach(function(user) {
expect(user.Group).to.be.ok;
});
done();
});
});
});
});
it('should be possible to define a belongsTo include as required with child hasMany with limit', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'})
, Category = this.sequelize.define('Category', {
category: DataTypes.STRING
}, {schema: 'account'});
User.belongsTo(Group);
Group.hasMany(Category);
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'A'},
{name: 'B'}
]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}]).done(function() {
User.findAll().done(callback);
});
},
categories: function(callback) {
Category.bulkCreate([{}, {}]).done(function() {
Category.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[0].setGroup(results.groups[1]));
chainer.add(results.users[1].setGroup(results.groups[0]));
chainer.run().done(callback);
}],
groupCategories: ['groups', 'categories', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.groups.forEach(function(group) {
chainer.add(group.setCategories(results.categories));
});
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, required: true, include: [
{model: Category}
]}
],
limit: 1
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1);
users.forEach(function(user) {
expect(user.Group).to.be.ok;
expect(user.Group.Categories).to.be.ok;
});
done();
});
});
});
});
it('should be possible to define a belongsTo include as required with child hasMany with limit and aliases', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'})
, Category = this.sequelize.define('Category', {
category: DataTypes.STRING
}, {schema: 'account'});
User.belongsTo(Group, {as: 'Team'});
Group.hasMany(Category, {as: 'Tags'});
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'A'},
{name: 'B'}
]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}]).done(function() {
User.findAll().done(callback);
});
},
categories: function(callback) {
Category.bulkCreate([{}, {}]).done(function() {
Category.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[0].setTeam(results.groups[1]));
chainer.add(results.users[1].setTeam(results.groups[0]));
chainer.run().done(callback);
}],
groupCategories: ['groups', 'categories', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.groups.forEach(function(group) {
chainer.add(group.setTags(results.categories));
});
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, required: true, as: 'Team', include: [
{model: Category, as: 'Tags'}
]}
],
limit: 1
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1);
users.forEach(function(user) {
expect(user.Team).to.be.ok;
expect(user.Team.Tags).to.be.ok;
});
done();
});
});
});
});
it('should be possible to define a belongsTo include as required with child hasMany which is not required with limit', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'})
, Category = this.sequelize.define('Category', {
category: DataTypes.STRING
}, {schema: 'account'});
User.belongsTo(Group);
Group.hasMany(Category);
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'A'},
{name: 'B'}
]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}]).done(function() {
User.findAll().done(callback);
});
},
categories: function(callback) {
Category.bulkCreate([{}, {}]).done(function() {
Category.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[0].setGroup(results.groups[1]));
chainer.add(results.users[1].setGroup(results.groups[0]));
chainer.run().done(callback);
}],
groupCategories: ['groups', 'categories', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
results.groups.forEach(function(group) {
chainer.add(group.setCategories(results.categories));
});
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, required: true, include: [
{model: Category, required: false}
]}
],
limit: 1
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1);
users.forEach(function(user) {
expect(user.Group).to.be.ok;
expect(user.Group.Categories).to.be.ok;
});
done();
});
});
});
});
it('should be possible to extend the on clause with a where option on a hasOne include', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Project = this.sequelize.define('Project', {
title: DataTypes.STRING
}, {schema: 'account'});
User.hasOne(Project, {as: 'LeaderOf'});
this.sequelize.sync({force: true}).done(function() {
async.auto({
projects: function(callback) {
Project.bulkCreate([
{title: 'Alpha'},
{title: 'Beta'}
]).done(function() {
Project.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}]).done(function() {
User.findAll().done(callback);
});
},
userProjects: ['users', 'projects', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[1].setLeaderOf(results.projects[1]));
chainer.add(results.users[0].setLeaderOf(results.projects[0]));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Project, as: 'LeaderOf', where: {title: 'Beta'}}
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(1);
expect(users[0].LeaderOf).to.be.ok;
expect(users[0].LeaderOf.title).to.equal('Beta');
done();
});
});
});
});
it('should be possible to extend the on clause with a where option on a hasMany include with a through model', function(done) {
var Product = this.sequelize.define('Product', {
title: DataTypes.STRING
}, {schema: 'account'})
, Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING
}, {schema: 'account'})
, ProductTag = this.sequelize.define('ProductTag', {
priority: DataTypes.INTEGER
}, {schema: 'account'});
Product.hasMany(Tag, {through: ProductTag});
Tag.hasMany(Product, {through: ProductTag});
this.sequelize.sync({force: true}).done(function() {
async.auto({
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'},
{title: 'Dress'}
]).done(function() {
Product.findAll().done(callback);
});
},
tags: function(callback) {
Tag.bulkCreate([
{name: 'A'},
{name: 'B'},
{name: 'C'}
]).done(function() {
Tag.findAll().done(callback);
});
},
productTags: ['products', 'tags', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[0].addTag(results.tags[0], {priority: 1}));
chainer.add(results.products[0].addTag(results.tags[1], {priority: 2}));
chainer.add(results.products[1].addTag(results.tags[1], {priority: 1}));
chainer.add(results.products[2].addTag(results.tags[0], {priority: 3}));
chainer.add(results.products[2].addTag(results.tags[1], {priority: 1}));
chainer.add(results.products[2].addTag(results.tags[2], {priority: 2}));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
Product.findAll({
include: [
{model: Tag, where: {name: 'C'}}
]
}).done(function(err, products) {
expect(err).not.to.be.ok;
expect(products.length).to.equal(1);
expect(products[0].Tags.length).to.equal(1);
done();
});
});
});
});
it('should be possible to extend the on clause with a where option on nested includes', function(done) {
var User = this.sequelize.define('User', {
name: DataTypes.STRING
}, {schema: 'account'})
, Product = this.sequelize.define('Product', {
title: DataTypes.STRING
}, {schema: 'account'})
, Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING
}, {schema: 'account'})
, Price = this.sequelize.define('Price', {
value: DataTypes.FLOAT
}, {schema: 'account'})
, Customer = this.sequelize.define('Customer', {
name: DataTypes.STRING
}, {schema: 'account'})
, Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'})
, GroupMember = this.sequelize.define('GroupMember', {
}, {schema: 'account'})
, Rank = this.sequelize.define('Rank', {
name: DataTypes.STRING,
canInvite: {
type: DataTypes.INTEGER,
defaultValue: 0
},
canRemove: {
type: DataTypes.INTEGER,
defaultValue: 0
}
}, {schema: 'account'});
User.hasMany(Product);
Product.belongsTo(User);
Product.hasMany(Tag);
Tag.hasMany(Product);
Product.belongsTo(Tag, {as: 'Category'});
Product.hasMany(Price);
Price.belongsTo(Product);
User.hasMany(GroupMember, {as: 'Memberships'});
GroupMember.belongsTo(User);
GroupMember.belongsTo(Rank);
GroupMember.belongsTo(Group);
Group.hasMany(GroupMember, {as: 'Memberships'});
this.sequelize.sync({force: true}).done(function() {
var count = 4
, i = -1;
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'Developers'},
{name: 'Designers'}
]).done(function() {
Group.findAll().done(callback);
});
},
ranks: function(callback) {
Rank.bulkCreate([
{name: 'Admin', canInvite: 1, canRemove: 1},
{name: 'Member', canInvite: 1, canRemove: 0}
]).done(function() {
Rank.findAll().done(callback);
});
},
tags: function(callback) {
Tag.bulkCreate([
{name: 'A'},
{name: 'B'},
{name: 'C'}
]).done(function() {
Tag.findAll().done(callback);
});
},
loop: ['groups', 'ranks', 'tags', function(done, results) {
var groups = results.groups
, ranks = results.ranks
, tags = results.tags;
async.whilst(
function() { return i < count; },
function(callback) {
i++;
async.auto({
user: function(callback) {
User.create({name: 'FooBarzz'}).done(callback);
},
memberships: ['user', function(callback, results) {
GroupMember.bulkCreate([
{UserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id},
{UserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id}
]).done(callback);
}],
products: function(callback) {
Product.bulkCreate([
{title: 'Chair'},
{title: 'Desk'}
]).done(function() {
Product.findAll().done(callback);
});
},
userProducts: ['user', 'products', function(callback, results) {
results.user.setProducts([
results.products[(i * 2) + 0],
results.products[(i * 2) + 1]
]).done(callback);
}],
productTags: ['products', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.products[(i * 2) + 0].setTags([
tags[0],
tags[2]
]));
chainer.add(results.products[(i * 2) + 1].setTags([
tags[1]
]));
chainer.add(results.products[(i * 2) + 0].setCategory(tags[1]));
chainer.run().done(callback);
}],
prices: ['products', function(callback, results) {
Price.bulkCreate([
{ProductId: results.products[(i * 2) + 0].id, value: 5},
{ProductId: results.products[(i * 2) + 0].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 5},
{ProductId: results.products[(i * 2) + 1].id, value: 10},
{ProductId: results.products[(i * 2) + 1].id, value: 15},
{ProductId: results.products[(i * 2) + 1].id, value: 20}
]).done(callback);
}]
}, callback);
},
function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: GroupMember, as: 'Memberships', include: [
Group,
{model: Rank, where: {name: 'Admin'}}
]},
{model: Product, include: [
Tag,
{model: Tag, as: 'Category'},
{model: Price, where: {
value: {
gt: 15
}
}}
]}
],
order: [
['id', 'ASC']
]
}).done(function(err, users) {
expect(err).not.to.be.ok;
users.forEach(function(user) {
expect(user.Memberships.length).to.equal(1);
expect(user.Memberships[0].Rank.name).to.equal('Admin');
expect(user.Products.length).to.equal(1);
expect(user.Products[0].Prices.length).to.equal(1);
});
done();
});
}
);
}]
}, done);
});
});
it('should be possible to use limit and a where with a belongsTo include', function(done) {
var User = this.sequelize.define('User', {}, {schema: 'account'})
, Group = this.sequelize.define('Group', {
name: DataTypes.STRING
}, {schema: 'account'});
User.belongsTo(Group);
this.sequelize.sync({force: true}).done(function() {
async.auto({
groups: function(callback) {
Group.bulkCreate([
{name: 'A'},
{name: 'B'}
]).done(function() {
Group.findAll().done(callback);
});
},
users: function(callback) {
User.bulkCreate([{}, {}, {}, {}]).done(function() {
User.findAll().done(callback);
});
},
userGroups: ['users', 'groups', function(callback, results) {
var chainer = new Sequelize.Utils.QueryChainer();
chainer.add(results.users[0].setGroup(results.groups[0]));
chainer.add(results.users[1].setGroup(results.groups[0]));
chainer.add(results.users[2].setGroup(results.groups[0]));
chainer.add(results.users[3].setGroup(results.groups[1]));
chainer.run().done(callback);
}]
}, function(err) {
expect(err).not.to.be.ok;
User.findAll({
include: [
{model: Group, where: {name: 'A'}}
],
limit: 2
}).done(function(err, users) {
expect(err).not.to.be.ok;
expect(users.length).to.equal(2);
users.forEach(function(user) {
expect(user.Group.name).to.equal('A');
});
done();
});
});
});
});
it('should be possible use limit, attributes and a where on a belongsTo with additional hasMany includes', function(done) {
var self = this;
this.fixtureA(function() {
self.models.Product.findAll({
attributes: ['title'],
include: [
{model: self.models.Company, where: {name: 'NYSE'}},
{model: self.models.Tag},
{model: self.models.Price}
],
limit: 3,
order: [
['id', 'ASC']
]
}).done(function(err, products) {
expect(err).not.to.be.ok;
expect(products.length).to.equal(3);
products.forEach(function(product) {
expect(product.Company.name).to.equal('NYSE');
expect(product.Tags.length).to.be.ok;
expect(product.Prices.length).to.be.ok;
});
done();
});
});
});
it('should be possible to use limit and a where on a hasMany with additional includes', function(done) {
var self = this;
this.fixtureA(function() {
self.models.Product.findAll({
include: [
{model: self.models.Company},
{model: self.models.Tag},
{model: self.models.Price, where: {
value: {gt: 5}
}}
],
limit: 6,
order: [
['id', 'ASC']
]
}).done(function(err, products) {
expect(err).not.to.be.ok;
expect(products.length).to.equal(6);
products.forEach(function(product) {
expect(product.Tags.length).to.be.ok;
expect(product.Prices.length).to.be.ok;
product.Prices.forEach(function(price) {
expect(price.value).to.be.above(5);
});
});
done();
});
});
});
it('should be possible to use limit and a where on a hasMany with a through model with additional includes', function(done) {
var self = this;
this.fixtureA(function() {
self.models.Product.findAll({
include: [
{model: self.models.Company},
{model: self.models.Tag, where: {name: ['A', 'B', 'C']}},
{model: self.models.Price}
],
limit: 10,
order: [
['id', 'ASC']
]
}).done(function(err, products) {
expect(err).not.to.be.ok;
expect(products.length).to.equal(10);
products.forEach(function(product) {
expect(product.Tags.length).to.be.ok;
expect(product.Prices.length).to.be.ok;
product.Tags.forEach(function(tag) {
expect(['A', 'B', 'C']).to.include(tag.name);
});
});
done();
});
});
});
it.skip('should support including date fields, with the correct timeszone', function(done) {
var User = this.sequelize.define('user', {
dateField: Sequelize.DATE
}, {timestamps: false, schema: 'account'})
, Group = this.sequelize.define('group', {
dateField: Sequelize.DATE
}, {timestamps: false, schema: 'account'});
User.hasMany(Group);
Group.hasMany(User);
this.sequelize.sync().success(function() {
User.create({ dateField: Date.UTC(2014, 1, 20) }).success(function(user) {
Group.create({ dateField: Date.UTC(2014, 1, 20) }).success(function(group) {
user.addGroup(group).success(function() {
User.findAll({
where: {
id: user.id
},
include: [Group]
}).success(function(users) {
expect(users[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
expect(users[0].groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
done();
});
});
});
});
});
});
});
describe('findOne', function() {
it('should work with schemas', function() {
var self = this;
var UserModel = this.sequelize.define('User', {
Id: {
type: DataTypes.INTEGER,
primaryKey: true
},
Name: DataTypes.STRING,
UserType: DataTypes.INTEGER,
Email: DataTypes.STRING,
PasswordHash: DataTypes.STRING,
Enabled: {
type: DataTypes.BOOLEAN
},
CreatedDatetime: DataTypes.DATE,
UpdatedDatetime: DataTypes.DATE
}, {
schema: 'hero',
tableName: 'User',
timestamps: false
});
var ResumeModel = this.sequelize.define('Resume', {
Id: {
type: Sequelize.INTEGER,
primaryKey: true
},
UserId: {
type: Sequelize.INTEGER,
references: UserModel,
referencesKey: 'Id'
},
Name: Sequelize.STRING,
Contact: Sequelize.STRING,
School: Sequelize.STRING,
WorkingAge: Sequelize.STRING,
Description: Sequelize.STRING,
PostType: Sequelize.INTEGER,
RefreshDatetime: Sequelize.DATE,
CreatedDatetime: Sequelize.DATE
}, {
schema: 'hero',
tableName: 'resume',
timestamps: false
});
UserModel.hasOne(ResumeModel, {
foreignKey: 'UserId',
as: 'Resume'
});
ResumeModel.belongsTo(UserModel, {
foreignKey: 'UserId'
});
return self.sequelize.dropAllSchemas().then(function() {
return self.sequelize.createSchema('hero');
}).then(function() {
return self.sequelize.sync({force: true}).then(function() {
return UserModel.find({
where: {
Id: 1
},
include: [{
model: ResumeModel,
as: 'Resume'
}]
}).on('sql', function(sql) {
console.log(sql);
});
});
});
});
});
});
| kevinawoo/sequelize | test/integration/include/schema.test.js | JavaScript | mit | 57,100 |
webpackJsonp([2,3],[function(n,c){}]); | moislunaire/hhFavoritesLocation | build/styles.060d376bf8bba46c929d.js | JavaScript | mit | 38 |
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
export default class TaskForm extends Component {
constructor(props, context) {
super(props, context);
this.state = {
text: this.props.text || ''
};
}
componentWillReceiveProps(nextProps) {
this.state = {
text: nextProps.text || ''
};
}
handleSubmit() {
const text = this.refs.taskInput.value.trim();
this.props.onAddClick(text);
}
handlePressEnter(e) {
const text = e.target.value.trim();
if (e.which === 13) {
this.props.onAddClick(text);
}
}
handleChange(e) {
const text = e.target.value.trim();
this.setState({text: text});
}
render() {
const style = {
btn: {
margin: "0 5px",
backgroundColor: "#dfe",
paddingLeft: "5px",
paddingRight: "5px"
}
};
const { addTodo } = this.props;
return (
<div style={{float: 'right', display: 'inline'}}>
<input type="text" size="20"
ref="taskInput"
value={this.state.text}
onChange={this.handleChange.bind(this)}
onKeyDown={this.handlePressEnter.bind(this)}/>
<button className="btn btn-sm" style={style.btn}
onClick={ () => this.handleSubmit()} >add</button>
</div>
);
}
}
TaskForm.propTypes = {
text: PropTypes.string,
onAddClick: PropTypes.func.isRequired
};
| onBass-naga/redux-react-spboot | assets/scripts/src/components/TaskForm.js | JavaScript | mit | 1,466 |
export default class Storage {
constructor(type, storageItemName) {
this.type = type || 'localStorage';
this.itemName = storageItemName || 'document';
this.available = Storage.storageAvailable(this.type);
}
static storageAvailable(type) {
try {
let storage = window[type];
let x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
console.warn(`${type} is not available`);
return false;
}
}
saveDoc(document) {
if (!this.available) return;
let storage = window[this.type];
storage.setItem(this.itemName, JSON.stringify(document));
}
loadDoc() {
if (!this.available) return;
const storage = window[this.type];
const item = storage.getItem(this.itemName);
if (item) return JSON.parse(item)
return item;
}
}
| vpodolyan/documenter | src/utils/storage.js | JavaScript | mit | 942 |
import TriggerableMixin from '../Common/TriggerableMixin.js';
import Introspectable from '../Common/Introspectable.js';
class GenericWrapper extends TriggerableMixin(Introspectable) {
constructor (options) {
super();
this.index = options.index;
this.table = options.table;
if (this.index === undefined || !this.table) {
throw new Error(`index and table are required`);
}
this.classObj = options.classObj || null;
this.row = options.row || {};
this.connectedItems = options.connectedItems || {};
this.duplicateItems = options.duplicateItems || [];
}
registerDuplicate (item) {
this.duplicateItems.push(item);
}
connectItem (item) {
this.connectedItems[item.table.tableId] = this.connectedItems[item.table.tableId] || [];
if (this.connectedItems[item.table.tableId].indexOf(item) === -1) {
this.connectedItems[item.table.tableId].push(item);
}
for (const dup of this.duplicateItems) {
item.connectItem(dup);
dup.connectItem(item);
}
}
disconnect () {
for (const itemList of Object.values(this.connectedItems)) {
for (const item of itemList) {
const index = (item.connectedItems[this.table.tableId] || []).indexOf(this);
if (index !== -1) {
item.connectedItems[this.table.tableId].splice(index, 1);
}
}
}
this.connectedItems = {};
}
get instanceId () {
return `{"classId":"${this.classObj.classId}","index":"${this.index}"}`;
}
get exportId () {
return `${this.classObj.classId}_${this.index}`;
}
get label () {
return this.classObj.annotations.labelAttr ? this.row[this.classObj.annotations.labelAttr] : this.index;
}
equals (item) {
return this.instanceId === item.instanceId;
}
async * handleLimit (options, iterators) {
let limit = Infinity;
if (options.limit !== undefined) {
limit = options.limit;
delete options.limit;
}
let i = 0;
for (const iterator of iterators) {
for await (const item of iterator) {
yield item;
i++;
if (item === null || i >= limit) {
return;
}
}
}
}
async * iterateAcrossConnections (tableIds) {
// First make sure that all the table caches have been fully built and
// connected
await Promise.all(tableIds.map(tableId => {
return this.classObj.model.tables[tableId].buildCache();
}));
yield * this._iterateAcrossConnections(tableIds);
}
* _iterateAcrossConnections (tableIds) {
if (this.reset) {
return;
}
const nextTableId = tableIds[0];
if (tableIds.length === 1) {
yield * (this.connectedItems[nextTableId] || []);
} else {
const remainingTableIds = tableIds.slice(1);
for (const item of this.connectedItems[nextTableId] || []) {
yield * item._iterateAcrossConnections(remainingTableIds);
}
}
}
}
Object.defineProperty(GenericWrapper, 'type', {
get () {
return /(.*)Wrapper/.exec(this.name)[1];
}
});
export default GenericWrapper;
| mure-apps/mure-library | src/Wrappers/GenericWrapper.js | JavaScript | mit | 3,052 |
'use strict';
var getSubplotCalcData = require('../get_data').getSubplotCalcData;
var counterRegex = require('../../lib').counterRegex;
var createPolar = require('../polar/polar');
var constants = require('./constants');
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var attributes = {};
attributes[attr] = {
valType: 'subplotid',
dflt: name,
editType: 'calc',
description: [
'Sets a reference between this trace\'s data coordinates and',
'a smith subplot.',
'If *smith* (the default value), the data refer to `layout.smith`.',
'If *smith2*, the data refer to `layout.smith2`, and so on.'
].join(' ')
};
function plot(gd) {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var subplotIds = fullLayout._subplots[name];
for(var i = 0; i < subplotIds.length; i++) {
var id = subplotIds[i];
var subplotCalcData = getSubplotCalcData(calcData, name, id);
var subplot = fullLayout[id]._subplot;
if(!subplot) {
subplot = createPolar(gd, id, true);
fullLayout[id]._subplot = subplot;
}
subplot.plot(subplotCalcData, fullLayout, gd._promises);
}
}
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldIds = oldFullLayout._subplots[name] || [];
for(var i = 0; i < oldIds.length; i++) {
var id = oldIds[i];
var oldSubplot = oldFullLayout[id]._subplot;
if(!newFullLayout[id] && !!oldSubplot) {
oldSubplot.framework.remove();
for(var k in oldSubplot.clipPaths) {
oldSubplot.clipPaths[k].remove();
}
}
}
}
module.exports = {
attr: attr,
name: name,
idRoot: name,
idRegex: counter,
attrRegex: counter,
attributes: attributes,
layoutAttributes: require('./layout_attributes'),
supplyLayoutDefaults: require('./layout_defaults'),
plot: plot,
clean: clean,
toSVG: require('../cartesian').toSVG
};
| plotly/plotly.js | src/plots/smith/index.js | JavaScript | mit | 2,055 |
function extend(child, super)
{
for (var property in super.prototype) {
if (typeof child.prototype[property] == "undefined")
child.prototype[property] = new super.prototype[property];
}
return child;
};
| ccamensuli/stage_full | vendors/crypto/js-encrypt/js/crypto/CommonFunctions.js | JavaScript | mit | 219 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _IconBase = require('./../components/IconBase/IconBase');
var _IconBase2 = _interopRequireDefault(_IconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Easel = function (_React$Component) {
_inherits(Easel, _React$Component);
function Easel() {
_classCallCheck(this, Easel);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Easel).apply(this, arguments));
}
_createClass(Easel, [{
key: 'render',
value: function render() {
if (this.props.bare) {
return _react2.default.createElement(
'g',
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '80', y: '144', width: '352', height: '192' }),
_react2.default.createElement('path', { d: 'M464,96H48c-8.837,0-16,7.163-16,16v256c0,8.837,6.932,16,15.768,16H464c8.837,0,16-7.163,16-16V112 C480,103.163,472.837,96,464,96z M448,352H64V128h384V352z' }),
_react2.default.createElement('polygon', { points: '80,480 112,480 140.147,400 108.835,400 \t' }),
_react2.default.createElement('polygon', { points: '270.83,32 241.472,32 224.171,80 288.099,80 \t' }),
_react2.default.createElement('polygon', { points: '371.853,400 400,480 432,480 403.22,400 \t' }),
_react2.default.createElement('rect', { x: '240', y: '400', width: '32', height: '48' })
)
);
}return _react2.default.createElement(
_IconBase2.default,
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '80', y: '144', width: '352', height: '192' }),
_react2.default.createElement('path', { d: 'M464,96H48c-8.837,0-16,7.163-16,16v256c0,8.837,6.932,16,15.768,16H464c8.837,0,16-7.163,16-16V112 C480,103.163,472.837,96,464,96z M448,352H64V128h384V352z' }),
_react2.default.createElement('polygon', { points: '80,480 112,480 140.147,400 108.835,400 \t' }),
_react2.default.createElement('polygon', { points: '270.83,32 241.472,32 224.171,80 288.099,80 \t' }),
_react2.default.createElement('polygon', { points: '371.853,400 400,480 432,480 403.22,400 \t' }),
_react2.default.createElement('rect', { x: '240', y: '400', width: '32', height: '48' })
)
);
}
}]);
return Easel;
}(_react2.default.Component);
exports.default = Easel;
;Easel.defaultProps = { bare: false }; | fbfeix/react-icons | lib/icons/Easel.js | JavaScript | mit | 3,994 |
// server injected code
/* Debug info: {"server":"WEB519","utc_time":"2016-04-04T20:05:03.641Z","src_ip":"192.204.11.162","method":"HTTPS","api_key":"2_fq_ZOJSR4xNZtv2rA8DALl1Gxp7yTYMb3UdER6zerupB55mwkzh9pVBz4Blzi8SW","site_found":true} */
if (typeof gigya == 'undefined' || !gigya.isGigya) { gigya = { isGigya: true } };
if (!gigya.__initialized) {
gigya.__initialized = true;
gigya.env='prod';
gigya.gaeDomain='chat.gigya.com';
gigya.build={version:'6.2',time:'Mon 04/04/2016 16:16:02.34'};
if (typeof gigya.partnerSettings == 'undefined') {
gigya.partnerSettings={"authMode":"cookie","baseDomains":"agea.com.ar,clarin.com","ssoLogoutUrl":"http://clarin.com/login/logout","ssoKey":"3_IcGpUrIh3Kn0Wf3moX4YjqY4Km6evWEY0dqTU3Yh46OS622zpJQeo5-28q6_L-94"};
gigya.partnerSettings.plugins={"apiDomain":"US1.gigya.com"};
}
gigya.providersConfig = {"facebook":{"appID":"344479319002359","version":"v2.0"},"googlePlus":{"clientId":"8386975267.apps.googleusercontent.com","scopes":"https://www.googleapis.com/auth/plus.login email"}};
gigya.abTesting = null;
gigya.samlConfig = null;
//end server injected code
// API adapters
var gigya;
(function(b){(function(e){(function(e){(function(d){(function(d){function h(a,g){g=b.utils.object.clone(g);if(b.partnerSettings.ssoKey){g||(g={});var d=g.callback;g.callback=function(f){e.parentNode.removeChild(e);b.log.addLog("SSO: About to invoke callback for "+a+" with this response",f);d&&d(f)};g.m=a;g.d=f;g.lid=b.utils.xd._flashListenerID;b.thisScript.globalConf.legacyCrossSiteMethod&&"localstorage"!=b.thisScript.globalConf.legacyCrossSiteMethod.toLowerCase()&&(g.lid=b.thisScript.globalConf.legacyCrossSiteMethod+":"+
b.utils.xd._flashListenerID);g.callbackID="gig_sso_cb"+(new Date).getTime()+"_"+m++;b.utils.xd.addMessageListener(g.callbackID,{},!1,g.callback);delete g.callback;g.sAPIKey=b.thisScript.APIKey;var h=b.utils.keyValue.serialize(g),e=c(g.callbackID),k=function(){e.src="https://cdns.gigya.com/gs/sso.htm?APIKey="+b.partnerSettings.ssoKey+"&version=1#"+h;b.utils.DOM.removeEventListener(e,"load",k)};b.utils.DOM.addEventListener(e,"load",k);b.log.addLog("SSO: Calling "+a,{SSOKey:b.partnerSettings.ssoKey,
params:g});document.body?b.utils.DOM.appendToBody(e):b.utils.functions.invokeOnPageLoad(function(){return b.utils.DOM.appendToBody(e)})}else g&&g.callback&&g.callback()}function c(a){var f=document.getElementById("gig_sso"),f=document.createElement("iframe");b.localInfo.isIOS||b.localInfo.isIOSChrome||b.localInfo.isAndroid?(f.style.width="0px",f.style.height="0px",f.style.display="none"):(f.style.width="30px",f.style.height="10px",f.style.position="absolute",f.style.top="-1000px",f.style.left="-1000px");
f.id="gig_sso_"+a;return f}function a(a){h("setToken",a)}var f=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2],m=0;d.getGroupToken=function(a){h("getToken",a)};d.setGroupTokenFromResponse=function(b,f,m){b.sessionInfo&&(b=b.sessionInfo);var c=b.expires_in,c=null==c||""===c||isNaN(c)?47304E7:0==c?null:1E3*c,d=new Date;d.setTime(d.getTime()+c);a({lt:b.login_token,expiration:null==c?0:d.getTime(),legacyCrossSiteMethod:m,callback:f})};d.setGroupToken=a;
d.logout=function(a){h("logout",a)};d.removeGroupToken=function(a){h("removeToken",a)}})(d.sso||(d.sso={}))})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(e){(function(d){var e=function(){function h(b,a,f,m,d,g){void 0===g&&(g={});this.id=b;this.baseUrl=a;this.methodName=f;this.params=m;this.callback=d;this.settings=g}h.prototype.getUrl=function(){return this.baseUrl+"/"+this.methodName};h.prototype.send=function(b){};h.prototype.getAuthParams=function(){var c={};if(this.params.oauth_token)this.params.authMode="token";else if(!this.params.noAuth){var a=d.tokenStore.get(this.params.APIKey);if(a){this.sentLoginToken=
a;var f=b.utils.cookie.get("gltexp_"+this.params.APIKey);null!=f&&(c.loginTokenExp=f);c.login_token=a}c.authMode="cookie"}delete this.params.noAuth;b.localInfo.isAndroidBrowser&&(delete this.params.login_token,delete this.params.loginTokenExp,delete this.params.authMode);return c};return h}();d.BaseRequest=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
var __extends=this&&this.__extends||function(b,e){function k(){this.constructor=b}for(var d in e)e.hasOwnProperty(d)&&(b[d]=e[d]);k.prototype=e.prototype;b.prototype=new k};
(function(b){(function(e){(function(e){(function(d){d.callback=function(b,c){!c&&b&&(c=b.context);if(c){var a=d.pendingRequests[c];a&&a.handleResponse(b)}};var e=function(e){function c(){e.apply(this,arguments);this.ifrName="gigyaPostIframe_"+(new Date).getTime();this.retry=0}__extends(c,e);c.prototype.addDefaultParams=function(){this.params.format="jsonp";this.params.callback=c.callbackName;this.params.context=this.id;var a=this.getAuthParams();this.paramsLoginToken=this.params.login_token;b.utils.object.add(this.params,
a,!0);this.sentLoginToken=this.params.login_token};c.prototype.getCacheKey=function(){return this.methodName+"_"+b.utils.keyValue.serialize(this.params)};c.prototype.send=function(a){var f=this;if(!this.inProgress){d.pendingRequests[this.id]=this;this.inProgress=!0;this.params.sdk="js_"+b.build.version;this.addDefaultParams();var c=b.utils.keyValue.serialize(this.params);if(!a&&this.settings.cacheTimeout)c=this.getCacheKey(),b.utils.sessionCache.get(c,this.settings.cacheTimeout,function(a){a?(delete f.settings.cacheTimeout,
d.callback(a,f.id)):(f.inProgress=!1,f.send(!0))});else{a=0;b.localInfo.isIE&&(a=2048);var l=this.getUrl();b.events.global.dispatch({eventName:"jsonp-beforeRequest",url:l,params:this.params,level:9});4096>=l.length+1+c.length+a&&!this.settings.forcePost?b.utils.script.load(l+"?"+c,function(){d.callback({context:f.id,errorCode:500026,errorMessage:"Network_error"})}):b.utils.functions.invokeOnPageLoad(function(){var a=document.getElementById("gigyaRequestForms");null==a&&(a=document.createElement("span"),
a.id="gigyaRequestForms",a.style.display="none",b.utils.DOM.appendToBody(a));var c=f.getPostContainer();a.appendChild(c)})}}};c.prototype.createParamFormElements=function(){var a=[],f="";for(f in this.params)a=a.concat(['<textarea name="',f,'">']),"object"==typeof this.params[f]?a.push(b.utils.URL.URLEncode(b.utils.JSON.serialize(this.params[f]))):a.push(this.params[f]),a.push("</textarea>");return a.join("")};c.prototype.getPostContainer=function(){var a=this;if(!this.postContainer){var f=document.createElement("span"),
c=this.ifrName+"form",d=this.id;f.innerHTML=['<form accept-charset="UTF-8" id="',c,'" method="post" action="',this.getUrl(),"?context="+this.id+"&saveResponseID="+this.id+'" target="',this.ifrName,'">',this.createParamFormElements(),'<input name="utf8" type="hidden" value="✓" /><input type="submit" value="" /></form>'].join("");var g,e=b.utils.DOM.createElement("iframe",this.ifrName);e.setAttribute("id",this.ifrName);b.utils.DOM.addEventListener(e,"load",function(){g?a.getSavedFormResponse(d):
(window.setTimeout(function(){var a=document.getElementById(c);a&&a.submit()},10),g=!0)});f.appendChild(e);this.postContainer=f}return f};c.prototype.getSavedFormResponse=function(a){var b=this;(new c(a,this.baseUrl,"socialize.getSavedResponse",{APIKey:this.params.APIKey,saveResponseID:this.id,ucid:this.params.ucid,noAuth:!0},function(a){b.handleResponse(a)})).send()};c.prototype.getDataPendingTimeout=function(a){return 4>=a?500:8>=a?1E3:21>=a?2E3:39>=a?5E3:-1};c.prototype.handleResponse=function(a){var f=
this;this.settings.cacheTimeout&&b.utils.sessionCache.set(this.getCacheKey(),0==a.errorCode?a:null);null!=this.retryTimerID&&window.clearTimeout(this.retryTimerID);this.loaded=!0;this.inProgress=!1;100001==a.errorCode?(a=this.getDataPendingTimeout(this.retry++),0<a&&window.setTimeout(function(){f.send()},a)):(this.dispose(),this.callback(a))};c.prototype.dispose=function(){delete d.pendingRequests[this.id];this.postContainer&&b.utils.DOM.removeElement(this.postContainer);delete this.postContainer};
c.callbackName="gigya._.apiAdapters.web.callback";return c}(d.BaseRequest);d.JsonpRequest=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(k){(function(d){var k=function(h){function c(a,b,c,d,g,e){void 0===e&&(e={});h.call(this,a,b,c,d,g,e);this.windowName=this.methodName.replace(/\./g,"_").replace(/\//g,"")+"_"+(new Date).getTime();this.requestID=this.windowName+(new Date).getTime()}__extends(c,h);c.prototype.beforeRequest=function(){};c.prototype.afterResponse=function(a){a.dontClose&&"false"!=a.dontClose||b.utils.win.close(this.windowName);this.callback(a)};c.prototype.getAuthFlow=function(){return this.params.authFlow?
this.params.authFlow:"popup"};c.prototype.getStateString=function(){var a=b.utils.xd._flashListenerID;if(b.thisScript.globalConf.legacyCrossSiteMethod&&"localstorage"!=b.thisScript.globalConf.legacyCrossSiteMethod.toLowerCase()||b.localInfo.isIE&&window.navigator.msDoNotTrack)a=b.thisScript.globalConf.legacyCrossSiteMethod+":"+b.utils.xd._flashListenerID;var f=this.getAuthFlow(),a={domain:document.location.href.split("?")[0].split("#")[0],id:this.requestID,lid:a,messaging:b.localInfo.messagingMethod};
b.localInfo.isIE11&&window.indexedDB&&(a.messaging=e.MessagingMethod.LocalStorageListener);if("redirect"==f||b.localInfo.isWindowsPhone)a.sourceURL=window.top.document.location.href,this.params.redirectURL?(a.redirectURL=b.utils.URL.addParamsToURL(this.params.redirectURL,{gig_events:b.events.global.getEventsForOperation(this.methodName)}),a.addUserInfo=!0,this.params.redirectMethod&&(a.redirectMethod=this.params.redirectMethod)):a.sourceURL=b.utils.URL.addParamsToURL(a.sourceURL,{gig_events:b.events.global.getEventsForOperation(this.methodName)});
this.params.provider&&"facebook"==this.params.provider.toLowerCase()&&(a.invite=this.params.invite);(f=b.external.backplane.getChannelId())&&(a.bp_channel_url=f);return b.utils.keyValue.serialize(a)};c.prototype.getServerParamsString=function(){var a={},f;for(f in this.params)0!=f.indexOf("x_")&&null!=this.params[f]&&(a["x_"+f]=this.params[f],delete a[f]);a.x_APIKey&&(a.client_id=a.x_APIKey,delete a.x_APIKey);a.x_oauth_token&&(a.oauth_token=a.x_oauth_token,delete a.x_oauth_token);a.redirect_uri="/GS/AfterLogin.aspx";
a.response_type=this.params.authCodeOnly?"code":"server_token";a.format="jsonp";a.x_sdk="js_"+b.build.version;(f=b.utils.cookie.get("_gigRefUid_"+this.params.APIKey))&&(a.x_refUID=f);(f=b.utils.cookie.get("_gigRefUid_"+this.params.APIKey))&&(a.x_refUID=f);a.state=this.getStateString();b.utils.object.add(a,this.getAuthParams());d.useAPIProxy&&d.gmidTicket&&(a.gmidTicket=d.gmidTicket);delete a.redirectURL;this.sentLoginToken=a.login_token;return b.utils.keyValue.serialize(a)};c.prototype.send=function(){var a=
this;this.beforeRequest();var f=this.getServerParamsString(),c;this.params.provider&&(c=b.socialize._getProviderByName(this.params.provider.toLowerCase()));var d=null;null!=c&&(d=(this.params.enablePopupLocation?"location=1,toolbar=1":"toolbar=0,")+"menubar=0,resizable=1,scrollbars=1,width="+c.width+",height="+c.height);var g=this.methodName.split(".");b.reports.report(this.params.originalMethodName||g[g.length-1],this.params.APIKey,this.params.cid,this.params.source,this.params.sourceData,{sn:c?
c.toString():null});f=this.getUrl()+"?"+f;"redirect"==this.getAuthFlow()?window.top.document.location.href=f:(b.utils.xd.addMessageListener(this.requestID,this.params,!0,function(b){a.afterResponse(b)}),b.utils.win.open(f,this.windowName,d))};return c}(d.BaseRequest);d.OauthRequest=k})(k.web||(k.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(e){(function(d){var e=function(e){function c(){e.apply(this,arguments)}__extends(c,e);c.prototype.send=function(a){var f=this;if(d.proxyState.ready){var c=function(a){(a=b.utils.JSON.deserialize(a.data))&&a.id==f.id&&(b.utils.DOM.removeEventListener(window,"message",c),f.callback(a.response))};b.utils.DOM.addEventListener(window,"message",c);b.utils.object.add(this.params,this.getAuthParams());d.ifrAPIProxy.contentWindow.postMessage(this.json(),"https://cdns.gigya.com")}else d.proxyState.error&&
this.callback({context:this.id,errorCode:500026,errorMessage:"APIProxy error: "+d.proxyState.error})};c.prototype.json=function(){return b.utils.JSON.serialize({id:this.id,methodName:this.methodName,params:this.params,settings:this.settings})};return c}(d.BaseRequest);d.APIProxyRequest=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(k){(function(d){(function(k){function h(a){void 0===a&&(a=b.thisScript.APIKey);return a?"glt_"+a:"_gig_lt"}var c={};k.activeNamespaces={};k.get=function(a){void 0===a&&(a=b.thisScript.APIKey);return(a=b.utils.cookie.get(h(a)))?a.split("|")[0]:null};k.set=function(a,f,c,d){b.utils.localStorage.removeItem("gigyaSettings");a||(a=b.thisScript.APIKey);a?(b.utils.cookie.set("glt_"+a,f,c),b.utils.cookie.remove("gac_"+a)):b.utils.cookie.set("_gig_lt",f,c)};k.setFromGAC=
function(a,f){if(b.thisScript.APIKey){var d=b.utils.cookie.get("gac_"+b.thisScript.APIKey);d&&!a.neverTryGAC?('"'==d.charAt(0)&&'"'==d.charAt(d.length-1)&&(d=d.substring(1,d.length-1)),c[d]?f():(c[d]=!0,b.socialize.updateRefUID(),b.socialize.notifyLogin({ignoreApiQueue:!0,neverTryGAC:!0,authCode:d,APIKey:b.thisScript.APIKey,client_id:b.thisScript.APIKey},{callback:function(){b.utils.cookie.remove("gac_"+b.thisScript.APIKey);f();b.socialize.refreshUI({neverTryGAC:!0})}}))):f()}else f()};k.setFromSsoResponse=
function(a,f){void 0===f&&(f=b.thisScript.APIKey);0==a.errorCode&&(k.set(f,a.login_token,a.expires_in),b.accounts.verifyLogin({include:"profile,data",extraProfileFields:"samlData",callback:function(a){b.events.global.dispatchWhenHandlerAdded({eventName:"socialize.login"},null,function(f,c){b.socialize.getUserInfo({signIDs:!0,extraFields:"samlData",callback:function(d){f||(f={});0==a.errorCode&&0==d.errorCode?(f=e.addUserInfoToEvent(d,{eventName:"login"},!0),b.external.backplane.executeOnInit(function(){b.external.backplane.getChannelId()&&
b.socialize.notifySSOLogin({bp_channel_url:b.external.backplane.getChannelId()})})):f.cancel=!0;c(f)}})});b.events.global.dispatchWhenHandlerAdded({eventName:"accounts.login"},null,function(f,c){f||(f={});0==a.errorCode?(f.eventName="accounts.login",b.utils.object.extractProperties(a,f,"signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data")):f.cancel=!0;c(f)})}}))};k.remove=function(a){void 0===a&&(a=b.thisScript.APIKey);d.sso.removeGroupToken();b.utils.cookie.remove("glt_"+
a);b.utils.cookie.remove("_gig_lt")};k.migrateExisting=function(){var a=b.utils.cookie.get("_gig_lt");a&&b.thisScript.APIKey&&!k.get(b.thisScript.APIKey)&&(b.utils.cookie.remove("_gig_lt"),k.set(b.thisScript.APIKey,a))};k.getTokenParam=function(a,f){var c=b.utils.cookie.get(h(a));if(c)return c=c.split("|"),1<c.length?b.utils.keyValue.deserialize(c[1])[f]:null}})(d.tokenStore||(d.tokenStore={}))})(k.web||(k.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
gigya.isGigya||(gigya.isGigya=!0);
(function(b){(function(e){(function(k){(function(d){d.newApiAdapter=function(b){return new h(b)};var k=function(){return function(){}}();d.APIProxyState=k;d.useAPIProxy;d.ifrAPIProxy;d.proxyState;d.gmidTicket;d.callbacks={};d.pendingRequests={};var h=function(){function c(a){this.name="Web"}c.prototype.init=function(a){var f=this;this.initAPIProxy(function(){b.utils.functions.createAlias("gigya.auth.loginToken.get",d.tokenStore.get);f.checkReturnFromURL();f.isSessionValid(void 0,function(b){b?a():
d.sso.getGroupToken({callback:function(b){b&&d.tokenStore.setFromSsoResponse(b);a()}})})})};c.prototype.initAPIProxy=function(a){d.ifrAPIProxy&&(b.utils.DOM.removeElement(d.ifrAPIProxy),d.ifrAPIProxy=null);this.isAPIProxyNeeded()?this.loadAPIProxy(a):this.isThirdPartyCookiesBlockCheckNeeded()?this.checkThirdPartyCookiesBlocked(a):(d.useAPIProxy=!1,a())};c.prototype.isAPIProxyNeeded=function(){d.useAPIProxy=!1;if(b.partnerSettings.ssoKey&&b.partnerSettings.customAPIDomainPrefix||"1"===b.utils.localStorage.getItem("_gig_APIProxy_enabled"))b.utils.localStorage.setItem("_gig_APIProxy_enabled",
"1"),d.useAPIProxy=!0;return d.useAPIProxy};c.prototype.isThirdPartyCookiesBlockCheckNeeded=function(){var a=b.thisScript.globalConf.bypassCookiePolicy||"whenBlockedByDefault";return("whenBlockedByDefault"==a&&b.localInfo.isSafari||"always"==a)&&!window._isAPIProxy&&b.localInfo.supportsPostMessage&&!b.partnerSettings.customAPIDomainPrefix};c.prototype.checkThirdPartyCookiesBlocked=function(a){var f=this,c=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2],
e=b.utils.DOM.createHiddenIframe(("https:"==document.location.protocol?"https://cdns.gigya.com":"http://cdn.gigya.com")+"/gs/3PCTest.html#domain="+encodeURIComponent(c)),g=function(c){(c=b.utils.keyValue.deserialize(c.data))&&"3pcTestResult"==c.id&&(b.utils.DOM.removeEventListener(window,"message",g),"true"==c.enabled?(d.useAPIProxy=!1,d.gmidTicket=null,a()):(b.utils.localStorage.setItem("_gig_APIProxy_enabled","1"),d.useAPIProxy=!0,f.loadAPIProxy(a)),e.parentElement.removeChild(e))};b.utils.DOM.addEventListener(window,
"message",g)};c.prototype.loadAPIProxy=function(a){var f=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2];d.gmidTicket=b.utils.localStorage.getItem("_gig_gmidt");var f="https://cdns.gigya.com/gs/APIProxy.html#apikey="+encodeURIComponent(b.thisScript.APIKey)+"&domain="+encodeURIComponent(f)+"&hasTicket="+(d.gmidTicket?"true":"false"),c=function(f){(f=b.utils.JSON.deserialize(f.data))&&f.apiKey==b.thisScript.APIKey&&(d.proxyState=f,d.proxyState.gmidTicket&&
(d.gmidTicket=d.proxyState.gmidTicket,b.utils.localStorage.setItem("_gig_gmidt",d.gmidTicket,86400)),b.utils.DOM.removeEventListener(window,"message",c),a())};b.utils.DOM.addEventListener(window,"message",c);d.ifrAPIProxy=b.utils.DOM.createHiddenIframe(f)};c.prototype.isSessionValid=function(a,b){void 0===a&&(a={});d.tokenStore.setFromGAC(a,function(){if(b){var c=null!=d.tokenStore.get(a.APIKey)||null!=a.oauth_token;b(c)}})};c.prototype.registerForNamespaceEvents=function(a){};c.prototype.onPluginEvent=
function(a){};c.prototype.onJSLog=function(a,b){};c.prototype.getGmidTicket=function(a){a&&a(d.useAPIProxy?d.gmidTicket:null)};c.prototype.sendRequest=function(a,b,c,l){var g=this;void 0===l&&(l={});this.beforeRequest(a,b,l);var h=this.getBaseUrl(a,b,l),k=this.getRequestId({baseUrl:h,methodName:a,params:b,settings:l});d.callbacks[k]=d.callbacks[k]||[];d.callbacks[k].push(c);if(!d.pendingRequests[k]){var n;c=function(a){g.afterResponse(n,a,function(a){g.dispatchCallbacks(k,a)})};n=d.useAPIProxy&&0!=
h.indexOf("http://")?new d.APIProxyRequest(k,h,a,b,c,l):new d.JsonpRequest(k,h,a,b,c,l);n.send();e.logoutMethods[a]&&e.logoutBehaviour.logoutBeforeServerResponse&&this.clearSession(b)}};c.prototype.clearSession=function(a,b){d.tokenStore.remove(a.APIKey);b&&b()};c.prototype.sendOauthRequest=function(a,b,c,e){var g=this;this.beforeRequest(a,b,e);var h=this.getBaseUrl(a,b,e),k=new d.OauthRequest("",h,a,b,function(a){g.afterResponse(k,a,function(a){c(a)})},e);k.send()};c.prototype.getBaseUrl=function(a,
f,c){a=a.split(".");a=b.partnerSettings.customAPIDomainPrefix?b.partnerSettings.customAPIDomainPrefix+"."+b.partnerSettings.baseDomain:b.utils.stringUtils.format("{0}.{1}",a[0],f.apiDomain?f.apiDomain:b.partnerSettings.plugins.apiDomain);return((d.tokenStore.get()||f.regToken||f.oauth_token)&&!f.noAuth||c.forceHttps||"https"==b.thisScript.protocol?"https://":"http://")+a};c.prototype.beforeRequest=function(a,f,c){void 0===c&&(c={});(c.clearSession||c.clearSessionCondition&&c.clearSessionCondition(f))&&
d.tokenStore.remove(f.APIKey);!b.utils.localStorage.getItem("_gig_3pc_enabled")&&b.thisScript.globalConf.enableSSOToken&&e.loginMethods[a]&&(f.includeSSOToken=!0)};c.prototype.afterResponse=function(a,b,c){var d=this;this.handleTokenResponse(a,b,function(){d.logoutSsoIfNeeded(a,b,function(){c(b)})})};c.prototype.onSDKEvent=function(a){};c.prototype.getTokenParam=function(a,b){return d.tokenStore.getTokenParam(a,b)};c.prototype.checkReturnFromURL=function(){var a=b.utils.URL.getParamsFromURL(document.location.href);
a.gig_events&&0==a.errorCode&&null!=d.tokenStore.get()&&d.sso.setGroupTokenFromResponse({errorCode:0,login_token:d.tokenStore.get(),expires_in:a.expires_in},function(){var c=a.gig_events.split(",");-1!=b.utils.array.indexOf(c,"accounts.login")?b.accounts.getAccountInfo({extraProfileFields:"samlData",include:"profile,data,userinfo",callback:function(a){var d={errorCode:0,eventName:"accounts.login"};b.utils.object.extractProperties(a,d,"signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data");
b.events.global.dispatchWhenHandlerAdded(d);-1!=b.utils.array.indexOf(c,"socialize.login")&&(a=e.addUserInfoToEvent(a,{errorCode:0,eventName:"socialize.login"},!0),b.events.global.dispatchWhenHandlerAdded(a))}}):b.socialize.getUserInfo({signIDs:!0,extraFields:"samlData",callback:function(a){for(var d=0;d<c.length;d++){var e=b._.addUserInfoToEvent(a,{errorCode:0,eventName:c[d]},!0);b.events.global.dispatchWhenHandlerAdded(e)}}})},b.thisScript.globalConf.legacyCrossSiteMethod)};c.prototype.setNewLoginTokenFromResponse=
function(a,c,e){var h=c.sessionInfo?c.sessionInfo.login_token:c.login_token;if(h){var g=null!=c.sessionInfo?c.sessionInfo.expires_in:c.expires_in;(!g||0==g)&&0>a.params.sessionExpiration&&(g=b.utils.cookie.setInfiniteExpirationTimeInSeconds());d.tokenStore.set(a.params.APIKey,h,g,b.thisScript.globalConf.legacyCrossSiteMethod);d.sso.setGroupTokenFromResponse(c,e,b.thisScript.globalConf.legacyCrossSiteMethod)}else e()};c.prototype.onInvalidTokenResponse=function(a,b){var c=this;a.paramsLoginToken?b():
d.sso.getGroupToken({callback:function(e){e&&e.login_token&&e.login_token.split("|")[0]!=a.sentLoginToken&&!a.paramsLoginToken?c.initAPIProxy(function(){d.tokenStore.setFromSsoResponse(e,a.params.APIKey);a.params.login_token=void 0;a.send()}):(d.tokenStore.remove(a.params.APIKey),a.settings.requiresSession()?b():(delete a.params.login_token,delete a.sentLoginToken,a.send()))}})};c.prototype.handleTokenResponse=function(a,c,h){var l=this;c=b.utils.object.clone(c);if(c.ssoToken){var g=(new Date).getTime();
(new Date(g+3E5)).getTime();b.utils.localStorage.setItem("_gig_ssoToken",b.utils.JSON.serialize({ssoToken:c.ssoToken,exp:g}))}if(403030==c.errorCode){if(this.shouldWaitForService(a,c))return}else 409012==c.errorCode&&(d.gmidTicket=null,b.utils.localStorage.removeItem("_gig_gmidt"));a.sentLoginToken&&e.logoutMethods[a.methodName]&&0==c.errorCode&&c.logoutActiveSession&&this.clearSession(a.params);this.setNewLoginTokenFromResponse(a,c,function(){if(a.sentLoginToken&&403005==c.errorCode)l.onInvalidTokenResponse(a,
h);else h()})};c.prototype.logoutSsoIfNeeded=function(a,c,h){var l=this;b.partnerSettings.ssoKey&&e.logoutMethods[a.methodName]&&0==c.errorCode&&c.logoutActiveSession?document.location.href!=b.partnerSettings.ssoLogoutUrl?d.sso.logout({callback:function(b){var d;void 0!==a.params.sustainLogoutURLs&&(d=!a.params.sustainLogoutURLs);l.loadLogoutUrls(b.logoutURLs,h,{UID:c.UID,UIDSignature:c.UIDSignature,signatureTimestamp:c.signatureTimestamp},d)}}):h():h()};c.prototype.loadLogoutUrls=function(a,c,d,
e){var g=0,h=a?a.split(","):[];a=function(){g++;g>h.length&&c()};for(var k=0;k<h.length;k++)if(h[k]){var n=b.utils.URL.addParamsToURL(h[k],d);this.loadLogoutUrl(n,a,e)}else a();a()};c.prototype.loadLogoutUrl=function(a,c,d){void 0===d&&(d=5E3);var e=document.createElement("iframe");e.src=a;e.style.position="absolute";e.style.top="-1000px";e.style.left="-1000px";var g=!1,h=function(){g=!0;!1!==d&&e.parentElement.removeChild(e);c()};window.setTimeout(function(){g||h()},d);e.onload=function(){h()};b.utils.DOM.appendToBody(e)};
c.prototype.shouldWaitForService=function(a,c){return 1==a.params.retryPossible?(a.params.retryPossible=!1,b.external.facebook.runWhenLoaded(function(){a.send()}),!0):!1};c.prototype.dispatchCallbacks=function(a,c){var e=d.callbacks[a];if(e)for(var h=0;h<e.length;h++)if("function"==typeof e[h])e[h](b.utils.object.clone(c,!0));delete d.callbacks[a]};c.prototype.getRequestId=function(a){var c=a.settings.jsSdkRequestId;if(c)return c;if(a.settings.disableCache||this.getIsForceBrowserRequest(a))return"R"+
(new Date).getTime()+"_"+Math.random();var c=b.utils.object.clone(a.params),d;for(d in c)0!=d.indexOf("fb_")&&"source"!=d&&"sourceData"!=d||delete c[d];return"R"+b.utils.object.getMurmurHash(a.baseUrl+a.methodName+b.utils.object.getHash(c))};c.prototype.getIsForceBrowserRequest=function(a){return b.localInfo.isSafari||b.localInfo.isIE10&&"accounts.getAccountInfo"===a.methodName?!0:!1};return c}();d.WebAdapter=h})(k.web||(k.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya=
{}));
(function(b){(function(e){(function(e){(function(d){var e=function(){function d(){this.flashStorageLoaded=!1;this.swfStorage=null;var b=document.location.href.split("#")[1];this.apiKey=decodeURIComponent(b.split("apikey=")[1].split("&")[0]);this.originDomain=decodeURIComponent(b.split("domain=")[1].split("&")[0]);this.hasTicket="true"===decodeURIComponent(b.split("hasTicket=")[1].split("&")[0]);this.urlScheme=0==document.location.href.indexOf("https:")?"https":"http"}d.init=function(){d.instance=new d;
d.instance.init()};d.prototype.init=function(){var c=this;this.isOriginDomainValid()?this.loadIDs(function(a){if(a)c.postState({ready:!1,error:a});else{if(c.gmid&&c.ucid)c.hasTicket?c.postState({ready:!0}):c.getGmidTicketFromServer(function(a){c.postState({ready:!0,gmidTicket:a})});else{var d=10,e=function(a,b,e,k,m){0!=a&&403036!=a&&--d?window.setTimeout(h,10):(c.gmid=b,c.ucid=k,c.storeIDs(function(){c.postState({ready:0==a,gmidTicket:e,error:m})}))},h=function(){return c.getIDsFromServer(e)};h()}b.utils.DOM.addEventListener(window,
"message",function(a){return c.onRequest(a)})}}):this.postState({ready:!1,error:"domain_mismatch"})};d.prototype.onRequest=function(c){var a=this;c=b.utils.JSON.deserialize(c.data);var d,e;if(c&&"object"==typeof c&&c.methodName&&c.id&&c.params){d=c.methodName;e=c.id;var h=b.utils.object.clone(c.params,!0,!0);h.gmid=this.gmid;h.ucid=this.ucid;(new b._.apiAdapters.web.JsonpRequest(e,this.getAPIBaseUrl(d),d,h,function(c){c=b.utils.JSON.serialize({id:e,response:c});b.utils.JSON.deserialize(c)||(c=b.utils.JSON.serialize({id:e,
response:{errorCode:400004,errorMessage:"Invalid parameter format. One of the parameters of this request has been set with a value which is not in the expected format."}}));window.parent.postMessage(c,a.originDomain)},c.settings)).send()}};d.prototype.isOriginDomainValid=function(){return!!b._.getPageBaseDomain(this.originDomain)};d.prototype.getIDsFromServer=function(c){var a={APIKey:this.apiKey,includeTicket:!0,ticketExpires:86400};(new b._.apiAdapters.web.JsonpRequest("idsRequest",this.getAPIBaseUrl("socialize.getIDs"),
"socialize.getIDs",a,function(a){var d=a.errorCode;0!=d&&b.log.addLog("Failed to get IDs from server",a);c(d,a.gcid,a.gmidTicket,a.ucid,a.errorMessage)})).send()};d.prototype.getGmidTicketFromServer=function(c){var a={gmid:this.gmid,APIKey:this.apiKey,expires:86400};(new b._.apiAdapters.web.JsonpRequest("gmidTicketRequest",this.getAPIBaseUrl("socialize.getGmidTicket"),"socialize.getGmidTicket",a,function(a){c(a.gmidTicket)})).send()};d.prototype.getAPIBaseUrl=function(c){c=c.split(".");return"https://"+
b.utils.stringUtils.format("{0}.{1}",c[0],b.partnerSettings.plugins.apiDomain)};d.prototype.postState=function(c){c||(c={});c.apiKey=this.apiKey;window.parent.postMessage(b.utils.JSON.serialize(c),this.originDomain)};d.prototype.loadIDs=function(b){var a=this;this.getIDsFromStorage(function(d,e,h,g){a.gmid=d;a.ucid=e;h?(a.hasTicket=!1,a.storeIDs(function(){b(g)})):b(g)})};d.prototype.getIDsFromStorage=function(c){var a=this,f,e,k,g;try{var p=function(a){a=localStorage.getItem(a);return"undefined"==
a?null:a};f=p(d.SSO_GMID_STORAGE_KEY);e=p(d.GMID_STORAGE_KEY);f&&f!=e&&(g=!0,e=f);(k=p(d.SSO_UCID_STORAGE_EKY))||(k=p(d.UCID_STORAGE_EKY));c(e,k,g)}catch(q){b.localInfo.isMobile?c(null,null,!1,"no_supported_cookie_storage"):this.loadFlashStorageJS(function(b){if(b){b=function(b){b=a.swfStorage.get(b);return"undefined"==b?null:b};var e=b(d.GMID_STORAGE_KEY),f=b(d.UCID_STORAGE_EKY)}else var g="no_supported_cookie_storage";c(e,f,!1,g)})}};d.prototype.storeIDs=function(b){var a=this;try{localStorage.setItem(d.GMID_STORAGE_KEY,
this.gmid),localStorage.setItem(d.UCID_STORAGE_EKY,this.ucid),b()}catch(e){this.loadFlashStorageJS(function(e){e&&(a.swfStorage.set(d.GMID_STORAGE_KEY,a.gmid),a.swfStorage.set(d.UCID_STORAGE_EKY,a.ucid));b()})}};d.prototype.loadFlashStorageJS=function(c){var a=this,d=function(b){a.flashStorageLoaded=!0;try{a.swfStorage?b(!0):a.swfStorage=new SwfStore({namespace:"gigIDs",swf_url:"https://cdns.gigya.com/gs/swf/swfstore.swf",onready:function(){b(!0)},onerror:function(){"object"==typeof console&&console.log&&
console.log("Failed loading swfstore.swf");b(!1)}})}catch(c){b(!1)}};this.flashStorageLoaded?d(c):b.utils.script.load("https://cdns.gigya.com/gs/js/swfstore.min.js",null,function(){d(c)})};d.SSO_GMID_STORAGE_KEY="gig_sso_gmid";d.SSO_UCID_STORAGE_EKY="gig_sso_ucid";d.GMID_STORAGE_KEY="gig_gmid";d.UCID_STORAGE_EKY="gig_ucid";return d}();d.APIProxy=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
var gigya;
(function(b){(function(g){(function(e){(function(h){h.newApiAdapter=function(a){return new d(a)};h.mobileCallbacks={};var e="is_session_valid send_request send_oauth_request get_ids on_plugin_event on_custom_event register_for_namespace_events".split(" "),f={logLevel:[]},d=function(){function a(c){this.adapterSettings=c;this.name="Mobile"}a.prototype.init=function(c){var a=this;this.features=this.adapterSettings&&"function"===typeof this.adapterSettings.getFeatures?b.utils.JSON.deserialize(this.adapterSettings.getFeatures()):e;
this.adapterSettings&&"function"===typeof this.adapterSettings.getSettings?(this.settings=b.utils.JSON.deserialize(this.adapterSettings.getSettings())||{},this.settings.logLevel=b.utils.array.getArrayFromString(this.settings.logLevel||f.logLevel.join(","),",")):this.settings=f;b.events.addMap({defaultMethod:function(c){a.onPluginEvent(c)},eventMap:[{events:"*",args:["$event"]}]});this.sendToMobile("get_ids",null,function(d){a.ucid=d.ucid;a.gcid=d.gcid;for(var l in b.events.global._activeNamespaces)a.registerForNamespaceEvents(l);
b.localInfo.isNativeMobileApp=!0;c()})};a.prototype.getTokenParam=function(c,a){return""};a.prototype.onPluginEvent=function(c){c.isGlobal||this.sendToMobile("on_plugin_event",c)};a.prototype.onCustomEvent=function(c){this.sendToMobile("on_custom_event",c)};a.prototype.onJSLog=function(c,a){this.isLogLevelSupported(c)&&this.sendToMobile("on_js_log",{logType:c,logInfo:a})};a.prototype.registerForNamespaceEvents=function(c){this.sendToMobile("register_for_namespace_events",{namespace:c})};a.prototype.getGmidTicket=
function(c){c&&this.sendRequest("socialize.getGmidTicket",{expires:30},function(a){c(a.gmidTicket)},{forceHttps:!0})};a.prototype.clearSession=function(c,a){this.sendToMobile("clear_session",c,a)};a.prototype.isSessionValid=function(c,a){this.sendToMobile("is_session_valid",{},a)};a.prototype.sendRequest=function(c,a,b,d){this.sendToMobile("send_request/"+c,a,b,d)};a.prototype.sendOauthRequest=function(a,b,d,e){this.sendToMobile("send_oauth_request/"+a,b,d,e)};a.prototype.sendToMobile=function(a,
d,e,g){if(this.isActionSupported(a)){var f=document.createElement("iframe");f.style.display="none";d&&delete d.APIKey;if(e){var k=(new Date).getTime()+"_"+Math.random();h.mobileCallbacks[k]=function(a){e(a);document.documentElement.removeChild(f);delete h.mobileCallbacks[k]}}a="gsapi://"+a+"?callbackID="+(k||"")+"¶ms="+(d?encodeURIComponent(b.utils.keyValue.serialize(d)):"")+"&settings="+(g?encodeURIComponent(b.utils.keyValue.serialize(g)):"");f.src=a;window.setTimeout(function(){return document.documentElement.appendChild(f)},
0)}else e&&e({errorCode:400096,errorMessage:"Mobile SDK does not support feature "+a})};a.prototype.onSDKEvent=function(a){a&&a.user&&g.convertIdentitiesArrayToObject(a.user);b.events.global.dispatch(a)};a.prototype.isActionSupported=function(a){if(!a)return!1;a=a.split("/")[0].toLowerCase();return-1<b.utils.array.indexOf(this.features,a)};a.prototype.isLogLevelSupported=function(a){return-1!=b.utils.array.indexOf(this.settings.logLevel,"*")||-1!=b.utils.array.indexOf(this.settings.logLevel,a)};return a}();
h.MobileAdapter=d})(e.mobile||(e.mobile={}))})(g.apiAdapters||(g.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(g){(function(e){(function(e){e.showPlugin=function(e,f){var d=e.split("."),a=d.splice(d.length-1,1)[0];d.length||(d=["socialize"]);"commentsUI"==e&&(d=["comments"]);a="show"+b.utils.stringUtils.capitalize(a);d.push(a);for(a=b;a&&d.length;)a=a[d.shift()];if("function"!==typeof a)return b.events.dispatchInvalidParamError(b.utils.object.merge([{plugin:e},f]),"plugin");a(f)}})(e.mobile||(e.mobile={}))})(g.apiAdapters||(g.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
// end API adapters
var gigya;
(function(a){var b=navigator.userAgent.toLowerCase(),g="function"===typeof FileReader||"object"===typeof FileReader?!0:!1,h=new Date,f=document.location.hostname,e="http:"==document.location.protocol?"http":"https",d=-1!=b.indexOf("win"),c=-1!=b.indexOf("msie")||-1!=b.indexOf("mozilla")&&-1!=b.indexOf("trident"),l=-1!=b.indexOf("msie 6."),p=-1!=b.indexOf("msie 7."),q=-1!=b.indexOf("msie 8."),k=-1!=b.indexOf("msie 9."),m=-1!=b.indexOf("msie 10."),r=-1!=b.indexOf("mozilla")&&-1!=b.indexOf("trident/7.0"),n=
-1!=b.indexOf("edge"),t=-1!=b.indexOf("iphone")||-1!=b.indexOf("ipad")||-1!=b.indexOf("ipod"),u=-1!=b.indexOf("safari/534"),v;v=-1!=b.indexOf("applewebkit")&&-1!=b.indexOf("version/")?parseInt(b.split("version/")[1].split(" ")[0]):0;var w=-1!=b.indexOf("android"),A=function(a){return-1===a.indexOf("mozilla/5.0")||-1===a.indexOf("android 4")||-1===a.indexOf("applewebkit")||-1!==a.indexOf("windows phone")?!1:(a=/chrome\/(\d+)/.exec(a))?20>parseInt(a[1]):!0}(b),x;x=-1!=b.indexOf("android")?parseFloat(b.slice(b.indexOf("android")+
8)):0;a.localInfo={isBrowserSupportsFilesAPI:g,initTime:h,version:0,pageDomain:f,protocol:e,userAgent:b,isWin:d,isIE:c,isIE6:l,isIE7:p,isIE8:q,isIE9:k,isIE10:m,isIE11:r,isEdge:n,isIOS:t,isSafari534:u,iosVersion:v,isAndroid:w,isAndroidBrowser:A,currentBrowser:"",androidVersion:x,isChrome:-1!=b.indexOf("chrome")&&-1==b.indexOf("edge"),isFF:-1!=b.indexOf("firefox"),isOpera:-1!=b.indexOf("opera"),isSafari:navigator.appVersion&&-1!=navigator.appVersion.toLowerCase().indexOf("safari")&&-1==navigator.appVersion.toLowerCase().indexOf("chrome")&&
-1==b.indexOf("android"),isIOSWebView:/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent),isIOSChrome:-1!=b.indexOf("crios"),isMAC:navigator.appVersion&&-1!=navigator.appVersion.toLowerCase().indexOf("mac")?!0:!1,isWindowsPhone:-1!=b.indexOf("windows phone"),supportsPostMessage:null!=window.postMessage&&(-1==b.indexOf("msie")||-1!=b.indexOf("iemobile")),supportsLocalStorage:function(){try{if(null!=window.localStorage){var a=window.localStorage.getItem("_gig_localStorage_test");
window.localStorage.setItem("_gig_localStorage_test","just checking for localStorage");var d="just checking for localStorage"===window.localStorage.getItem("_gig_localStorage_test");a?window.localStorage.setItem("_gig_localStorage_test",a):window.localStorage.removeItem("_gig_localStorage_test");return d}return!1}catch(c){return!1}}(),quirksMode:"BackCompat"==document.compatMode&&-1!=b.indexOf("msie"),backCompat:"BackCompat"==document.compatMode,isMobile:function(){var a="iphone;ipod;android;midp;240x320;blackberry;netfront;nokia;panasonic;portalmmm;sharp;sie-;sonyericsson;symbian;windows ce;benq;mda;mot-;opera mini;philips;pocket pc;sagem;samsung;htc".split(";"),
d;for(d in a)if(-1!=b.indexOf(a[d]))return!0;return!1}(),isMobileApp:function(){if(!document.getElementsByTagName)return!1;for(var a=document.getElementsByTagName("meta"),d=0;d<a.length;d++)if("viewport"==a[d].getAttribute("name")){var c=a[d].getAttribute("content");if(c&&-1!==c.indexOf("width=device-width"))return!0}return!1}(),isNativeMobileApp:!1,isTouch:function(){if("ontouchstart"in window)return!0;if("onmsgesturechange"in window)try{new ActiveXObject("htmlfile")}catch(a){return!0}return!1}(),
messagingMethod:0};a.localInfo.isIE11&&!window.indexedDB&&(a.localInfo.supportsPostMessage=!1);a.localInfo.isMAC=a.localInfo.isMAC&&!a.localInfo.isIOS;(g=a.localInfo.isWin?"windows":a.localInfo.isWindowsPhone?"winphone":a.localInfo.isIOS?"ios-v"+a.localInfo.iosVersion:a.localInfo.isMAC?"mac":a.localInfo.isAndroid?"android":"")&&(g+=" ");a.localInfo.currentBrowser=g+(a.localInfo.isChrome?"chrome":a.localInfo.isFF?"firefox":a.localInfo.isSafari?"safari":a.localInfo.isEdge?"edge":a.localInfo.isIE11?
"ie11":a.localInfo.isIE10?"ie10":a.localInfo.isIE9?"ie9":a.localInfo.isIE8?"ie8":"")})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a,c){for(var e=0;e<a.length;++e)c(a[e],e,a)}function f(a,c){for(var e=0;e<a.length;++e)if(c(a[e],e,a))return!0;return!1}function e(a,c){var e=-1;f(a,function(a,d,f){return c(a,d,f)?(e=d,!0):!1});return e}a.indexOf=function(a,c){for(var e=0;e<a.length;e++)if(a[e]==c)return e;return-1};a.clone=function(a){for(var c=[],e=0;e<a.length;e++)c[e]=a[e];return c};a.removeByValue=function(a,c){if(a)for(var e=a.length-1;0<=e;e--)a[e]==c&&a.splice(e,1)};a.removeByProperty=
function(a,c,e){if(a)for(var f=a.length-1;0<=f;f--)a[f][c]==e&&a.splice(f,1)};a.getArrayFromString=function(a,c,e){if(!a||"string"!=typeof a)return[];e&&(a=a.toLowerCase());return(a=a.replace(/[ ]/g,"").replace(/,,/g,","))?a.split(c):[]};a.intersect=function(a){for(var c=1;c<arguments.length;c++);if(null==a)return[];for(var c=[],e=arguments.length,f=0,b=a.length;f<b;f++){var g=a[f];if(-1==this.indexOf(c,g)){for(var h=1;h<e;h++){var r=arguments[h];if(null==r||-1==this.indexOf(r,g))break}h===e&&c.push(g)}}return c};
a.lastIndexOf=function(a,c,e){void 0===e&&(e=0);for(var f=a.length;--f>=e;)if(a[f]===c)return f;return-1};a.forEach=b;a.forEachProp=function(a,c){for(var e in a)a.hasOwnProperty(e)&&c(a[e],e,a)};a.some=f;a.every=function(a,c){for(var e=0;e<a.length;++e)if(!c(a[e],e,a))return!1;return!0};a.everyProp=function(a,c){for(var e in a)if(a.hasOwnProperty(e)&&!c(a[e],e,a))return!1;return!0};a.map=function(a,c){var e=[];b(a,function(a,d,f){return e.push(c(a,d,f))});return e};a.firstIndex=e;a.first=function(a,
c){return a[e(a,c)]};a.getAllEnumValues=function(a){var c=[],e;for(e in a)"number"==typeof a[e]&&c.push(a[e]);return c}})(a.array||(a.array={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));(function(a){(function(a){(function(a){a.create=function(a,f){return function(){for(var e=[],d=0;d<arguments.length;d++)e[d-0]=arguments[d];return f.apply(a,e)}}})(a.delegate||(a.delegate={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.fill=function(b,f){"function"==typeof b&&(b=b(f));b instanceof Array&&(b=b.join(""));var e=/(\$)(!?)([a-z_][a-z_.\d]*)([(][^()]*[)])?|(\$)(!?)\{([a-z_][a-z_.\d]*)([(][^()]*[)])?\}/gi;e.lastIndex=0;for(var d=b,c=e.exec(d),l;null!=c;){l="$"==c[1]?0:4;var p="!"==c[2+l],g=c[3+l];l=c[4+l];null==l&&(l="");"."==g.substring(0,1)&&(g=g.substring(1));"DBG"==g.substring(0,3)&&(g=g.substring(3));var k="";for(l=g+l;l!=k;){var k=l,m=e.lastIndex;l=a.utils.templates.fill(k,
f);e.lastIndex=m}k="";m=0;if(null!=f[g.split(".")[0]])try{k=(new Function("o","p",'return eval("o." + p)'))(f,l)}catch(r){}else k="$"+(p?"!":"")+l,m=1;d=p?d.replace(c[0],""):d.substr(0,c.index)+k+d.substr(c.index+c[0].length);e.lastIndex=c.index+m;c=e.exec(d)}return d}})(b.templates||(b.templates={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.callFunction=function(a,f){var e=eval(a),d=a.split(".");d.splice(d.length-1,1);d=eval(d.join("."));e.apply(d,f)};b.invokeOnPageLoad=function(b,f){if(!document.readyState&&document.body||"loaded"==document.readyState||"complete"==document.readyState||!f&&"interactive"==document.readyState&&document.body)b();else{var e=!1,d=function(){e||(e=!0,b())};window.setTimeout(d,2E4);a.utils.DOM.addEventListener(window,"load",d);a.utils.DOM.addEventListener(document,"DOMContentLoaded",
d)}};b.createAlias=function(a,f){for(var e=a.split("."),d=window,c=0;c<e.length-1;c++){var b=e[c];d[b]||(d[b]={});d=d[b]}d[e[e.length-1]]=f}})(b.functions||(b.functions={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h={},f=0;b.open=function(e,d,c){c||(c="menubar=0,toolbar=0,resizable=1,scrollbars=1,width=960,height=680");var b=c;try{var p=parseInt(c.split("width=")[1].split(",")[0]),g=parseInt(c.split("height=")[1].split(",")[0]),k=(screen.width-p)/2,m=(screen.height-g)/2;0>k&&(k=0);0>m&&(m=0);b+=",top="+m+",left="+k}catch(r){}c=a.localInfo.isIE&&2048<e.length||4096<e.length;p=e;c&&(p="",a.localInfo.isIE&&(p="about:blank"),d&&"_blank"!=d.toLowerCase()||(d="_gigWindow_"+
(new Date).getTime()+"_"+ ++f));(b=window.open(p,d,b))&&b.focus&&b.focus();h[d]=b;c&&a.utils.HTTP.redirect(e.split("?")[0],[a.utils.URL.getParamsFromURL(e)],"POST",d);return null!=h[d]};b.close=function(e){if(null!=h[e]){var d=function(){try{null!=h[e]&&h[e].close(),delete h[e]}catch(a){}};6<=a.localInfo.iosVersion?d():window.setTimeout(d,10)}}})(b.win||(b.win={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.isExplicitTrue=function(a){a=(""+a).toLowerCase();return"true"==a||"1"==a};a.isExplicitFalse=function(a){a=(""+a).toLowerCase();return"false"==a||"0"==a}})(a.validation||(a.validation={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a,e,d,c,l){void 0===e&&(e=!1);void 0===d&&(d=!1);void 0===c&&(c=0);void 0===l&&(l=20);c||(c=0);if(c>l)return"[Too deep]";var p=l="",g="";if(d)for(var g="\t",p="\n",k=0;k<c+1;k++)l+=g;var m=typeof a;if("function"==m)return m.toString();if("object"!=m||null===a)return"string"==m&&(a='"'+a.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'"'),String(a);var r,n,t=[],u=a&&a.constructor==Array;if(u)for(k=0;k<a.length;k++)n=a[k],m=typeof n,null==n||
"undefined"==m?n="":"string"==m?n='"'+n.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'"':"function"==m?n=e?"Function":"":n.parentNode&&n.innerHTML?n="HTMLElement":n.constructor==Date?n="":"object"==m&&null!==n&&(n=b(n,e,d,c+1)),""!=String(n)&&t.push(l+g+String(n));else for(r in a)n=a[r],m=typeof n,null==n||"undefined"==m?n=String(n):"string"==m?n='"'+n.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'"':"function"==m?n=e?"Function":"":n.parentNode&&n.innerHTML?n="HTMLElement":n.constructor==
Date?n="":"object"==m&&null!==n&&(n=p+b(n,e,d,c+1)),""!=String(n)&&t.push(l+g+'"'+r.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'":'+String(n));return p+l+(u?"[":"{")+p+t.join(","+p)+p+l+(u?"]":"}")}a.serialize=b;a.deserialize=function(a){""===a&&(a='""');eval("var o");try{eval("o="+a)}catch(e){}return eval("o")}})(a.JSON||(a.JSON={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(a,c,e){if(!c)return a;c=c.split(".");for(var b=0;b<c.length;b++){var f=c[b];e&&!a[f]&&(a[f]={});if(a[f])a=a[f];else return null}return a}function f(a,c,e,b,g,h){void 0===b&&(b=20);void 0===g&&(g=0);if(g>b||"undefined"==typeof a||null==a||"function"==typeof a&&e)return null;if(a.constructor==Array){for(var m=[],r=0;r<a.length;r++)e&&"function"==typeof a[r]||(m[r]=c?f(a[r],c,e,b,g+1,h):a[r]);return m}if("object"==typeof a){m={};for(r in a)h&&"context"==
r||e&&"function"==typeof a[r]||(m[r]=c?f(a[r],c,e,b,g+1,h):a[r]);return m}return a}function e(d,c,b){if(null!=d){null==c&&(c={});if(d.constructor==Array)for(var f=0;f<d.length;f++)e(d[f],c,b);else if(b){b=b.split("|");var f={},g;for(g in d)f[g.toLowerCase()]=1;for(g=0;g<b.length;g++){var h=b[g];f[h.toLowerCase()]&&(c[h]=d[h])}}else c=a.utils.object.clone(d,!1);return c}}b.removeUndefined=function(a){var c={},e;for(e in a)null!=a[e]&&void 0!=a[e]&&(c[e]=a[e]);return c};b.getPropertyBySerializedName=
h;b.setPropertyBySerializedName=function(a,c,e){c=c.split(".");var b=c.pop();h(a,c.join("."),!0)[b]=e};b.add=function(a,c,e){for(var b in c)e&&"undefined"!=typeof a[b]||(a[b]=c[b])};b.getHash=function(d){var c=[],e;for(e in d){var b;"object"==typeof d[e]?b=a.utils.JSON.serialize(d[e],!1):d[e]&&(b=d[e].toString());c.push(e+"="+b)}return c.sort().join("&")};b.getMurmurHash=function(a,c){c||(c=0);var e,b,f,g,h;e=a.length&3;b=a.length-e;f=c;for(h=0;h<b;)g=a.charCodeAt(h)&255|(a.charCodeAt(++h)&255)<<
8|(a.charCodeAt(++h)&255)<<16|(a.charCodeAt(++h)&255)<<24,++h,g=3432918353*(g&65535)+((3432918353*(g>>>16)&65535)<<16)&4294967295,g=g<<15|g>>>17,g=461845907*(g&65535)+((461845907*(g>>>16)&65535)<<16)&4294967295,f^=g,f=f<<13|f>>>19,f=5*(f&65535)+((5*(f>>>16)&65535)<<16)&4294967295,f=(f&65535)+27492+(((f>>>16)+58964&65535)<<16);g=0;switch(e){case 3:g^=(a.charCodeAt(h+2)&255)<<16;case 2:g^=(a.charCodeAt(h+1)&255)<<8;case 1:g^=a.charCodeAt(h)&255,g=3432918353*(g&65535)+((3432918353*(g>>>16)&65535)<<16)&
4294967295,g=g<<15|g>>>17,f^=461845907*(g&65535)+((461845907*(g>>>16)&65535)<<16)&4294967295}f^=a.length;f^=f>>>16;f=2246822507*(f&65535)+((2246822507*(f>>>16)&65535)<<16)&4294967295;f^=f>>>13;f=3266489909*(f&65535)+((3266489909*(f>>>16)&65535)<<16)&4294967295;return(f^f>>>16)>>>0};b.clone=f;b.merge=function(a){for(var c={},e=0;e<a.length;e++)if(a[e]&&a[e].length)for(var b=0;b<a[e].length;b++)for(var f in a[e][b])c[f]=a[e][b][f];else for(f in a[e])c[f]=a[e][f];return c};b.extractProperties=e;b.extractProperty=
function(a,c){return e(a,void 0,c)[c]}})(b.object||(b.object={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(f,e,d,c,l){var p=a.localInfo.pageDomain,h=a.partnerSettings.baseDomain;null==c&&(c=0<h.length&&p.length>=h.length&&p.lastIndexOf(h)==p.length-h.length?h:p);d=null==d||""===d||isNaN(d)?47304E7:0==d?null:1E3*d;h=new Date;h.setTime(h.getTime()+d);c=f+"="+escape(e)+(l?"":"; path=/")+(null==d?"":"; expires="+h.toUTCString())+(c&&""!=c&&-1!=c.indexOf(".")?"; domain="+c:"");document.cookie=c;d&&!(0<d)||b.get(f)||(c=f+"="+escape(e)+(l?"":"; path=/")+(null==
d?"":"; expires="+h.toUTCString())+(p&&""!=p&&-1!=p.indexOf(".")?"; domain="+p:""),document.cookie=c)}b.get=function(a){a=a.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1").replace(/^[ \t]+|[ \t]+$/g,"");return(a=document.cookie.match(new RegExp("(?:^|;)\\s?"+a+"=(.*?)(?:;|$)")))&&unescape(a[1])};b.set=h;b.remove=function(b){var e=a.localInfo.pageDomain,d=a.partnerSettings.baseDomain;0<d.length&&e.length>=d.length&&e.lastIndexOf(d)==e.length-d.length&&(h(b,"",-1,d),h(b,"",-1,d,!0));h(b,"",-1,a.localInfo.pageDomain);
h(b,"",-1,a.localInfo.pageDomain,!0);h(b,"",-1,"");h(b,"",-1,"",!0)};b.setInfiniteExpirationTimeInSeconds=function(){return 47304E4}})(b.cookie||(b.cookie={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.sanitizeHTML=function(a){return null==a||"undefined"==typeof a?a:a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/'/g,"'").replace(/&#173;/g,"­")};a.sanitizeAttribute=function(a){return null==a||"undefined"==typeof a?a:a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/\=/g,"=")}})(a.sanitize||(a.sanitize={}))})(a.utils||(a.utils={}))})(gigya||
(gigya={}));
(function(a){(function(a){(function(a){function b(){var a=0,d=0;"number"==typeof window.pageYOffset?(d=window.pageYOffset,a=window.pageXOffset):document.body&&(document.body.scrollLeft||document.body.scrollTop)?(d=document.body.scrollTop,a=document.body.scrollLeft):document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)&&(d=document.documentElement.scrollTop,a=document.documentElement.scrollLeft);return{left:a,top:d}}function f(){var a,d;d=document.documentElement;var c=
document.body;window.innerHeight?(a=window.innerHeight,d=window.innerWidth):(a=d.clientHeight,0==a&&(a=c.clientHeight),d=d.clientWidth,0==d&&(d=c.clientWidth));return{w:d,h:a}}a.getScroll=b;a.getFullSize=function(){var a=document.documentElement,d=document.body,c=a.clientHeight;0==c&&(c=d.clientHeight);a=a.clientWidth;0==a&&(a=d.clientWidth);return{w:a,h:c}};a.getOrientation=function(){var a=parseInt(window.orientation||"0");0>a&&(a+=360);return a};a.getInnerSize=f;a.getMiddleCenter=function(){var a=
b(),d=f();return{top:a.top+Math.floor(d.h/2),left:a.left+Math.floor(d.w/2)}};a.isRectHorizontallyVisible=function(a){var d=b(),c=f();return a.left>=d.left&&a.right<=d.left+c.w};a.isRectFullyVisible=function(a){var d=b(),c=f();return a.top>=d.top&&a.bottom<=d.top+c.h&&a.left>=d.left&&a.right<=d.left+c.w};a.scrollIntoView=function(a){a&&a.scrollIntoView&&a.scrollIntoView()}})(a.viewport||(a.viewport={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.getPosition=function(){var a=0,b=0;if(document.body){var e=null,e={clientX:0,clientY:0};if(e.pageX||e.pageY)a=e.pageX,b=e.pageY;else if(e.clientX||e.clientY)a=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,b=e.clientY+document.body.scrollTop+document.documentElement.scrollTop;return{x:a,y:b}}}})(a.mouse||(a.mouse={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){var g=function(){function b(a,e){void 0===e&&(e="/");this.domain=a;this.path=e}b.prototype.isIn=function(a){return(this.domain==a.domain||this.isSubDomainOf(a))&&(!a.path||0==this.path.indexOf(a.path))};b.prototype.isForSubDomains=function(){return 0==this.domain.indexOf(".")};b.prototype.isSubDomainOf=function(b){var e="";b.isForSubDomains()||(e=".");e+=b.domain;return a.utils.stringUtils.endsWith(this.domain,e)};b.parse=function(a,e){void 0===e&&(e=!0);if(a){var d=document.createElement("a");
e&&0!=a.indexOf("http")&&(a="http://"+a);d.href=a;return new b(d.hostname,d.pathname)}};return b}();b.Uri=g})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.URLEncode=function(a){return encodeURIComponent(a)};b.URLDecode=function(a){return decodeURIComponent(a.replace(/\+/g," "))};b.getParamsFromURL=function(b,f){return-1==b.indexOf("?")?{}:a.utils.keyValue.deserialize(b.split("#")[0].split("?")[1],"&",f)};b.getParamValueFromURL=function(a,b,e){if(null==b||""==b)return e;var d=b.indexOf("?");if(-1==d)return e;d="&"+b.substr(d+1);b=d.toLowerCase().indexOf("&"+a.toLowerCase()+"=");if(-1==b)return e;a=d.substr(b+
(1+a.length+1))+"&";b=a.indexOf("&");return a.substr(0,b)};b.addParamsToURL=function(b,f){var e=a.utils.URL.getParamsFromURL(b);a.utils.object.add(e,f);var d=b.split("#"),e=d[0].split("?")[0]+"?"+a.utils.keyValue.serialize(e,"&");1<d.length&&(e+="#"+d[1]);return e}})(b.URL||(b.URL={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.serialize=function(b,f){var e=[];f||(f="&");for(var d in b)switch(typeof b[d]){case "function":break;case "array":case "object":null!=b[d]&&e.push(d+"="+a.utils.URL.URLEncode(a.utils.JSON.serialize(b[d])));break;case "undefined":break;default:e.push(d+"="+a.utils.URL.URLEncode(b[d]))}return e.join(f)};b.deserialize=function(b,f,e,d){var c={};if(!b)return c;f||(f="&");b=b.split(f);for(f=0;f<b.length;f++){var l=b[f],p=l.indexOf("=");if(-1==p){var g=e?l.toLowerCase():
l;c[g]="1"}else{g=l.substr(0,p);e&&(g=g.toLowerCase());l=l.substr(p+1).replace(/\+/g," ");try{c[g]=d?unescape(l):a.utils.URL.URLDecode(l)}catch(k){c[g]=unescape(l)}}}return c}})(b.keyValue||(b.keyValue={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(a,c,d){"undefined"!==typeof d&&(d=(new Date).getTime()+1E3*d,c=c+"|exp="+d);f(a,c)}var f=function(a,c){},e=function(a){return null},d=function(a){};if(a.localInfo.supportsLocalStorage)f=function(a,c){try{window.localStorage[a]=c}catch(d){}},e=function(a){return window.localStorage[a]},d=function(a){window.localStorage.removeItem(a)};else if(a.localInfo.isIE6||a.localInfo.isIE7)var c=function(){try{p(),q.load("gigya_ud")}catch(a){}},l=function(){try{p(),
q.save("gigya_ud")}catch(a){}},p=function(){q||(q=document.createElement("div"),q.addBehavior("#default#userData"),a.utils.DOM.appendToBody(q))},q,f=function(a,d){c();q.setAttribute(encodeURIComponent(a).replace(/\%/g,""),d);l()},e=function(a){c();return q.getAttribute(encodeURIComponent(a).replace(/\%/g,""))},d=function(a){c();q.removeAttribute(encodeURIComponent(a).replace(/\%/g,""));l()};else if(a.localInfo.isFF&&window.globalStorage)var k=window.globalStorage,f=function(a,c){try{k[location.hostname][a]=
c}catch(d){}},e=function(a){return k[location.hostname][a]},d=function(a){delete k[location.hostname][a]};b.getItem=function(a){var c=e(a);if(c&&c.split){var b=c.split("|exp=");if(1<b.length){c=parseInt(b[1]);if((new Date).getTime()<c)return b[0];d(a);return}}return c};b.setItem=h;b.removeItem=function(a){d(a)};b.setObject=function(c,d){h(c,a.utils.JSON.serialize(d))};b.getObject=function(c){c=this.getItem(c);try{c=a.utils.JSON.deserialize(c)}catch(d){}return c}})(b.localStorage||(b.localStorage=
{}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(g){function h(a,d){if(a){if(!d)return!0;if(!a.className)return!1}else return!1;for(var c=!1,b=a.className.split(" "),f=0;f<b.length;f++)if(b[f]==d){c=!0;break}return c}g._nextZIndex=999999999;g._popupContainers=[];g._pseudoContainers=[];var f=null;g.addEventListener=function(a,d,c){a&&c&&(a.addEventListener?a.addEventListener(d,c,!0):a.attachEvent("on"+d,c))};g.removeEventListener=function(a,d,c){c&&(a.removeEventListener?a.removeEventListener(d,c,!0):a.detachEvent("on"+
d,c))};g.disableDefaultEventHandling=function(a){a.preventDefault?a.preventDefault():window.event&&(window.event.returnValue=!1)};g.addDialogBackListener=function(e){a.utils.DOM._removeDialogBackListener();f=function(d){d&&d.newURL&&-1==d.newURL.indexOf("|gigyaMobileDialog")&&(e(d),a.utils.DOM._removeDialogBackListener())};window.setTimeout(function(){-1==window.location.hash.indexOf("|gigyaMobileDialog")&&(window.location.hash+="|gigyaMobileDialog");a.utils.DOM.addEventListener(window,"hashchange",
f)},50)};g._removeDialogBackListener=function(){f&&(a.utils.DOM.removeEventListener(window,"hashchange",f),f=null,window.location.hash=window.location.hash.replace("|gigyaMobileDialog",""))};g.appendToBody=function(a){document.body&&(document.body.insertBefore&&document.body.firstChild?document.body.insertBefore(a,document.body.firstChild):document.body.appendChild(a))};g.removeElement=function(a){a&&a.parentElement&&a.parentElement.removeChild(a)};g.isChildOf=function(a,d){for(var c=a.parentNode;c;){if(d==
c)return!0;c=c.parentNode}return!1};g.isVisible=function(e){if(!e||!e.parentNode||e.style&&"none"==e.style.display)return!1;if(e.parentNode)return a.utils.DOM.isVisible(e.parentNode)};g.getCenteredDivID=function(e){return"gig_"+a.localInfo.initTime.getTime().toString()+"_"+e};g.createTopLevelDiv=function(e){var d;d=document.createElement("iframe");d.id="gigya_ifr_"+e;d.frameborder="0";d.frameBorder="0";d.allowtransparency=!0;d.style.position="absolute";d.style.width=a.localInfo.isChrome?"30px":"1px";
d.style.height="1px";null!=d.style.zIndex&&(d.style.zIndex=a.utils.DOM._nextZIndex++);a.localInfo.isIE6&&(d.src=a._.getCdnResource("/gs/blank.htm"));var c=document.createElement("div");null!=c.style.zIndex&&(c.style.zIndex=""+a.utils.DOM._nextZIndex++);c.innerHTML="";e&&(c.id=e);document.body&&document.body.insertBefore&&(document.body.firstChild?(null!=d&&document.body.insertBefore(d,document.body.firstChild),document.body.insertBefore(c,document.body.firstChild)):document.body.appendChild&&(null!=
d&&document.body.appendChild(d),document.body.appendChild(c)));return c};g.hideByID=function(a){if(a=document.getElementById(a))a.style.display="none"};g.showByID=function(e){if(e=document.getElementById(e))e.style.display=a.localInfo.isIE6?"TD"==e.tagName?"table-cell":"TR"==e.tagName?"":"TABLE"==e.tagName?"":"block":""};g.clearByID=function(a){try{var d=document.getElementById(a);null!=d&&(d.innerHTML="")}catch(c){}};g.getHTMLSize=function(a,d){var c=document.createElement("div");c.style.position=
"absolute";c.style.left="-1000px";c.innerHTML=a;d.appendChild(c);var b=c.offsetWidth,f=c.offsetHeight;c.parentNode.removeChild(c);return{w:b,h:f}};g.getElementsByClass=function(a,d,c){if(!a)return[];var b=[];c&&h(a,d)&&b.push(a);a=a.getElementsByTagName("*");for(c=0;c<a.length;c++)h(a[c],d)&&b.push(a[c]);return b||[]};g.getElementsByAttribute=function(a,d,c,b){var f=[];a=a.getElementsByTagName(d);for(d=0;d<a.length;d++)a[d].getAttribute(c)==b&&f.push(a[d]);return f};g.getElementPosition=function(e){if(!e)return{left:0,
top:0,bottom:0,right:0};e=e.getBoundingClientRect();var d=a.utils.viewport.getScroll(),c=e.left+d.left,d=e.top+d.top;return{left:c,top:d,right:c+e.width,bottom:d+e.height}};g.addClassToElement=function(a,d){if(a){var c=a.className?a.className.split(" "):[],b=c.length,f=d.split(" "),g;for(g in f){var h=!1;if(!f[g])break;for(var m in c)if(c[m]==f[g]){h=!0;break}h||c.push(f[g])}c.length!=b&&(a.className=c.join(" "))}};g.removeClassFromElement=function(a,d,c){void 0===c&&(c=!1);if(a){for(var b=a.className.split(" "),
f=b.length-1;0<=f;f--)(b[f]==d||c&&-1!=b[f].indexOf(d))&&b.splice(f,1);a.className=b.join(" ")}};g.isElementClass=h;g.cancelEvent=function(a){a&&("cancelable"in a?a.preventDefault():a.returnValue=!1)};g.createElement=function(a,d){var c=document.createElement("div");d=d||"";c.innerHTML="<"+a+' name="'+d+'" id="'+d+'"></'+a+">";return c.firstChild};g.setSize=function(e,d,c,f){if(null!=e&&null!=e.style){if(d){d=""+d;var g=0<d.indexOf("%");if(!isNaN(d)||g)g=""+(g?d:d+"px"),e.style.width!=g&&(e.style.width=
g)}c&&(c=""+c,g=0<c.indexOf("%"),!isNaN(d)||g)&&(g=""+(g?c:c+"px"),e.style.height!=g&&(e.style.height=g));if(f&&d&&c){if(null==e.style.zIndex||f)e.style.zIndex=(this._nextZIndex++).toString();f=b.viewport.getInnerSize();var g=a.utils.viewport.getScroll(),h=g.left;e.style.top=""+Math.max(0,g.top+Math.floor((f.h-c)/2))+"px";e.style.left=""+Math.max(0,h+Math.floor((f.w-d)/2))+"px";e.style.visibility=""}}};g.createHiddenIframe=function(b){var d=document.createElement("iframe");d.src=b;d.style.width="30px";
d.style.height="10px";d.style.position="absolute";d.style.top="-1000px";d.style.left="-1000px";document.body?a.utils.DOM.appendToBody(d):a.utils.functions.invokeOnPageLoad(function(){a.utils.DOM.appendToBody(d)});return d};g.attributeEncode=function(a){return a.replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/\'/g,"'")}})(b.DOM||(b.DOM={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(c){c=a.utils.object.clone(c);var b=function(){var b=c.data.split("="),f=d[b[0]];if(null!=f){if("function"==typeof f.callback){var l=unescape(b[1]),l=a.utils.keyValue.deserialize(l,null,null,!0);f.callback(l,f.context)}e(b[0]);(b=document.getElementById(b[0]))&&b.parentElement&&b.parentElement.removeChild(b)}};c&&c.data&&c.data.split&&(6<=a.localInfo.iosVersion?b():window.setTimeout(b,100))}function f(c){var d=document.createElement("iframe");d.style.width=
"30px";d.style.height="10px";d.style.position="absolute";d.style.top="-1000px";d.style.left="-1000px";d.id=c;d.src="https://cdns.gigya.com/gs/LocalStorageListener.htm?mode=receive&id="+encodeURIComponent(c);a.utils.DOM.appendToBody(d);return d}function e(a){delete d[a]}var d={};b._flashListenerID="flid"+(new Date).getTime();var c=!1,l={};b._onFlashMessage=function(c){c=a.utils.keyValue.deserialize(c,null,null,!0);var b=c.id,f=d[b];null!=f&&("function"==typeof f.callback&&f.callback(c,f.context),e(b))};
b.addMessageListener=function(e,q,k,m){d[e]={callback:m,context:q,t:(new Date).getTime()};q=a.localInfo.messagingMethod;a.localInfo.isIE11&&k&&window.indexedDB&&(q=a._.MessagingMethod.LocalStorageListener);if(q==a._.MessagingMethod.LocalStorageListener||q==a._.MessagingMethod.PostMessage)q==a._.MessagingMethod.LocalStorageListener&&k&&f(e),c||(e=function(a){if(a&&a.data&&"string"===typeof a.data){var c=a.data.split("=")[0];d[c]&&h(a)}},window.addEventListener?window.addEventListener("message",e,!1):
window.attachEvent&&window.attachEvent("onmessage",e),c=!0);else{var r="localstorage";a.thisScript.globalConf.legacyCrossSiteMethod&&"localstorage"!=a.thisScript.globalConf.legacyCrossSiteMethod.toLowerCase()&&(r=a.thisScript.globalConf.legacyCrossSiteMethod);l[r]||window.setTimeout(function(){var c=document.createElement("div");c.style.width="1px";c.style.height="1px";c.style.overflow="hidden";c.style.position="absolute";c.style.left="-1000px";var d=b._flashListenerID;"localstorage"!=r&&(d=r+":"+
b._flashListenerID);var e=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2],f=(new Date).getTime(),p=document.createElement("object");p.setAttribute("id","eventsBroadcaster"+f);p.setAttribute("codebase","https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0");p.setAttribute("width","50");p.setAttribute("height","50");p.setAttribute("src","https://cdns.gigya.com/GS/swf/eventsBroadcaster2.swf");p.setAttribute("data","https://cdns.gigya.com/GS/swf/eventsBroadcaster2.swf");
p.setAttribute("style","display:inline");f=document.createElement("param");f.name="movie";f.setAttribute("value","https://cdns.gigya.com/GS/swf/eventsBroadcaster2.swf");p.appendChild(f);f=document.createElement("param");f.setAttribute("name","allowScriptAccess");f.setAttribute("value","always");p.appendChild(f);f=document.createElement("param");f.setAttribute("name","FlashVars");f.setAttribute("value","action=listen&id="+d+"&eventName=loginComplete&callback=gigya.utils.xd._onFlashMessage&domain="+
e);p.appendChild(f);c.appendChild(p);a.utils.functions.invokeOnPageLoad(function(){a.utils.DOM.appendToBody(c);p.setAttribute("type","application/x-shockwave-flash");p.setAttribute("classid","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000")});l[r]=!0},500)}};b.removeMessageListener=e})(b.xd||(b.xd={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(g){function h(a){return a.replace(/^http(s?):\/\/cdn(s?)[0-9]*.gigya.com\//,"http$1://cdn$2.gigya.com/")}function f(d,b,e,f,l,g){void 0===l&&(l=5E3);var t;if(f){f=h(d);if(c[f]){c[f].loaded?e&&e():(c[f].onLoad.push(e),c[f].onError.push(b));return}t=c[f]={loaded:!1,onLoad:[e],onError:[b]};g&&0<g.length&&a.utils.array.forEach(g,function(a){c[a]=t})}else t={loaded:!1,onLoad:[e],onError:[b]};b=function(){var b=document.createElement("script");b.async=!0;b.type="text/javascript";
b.charset="UTF-8";var e=!1,f=function(){if(!e){if(t.onLoad&&t.onLoad.length)for(var a=0;a<t.onLoad.length;a++)if("function"==typeof t.onLoad[a])t.onLoad[a]();t.loaded=!0;t.onError=t.onLoad=null;e=!0;!0===l&&(l=0);!1!==l&&setTimeout(function(){b.parentNode&&b.parentNode.removeChild(b)},l)}};b.onload=f;b.onreadystatechange=function(){"loaded"==this.readyState&&f()};b.onerror=function(){for(var a=0;a<t.onError.length;a++)if("function"==typeof t.onError[a])t.onError[a]();delete c[d]};var g=document.getElementsByTagName("head");
g&&0<g.length&&g[0].appendChild(b);g=function(){b.src=d};6<=a.localInfo.iosVersion?g():setTimeout(g,1)};a.localInfo.isIE?a.utils.functions.invokeOnPageLoad(b):b()}function e(a,c){var d=new Image,b=!1;d.onload=d.onerror=function(){b||(b=!0,c())};d.src=a}function d(c,d,e){void 0===e&&(e=5E3);var f=document.createElement("iframe");f.style.width="30px";f.style.height="10px";f.style.position="absolute";f.style.top="-1000px";f.style.left="-1000px";!0===e&&(e=0);var l=function(a){var c;c=a&&a.srcElement?
a.srcElement:a&&a.target?a.target:this;!c.loaded&&c.parentNode&&(c.loaded=!0,d(),!1!==e&&window.setTimeout(function(){try{document.body.removeChild(c)}catch(a){}},e))};b.DOM.addEventListener(f,"load",l);b.DOM.addEventListener(f,"error",l);f.onload=function(a){l(a)};f.onerror=l;f.src=c;a.utils.DOM.appendToBody(f)}var c={};g.isLoaded=function(a){a=h(a);return!(!c[a]||!c[a].loaded)};g.load=f;(function(a){a[a.script=0]="script";a[a.image=1]="image";a[a.iframe=2]="iframe"})(g.ResourceTypes||(g.ResourceTypes=
{}));var l=g.ResourceTypes;g.triggerResource=function(a,c,b,g){void 0===b&&(b=l.image);void 0===g&&(g=5E3);switch(b){case l.script:f(a,c,c,!1,g);break;case l.image:e(a,c);break;case l.iframe:d(a,c,g);break;default:throw Error("Unsupported resource type");}};g.loadService=function(c,d,b){var e=a._.getCdnResource()+"/js/gigya.services."+c+".js";f(e,function(){"object"==typeof console&&console.error&&(console.error("error loading gigya service "+c+" from url: "+e),d&&d())},b,!0)}})(b.script||(b.script=
{}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h;try{h=!!window.sessionStorage}catch(f){h=!1}b.set=function(b,d){if(h){var c;try{(c=a.utils.JSON.deserialize(window.sessionStorage.getItem("gigyaCache")))||(c={}),null==d&&c[b]?delete c[b]:c[b]={response:d,time:(new Date).getTime()},window.sessionStorage.setItem("gigyaCache",a.utils.JSON.serialize(c))}catch(f){}a.utils.queue.release("cache","cache_"+b)}};b.get=function(b,d,c){if(h)try{if(!a.utils.queue.isActive("cache_"+b)){var f=window.sessionStorage.getItem("gigyaCache"),
g=a.utils.JSON.deserialize(f),q=g?g[b]:null;if(q){if(d&&d+q.time>(new Date).getTime()){c(q.response);return}a.utils.sessionCache.remove(b);q=null}if(!q){a.utils.queue.hold("cache","cache_"+b);c(null);return}}a.utils.queue.isActive("cache_"+b)&&a.utils.queue.waitFor("cache_"+b,a.utils.sessionCache.get,arguments)}catch(k){c(null)}else"function"==typeof c&&c(null)};b.remove=function(b){a.utils.sessionCache.set(b,null)}})(b.sessionCache||(b.sessionCache={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h=navigator.userAgent.toLowerCase(),f=null;b.isModern=function(){return a.localInfo.isChrome||a.localInfo.isFF||a.localInfo.isOpera||a.localInfo.isIOSWebView||a.localInfo.isIE&&9<=a.utils.browser.getVersion()||a.localInfo.isEdge||a.localInfo.isSafari&&4<=a.utils.browser.getVersion()};b.getVersion=function(){if(f)return f;try{var a=h.match(/(opera|chrome|safari|firefox|msie|trident.*rv:)\/?\s*(\.?\d+(\.\d+)*)/i);if(a[2]){var d=a[2].split(".")[0];if(!isNaN(parseInt(d)))return f=
parseInt(d)}}catch(c){}return 0}})(b.browser||(b.browser={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a){return a.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")}a.trim=function(a){return a.replace(/^\s*(\S*(.*\S)?)\s*$/,"$1")};a.format=function(a){for(var b=1;b<arguments.length;b++);for(b=0;b<arguments.length-1;b++)null!=arguments[b+1]&&(a=a.split("{"+b+"}").join(arguments[b+1]));return a};a.capitalize=function(a){return a.substring(0,1).toUpperCase()+a.substring(1)};a.endsWith=function(a,b){return-1!==a.indexOf(b,a.length-b.length)};a.escapeRegExp=
b;a.replaceAll=function(a,e,d){return e?a.replace(new RegExp(b(e),"g"),d):a}})(a.stringUtils||(a.stringUtils={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(a){if(!f[a])return!1;for(var d in f[a].ids)return!0;return!1}var f={};b._servicesStatus=function(){var a={},d;for(d in f)h(d)?a[d]={active:!0,waitingFor:f[d].ids,queuedCount:f[d].q.length}:a[d]={active:!1};return a};b.isActive=h;b.release=function(a,d){if(f[d]&&(delete f[d].ids[a],!h(d))){var c=f[d].q;for(f[d].q=[];0<c.length;){var b=c.splice(0,1)[0];try{b.func.apply(this,b.args)}catch(g){"object"==typeof console&&console.log&&console.log("Gigya: Exception while invoking queued method ("+
d+": "+a+")")}if(h(d)){f[d].q=c;break}}}};b.hold=function(a,d){f[d]||(f[d]={q:[],ids:{}});f[d].ids[a]=!0};b.waitFor=function(a,d,c){f[a]||(f[a]={q:[],ids:{}});f[a].q.push({func:d,args:c})};b.queueForExecution=function(b,d,c){c=c||[];a.utils.queue.isActive(b)?a.utils.queue.waitFor(b,d,c):d.apply(this,c)}})(b.queue||(b.queue={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.redirect=function(b,f,e,d){if(e&&"post"==e.toLowerCase()){e=document.createElement("form");var c=[];e.setAttribute("accept-charset","UTF-8");e.setAttribute("method","POST");e.setAttribute("action",b);d&&e.setAttribute("target",d);b=a.utils.object.merge(f);for(var l in b)"boolean"!=typeof b[l]&&"string"!=typeof b[l]||"eventName"==l||c.push('<textarea name="'+encodeURIComponent(l)+'">'+b[l].toString().replace(/\&/g,"&")+"</textarea>");e.innerHTML=c.join("");
e.style.display="none";a.utils.DOM.appendToBody(e);e.submit()}else{e=b.split("?");b=e[0];d={};if(1<e.length)for(e=e[1].split("&"),c=0;c<e.length;c++){var g=e[c].split("=");d[decodeURIComponent(g[0])]=decodeURIComponent(g[1])}for(e=0;e<f.length;e++)for(l in c=f[e],c)"boolean"!=typeof c[l]&&"string"!=typeof c[l]||"eventName"==l||(d[l]=c[l]);f=[];for(l in d)f.push(l+"="+encodeURIComponent(d[l]));document.location.href=b+"?"+f.join("&")}}})(b.HTTP||(b.HTTP={}))})(a.utils||(a.utils={}))})(gigya||(gigya=
{}));(function(a){a.socialize={};a.gcs={};a.gm={};a.comments={};a.accounts={};a.chat={};a.gscounters={}})(gigya||(gigya={}));
(function(a){(function(b){function g(c){var d,b=a.localInfo.protocol;"cdn.gigya.com"==a.thisScript.baseDomain||"cdns.gigya.com"==a.thisScript.baseDomain?(d=e[b],d.length<=f&&(f=0),d=d[f++]):d=a.thisScript.baseDomain;return b+"://"+d+(c?c:"")}var h={};b.getApi=function(a){return h[a]};var f=0,e={http:["cdn.gigya.com","cdn1.gigya.com","cdn2.gigya.com","cdn3.gigya.com"],https:["cdns.gigya.com","cdns1.gigya.com","cdns2.gigya.com","cdns3.gigya.com"]};b.getCdnResource=g;b.getImgCdnResource=function(){return g("/gs/i/")};
var d=function(){function c(a,c){this.methodName=a;this.settings=c;this.addAlias();h[a]=this}c.prototype.run=function(a){};c.prototype.preprocessRequest=function(a,c){this.settings.preprocessor?this.settings.preprocessor(a,c):c()};c.prototype.addAlias=function(){var c=this;a.utils.functions.createAlias("gigya."+this.methodName,function(){for(var d=[],b=0;b<arguments.length;b++)d[b-0]=arguments[b];var b=function(){var d=a.utils.object.merge([a.thisScript.globalConf,e]);c.run(d)},e=a.utils.object.merge([d]);
a.thisScript&&a.thisScript.globalConf?b():a.utils.queue.queueForExecution("API",b)})};return c}();b.BaseApi=d})(a._||(a._={}))})(gigya||(gigya={}));(function(a){a.defaultEventMaps=a.defaultEventMaps||[]})(gigya||(gigya={}));
(function(a){(function(b){function g(a){return"on"===a.substring(0,2)?a:"on"+a.substring(0,1).toUpperCase()+a.substring(1)}function h(b,e){var d;try{"function"==typeof b?d=b(e):b instanceof Array?a.utils.array.forEach(b,function(c){"function"==typeof c?c(e):a.log.addLog("Not a function registered to event: "+c,c)}):a.log.addLog("Not a function or function array registered to event",b)}catch(c){a.log.addLog("Error invoking function registered to event",b)}return d}(function(b){function e(c,b,d,e){var f=
function(c){var d=0;c.cancel||(d=a.events.global.dispatch(c,b));e&&e(d)};d?d(c,f):f(c)}var d={},c={};b._activeNamespaces={};b.add=function(b,f,h,k,m,r){void 0===h&&(h="other");void 0===m&&(m="socialize");b=m+"_"+g(b);d[b]||(d[b]=[]);f={handler:f,type:h,context:k,params:r,fullEventName:b};d[b].push(f);!this._activeNamespaces[m]&&a._.apiAdapter&&a._.apiAdapter.registerForNamespaceEvents(m);this._activeNamespaces[m]=1;if((m=c[b])&&"other"==h)for(c[b]=[],h=0;h<m.length;h++)b=m[h],e(b.eventObj,b.params,
b.preProcess);return f};b.remove=function(c,b){d[c]&&a.utils.array.removeByValue(d[c],b)};b.dispatch=function(c,b){var e=0,f=c.isInternal,h=c.eventName.split(",");a.log.addLog('Dispatching global event "'+c.eventName+'" with this event object',c);for(var r=0;r<h.length;r++){var n=h[r].split("."),t=1<n.length?n.shift():"socialize",u=n[0],n=g(u),v=a.utils.object.clone(d[t+"_"+n]);v||(v=[]);n=a.utils.object.clone(c);n.isGlobal=!0;n.eventName=u;b&&(b.source&&(n.source=b.source),b.sourceData&&(n.sourceData=
b.sourceData),b.context&&(n.context=b.context));u=["component"];f||u.push("other");for(var w=0;w<u.length;w++)for(var A=u[w],x=0;x<v.length;x++){var z=v[x];if(z.type==A){var y=a.utils.object.clone(n);null==y.context&&null!=z.context&&(y.context=z.context);null==y.context&&delete y.context;"component"!=A&&(e++,a._.handleSpecialFields(y));z.params&&z.params.signKey&&(y.UIDSignature=c.signKeysUIDSignature[z.params.signKey],delete y.signKeysUIDSignature);try{z.handler(y)}catch(B){a.log.addLog('Error while trying to invoke "'+
c.eventName+'" global event handler',B)}}}f||a.events._dispatchFromMaps(n,!0);v=window.GenesisExchange_Gigya;u=window.gigya_omniture_conf;w=window.myOmnitureIntegrationFunc;f||"undefined"==typeof v||"undefined"==typeof u||"socialize"!=t||((new v(u)).processAction(n),"undefined"!=typeof w&&w(u,n))}return e};b.dispatchWhenHandlerAdded=function(a,b,d){void 0===b&&(b={});var f=a.eventName.split("."),g=1<f.length?f.shift():"socialize",h=f[0];e(a,b,d,function(e){0==e&&(e="on"+h.substring(0,1).toUpperCase()+
h.substring(1),e=g+"_"+e,c[e]||(c[e]=[]),c[e].push({eventObj:a,params:b,preProcess:d}))})};b.getEventsForOperation=function(a){var c=[];-1!=a.toLowerCase().indexOf("login")?(this._activeNamespaces.socialize&&c.push("socialize.login"),this._activeNamespaces.accounts&&c.push("accounts.login")):-1!=a.toLowerCase().indexOf("addconnection")&&this._activeNamespaces.socialize&&c.push("socialize.connectionAdded");return c.join(",")}})(b.global||(b.global={}));b.addMap=function(b){a.defaultEventMaps.splice(0,
0,b)};b.dispatchErrorFromResponse=function(b,e,d){e||(e={});var c=e;c.response&&(c=c.response);e={eventName:"error",status:c.status?c.status:"FAIL",statusMessage:c.statusMessage?c.statusMessage:"General Server Error",errorMessage:c.errorMessage?c.errorMessage:"General Server Error",errorDetails:c.errorDetails?c.errorDetails:"",errorCode:c.errorCode?c.errorCode:500001,response:e};a.utils.object.add(e,d);a.events.dispatchForWidget(e,b)};b.dispatchInvalidParamError=function(b,e){var d={eventName:"error"};
"undefined"==typeof b[e]||null==b[e]?(d.errorCode=400002,d.errorMessage="Missing_required_parameter ("+e+")"):(d.errorCode=400006,d.errorMessage="Invalid_parameter_value ("+e+")");d.status=d.errorCode;d.statusMessage=d.errorMessage;a.events.dispatchForWidget(d,b)};b.dispatchForWidget=function(b,e){if(b&&b.eventName){var d=b.eventName;a.log.addLog('Dispatching widget event "'+d+'" for '+e.lastSource+" with this event object",b);a._.handleSpecialFields(b);for(var c=d.split(","),l,p=0;p<c.length;p++){var d=
c[p],q=g(d);e&&(e.context&&(b.context=e.context),e.source&&(b.source=e.source),e.sourceData&&(b.sourceData=e.sourceData),e.containerID&&(b.sourceContainerID=e.containerID),e.instanceID&&(b.instanceID=e.instanceID));e[q]&&(l=h(e[q],b));"undefined"===typeof l&&(l=!0);if(-1==d.indexOf("login")&&-1==d.indexOf("logout")&&"connectionRemoved"!=d&&"connectionAdded"!=d){this._dispatchFromMaps(b);var d=window.GenesisExchange_Gigya,q=window.gigya_omniture_conf,k=window.myOmnitureIntegrationFunc;"undefined"!=
typeof d&&"undefined"!=typeof q&&((new d(q)).processAction(b),"undefined"!=typeof k&&k(q,b))}}return l}};b.dispatchEventObject=h;b._dispatchFromMaps=function(b,e){for(var d=[],c=!1,g=0;g<a.defaultEventMaps.length;g++){for(var h=a.defaultEventMaps[g].eventMap,q=a.defaultEventMaps[g].defaultMethod,k=0;k<h.length;k++){var m=h[k],r=[];m.args||(m.args=[]);for(var n=0;n<m.args.length;n++)"$event"==m.args[n]?r.push(b):r.push(a.utils.templates.fill(m.args[n],b));m.events.split(",");n=","+m.events.toLowerCase()+
",";-1==n.indexOf(",*,")&&(-1==n.indexOf(",on"+b.eventName.toLowerCase()+",")&&-1==n.indexOf(","+b.eventName.toLowerCase()+",")||(b.source||m.sources)&&m.sources&&-1==m.sources.indexOf(b.source))||(d.push(m),(m.method?m.method:q).apply(this,r),m.override&&(c=!0))}if(c)break}}})(a.events||(a.events={}))})(gigya||(gigya={}));var __extends=this&&this.__extends||function(a,b){function g(){this.constructor=a}for(var h in b)b.hasOwnProperty(h)&&(a[h]=b[h]);g.prototype=b.prototype;a.prototype=new g};
(function(a){(function(b){b.apiAdapter;var g=function(g){function f(a,b,c,f,p,q){void 0===f&&(f={});void 0===p&&(p={});g.call(this,a,f);this.schema=b;this.requiresSession=c;this.settings=f;this.adapterSettings=p;this.altSessionParams=q;"undefined"===typeof p.requiresSession&&(p.requiresSession=function(){return c})}__extends(f,g);f.prototype.run=function(e){var d=this,c=function(){g.prototype.run.call(d,e);(new b.ServerApiRequest(d,e)).start()};e.ignoreApiQueue?c():a.utils.queue.queueForExecution("API",
function(){c()})};return f}(b.BaseApi);b.ServerApi=g})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){function g(a){return{status:"OK",statusMessage:"",errorCode:0,statusCode:0,errorMessage:"",errorDetails:"",statusReason:"",originalResponse:a}}var h;a.events.global.add("onFBCRefreshed",function(){h=!1},"component");var f;(function(a){a[a._unknown=0]="_unknown";a[a.facebook=1]="facebook";a[a.yahoo=2]="yahoo";a[a.googleplus=3]="googleplus";a[a.linkedin=4]="linkedin";a[a.samlProvider=5]="samlProvider";a[a.samlSession=6]="samlSession"})(f||(f={}));var e=function(){function d(c,
b){this.api=c;this.params=a.utils.object.merge([a.utils.object.clone(b),c.settings.defaultParams]);this.originalParams=a.utils.object.clone(b);this.callback=b.callback}d.prototype.start=function(){var c=this;b.apiAdapter.isSessionValid(this.params,function(b){!c.api.adapterSettings.requiresSession()||b||c.doesHaveAltSessionParam()?c.sendRequest(b):c.afterServerApiResponse(a.utils.object.clone({status:"FAIL",errorMessage:"Unauthorized user",statusMessage:"Unauthorized user",errorCode:403005}),!1)})};
d.prototype.sendRequest=function(c){var d=this,e=a.utils.object.merge([this.api.adapterSettings,{cacheTimeout:this.params.cacheTimeout}]);this.beforeRequest(c,function(f){f?d.afterServerApiResponse(f,c):(a.events.global.dispatch({eventName:"beforeRequest",methodName:d.api.methodName,rawParams:d.originalParams,params:d.params},d.originalParams),d.api.settings.oauth?b.apiAdapter.sendOauthRequest(d.api.methodName,d.params,function(a){d.afterServerApiResponse(a,c)},e):b.apiAdapter.sendRequest(d.api.methodName,
d.params,function(a){d.afterServerApiResponse(a,c)},e))})};d.prototype.beforeRequest=function(c,d){var e=this;a.external.backplane.isLoaded()&&!a.external.backplane._ready&&b.loginMethods[this.api.methodName]?a.external.backplane.executeOnInit(function(){e.beforeRequest(c,d)}):(a._.logoutMethods[this.api.methodName]&&(!c&&!this.params.regToken||a.partnerSettings.ssoLogoutUrl&&document.location.href==a.partnerSettings.ssoLogoutUrl)&&d(g(null)),this.handleDeprecatedParams(),this.handleCollections(),
this.handleConnectWithoutLoginBehavior(c),this.params.extraPermissions=this.params[this.params.provider+"ExtraPermissions"]||this.params.permissions,this.api.preprocessRequest(this.params,function(){e.setOverridableParams(function(){e.setNonOverridableParams(c,function(){e.filterParams(e.params);a.log.logCall(e.api.methodName,e.originalParams,e.originalParams.lastSource);d()})})}))};d.prototype.setOverridableParams=function(c){a.utils.object.merge([{},this.params]);c()};d.prototype.doesHaveAltSessionParam=
function(){if(this.api.altSessionParams){for(var a=this.api.altSessionParams.split("|"),b=0;b<a.length;b++)if(this.params[a[b]])return!0;return!1}};d.prototype.setNonOverridableParams=function(c,d){if(null!=this.params.APIKey){var e=a.utils.cookie.get("gltexp_"+this.params.APIKey);null!=e&&(this.params.loginTokenExp=e)}(e=a.utils.cookie.get("_gigRefUid_"+this.params.APIKey))&&(c||b.loginMethods[this.api.methodName])&&(this.params.refUID=e);if(a.providersConfig.facebook&&!h){var e=a.external.facebook.getParams(),
f;for(f in e)this.params[f]=e[f];h=!0}0==this.api.methodName.indexOf("accounts.")&&(a.events.global._activeNamespaces.socialize&&null==this.params.includeUserInfo&&(this.params.includeUserInfo=!0),this.params.include=this.params.include?this.params.include+",":"profile,data");"accounts.getSchema"==this.api.methodName&&(this.params.includeDynamicSchema="clientOnly");(f=a.external.backplane.getChannelId())&&(this.params.bp_channel_url=f);this.params.targetEnv="jssdk";d()};d.prototype.handleDeprecatedParams=
function(){this.params.pendingRegistration?this.params.pending_registration=this.params.pendingRegistration:this.params.newUsersPendingRegistration&&(this.params.pending_registration=this.params.newUsersPendingRegistration);1==this.params.alwaysForceAuthentication&&(this.params.forceAuthentication=!0);this.params.timestamp&&(this.params.UIDTimestamp=this.params.timestamp,delete this.params.timestamp);this.params.signature&&0==this.api.methodName.indexOf("socialize.")&&(this.params.UIDSig=this.params.signature,
delete this.params.signature);this.params.nonce&&(this.params.UIDNonce=this.params.nonce,delete this.params.nonce);this.params.format&&!this.params.dataFormat&&(this.params.dataFormat=this.params.format,delete this.params.format)};d.prototype.handleCollections=function(){this.params.recipients&&(this.params.recipients=this.extractListOfGIGUIDs(this.params.recipients));if(this.params.friends){var a=this.extractListOfGIGUIDs(this.params.friends);0<this.params.UIDs.length&&(this.params.UIDs+=",");this.params.UIDs+=
a}};d.prototype.extractListOfGIGUIDs=function(c){var b=this;switch(typeof c){case "string":return c;case "object":if("undefined"!=typeof c.UID)return c.UID;if(c instanceof a.socialize.Collection){var d=[];c.each(function(a,c){var e=b.extractListOfGIGUIDs(a);null!=e&&""!=e&&d.push(e)});return d.join(",")}}};d.prototype.handleConnectWithoutLoginBehavior=function(a){if("socialize.addConnection"==this.api.methodName){var d=this.params.connectWithoutLoginBehavior;d&&(d=d.toLowerCase());"loginexistinguser"==
d&&(this.params.loginIfExists=!0);a||(this.api=b.getApi("socialize.login"),"alwayslogin"!=d&&(this.params.temporary_account=!0))}};d.prototype.filterParams=function(c){this.params=a.utils.object.extractProperties(c,{},this.getFullSchema())};d.prototype.getFullSchema=function(){if(null==this.api.schema)return"";for(var c=(this.api.schema+"|"+a._.defaultApiSchema).split("|"),b=0;b<c.length;b++){var d=c[b];if(-1!=d.toLowerCase().indexOf("[providercapability=")){for(var e=d.toLowerCase().split("=")[1].split("]")[0],
d=d.split("]")[1],e=a.socialize.getProvidersForRequiredCapabilities(a.socialize.getProvidersByName("*"),[e]),f=[],g=0;g<e.length;g++)f.push(e[g].name+d);c[b]=f.join("|")}}return c.join("|")};d.prototype.preprocessServerResponse=function(c){c.userInfo&&0!=this.api.methodName.indexOf("accounts.")&&("string"==typeof c.userInfo&&(c.userInfo=a.utils.JSON.deserialize(c.userInfo)),c.userInfo&&(c=a.utils.object.merge([c.userInfo,c]),c.errorCode=c.userInfo.errorCode,delete c.userInfo));c.accountInfo&&"string"==
typeof c.accountInfo&&(c.accountInfo=a.utils.JSON.deserialize(c.accountInfo),c.accountInfo&&(c=a.utils.object.merge([c.accountInfo,c]),delete c.accountInfo));try{c.settings&&"string"==typeof c.settings&&(c.settings=a.utils.JSON.deserialize(c.settings))}catch(b){}return c};d.prototype.onAfterLogoutMethod=function(){a.external.backplane.resetChannel()};d.prototype.getExpiredSessionResponse=function(a){switch(this.api.methodName){case "socialize.setUserSettings":this.originalParams.disableLocalSettings||
(b.setGigyaSettings(this.params.group,this.params.settings),a=g(a));break;case "socialize.delUserSettings":this.originalParams.disableLocalSettings||(b.delGigyaSettings(this.params.group,this.params.settings),a=g(a));break;case "socialize.getUserSettings":if(!this.originalParams.disableLocalSettings){var d=b.getGigyaSettings(this.params.group);a=g(a);a.settings=d}break;case "socialize.getUserInfo":a.status="OK";a.statusMessage="";a.errorCode=0;a.statusCode=0;a.errorMessage="";a.errorDetails="";a.statusReason=
"";break;case "accounts.logout":case "socialize.logout":a=g(a)}return a};d.prototype.afterServerApiResponse=function(c,d){var e=this;b.checkCompleteRegistration(c,this.originalParams,function(f,g,h){c=f;c=e.preprocessServerResponse(c);if(b.logoutMethods[e.api.methodName]&&0==c.errorCode&&c.logoutActiveSession)e.onAfterLogoutMethod();403005==c.errorCode&&(c=e.getExpiredSessionResponse(c));0==c.errorCode&&(d||b.loginMethods[e.api.methodName])&&a.utils.cookie.remove("_gigRefUid_"+e.originalParams.APIKey);
e.handleMethodResponse(c,function(f){c=f;e.addDefaultResponseProperties(c);b.handleSpecialFields(c);e.logoutFromProvidersIfNeeded(c,function(b){b?e.sendRequest(d):(g||e.generateEventsFromResponse(c,d),h?e.sendRequest(d):(a.events.global.dispatch({eventName:"afterResponse",methodName:e.api.methodName,filteredParams:e.params,response:c},e.originalParams),"function"==typeof e.callback&&(a.log.addLog("Calling callback for "+e.api.methodName+" with this response object",c),e.callback(c)),e.api.settings.postprocessor&&
e.api.settings.postprocessor(e.originalParams,c)))})})})};d.prototype.addDefaultResponseProperties=function(a){delete a.statusCode;delete a.statusReason;a.errorCode=a.errorCode||0;a.status=a.status||(0==a.errorCode?"OK":"FAIL");a.errorMessage=a.errorMessage||"";a.statusMessage=a.statusMessage||a.errorMessage;a.requestParams=this.originalParams;a.requestParams.password&&delete a.requestParams.password;a.context=this.originalParams.context;var b=this.api.methodName.split(".")[0];a.operation="socialize"==
b?this.api.methodName.split(".")[1]:"/"+this.api.methodName};d.prototype.handleMethodResponse=function(c,d){if(0==c.errorCode)switch(this.api.methodName){case "accounts.socialLogin":case "socialize.login":c.newUser=c.x_newUser?!0:!1,delete c.x_newUser;case "socialize.notifyLogin":case "socialize.addConnection":case "accounts.linkAccounts":case "accounts.finalizeRegistration":case "accounts.login":case "accounts.register":case "socialize.getUserInfo":delete c.login_token;delete c.expires_in;delete c.id;
c.code&&(c.authCode=c.code,delete c.code);if(!(c.authCode||"socialize.notifyLogin"==this.api.methodName&&this.params.authCode)){var e=c;c.userInfo&&(e=c.userInfo,delete c.userInfo);-1==this.api.methodName.indexOf("accounts.")?(c={user:e},a.utils.object.extractProperties(e,c,"status|statusMessage|callId|errorCode|errorMessage|errorDetails|settings|context|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data|newUser|signKeysUIDSignature"),c.user.hasOwnProperty("UIDSig")&&(c.signature=c.user.UIDSig),
e.profile&&delete e.profile,e.data&&delete e.data,delete e.status,delete e.statusMessage,delete e.callId,delete e.errorCode,delete e.errorMessage,delete e.errorDetails,delete e.settings,delete e.context):c!=e&&(c.user=e);""==e.age||isNaN(parseInt(e.age))||(e.age=parseInt(e.age));e.suppressEvents&&(c.suppressEvents=!0);if("string"==typeof e.capabilities){var f=e.capabilities;f||(f="");"object"!=typeof e.capabilities&&(e.capabilities={});f=f.toLowerCase();e.capabilities={actions:-1<f.indexOf("actions"),
friends:-1<f.indexOf("friends"),login:-1<f.indexOf("login"),status:-1<f.indexOf("status"),notifications:-1<f.indexOf("notifications"),contacts:-1<f.indexOf("contacts"),photos:-1<f.indexOf("photos")}}b.convertIdentitiesArrayToObject(e);"string"==typeof e.providers&&(e.providers=e.providers.split(","));this.params.group&&!c.settings&&(e=b.getGigyaSettings(this.params.group),c.settings=e)}break;case "socialize.getAvailableProviders":e={};for(f=0;f<c.availableProviders.length;f++)e[c.availableProviders[f].name]=
c.availableProviders[f];c.availableProviders=e}"socialize.removeConnection"==this.api.methodName&&0==c.errorCode?a.socialize.getUserInfo(this.originalParams,{callback:function(a){d(a)}}):d(c)};d.prototype.logoutFromProvidersIfNeeded=function(c,d){var e=c.errorCode;if(b.logoutMethods[this.api.methodName]&&0===e){c.logoutActiveSession&&a._.apiAdapter.clearSession(this.params.APIKey);var g=[],e=5E3,h=0,m;c.connectedProviders?m=c.connectedProviders.toLowerCase():c.provider&&(m=c.provider.toLowerCase());
if(m&&!a.utils.validation.isExplicitFalse(this.originalParams.forceProvidersLogout)){var r=m.split(",");for(m=0;m<r.length;++m){var n=r[m],t=f[n],u=null,v=5E3;0===n.indexOf("saml-")&&(t=f.samlProvider,u=n.substring(5),v=!1,e=1E4,h=5E3);g.push({type:t,data:u,removeAfter:v})}}if(c.samlContext&&c.connectedSamlSessions)for(r=c.samlContext,n=c.connectedSamlSessions.split(","),m=0;m<n.length;++m)g.push({type:f.samlSession,data:{samlContext:r,samlSession:n[m]},removeAfter:!1}),e=1E4,h=5E3;if(g.length){var w=
0,A=!1,x=function(){A||(A=!0,d(!1))};window.setTimeout(x,e);e=function(){w++;w==g.length&&window.setTimeout(x,h)};for(m=0;m<g.length;m++)this.logoutFromProvider(g[m],e)}else d(!1)}else 403013==c.errorCode&&"accounts.verifyLogin"!=this.api.methodName?a.accounts.verifyLogin({callback:function(a){0==a.errorCode?d(!0):d(!1)}}):d(!1)};d.prototype.logoutFromProvider=function(b,d){var e="",g=!1,h=!0,m;m=a.partnerSettings.customAPIDomainPrefix?a.partnerSettings.customAPIDomainPrefix+"."+a.partnerSettings.baseDomain:
"fidm."+a.partnerSettings.plugins.apiDomain;switch(b.type){case f.facebook:if(a.providersConfig.facebook){a.socialize.waitForService({service:"facebook",callback:function(){a.external.facebook.isLoggedIn&&FB.logout?FB.logout(function(){a.external.facebook.refreshSession();d()}):d()}});return}break;case f.yahoo:e="https://login.yahoo.com/config/login?.src=fpctx&logout=1&r=";break;case f.googleplus:e="https://accounts.google.com/logout";h=!1;break;case f.samlProvider:e=a.utils.URL.addParamsToURL("https://"+
m+"/saml/v2.0/"+this.params.APIKey+"/sp/jsslo",{name:b.data});g=!0;h=!1;break;case f.samlSession:e=a.utils.URL.addParamsToURL("https://"+m+"/saml/v2.0/"+this.params.APIKey+"/idp/slo/continue/",b.data),g=!0,h=!1}e?(h&&(e+=(new Date).getTime()),a.utils.script.triggerResource(e,d,g?a.utils.script.ResourceTypes.iframe:a.utils.script.ResourceTypes.image,b.removeAfter)):d()};d.prototype.generateEventsFromResponse=function(c,d){var e=this,f;if(0==c.errorCode)switch(this.api.methodName){case "accounts.logout":case "socialize.logout":case "socialize.unlinkAccounts":case "socialize.deleteAccount":f=
{eventName:"logout,accounts.logout"};break;case "socialize.linkAccounts":case "socialize.setUID":b.addUserInfoToEvent(c,f,!0);break;case "socialize.removeConnection":f={eventName:"connectionRemoved,disconnect",provider:this.params.provider||""};b.addUserInfoToEvent(c,f);break;case "socialize.addConnection":!d&&c.user.isLoggedIn?(f={eventName:"login",provider:this.params.provider},b.addUserInfoToEvent(c,f,!0)):(f={eventName:"connectionAdded,connect",provider:this.params.provider},b.addUserInfoToEvent(c,
f));break;case "accounts.linkAccounts":case "accounts.finalizeRegistration":case "accounts.login":case "accounts.register":case "accounts.socialLogin":this.dispatchAccountsLoginEvent(c);case "socialize.finalizeRegistration":case "socialize.register":case "socialize.login":if(!c.user&&!c.authCode)break;f={eventName:"login"};var g=this.params.provider;if(!g&&c.providerSessions)for(var h in c.providerSessions){g=h;break}f.provider=g||"site";f.loginMode=this.originalParams.loginMode||"standard";f.newUser=
c.newUser||!1;c.authCode&&(f.authCode=c.authCode);b.addUserInfoToEvent(c,f,!0);c.user&&g&&(g=g.toLowerCase(),a.utils.cookie.set("_gig_llp",g),a.utils.cookie.set("_gig_llu",c.user.firstName||""));break;case "socialize.notifyLogin":this.params.authCode||(f||(f={eventName:"login"}),f.provider="site",b.addUserInfoToEvent(c,f,!0));break;case "gm.notifyAction":a.events.global.dispatch({eventName:"actionNotified",isInternal:!0})}b.loginMethods[this.api.methodName]&&this.originalParams.redirectURL&&f&&f.user&&
0==c.errorCode&&a.utils.HTTP.redirect(this.originalParams.redirectURL,[f,f.user],this.originalParams.redirectMethod);0==c.errorCode&&f&&"login"==f.eventName&&!c.profile&&a.events.global._activeNamespaces.accounts&&-1==this.api.methodName.indexOf("accounts")&&a.accounts.getAccountInfo(this.originalParams,{include:"profile,data",includeUserInfo:!1,callback:function(a){e.dispatchAccountsLoginEvent(a)}});null!=f&&(f.context=this.originalParams.context,a.events.global.dispatch(f,this.originalParams))};
d.prototype.dispatchAccountsLoginEvent=function(b){var d={eventName:"accounts.login",remember:a.utils.validation.isExplicitTrue(this.originalParams.remember),provider:this.originalParams.provider?this.originalParams.provider.toLowerCase():"",loginMode:this.originalParams.loginMode||"standard"};a.utils.object.extractProperties(b,d,"newUser|signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data|signKeysUIDSignature");a.events.global.dispatch(d,this.originalParams)};return d}();
b.ServerApiRequest=e})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){b.__pluginsCoreLoaded=!1;var g={showReactionsBarUI:["barID"],showCommentsUI:["categoryID","streamID"],showFeedUI:["feedID"],showChatUI:["configID","streamID","chatID"]},h=function(f){function e(a,b,g,h,q,k){void 0===g&&(g={});void 0===h&&(h={});void 0===q&&(q="");void 0===k&&(k={});f.call(this,e.getApiName(b,a,k),k);this.methodName=a;this.jsName=b;this.settings=k;k.defaultParams=g||{};k.defaultPopupParams=h||{};k.requiredParams=q||""}__extends(e,f);e.getApiName=function(a,
b,e){void 0===e&&(e={});return e.apiName||a.split(".")[0]+"."+b};e.versionSelector=function(d,c,e,f,g){void 0===g&&(g="version");var h=new b.api.VersionSelector(d,f,e);a.utils.functions.createAlias("gigya."+c+"."+d,function(){for(var b=[],c=0;c<arguments.length;c++)b[c-0]=arguments[c];var d=b[0],c=b[1];c||(c=d,d=null);c||(c={},b.push(c));d=a.utils.object.merge([{},d,c]);h.callVersion(""+d[g],c,b)});return h};e.createApi=function(a,b,f,g,h,k){void 0===h&&(h={});h.useBasePlugin=!0;a=new e(a,g,null,
null,null,h);a.namespace=b;a.className=f;a.instanceMethods=k||[];a.addInstanceMethodsAliases();return a};e.prototype.addInstanceMethodsAliases=function(){for(var a=0;a<this.instanceMethods.length;a++)this.createInstanceMethodAlias(this.instanceMethods[a])};e.prototype.createInstanceMethodAlias=function(d){var c=this;a.utils.functions.createAlias("gigya."+this.namespace+"."+d,function(e){if(c.injectionInfo){var f=c.getPublicMethod(d),g=b.plugins.getPluginInstance(e,c.injectionInfo);if(g){var h=[];
a.utils.array.forEach(f.argNames,function(a){a&&void 0!==e[a]&&h.push(e[a])});g[f.instanceMethod].apply(g,h)}else a.log.addLog("couldn't find instance",c,!1)}else a.log.addLog("invalid injection info",c,!1)})};e.prototype.getPublicMethod=function(a){var b;this.injectionInfo.publicMethods&&(b=this.injectionInfo.publicMethods[a]);if(!b)throw Error("public method "+a+" is not configured for "+this.injectionInfo.name);return b};e.prototype.preprocessRequest=function(a,b){var e=this;f.prototype.preprocessRequest.call(this,
a,function(){a.source||e.setSourceData(a);b&&b()})};e.prototype.run=function(b){var c=this;!this.settings.waitForAPIQueue||b.ignoreApiQueue?this.startUI(b):a.utils.queue.queueForExecution("API",function(){c.startUI(b)})};e.prototype.startUI=function(b){var c=this;f.prototype.run.call(this,b);b=a.utils.object.clone(b);this.prepareParameters(b);this.preprocessRequest(b,function(){c.settings.useBasePlugin?c.loadPluginJS(b,function(e){a.utils.queue.queueForExecution("UI",function(){e&&c.className&&(c.pluginType=
eval("gigya._.plugins."+c.className),c.injectionInfo=c.pluginType.injectionInfo(c));var f=function(){c.startPlugin(b)};0==b.waitForDebug?f():a.utils.queue.queueForExecution("debug",f)})}):c.legacyStartUI(b)})};e.prototype.startPlugin=function(d){var c=this;a.events.global.dispatch({eventName:"beforePluginRequest",methodName:this.methodName,params:d},d);var e=d.originalMethodName||this.methodName;a.log.logCall(e,d);a.reports.reportLoad(e,d);if(this.pluginType){d&&(e=b.plugins.getPluginInstance(d,this.injectionInfo))&&
e.dispose&&!d._allowMultipleInstances&&!d.newModal&&e.dispose();e=new this.pluginType(d,this.injectionInfo);b.plugins.setPluginInstance(d,this.injectionInfo,e);e.onDisposedEvent().add(function(){return b.plugins.removePluginInstance(d,c.injectionInfo)});e.start();if(e.containerID){var f=document.getElementById(e.containerID);f&&(f.gigyaPluginInstance=e)}d.getInstance&&d.getInstance(e)}else a.utils.functions.callFunction("gigya."+this.jsName+"."+this.methodName,[d,d,d])};e.prototype.loadPluginJS=function(d,
c){if(this.wasPluginJSLoaded(d))c&&c(!1);else{var e=!1,f=a._.getCdnResource("/js/"),g="gigya.services."+this.jsName,h=f+g+".min.js"+(d.lang?"?lang="+d.lang:""),f=f+"gigya.services.plugins.base.min.js?services="+g+(d.lang?"&lang="+d.lang:"");b.__pluginsCoreLoaded?g=h:(g=f,e=b.__pluginsCoreLoaded=!0,a.utils.queue.hold("pluginsJS","UI"));a.utils.script.load(g,null,function(){e&&a.utils.queue.release("pluginsJS","UI");c&&c(!0)},!0,void 0,[h,f])}};e.prototype.wasPluginJSLoaded=function(b){var c="gigya."+
this.jsName+"."+this.methodName,e="gigya.services."+this.jsName+".js";try{var f=eval(c),g=a.i18n[e][b.lang]}catch(h){return!1}return"undefined"!=typeof f&&"undefined"!=typeof g};e.prototype.setSourceData=function(a){a.source="socialize.showSimpleShareUI"==this.methodName?"socialize.showShareUI":a.originalMethodName||this.methodName;if(!a.sourceData&&g[this.methodName]){for(var b={},e,f=0;f<g[this.methodName].length;f++){var h=g[this.methodName][f];null!=a[h]&&(e=!0,b[h]=a[h])}e&&(a.sourceData=b)}a.pluginsStack||
(a.pluginsStack=[]);a.pluginsStack.push({source:this.methodName});a.lastSource=this.methodName};e.prototype.validateRequiredParams=function(b){for(var c=this.settings.requiredParams.split("|"),e=0;e<c.length;e++){var f=c[e];if(""!=f&&(null==b[f]||""==b[f]))return a.events.dispatchInvalidParamError(b,f),!1}return!0};e.prototype.setDefaultParams=function(a){var b=!a.containerID||a.isPopup,e;for(e in this.settings.defaultParams)null==a[e]&&(a[e]=b&&this.settings.defaultPopupParams[e]?this.settings.defaultPopupParams[e]:
this.settings.defaultParams[e]);if(b)for(e in this.settings.defaultPopupParams)a[e]||(a[e]=this.settings.defaultParams[e])};e.prototype.prepareParameters=function(b){for(var c in b)-1!=c.toLowerCase().indexOf("provider")&&"string"==typeof b[c]&&(b[c]=a._.providers.replaceProviderAliases(b[c]));b.lang||(b.lang=a.thisScript.lang.langCode);b.source?b.isPopup=!1:this.setSourceData(b)};e.prototype.legacyStartUI=function(b){var c=this,e=b.containerID;if(this.settings.ignoreContainerId)e=b.containerID="";
else if(null==b.containerID&&!this.settings.allowPopup||b.containerID&&!document.getElementById(b.containerID)){a.events.dispatchInvalidParamError(b,"containerID");return}var f=this.settings.allowPopup&&(!e||b.isPopup);f&&this.settings.useNewModal&&(b.useNewModal=!0);this.setDefaultParams(b);this.settings.allowPopup||f||a.utils.DOM.clearByID(e);this.validateRequiredParams(b)&&this.loadPluginJS(b,function(){var e=function(){c.prepareContainer(b,f,function(){c.startPlugin(b)})};a.utils.queue.queueForExecution("UI",
function(){0==b.waitForDebug?e():a.utils.queue.queueForExecution("debug",e)})})};e.prototype.prepareContainer=function(b,c,e){var f=this;if(document.body){var g=b.containerID,h;c&&(g=a.utils.DOM.getCenteredDivID(this.methodName),b.newModal&&(g+=(new Date).getTime()),b.containerID=g,b.isPopup=!0,document.getElementById(g)||(h=a.utils.DOM.createTopLevelDiv(g),h.style.position="absolute"));if(h=h||document.getElementById(g)){var m=h.Reqs?h.Reqs:h.Reqs=[],r=m.length+"@0@"+g;b.rid=r;m[m.length]={rid:r,
container:h,method:this.methodName,context:b.context,c:b,p:b,i:b,operation:this.methodName,isHTML:!0};if(h&&h.style){h.style.display="";h.style.visibility="";if(g=document.getElementById("gigya_ifr_"+g))g.style.display="",g.style.visibility="";null!=g&&(a.utils.DOM.setSize(g,b.width,b.height,c),g.style.visibility="visible");a.utils.DOM.setSize(h,b.width,b.height,c)}g=this.methodName.split(".").pop();h.setAttribute&&h.setAttribute("gigid",(b.source&&b.source!=g?b.source+"_":"")+g)}else a.events.dispatchInvalidParamError(b,
"containerID");e()}else window.setTimeout(function(){f.prepareContainer(b,c,e)},200)};return e}(b.BaseApi);b.UiApi=h})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a,e){return a.instanceID?a.instanceID:a.isPopup?"gigya-modal-plugin-container-"+e.methodName:a.containerID?a.containerID:e.name}a.instances={};a.getPluginInstance=function(f,e){var d=b(f,e);return a.instances[d]};a.setPluginInstance=function(f,e,d,c){void 0===c&&(c=!1);e=b(f,e);if(!c){c=e;for(var l=2;a.instances[e];l++)e=c+l.toString()}f.instanceID=e;a.instances[e]=d};a.removePluginInstance=function(f,e){delete a.instances[b(f,e)];delete f.instanceID}})(a.plugins||
(a.plugins={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.registerPlugin=function(b){a.utils.queue.queueForExecution("UI",b)};b.attachPlugin=function(b,f,e,d){f||(f="socialize");a[f]||(a[f]={});a[f].plugins||(a[f].plugins={});a[f].plugins[e]||(a[f].plugins[e]={instances:[]});var c=a[f].plugins[e];c[d]||(c[d]=function(a){a=new b(a,"gigya."+f+".plugins."+e+".instances["+c.instances.length+"]");c.instances.push(a)});if(b.StaticApi)for(var g in b.StaticApi)a.utils.functions.createAlias("gigya."+f+".plugins."+e+"."+g,
b[b.StaticApi[g]])}})(b.UI||(b.UI={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h=function(){function b(a,d,c){this.methodName=a;this._versions=d;if(!this._versions||1>this._versions.length)throw Error(this.methodName+": required at least one valid version");if(c){if(this._defaultVersionIndex=this.findVersionIndexOrDefault(c),-1==this._defaultVersionIndex)throw Error(this.methodName+": default version is not defined as a version");}else this._defaultVersionIndex=0}b.prototype.callVersion=function(a,b,c){void 0===b&&(b={});void 0===c&&
(c=[b]);var f=this.findVersionIndexOrDefault(a);if(-1==f)throw Error("gigya plugin version doesn't exist");if(f=this.findSupportedVersion(f))this.invokeVersionMethod(f,b,c);else throw Error(a+": could not find supported version for this browser");};b.prototype.findSupportedVersion=function(a){for(var b=this._versions.length,c=0;c<b;++c){var f=this._versions[(a-c+b)%b];if(!f.isSupported||f.isSupported({directCall:0==c}))return f}};b.prototype.findVersionIndexOrDefault=function(b){var d=-1;b&&(d=a.utils.array.firstIndex(this._versions,
function(a){return a.versionName==b}));-1==d&&(d=void 0!==this._defaultVersionIndex?this._defaultVersionIndex:-1);return d};b.prototype.invokeVersionMethod=function(a,b,c){void 0===b&&(b={});void 0===c&&(c=[b]);var f;switch(typeof a.method){case "function":f=a.method;break;case "string":f=eval(a.method);b.selectedMethodName=a.method;break;default:throw Error(this.methodName+" "+a.versionName+": unsupported gigya-version method");}for(var g in a.additionalParams)b[g]=a.additionalParams[g];b.originalMethodName=
this.methodName;f.apply(this,c)};return b}();b.VersionSelector=h})(b.api||(b.api={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.didChatAuthenticate=!1;b.init=function(){a.socialize.addEventHandlers({listenerType:"component"},{onLogin:function(){b.didChatAuthenticate=!1}});b.didChatAuthenticate=!1};b.beforeChatRequest=function(h,f){b.didChatAuthenticate?f():(b.didChatAuthenticate=!0,a.socialize.getUserInfo({signIDs:!0,callback:function(a){0==a.errorCode&&""!=a.user.UID&&""!=a.user.UIDSignature&&""!=a.user.signatureTimestamp&&(h.UID=a.user.UID,h.UIDSignature=a.user.UIDSignature,h.signatureTimestamp=
a.user.signatureTimestamp,h.loginTokenExp=a.user.loginTokenExp?a.user.loginTokenExp:0);f()}}))}})(b.chat||(b.chat={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){b.defaultApiSchema="ctag|APIKey|cid|oauth_token|source|sourceData|usePost|refUID|fb_UID|fb_at|fb_exp|environment";b.defaultOauthSchema="ctag|temporary_account|authFlow|connectWithoutLogin|provider|redirectMethod|redirect_uri|pendingRegistration|lang|regSource|extraPermissions|sessionExpiration|forceAuthentication|includeiRank|includeAllIdentities|extraFields|enabledProviders|disabledProviders|signIDs|openIDUsername|openIDURL|openIDProviderLogo|openIDProviderName|finalizeRegistration|include|actionAttributes|profileAttributes|googlePlayAppID|bp_channel_url|loginIfExists|includeUserInfo|redirectURL|authCodeOnly|enablePopupLocation|invite|regToken|loginMode|apiDomain|conflictHandling|forcePermissions|signKeys";b.postBookmarkSchema=
"provider|URL|url|title|description|target|cid|APIKey|shortURLs|source|sourceData|providerKey|thumbnailURL|tags|userAction|[providerCapability=actions]UserAction|actionAttributes|facebookDialogType";b.loginMethods={"socialize.login":1,"socialize.addConnection":1,"socialize.notifyLogin":1,"socialize.linkAccounts":1,"accounts.login":1,"accounts.socialLogin":1,"accounts.linkAccounts":1,"accounts.register":1,"accounts.finalizeRegistration":1};var g=function(a){return"link"!==a.loginMode&&"reAuth"!==a.loginMode},
h=function(a,b){b()};b.logoutBehaviour={logoutBeforeServerResponse:!0,alwaysSendLogoutToServer:!1};b.logoutMethods={"socialize.logout":1,"accounts.logout":1,"socialize.deleteAccount":1,"socialize.unlinkAccounts":1};var f=function(b,e){a.partnerSettings.ssoKey&&(b.signIDs=!0);e()},e=function(){return!b.logoutBehaviour.alwaysSendLogoutToServer},d={preprocessor:a._.chat.beforeChatRequest};b.arApiList=[new b.ServerApi("socialize.login",b.defaultOauthSchema,!1,{oauth:!0},{preprocessor:h,clearSessionCondition:g,
forceHttps:!0}),new b.ServerApi("socialize.addConnection",b.defaultOauthSchema,!1,{oauth:!0},{forceHttps:!0}),new b.ServerApi("socialize.requestPermissions",b.defaultOauthSchema,!0,{oauth:!0,defaultParams:{forcePermissions:!0}}),new b.ServerApi("accounts.socialLogin",b.defaultOauthSchema,!1,{oauth:!0},{preprocessor:h,clearSessionCondition:g,forceHttps:!0}),new b.UiApi("showDebugUI","socialize.plugins.debug",{},{},"",{allowPopup:!0}),b.UiApi.createApi("showMyPhotoUI","accounts","profilePhoto.MyPhotoPlugin",
"accounts.plugins.profilePhoto"),b.UiApi.createApi("showRatingUI","comments","rating.RatingPlugin","comments.plugins.rating"),b.UiApi.createApi("runJsUnitTests","_","JsUtRunner.Jasmine.JasmineUtRunnerPlugin","_.plugins.jsUtRunner"),b.UiApi.createApi("loadBasePlugin","_","Mock.MockPlugin","_.plugins.mock"),new b.UiApi("showCommentsUI","comments.plugins.comments",{width:500},{},"",{apiName:"comments.showCommentsUI1"}),new b.UiApi("showCommentsUI","comments.plugins.comments2",{width:500},{},"",{apiName:"comments.showCommentsUI2"}),
b.UiApi.versionSelector("showCommentsUI","comments","2",[{versionName:"1",method:a.comments.showCommentsUI1,additionalParams:{ctag:"comments_v1"}},{versionName:"2",method:a.comments.showCommentsUI2,additionalParams:{ctag:"comments_v2"},isSupported:function(){return a.utils.browser.isModern()}}]),new b.UiApi("showShareUI","socialize.plugins.share",{width:520,height:320},{width:595,height:324},"userAction",{allowPopup:!0,preprocessor:function(c,e){var d=c.operationMode;d&&(d=d.toLowerCase().replace(/ /g,
""));c.containerID||(delete c.width,delete c.height);b.apiAdapter.isSessionValid(c,function(b){"simpleshare"==d||"autodetect"==d&&!b?a.socialize.showSimpleShareUI(c):e()})}}),b.UiApi.createApi("showMessageUI","_","messages.MessagesPlugin","_.plugins.messages"),new b.UiApi("showLoginUI_v1","socialize.plugins.login",{width:120,height:110},{width:280,height:220},"",{allowPopup:!0}),b.UiApi.createApi("showLoginUI_v2","socialize","login_v2.LoginPlugin","socialize.plugins.login_v2"),b.UiApi.versionSelector("showLoginUI",
"socialize","1",[{versionName:"1",method:a.socialize.showLoginUI_v1},{versionName:"2",method:a.socialize.showLoginUI_v2}]),new b.UiApi("showAddConnectionsUI_v1","socialize.plugins.login",{width:110,height:65},{width:250,height:200},"",{allowPopup:!0}),b.UiApi.createApi("showAddConnectionsUI_v2","socialize","login_v2.LoginPlugin","socialize.plugins.login_v2"),b.UiApi.versionSelector("showAddConnectionsUI","socialize","1",[{versionName:"1",method:a.socialize.showAddConnectionsUI_v1},{versionName:"2",
method:a.socialize.showAddConnectionsUI_v2}]),new b.UiApi("showFriendSelectorUI","socialize.plugins.friendSelector",{width:400,height:360},{},"",{allowPopup:!0}),new b.UiApi("showFeedUI","socialize.plugins.newsfeed",{width:304,height:265}),new b.UiApi("showChatUI","chat.plugins.chat",{width:300,height:450},{},"",{preprocessor:function(a,b){a.site&&(a.categoryID=a.site);a.stream&&(a.streamID=a.stream);a.skin&&(a.skinID=a.skin);a.streamID=a.streamID||0;b()}}),b.UiApi.createApi("showEditConnectionsUI",
"socialize","editConnections.EditConnectionPlugin","socialize.plugins.edit"),new b.UiApi("showShareBarUI","socialize.plugins.reactions",{shareCountCacheTimeout:3E5},{},"userAction|shareButtons"),new b.UiApi("showReactionsBarUI","socialize.plugins.reactions",{},{},"userAction|barID|reactions",{preprocessor:function(a,b){a.barID||(a.barID=a.itemID);b()}}),new b.UiApi("showMiniShareUI","socialize.plugins.minishare",{width:320,height:153},{},"",{allowPopup:!0}),new b.UiApi("showFollowBarUI","socialize.plugins.followbar",
{},{},"buttons"),new b.UiApi("showBookmarkUI","socialize.plugins.bookmark",{width:310,height:250},{width:310,height:310}),new b.UiApi("showSimpleShareUI","socialize.plugins.simpleShare",{width:280,height:175},{},"userAction",{allowPopup:!0,dontLoadPluginsCore:!0,waitForAPIQueue:!0}),new b.UiApi("showShareMobileUI","socialize.plugins.shareMobile",{},{},"userAction",{allowPopup:!0}),new b.UiApi("showUserStatusUI","gm.plugins.userStatus",{width:300,hidePoints:!1,hideActions:!1},{},"",{requireSession:!0}),
new b.UiApi("showAchievementsUI","gm.plugins.achievements",{width:300,height:100,excludeChallenges:"_default"}),new b.UiApi("showChallengeStatusUI","gm.plugins.achievements",{width:300,height:100,challenge:"_default"}),new b.UiApi("showLeaderboardUI","gm.plugins.leaderboard",{width:300},{},"",{preprocessor:function(a,b){a&&a.height&&(a.height=null);b()}}),new b.UiApi("showNotifications","gm.plugins.notifications",{},{},"",{preprocessor:function(b,e){var d=a.utils.localStorage.getObject("gmSettings");
d&&d.disableNotifications||(b.containerID="gigNotifications",document.getElementById(b.containerID)||(d=document.createElement("div"),d.id=b.containerID,d.style.position="absolute",d.style.left="-1000px",a.utils.DOM.appendToBody(d)),e())}}),new b.UiApi("showTfaUI","accounts.plugins.tfa",{width:325}),b.UiApi.createApi("showScreenSet","accounts","ScreenSet.ScreenSetPlugin","accounts.plugins.screenSet",void 0,["hideScreenSet","switchScreen"]),new b.ServerApi("socialize.getAvailableProviders","enabledProviders|disabledProviders|requiredCapabilities"),
new b.ServerApi("socialize.notifyLogin","siteUID|UIDTimestamp|UIDSig|UIDNonce|provider|authToken|tokenSecret|regSource|tokenExpiration|sessionHandle|sessionHandleExpiration|userInfo|providerSessions|sessionExpiration|authCode|includeAllIdentitiesincludeiRank|group|settings|extraFields|signIDs|newUser|actionAttributes|profileAttributes|bp_channel_url|signKeys",!1,void 0,{forceHttps:!0,clearSession:!0}),new b.ServerApi("socialize.shortenURL","URL"),new b.ServerApi("socialize.convertAction","userAction|[providerCapability=actions]UserAction|provider"),
new b.ServerApi("socialize.getReactionsCount","barID|buttonIDs|reportLoad"),new b.ServerApi("socialize.incrementReactionsCount","barID|buttonID|count|actionAttributes|profileAttributes"),new b.ServerApi("socialize.deleteAccount",void 0,!0),new b.ServerApi("socialize.delUserSettings","group|settings",!0),new b.ServerApi("socialize.getAlbums","type|enabledProviders|disabledProviders",!0),new b.ServerApi("socialize.getContacts","enabledProviders|disabledProviders",!0),new b.ServerApi("socialize.getFriendsInfo",
"enabledProviders|disabledProviders|detailLevel|UIDs|siteUsersOnly|requiredCapabilities|signIDs",!0),new b.ServerApi("socialize.getPhotos","enabledProviders|disabledProviders|albumIDs|tags",!0),new b.ServerApi("socialize.getRawData","provider|UID|fields|dataFormat|path",!0),new b.ServerApi("socialize.getSessionInfo","provider|paddingMode|encrypt|signIDs|encryptAll",!0),new b.ServerApi("socialize.getUserInfo","enabledProviders|disabledProviders|signIDs|includeiRank|includeAllIdentities|extraFields|group|settings|includeOpenidUID",
!0),new b.ServerApi("socialize.getUserSettings","group|settings|regToken",!0,void 0,{forceHttps:!0},"regToken"),new b.ServerApi("socialize.getPlaces","enabledProviders|disabledProviders|latitude|longitude|query|radius|unifyResults",!0),new b.ServerApi("socialize.checkin","enabledProviders|disabledProviders|placeID|comment|latitude|longitude|actionAttributes|profileAttributes",!0),new b.ServerApi("socialize.logout","signIDs|samlContext|sustainLogoutURLs",!0,{preprocessor:f,disableCache:!0},{requiresSession:e}),
new b.ServerApi("socialize.notifyRegistration","siteUID|UIDTimestamp|UIDSig",!0),new b.ServerApi("socialize.publishUserAction","userAction|[providerCapability=actions]UserAction|enabledProviders|disabledProviders|target|shortURLs|scope|privacy|feedID|userLocation|tags|actionAttributes|profileAttributes",!0),new b.ServerApi("socialize.removeConnection","provider|lastIdentityHandling|removeLoginID",!0),new b.ServerApi("socialize.sendNotification","recipients|body|subject|shortURLs|actionAttributes|profileAttributes",
!0),new b.ServerApi("socialize.setStatus","shortURLs|status|[providerCapability=status]Status|enabledProviders|disabledProviders|userLocation|actionAttributes|profileAttributes",!0),new b.ServerApi("socialize.setUID","siteUID|UIDTimestamp|UIDSig",!0),new b.ServerApi("socialize.setUserSettings","group|settings|regToken",!0,void 0,{forceHttps:!0},"regToken"),new b.ServerApi("socialize.unlinkAccounts",void 0,!0),new b.ServerApi("socialize.getFeed","feedID|startTS|endTS|groups|limit|includeUID"),new b.ServerApi("socialize.sendEmail",
"dontSendEmail|companyName|lang|emails|emailSubject|emailBody|linkBack|senderEmail|senderName|userMsg|shortURLs|userAction|[providerCapability=actions]UserAction|actionAttributes|profileAttributes|captchaTicket|lang",!1,void 0,{forceHttps:!0}),new b.ServerApi("socialize.facebookGraphOperation","graphPath|graphParams|authRequired|method|authType"),new b.ServerApi("socialize.getTopShares","age|tag|limit"),new b.ServerApi("socialize.notifySSOLogin","bp_channel_url"),new b.ServerApi("gm.getChallengeStatus",
"UID|includeChallenges|excludeChallenges|details|lang|actionAttributes|profileAttributes"),new b.ServerApi("gm.resetLevelStatus","challenges|actionAttributes|profileAttributes",!0),new b.ServerApi("gm.getTopUsers","challenge|totalCount|friendsCount|includeSelf|period|lang|actionAttributes|profileAttributes"),new b.ServerApi("gm.getChallengeConfig","UID|includeChallenges|excludeChallenges|lang|actionAttributes|profileAttributes|expandActions"),new b.ServerApi("gm.notifyAction","action|operation|challengeIDs|actionAttributes|profileAttributes",
!0),new b.ServerApi("comments.updateComment","categoryID|streamID|commentID|commentText|commentTitle|ratings|mediaItems|taggedUsers"),new b.ServerApi("comments.postComment","categoryID|streamID|parentID|guestName|guestEmail|commentText|anonymous|mediaItems|privacy|feedID|userAction|[providerCapability=actions]UserAction|scope|enabledProviders|disabledProviders|shortURLs|commentTitle|ratings|tags|taggedUsers|streamTags|actionAttributes|profileAttributes"),new b.ServerApi("comments.getComments","categoryID|streamID|includeSettings|start|startTS|threadLimit|sort|threaded|threadDepth|includeStreamInfo|includeOpenidUID|includeUID|includeReplies|tags|dataFormat|markupType|includeUserOptions|includeUserComments|includeRatingsDims|includeUserHighlighting|pinnedCommentID|lang"),
new b.ServerApi("comments.setStreamInfo","categoryID|streamID|streamTitle|streamURL|streamInfoSig|streamTags"),new b.ServerApi("comments.getTopStreams","categoryID|limit|maxStreamAge|includeLastComment|streamTag|minRatingsCount"),new b.ServerApi("comments.getTopRatedStreams","categoryID|limit|maxStreamAge|ratingClass|minRatingsCount|streamTag"),new b.ServerApi("comments.getStreamInfo","categoryID|streamID|streamIDs|includeLastComment|includeRatingsDims|includeRatingDetails"),new b.ServerApi("comments.flagComment",
"categoryID|streamID|commentID|actionAttributes|profileAttributes"),new b.ServerApi("comments.vote","categoryID|streamID|commentID|vote|actionAttributes|profileAttributes",!0),new b.ServerApi("comments.getUserVotes","categoryID|streamID",!0),new b.ServerApi("comments.getUserComments","categoryID|streamID|tag|senderUID|start|limit|sort|includeReplies|includeStreamInfo|includeUserHighlighting",!0),new b.ServerApi("comments.getFriendsComments","categoryID|streamID|start|limit|includeUID|sort|includeReplies|includeStreamInfo",
!0),new b.ServerApi("comments.getThread","categoryID|streamID|commentID|start|includeUID|limit|threadDepth|sort"),new b.ServerApi("comments.deleteComment","categoryID|streamID|commentID",!0),new b.ServerApi("comments.getRelatedUsers","categoryID|streamID|parentCommentID|usernamePrefix|limit"),new b.ServerApi("comments.analyzeMediaItem","categoryID|urls"),new b.ServerApi("comments.subscribe","categoryID|streamID|email|lang"),new b.ServerApi("comments.unsubscribe","categoryID|streamID|unsubscribeToken"),
new b.ServerApi("comments.setUserOptions","replyNotifications|notificationsEmail|notificationsLanguage",!0),new b.ServerApi("comments.getUserOptions","ServerApiKey",!0),new b.ServerApi("gcs.getUserData","type|fields",!0),new b.ServerApi("gcs.setUserData","data|type|updateBehavior",!0),new b.ServerApi("gcs.search","expTime|querySig|query"),new b.ServerApi("gcs.getSchema","schemaType"),new b.ServerApi("chat.getSettings","categoryID|streamID|skinID|UID|UIDSignature|signatureTimestamp|loginTokenExp",
!1,d),new b.ServerApi("chat.getMessages","categoryID|streamID|start|includeSettings|chatSignature|UID|UIDSignature|signatureTimestamp|loginTokenExp",!1,d),new b.ServerApi("chat.postMessage","categoryID|streamID|messageText|isPrivate|actionAttributes|profileAttributes|signatureTimestamp|loginTokenExp",!0,d),new b.ServerApi("chat.resetChat","categoryID|streamID|timestamp|chatSignature"),new b.ServerApi("chat.blockUser","categoryID|streamID|UID|chatSignature"),new b.ServerApi("chat.blockIP","categoryID|streamID|ip|chatSignature"),
new b.ServerApi("chat.deleteMessage","categoryID|streamID|messageId|chatSignature"),new b.ServerApi("accounts.login","loginID|password|sessionExpiration|targetEnv|regToken|include|actionAttributes|profileAttributes|includeUserInfo|includeDynamicSchema|bp_channel_url|captchaToken|captchaText|loginMode|signKeys",!1,void 0,{preprocessor:h,clearSessionCondition:g,forceHttps:!0,forcePost:!0}),new b.ServerApi("accounts.linkAccounts","loginID|password|sessionExpiration|targetEnv|include|regToken|includeUserInfo|bp_channel_url|signKeys",
!1,void 0,{forceHttps:!0,forcePost:!0}),new b.ServerApi("accounts.initRegistration","sdk",!1,void 0,{clearSession:!0}),new b.ServerApi("accounts.register","username|email|password|UID|regToken|siteUID|secretQuestion|secretAnswer|regSource|profile|data|captchaText|captchaToken|lang|hashedPassword|pwHashAlgorithm|skipVerification|finalizeRegistration|targetEnv|sessionExpiration|include|actionAttributes|profileAttributes|includeUserInfo|bp_channel_url|signKeys",!1,void 0,{forceHttps:!0,forcePost:!0}),
new b.ServerApi("accounts.finalizeRegistration","regToken|targetEnv|include|includeUserInfo|bp_channel_url|allowAccountsLinking|signKeys"),new b.ServerApi("accounts.captchaImage","regToken"),new b.ServerApi("accounts.importProfilePhoto","regToken|URL|publish"),new b.ServerApi("accounts.setProfilePhoto","regToken|publish|photoBytes"),new b.ServerApi("accounts.resetPassword","lang|loginID|passwordResetToken|secretAnswer|securityFields|newPassword|email",!1,void 0,{forceHttps:!0,forcePost:!0}),new b.ServerApi("accounts.isAvailableLoginID",
"loginID"),new b.ServerApi("accounts.resendVerificationCode","regToken|email"),new b.ServerApi("accounts.getCaptcha",""),new b.ServerApi("accounts.getPolicies","sections"),new b.ServerApi("accounts.getSchema","sections|schemaType"),new b.ServerApi("accounts.verifyLogin","include|extraProfileFields|targetEnv",!0),new b.ServerApi("accounts.getAccountInfo","include|extraProfileFields|regToken",!0,{},{},"regToken"),new b.ServerApi("accounts.setAccountInfo","profile|data|regToken|oldPassword|password|newPassword|addLoginEmails|removeLoginEmails|username|secretQuestion|secretAnswer|requirePasswordChange|conflictHandling|tfaStatus|rba",
!1,void 0,{forceHttps:!0,forcePost:!0},"regToken"),new b.ServerApi("accounts.logout","signIDs|samlContext|sustainLogoutURLs",!0,{preprocessor:f,disableCache:!0},{requiresSession:e}),new b.ServerApi("accounts.search","expTime|querySig|query"),new b.ServerApi("accounts.getScreenSets","screenSetIDs|include"),new b.ServerApi("accounts.getConflictingAccount","regToken|loginID"),new b.ServerApi("accounts.incrementCounters","counters",!0,{preprocessor:function(a,b){var e=a.actionCounterPath,d=a.counters;
if(e&&d)for(var f=0;f<d.length;f++){var g=d[f];"object"!=typeof g||g.path||(g.path=e)}b()}}),new b.ServerApi("accounts.getCounters","counters",!0),new b.ServerApi("accounts.tfa.getProviders","regToken",!0,{},{},"regToken"),new b.ServerApi("accounts.tfa.initTFA","provider|mode|regToken",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.finalizeTFA","gigyaAssertion|providerAssertion|tempDevice|regToken",!0,{},{},"regToken"),new b.ServerApi("accounts.tfa.deactivateProvider","provider",!0),new b.ServerApi("accounts.tfa.unregisterDevice",
"allDevices",!0),new b.ServerApi("accounts.tfa.phone.getRegisteredPhoneNumbers","gigyaAssertion",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.phone.removePhone","gigyaAssertion|phoneId",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.phone.sendVerificationCode","gigyaAssertion|lang|phoneID|phone|method",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.phone.completeVerification","gigyaAssertion|phvToken|code",!1,{},{forceHttps:!0}),new b.ServerApi("ds.store","type|data|oid|updateBehavior"),
new b.ServerApi("ds.get","type|data|oid|fields"),new b.ServerApi("ds.search","expTime|querySig|query"),new b.ServerApi("ds.getSchema",""),new b.ServerApi("ds.delete","type|oid|fields"),new b.ServerApi("ids.getAccountInfo","include|extraProfileFields",!0),new b.ServerApi("ids.setAccountInfo","profile|data|oldPassword|password|newPassword|addLoginEmails|removeLoginEmails|username|secretQuestion|secretAnswer|requirePasswordChange",!1,void 0,{forceHttps:!0,forcePost:!0}),new b.ServerApi("ids.search",
"expTime|querySig|query"),new b.ServerApi("gscounters.sendReport","reports|noAuth")];a.utils.functions.createAlias("gigya.socialize.showChatUI",a.chat.showChatUI);a.utils.functions.createAlias("gigya.socialize.showCommentsUI",a.comments.showCommentsUI);a.utils.functions.createAlias("gigya.socialize.showRatingUI",a.comments.showRatingUI);a.utils.functions.createAlias("gigya.services.socialize",a.socialize);a.utils.functions.createAlias("gigya.services.gcs",a.gcs);a.utils.functions.createAlias("gigya.services.gm",
a.gm);a.utils.functions.createAlias("gigya.services.comments",a.comments);a.utils.functions.createAlias("gigya.services.accounts",a.accounts);a.utils.functions.createAlias("gigya.socialize.connect",a.socialize.addConnection);a.utils.functions.createAlias("gigya.socialize.disconnect",a.socialize.removeConnection);a.utils.functions.createAlias("gigya.socialize.linkAccounts",a.socialize.setUID);a.utils.functions.createAlias("gigya.socialize.showConnectUI",a.socialize.showAddConnectionsUI);a.utils.functions.createAlias("gigya.socialize.showNewsfeedUI",
a.socialize.showFeedUI);a.utils.functions.createAlias("gigya.showDebugUI",a.socialize.showDebugUI)})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){a.socialize.addEventHandlers=function(){for(var b=[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];var b=a.utils.object.merge([a.thisScript.globalConf,b]),d=b.namespace?b.namespace:"socialize",c;for(c in b)0==c.indexOf("on")&&a.events.global.add(c,b[c],b.listenerType,b.context,d,b);"function"==typeof b.callback&&b.callback({status:"OK",statusMessage:"",errorCode:0,errorMessage:"",operation:"addEventHandlers",context:b.context})};a.accounts.addEventHandlers=function(){for(var b=
[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];b=a.utils.object.merge([b,{namespace:"accounts"}]);a.socialize.addEventHandlers(b)};a.socialize.isLoggedIn=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]);a.socialize.getUserInfo(b,{callback:function(d){var c=d.user,c={loggedIn:c?a.utils.validation.isExplicitTrue(c.isLoggedIn):!1};a.utils.object.extractProperties(d,c,"status|statusMessage|callId|errorCode|errorMessage|errorDetails|context");b.callback&&b.callback(c)}})};
a.socialize.waitForService=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]),d=b.service;if(d){var d=d.toLowerCase(),c=b.callback;if("fbconnect"==d||"facebook"==d)a.external.facebook.isLoaded()?c({context:b.context}):a.socialize.addEventHandlers({listenerType:"component"},{onFacebookLoaded:c,context:b.context});"googleplus"==d&&(a.external.googlePlus.isLoaded()?c({context:b.context}):a.socialize.addEventHandlers({listenerType:"component"},{onGooglePlusLoaded:c,context:b.context}))}};
var g={facebook:{w:640,h:370},twitter:{w:880,h:585},messenger:{w:710,h:905},linkedin:{w:560,h:500},yahoobookmarks:{w:840,h:975},digg:{w:1010,h:1045},delicious:{w:890,h:905},googlebookmarks:{w:710,h:905},mixi:{w:640,h:470},googleplus:{w:496,h:420}};a.socialize.postBookmark=function(){var e=a.utils.object.merge([a.thisScript.globalConf,arguments]);e.APIKey||(e.APIKey=a.thisScript.APIKey);var d={};a.utils.object.extractProperties([e],d,b.postBookmarkSchema);d.sdk="js_"+a.build.version;if(!d.URL&&!d.url&&
d.userAction&&!d.userAction.linkBack)for(var c=document.getElementsByTagName("meta"),f=0;f<c.length;f++)if("og:url"==c[f].getAttribute("property")&&c[f].getAttribute("content")){d.URL=c[f].getAttribute("content");break}d.URL||d.url||!d.userAction||d.userAction.linkBack||(d.URL=document.location.href);delete d.context;d.provider||(d.provider="");d.providerKey||"facebook"==d.provider.toLowerCase()&&(d.providerKey=a.external.opengraph.getMetaTag("fb:app_id"));a._.apiAdapter.getGmidTicket(function(b){b&&
(d.gmidTicket=b);b=a.utils.keyValue.serialize(d);var c=g[d.provider.toLowerCase()],f=e.enablePopupLocation?"location=1,toolbar=1":null;c&&c.w&&c.h&&(f=(e.enablePopupLocation?"location=1,toolbar=1,":"toolbar=0,")+"menubar=0,resizable=1,scrollbars=1,width="+c.w+",height="+c.h);a.log.logCall("postBookmark",d);a.utils.win.open(a.utils.stringUtils.format(a.partnerSettings.customAPIDomainPrefix?"https://{0}/gs/bookmark.aspx?{1}":"https://socialize.{0}/gs/bookmark.aspx?{1}",a.partnerSettings.plugins.apiDomain,
b),"gs_bookmark_"+d.provider,f)})};a.socialize.refreshUI=function(){var e=a.utils.object.merge([a.thisScript.globalConf,arguments]),d=e.callback;a.socialize.getUserInfo(e,{callback:function(c){var f={eventName:"login",isInternal:!0};e.provider&&(f.provider=e.provider);b.addUserInfoToEvent(c,f,!0);e.context&&(f.context=e.context);a.events.global.dispatch(f);"function"==typeof d&&d(c)}})};var h={"digg.com":"digg","stumbleupon.com":"stumbleupon","delicious.com":"delicious","technorati.com":"technorati",
"t.co":"twitter","plus.url.google.com":"googlePlus","facebook.com":"facebook","linkedin.com":"linkedIn","pinterest.com":"pinterest","mixi.jp":"mixi","b.hatena.ne.jp":"hatena","line.me":"line"},f;a.socialize.trackReferrals=function(){var e=a.utils.object.merge([a.thisScript.globalConf,arguments]),d={eventName:"linkback",CID:e.cid},c={},g={};-1!=document.location.href.indexOf("#")&&(g=a.utils.keyValue.deserialize(document.location.href.split("#")[1]));-1!=document.location.href.indexOf("?")&&(c=a.utils.keyValue.deserialize(document.location.href.split("?")[1].split("#")[0]));
a.socialize.updateRefUID(e.APIKey,g,c);var p=null!=g._gus||null!=c._gus;p&&(d.CID=g._gucid||c._gucid,d.shortCode=g._gsc||c._gsc,d.provider=g._gup||c._gup);if(!f){var q,g={url:document.location.href,ref:document.referrer};c.fb_ref?(q=a.utils.keyValue.deserialize(c.fb_ref,":"),g.uuid=q.uu,g.sn=q.p,q=q.s):document.referrer&&-1!=document.referrer.indexOf("://")&&(c=document.referrer.split("://")[1].split("/")[0],0==c.indexOf("www.")&&(c=c.split("www.")[1]),h[c]&&(d.provider=g.sn=h[c]));g.sn||document.referrer&&
(-1!=document.referrer.indexOf("http://soc.li")||-1!=document.referrer.indexOf("https://shr.gs"))||(c=document.location.href.split("#guid="),1<c.length&&(c=c[1].split("#")[0].split("&")[0],c!=b.apiAdapter.getTokenParam(e.APIKey,"UUID")&&(g.sn="AddressBarShares",g.uuid=c,"_"==c&&delete g.uuid,document.location.replace("#"),a.reports.trackAddressBarShares(),g.url=document.location.href.split("#")[0])));g.uuid&&a.utils.cookie.set("_gigRefUid_"+e.APIKey,g.uuid);g.sn&&!p&&a.reports.report("linkback",e.APIKey,
e.cid,q,null,g);(g.sn||p)&&a.events.global.dispatch(a.utils.object.removeUndefined(d));f=!0}"function"==typeof e.callback&&e.callback({status:"OK",statusMessage:"",operation:"trackReferrals",context:e.context,errorMessage:"",errorCode:0})};a.socialize.updateRefUID=function(b,d,c){b||(b=a.thisScript.globalConf.APIKey);d||(d={},-1!=document.location.href.indexOf("#")&&(d=a.utils.keyValue.deserialize(document.location.href.split("#")[1])));c||(c={},-1!=document.location.href.indexOf("?")&&(c=a.utils.keyValue.deserialize(document.location.href.split("?")[1].split("#")[0])));
d.guid&&"_"!=d.guid&&a.utils.cookie.set("_gigRefUid_"+b,d.guid);(d=d._giguuid||c._giguuid)&&a.utils.cookie.set("_gigRefUid_"+b,d)};a.socialize.hideUI=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]);"function"==typeof b.callback&&b.callback({status:"OK",statusMessage:"",operation:"hideUI",context:b.context,errorMessage:"",errorCode:0})};a.gcs.submitUserForm=function(){var b={},d=a.utils.object.merge([a.thisScript.globalConf,arguments]),c=document.getElementById(d.form);if(!c){var f=
document.getElementsByName(d.form);f&&0<f.length&&(d.form=f[0])}for(f=0;f<c.elements.length;f++){var g=c.elements[f];if(g.name){for(var h=g.name.split("."),k=b,m=0;m<h.length-1;m++){var r=h[m];k[r]||(k[r]={});k=k[r]}k[h[h.length-1]]=g.value}}d.data=b;a.gcs.setUserData(d)};a.socialize.getProviderShareCounts=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]);a.utils.script.load(a._.getCdnResource("/js/gigya.services.socialize.plugins.shareCounts.min.js"),null,function(){a.socialize.plugins.shareCounts.getProviderShareCounts(b)},
!0)};a.utils.functions.createAlias("gigya.setSSOToken",function(){for(var b=[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];var b=a.utils.object.merge([a.thisScript.globalConf,b]),d=b.redirectURL||document.location.href,c=null!=a.partnerSettings.ssoKey,f="1"!=a.utils.localStorage.getItem("_gig_3pc_enabled"),g=a.utils.JSON.deserialize(a.utils.localStorage.getItem("_gig_ssoToken"))||{},h=g.ssoToken,k=(new Date).getTime();g.exp<k&&a.thisScript.globalConf.enableSSOToken&&c&&f&&null!=h?a.utils.HTTP.redirect("https://socialize."+
(a.partnerSettings.plugins.originalApiDomain||a.partnerSettings.plugins.apiDomain)+"/gs/SSOGateway.aspx",[{apiKey:b.APIKey,redirectURL:d,ssoToken:h}],"GET","_top"):a.utils.HTTP.redirect(d,[{}],"GET","_top")})})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.initSSO=function(b){b=a.utils.URL.addParamsToURL(a.samlConfig.proxyPageURL,a.utils.object.merge([{mode:"initSSO"},b]));window.location.href=b};b.continueSSO=function(){var b=a.utils.URL.addParamsToURL(a.samlConfig.proxyPageURL,{mode:"afterLogin"});window.location.href=b}})(b.saml||(b.saml={}))})(a.fidm||(a.fidm={}))})(gigya||(gigya={}));(function(a){a=a._||(a._={});a=a.apiAdapters||(a.apiAdapters={});a.a})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(){if("undefined"!=typeof FB){var e=function(c){b.initializedTime=new Date;b.isConnected="connected"==c.status;b.isLoggedIn="unknown"!=c.status;a.events.global.dispatch({eventName:"FBCRefreshed"})};a.providersConfig.facebook.appID&&FB&&FB.getLoginStatus&&FB.getLoginStatus(e,!0)}}function f(){for(var a=e,b=0;b<a.length;b++)a[b]();e=[]}var e=[];b.initializedTime;b.isLoggedIn=!1;b.isConnected=!1;b.isLoaded=function(){return null!=b.initializedTime};b.load=
function(e){if(!b.initializedTime){b.initializedTime=null;window.setInterval(function(){a.external.facebook.refreshSession()},27E5);window.fbAsyncInit=function(){var c=a.utils.object.clone(a.thisScript.globalConf.facebookInitParams);c||(c={});a.providersConfig.facebook?(c.appId=a.providersConfig.facebook.appID,c.version=a.providersConfig.facebook.version):c.version="v1.0";c.status=!1;c.cookie=!0;c.xfbml=!0;c.oauth=!0;FB.init(c);1!=e?FB.getLoginStatus(function(c){b.initializedTime=new Date;b.isConnected=
"connected"==c.status;b.isLoggedIn="unknown"!=c.status;a.events.global.dispatch({eventName:"facebookLoaded",isLoggedIn:b.isLoggedIn,isConnected:b.isConnected});a.socialize.addEventHandlers({listenerType:"component"},{listenerDescription:"listener for updating Facebook Connect session",onLogin:function(){h()},onConnect:function(){h()},onLogout:function(){h()}})},!0):(b.initializedTime=new Date,a.events.global.dispatch({eventName:"facebookLoaded",isLoggedIn:b.isLoggedIn,isConnected:b.isConnected}))};
var c=document.createElement("div");c.id="fb-root";a.utils.DOM.appendToBody(c);a.utils.script.load(document.location.protocol+"//connect.facebook.net/"+a.thisScript.lang.full.replace("-","_")+"/sdk.js",null,function(){"none"==document.documentElement.style.display&&(document.documentElement.style.display="")},!0)}};b.refreshSession=h;b.retryPending=f;b.runWhenLoaded=function(a){e.push(a)};b.getParams=function(){var a={};if("undefined"!=typeof FB&&FB.getAuthResponse)try{var b=FB.getAuthResponse();
b&&(null!=b.userID&&(a.fb_UID=b.userID),null!=b.accessToken&&(a.fb_at=b.accessToken),null!=b.expiresIn&&(a.fb_exp=b.expiresIn))}catch(e){}return a};b.autoLogin=function(){a.socialize.waitForService({service:"facebook",callback:function(){a._.apiAdapter.isSessionValid(a.thisScript.globalConf,function(b){var c=a.external.facebook.getParams();!b&&c&&c.fb_at&&!a._.autoLoginInProgress&&(a._.autoLoginInProgress=!0,a.socialize.notifyLogin({providerSessions:{facebook:{authToken:c.fb_at,tokenExpiresIn:c.fb_exp}}}))})}})};
a.events.global.add("facebookLoaded",f,"component");a.events.global.add("onFBCRefreshed",f,"component")})(b.facebook||(b.facebook={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.initializedTime;b.isLoaded=function(){return null!=b.initializedTime};b.load=function(){var h=this;if(!b.initializedTime&&a.providersConfig.googlePlus){b.initializedTime=null;var f=document.createElement("script");f.type="text/javascript";f.async=!0;window.__gigya_handleClientLoad=function(){return h.handleClientLoad()};f.src="https://apis.google.com/js/client.js?onload=__gigya_handleClientLoad";var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(f,
e)}};b.handleClientLoad=function(){try{delete window.__gigya_handleClientLoad}catch(h){window.__gigya_handleClientLoad=void 0}b.initializedTime=new Date;a.events.global.dispatch({eventName:"googlePlusLoaded"})};b.refreshSession=function(){};b.autoLogin=function(){a.socialize.waitForService({service:"googlePlus",callback:function(){a._.apiAdapter.isSessionValid(a.thisScript.globalConf,function(b){b||gapi.auth.authorize({client_id:a.providersConfig.googlePlus.clientId,scope:a.providersConfig.googlePlus.scopes,
immediate:!0,response_type:"code"},function(b){b&&b.code&&!a._.autoLoginInProgress&&(a._.autoLoginInProgress=!0,a.socialize.notifyLogin({providerSessions:{googlePlus:{code:b.code}}}))})})}})}})(b.googlePlus||(b.googlePlus={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b._ready=null;b.executeOnInit=function(b,f){b&&(f||(f=2E3),a.external.backplane.isLoaded()?a.external.backplane.getChannelId()||a.external.backplane._ready?(a.external.backplane._ready=!0,b()):(window.setTimeout(function(){a.external.backplane._ready||(a.external.backplane._ready=!0,b())},f),Backplane(function(){a.external.backplane._ready=!0;b()})):b())};b.isLoaded=function(){return"undefined"!=typeof Backplane};b.getChannelId=function(){if(a.external.backplane.isLoaded())return Backplane.getChannelID()};
b.resetChannel=function(){a.external.backplane.isLoaded()&&Backplane.resetCookieChannel()};a.events.global.add("logout",a.external.backplane.resetChannel)})(b.backplane||(b.backplane={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.getMetaTag=function(a){for(var b=document.getElementsByTagName("meta"),e=0;e<b.length;e++)if(b[e].getAttribute("property")==a&&b[e].getAttribute("content"))return b[e].getAttribute("content")}})(a.opengraph||(a.opengraph={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(a){a[a.LocalStorageListener=0]="LocalStorageListener";a[a.PostMessage=1]="PostMessage";a[a.Flash=2]="Flash"})(b.MessagingMethod||(b.MessagingMethod={}));b.checkCompleteRegistration=function(b,h,f){var e,d;if(206005==b.errorCode)a.accounts.finalizeRegistration({regToken:b.regToken,callback:function(a){f(a)}});else if(!h.dontHandleScreenSet&&((b.regToken||h.regToken)&&(200010==b.errorCode||403043==b.errorCode)||206001==b.errorCode||206002==b.errorCode||206003==b.errorCode||
403101==b.errorCode||403102==b.errorCode||403110==b.errorCode||403100==b.errorCode)){var c;403110==b.errorCode&&(c=d=!0);h.defaultMobileRegScreenSet&&a.localInfo.isMobile?e=h.defaultMobileRegScreenSet:h.defaultRegScreenSet&&(e=h.defaultRegScreenSet)}e?a.accounts.showScreenSet({newModal:c,initialResponse:b,screenSet:e,onHide:function(a){"finished"===a.reason&&a.user?f({errorCode:0,userInfo:a.user},!0,d):f(b)}}):f(b)};b.getGigyaSettings=function(b){var h=a.utils.localStorage.getItem("gigyaSettings");
try{h=a.utils.JSON.deserialize(h)}catch(f){h={}}h||(h={});return a.utils.JSON.serialize(h[b])};b.setGigyaSettings=function(b,h){var f=a.utils.localStorage.getItem("gigyaSettings");try{f=a.utils.JSON.deserialize(f)}catch(e){f={}}f||(f={});f[b]||(f[b]={});for(var d in h)f[b][d]=h[d];a.utils.localStorage.setItem("gigyaSettings",a.utils.JSON.serialize(f))};b.delGigyaSettings=function(b,h){if(b){var f=a.utils.localStorage.getItem("gigyaSettings");f&&(f=a.utils.JSON.deserialize(f),delete f[b],a.utils.localStorage.setItem("gigyaSettings",
a.utils.JSON.serialize(f)))}else a.utils.localStorage.removeItem("gigyaSettings")};b.handleSpecialFields=function(g){var h=a.socialize.Collection,f=function(a,e){for(var d=[],f=0,g=a[f];g;)d.push(new e(g)),d[f].identities&&b.convertIdentitiesArrayToObject(d[f]),g=a[++f];return d};g.photos&&(g.photos=new h(g.photos,"photoID"));g.albums&&(g.albums=new h(g.albums,"albumID"));g.contacts&&(g.contacts=new h(f(g.contacts,a.socialize.Contact),"email"));g.friend&&(g.friend=new h(f(g.friend,a.socialize.Friend),
"UID"));g.user&&(g.user=new a.socialize.User(g.user));if(g.friends&&g.friends instanceof Array){for(var e=[],d=0;d<g.friends.length;d++)e.push(g.friends[d].UID);g.UIDs=e.join(",");g.friends=new h(f(g.friends,a.socialize.Friend),"UID")}};b.convertIdentitiesArrayToObject=function(b){if(null==b.identities)b.identities={};else if(b.identities.constructor==Array){var h=b.identities;b.identities={};for(var f=0;f<h.length;f++)b.identities[h[f].provider]=new a.socialize.Identity(h[f])}};b.addUserInfoToEvent=
function(b,h,f,e){e=b.user||b.userInfo;null==h&&(h={});null!=e&&(h.user=a.utils.object.clone(e),null!=b.isLoggedIn&&(h.user.isLoggedIn=b.isLoggedIn),null!=b.isSiteUID&&(h.user.isSiteUID=b.isSiteUID),null!=b.iRank&&(h.user.iRank=b.iRank));f&&(a.utils.object.extractProperties(b,h,"signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|signKeysUIDSignature"),null!=h.user&&(h.UID=e.UID,h.isSiteUID=e.isSiteUID));return h};b.sendEmailNative=function(b){var h=b.userAction||{},f=h.linkBack||"";document.location.href=
"mailto:?to=&subject="+a.utils.URL.URLEncode(h.title||"")+"&body="+a.utils.URL.URLEncode(f);a.socialize.sendEmail(b,{dontSendEmail:!0})};b.getPageBaseDomain=function(g,h){void 0===g&&(g=a.localInfo.pageDomain);void 0===h&&(h=a.partnerSettings.baseDomains);if(h){var f=b.Uri.parse(g);if(f)for(var e=h.split(","),d=0;d<e.length;d++){var c=a.utils.stringUtils.replaceAll(e[d],"*",""),c=b.Uri.parse(c);if(f.isIn(c))return c.isForSubDomains()?f.domain:c.domain}}return null}})(a._||(a._={}))})(gigya||(gigya=
{}));
(function(a){(function(b){function g(){a.utils.script.load(a._.getCdnResource("/js/gigya.services.socialize.plugins.log.min.js"),null,function(){a.log.showConfig()},!0)}b.CONSOLE_LOG_LEVELS=["debug","info","log","warn","error"];b.selectedConsoleLogLevels=[];b._log=[];b.enable=function(){a.utils.cookie.set("_gig_dbgConsole_log","1",null)};b.disable=function(){a.utils.cookie.set("_gig_dbgConsole_log","0",null)};b._isEnabled=function(){var g=a.utils.cookie.get("_gig_dbgConsole_log");return"undefined"!==typeof g&&
null!=g?"1"==g:0<b.selectedConsoleLogLevels.length};b.addLog=function(g,f,e){void 0===e&&(e=!1);if(a.log._isEnabled()||e){var d=g;f=a.utils.object.clone(f,!0,!1,4,null,!0);null!=f&&(d+=":"+("object"==typeof f?"\n":"")+a.utils.JSON.serialize(f,!0,!0));e&&"object"==typeof console&&console.log&&console.log(d);a.log._isEnabled()&&(b._log.push(d),null!=document.getElementById("gigya_log")&&a.log.show&&a.log.show(),g=-1!=a.utils.array.indexOf(a.log.CONSOLE_LOG_LEVELS,g)?g:"log",a._.apiAdapter.onJSLog(g,
d))}};b.logCall=function(b,f,e){e||(e=f.lastSource);a.log.addLog("Calling "+b+(e&&e!=b?" for "+e:"")+(f.source&&e!=f.source?" initiated from "+f.source:"")+" with these params",f)};b.debug=g;b.showLog=function(){a.utils.script.load(a._.getCdnResource("/js/gigya.services.socialize.plugins.log.min.js"),null,function(){a.log.show()},!0)};b.show=function(){};b.showConfig=function(){};a.utils.functions.createAlias("gigya.debug",g)})(a.log||(a.log={}))})(gigya||(gigya={}));
var defaultObjects={},defaultObjectsDef={User:"personwithuid+isLoggedIn|false,isConnected|false,isSiteUser|false,identities|{},providers|[],timestamp,UIDSig,UIDSignature,signatureTimestamp,loginProvider,loginProviderUID,capabilities|{}",Friend:"personwithuid+timestamp,friendshipSig,friendshipSignature,signatureTimestamp,timestamp,isSiteUser|false,identities|{}",Identity:"person+isExpiredSession|false,allowsLogin|false,providerUID,provider,isLoginIdentity|false,missingPermissions",Contact:"provider,firstName,lastName,nickname,email,photoURL",
person:"nickname,photoURL,thumbnailURL,birthDay|0,birthMonth|0,birthYear|0,gender,email,proxiedEmail,country,state,city,zip,firstName,lastName,profileURL,age|0",personwithuid:"person+UID,isSiteUID|false",UserAction:"actorUID,actorNickname,actionName,date|new Date(),targets|[],images|[],actionData1,actionData2,iconURL,title,linkBack,userMessage,description,actionLinks|[],mediaItems|[],subtitle"},createDefaultObject=function(a){var b={};a=defaultObjectsDef[a];-1!=a.indexOf("+")&&(b=createDefaultObject(a.split("+")[0]),
a=a.split("+")[1]);a=a.split(",");for(var g=0;g<a.length;g++){var h="",f=a[g].split("|");if(1<f.length)try{h=gigya.utils.JSON.deserialize(f[1])}catch(e){}b[f[0]]=h||""}return b},_createConstructor=function(a){return function(b){var g=defaultObjects[a],h;for(h in g)this[h]=gigya.utils.object.clone(g[h]);if("object"==typeof b)for(h in b)"function"!=typeof b[h]&&(this[h]=gigya.utils.object.clone(b[h]))}},def;
for(def in defaultObjectsDef)defaultObjects[def]=createDefaultObject(def),gigya.socialize[def]=_createConstructor(def);gigya.socialize.Collection=function(a,b){this.arr=a;this._key=b?b:""};
gigya.socialize.Collection.prototype={asArray:function(){return this.arr},each:function(a){for(var b=0,g=this.arr[b];g;)a(g,b),b++,g=this.arr[b]},getById:function(a){"undefined"==typeof this._hash&&this._buildHash();return(this._hash?this._hash:this.arr)[a]},getSize:function(){return this.arr.length},_buildHash:function(){var a=this._hash={},b=this._key;this.each(function(g,h){a["function"==typeof g[b]?g[b]():g[b]]=g})}};
gigya.socialize.UserAction.prototype={clone:function(){return new gigya.socialize.UserAction(gigya.utils.object.clone(this,!0,!0))},getTemplate:function(){return this.titleTemplate},setTemplate:function(a){this.titleTemplate=a},getActor:function(a){return{UID:this.actorUID,nickname:this.actorNickname}},setActionName:function(a){this.actionName=a;return this},getActionName:function(a){return this.actionName},getTemplateFields:function(){var a=[],b;for(b in this.templateFields)a.push(this.templateFields[b]);
return new gigya.socialize.Collection(a,"fieldName")},setTemplateField:function(a,b,g){this.templateFields[a]={fieldName:a,text:b,href:g};return this},getTemplateField:function(a){return this.templateFields[a]?this.templateFields[a]:null},addTarget:function(a){if("object"==typeof a)return this.targets.push({UID:a.UID,nickname:a.nickname?a.nickname:""}),this;if("string"==typeof a)return this.targets.push({UID:a,nickname:""}),this},addActionLink:function(a,b){this.actionLinks.push({text:a,href:b?b:
""});return this},addMediaItem:function(a){this.mediaItems.push(a);return this},setTitle:function(a){a&&(this.title=a);return this},setLinkBack:function(a){a&&a.toString&&(a=a.toString());a&&(this.linkBack=a);return this},setUserMessage:function(a){this.userMessage=a?a:"";return this},setDescription:function(a){this.description=a?a:"";return this},addImage:function(a,b){this.addMediaItem({type:"image",src:a,href:b})},getImages:function(){return new gigya.socialize.Collection(this.images,"")},getTargets:function(){return new gigya.socialize.Collection(this.targets,
"UID")},setIconURL:function(a){this.iconURL=a;return this},getIconURL:function(){return this.iconURL},getDate:function(){return this.date},setActionData1:function(a){this.actionData1=a;return this},getActionData1:function(a){return this.actionData1},setActionData2:function(a){this.actionData2=a;return this},getActionData2:function(a){return this.actionData2},setSubtitle:function(a){this.subtitle=a;return this},getSubtitle:function(){return this.subtitle}};
(function(a){(function(b){(function(g){function h(a,b){void 0===b&&(b=g.arProviders);for(var c=0;c<b.length;c++)if(b[c].name.toLowerCase()==a.toLowerCase())return b[c]}function f(a){if(null!=a){a=a.split(",");for(var c=0;c<a.length;c++){var e=a[c].replace(/^\s+|\s+$/g,"");b.providers._aliases[e]&&(a[c]=b.providers._aliases[e])}return a.join(",")}}function e(a,b){void 0===b&&(b=g.arProviders);for(var c=0;c<b.length;c++)if(b[c].ID==a)return b[c]}function d(a,b,c){void 0===b&&(b="");void 0===c&&(c=g.arProviders);
b=b.toLowerCase();b=b.split(" ").join("").split(".").join("").toLowerCase().split(",");b=q(b,c);for(c=0;c<b.length;c++)for(var e=0;e<a.length;e++){var d=a[e];(d=d.name||d.toString())&&(d=d.toLowerCase());d==b[c]&&a.splice(e,1)}return a}function c(a,b){null==b&&(b=[]);for(var c=[],e=0;e<a.length;e++){for(var d=a[e],f=!0,g=0;g<b.length;g++){for(var h=!1,l=0;l<d.arDefaultCapabilities.length;l++)if(d.arDefaultCapabilities[l].toLowerCase()==b[g].toLowerCase()){h=!0;break}if(!h){f=!1;break}}f&&c.push(d)}return c}
function l(){return g.arProviders.concat()}function p(b,c){void 0===c&&(c=g.arProviders);b=(""+b).split(" ").join("").split(".").join("").toLowerCase();b=f(b);for(var e=(""+b).split(","),e=q(e,c),d=[],l=0;l<e.length;l++){var k=h(e[l],c);null!=k&&-1==a.utils.array.indexOf(d,k)&&d.push(k)}return d}function q(a,b){b||(b=g.arProviders);for(var c=[],e=0;e<a.length;e++)if("*"==a[e])for(var d=0;d<b.length;d++){for(var f=!1,h=0;h<a.length;h++)a[h].toLowerCase()==b[d].name.toLowerCase()&&(f=!0);f||b[d].explicitOnly||
c.push(b[d].name)}else c.push(a[e]);return c}g._aliases={};var k=function(){function a(b,c,e,d,f,h,l){this.ID=b;this.displayName=c;this.width=e;this.height=d;this.explicitOnly=h;this.aliases=l;this.windowOptions="menubar=0,toolbar=0,resizable=1,scrollbars=1,width="+e+",height="+d;this.arDefaultCapabilities=f.split(",");this.name=c.toLowerCase().split(" ").join("").split("!").join("").split(".").join("").split("+").join("plus");if(l)for(g._aliases||(g._aliases={}),b=l.split("|"),c=0;c<b.length;c++)g._aliases[b[c]]=
this.name;switch(this.name){case "messenger":this.displayName="Microsoft";break;case "customopenid":this.displayName="OpenID";break;case "paypaloauth":this.displayName="PayPal"}}a.prototype.toString=function(){return this.name};return a}();g.Provider=k;g.arProviders=[new k(64,"Facebook",650,400,"login,friends,places,status,actions,photos,offlineaccess,proxiedemail,checkins,facebookactions"),new k(9012,"Twitter",800,440,"login,friends,notifications,actions,status,places,checkins"),new k(72,"Google+",
560,600,"login,friends,contacts",!1,"google|googleplus"),new k(9042,"LinkedIn",865,450,"login,friends,status,actions,notifications"),new k(9803,"Yahoo",500,567,"login,friends,contacts,notifications"),new k(1047,"Messenger",380,540,"login",!1,"messenger|microsoft"),new k(9832,"Instagram",440,420,"login,photos"),new k(9222,"Odnoklassniki",888,425,"login"),new k(9003,"Digg",730,590,"login",!0),new k(9007,"FourSquare",1E3,650,"login,friends,places,checkins"),new k(8191,"Renren",450,350,"login,friends,status,actions"),
new k(8203,"QQ",570,460,"login"),new k(9821,"Sina",640,380,"login,status,actions"),new k(4228,"Mixi",1E3,720,"login,friends,actions,photos",!0),new k(9830,"Yahoo! JAPAN",980,700,"login",!0),new k(8205,"Spiceworks",640,380,"login",!0),new k(8190,"Kaixin",610,510,"login,friends"),new k(9041,"VKontakte",610,510,"login,friends,photos,status,actions"),new k(9800,"AOL",530,720,"login"),new k(4096,"WordPress",700,540,"login"),new k(256,"Blogger",760,400,"login"),new k(16,"LiveJournal",670,360,"login"),new k(1043,
"VeriSign",940,500,"login"),new k(1024,"Typepad",730,590,"login"),new k(4120,"OpenID",730,590,"login"),new k(4218,"Netlog",730,590,"login",!0),new k(4222,"SignOn",870,900,"login",!0),new k(4224,"Orange France",730,590,"login",!0),new k(5002,"Livedoor",970,700,"login",!0),new k(8202,"VZnet",610,510,"login"),new k(9216,"Skyrock",610,510,"login,friends,status",!0),new k(5004,"Fox News",730,590,"login",!0),new k(1051,"PayPal",400,550,"login",!0),new k(9058,"Amazon",785,510,"login",!0),new k(9219,"Xing",
785,510,"login,friends",!0),new k(8206,"WeChat",730,590,"login",!1,"wechat|weixin"),new k(4121,"Custom OpenID",730,590,"login",!0),new k(4122,"Custom SAML",730,590,"login",!0),new k(6002,"Site",730,590,"",!0),new k(1052,"PayPalOAuth",730,590,"login",!0),new k(8207,"Line",730,590,"login")];g.getProviderByName=h;g.replaceProviderAliases=f;g.getProviderById=e;g.hideProvidersByName=d;g.getProvidersForRequiredCapabilities=c;g.getAllProviders=l;g.getProvidersByName=p;g.replaceWildcard=q;a.utils.functions.createAlias("gigya.socialize.getAllProviders",
l);a.utils.functions.createAlias("gigya.socialize.replaceProviderAliases",f);a.utils.functions.createAlias("gigya.socialize.getProvidersByName",p);a.utils.functions.createAlias("gigya.socialize._getProviderByName",h);a.utils.functions.createAlias("gigya.socialize.hideProvidersByName",d);a.utils.functions.createAlias("gigya.socialize._getProviderByID",e);a.utils.functions.createAlias("gigya.socialize.getProvidersForRequiredCapabilities",c)})(b.providers||(b.providers={}))})(a._||(a._={}))})(gigya||
(gigya={}));
(function(a){(function(b){function g(){for(;b.queue&&0<b.queue.length;){var f=a.utils.object.clone(b.queue.splice(0,5),!0,!0);a.gscounters.sendReport({reports:f,noAuth:!h(f)})}}function h(a){for(var b=0;b<a.length;b++){var d=a[b];if("loadc"!==d.name&&"load"!==d.name||"loadc"===d.name&&d.reportData&&d.reportData.actionCounterPath)return!0}return!1}b.queue;b.trackAddressBarShares=function(){if(a.thisScript.globalConf.trackAddressBarShares){var b=a._.apiAdapter.getTokenParam(a.thisScript.APIKey,"UUID"),
e=document.location.href.split("#");1!=e.length&&""!=e[1]||document.location.replace("#guid="+(b?b:"_"))}};b.report=function(f,e,d,c,g,p,q){void 0===p&&(p={});void 0===q&&(q=!1);f=a.utils.object.removeUndefined({name:f,time:(new Date).getTime().toString(),source:c,sourceData:g,reportData:p,cid:d});q?(q=[f],a.gscounters.sendReport({reports:q,noAuth:!h(q)})):(b.queue||(b.queue=[]),b.queue.push(f))};b.init=function(){setInterval(g,5E3)};b.reportLoad=function(a,b){if(!b._reportedLoad){b._reportedLoad=
!0;var d="load";"gigya.socialize.plugins.reactions.showReactionsBarUI"!=a&&("gigya.socialize.plugins.simpleshare.showSimpleShareUI"==a&&(d="loadSimple"),this.report(d,b.APIKey,b.cid,b.source,b.sourceData))}}})(a.reports||(a.reports={}))})(gigya||(gigya={}));
(function(a){(function(b){var g=function(){function g(b,e){void 0===e&&(e=!0);this.params=b;this._logger=a.log;this._eventDispatcher=function(b,e){return a.events.dispatchForWidget(b,e)};this._errorDispatcher=a.events;this._globalEventsManager=a.events.global;this._isDisposed=!1;this._eventWrappers={};this._globalEventHandlers={};this._id=++g.instanceCounter;this.params=b?a.utils.object.clone(b):{};e&&this.validateParams();for(var d in b)this[d]&&(this[d]=b[d])}g.prototype.onErrorEvent=function(){return this.getEvent("onError")};
g.prototype.onDisposedEvent=function(){return this.getEvent("onDisposed")};g.prototype.getType=function(){return this.constructor.name||this.getFunctionName(this.constructor)};g.prototype.getFunctionName=function(a){a=a.toString();a=a.substr(9);return a=a.substr(0,a.indexOf("("))};g.prototype.getConfig=function(){this.error(g.NOT_IMPLEMENTED_ERROR,400096);return{}};g.prototype.toString=function(){return this.getType()+" "+this.id()};g.prototype.id=function(){return this._id};g.prototype.warn=function(a,
b){var d=this.id()+" "+this.getType()+" - "+a;this._logger.addLog(d,b,!0)};g.prototype.error=function(a,b,d){void 0===b&&(b=300001);b={errorMessage:a,errorCode:b,errorDetails:this.id(),info:d};this.warn(a,b);this.dispatchEvent("error",b)};g.prototype.validateParams=function(b){b||(b=this.getConfig().requiredParams||[]);this.getConfig().defaultParams&&(this.params=a.utils.object.merge([this.getConfig().defaultParams,this.params]));var e=[];if(0<b.length)for(var d in b)if(b.hasOwnProperty(d)){var c=
b[d];this.params[c]||e.push(c)}return 0<e.length?(this.dispatchInvalidParamError(e[0]),!1):!0};g.prototype.dispatchEvent=function(a,b){void 0===b&&(b={});b.eventName=a;return this._eventDispatcher(b,this.params)};g.prototype.dispatchErrorFromResponse=function(a){this._errorDispatcher.dispatchErrorFromResponse(this.params,a)};g.prototype.dispatchInvalidParamError=function(a){this._errorDispatcher.dispatchInvalidParamError(this.params,a)};g.prototype.getEvent=function(a){this._eventWrappers[a]||(this.params[a]?
this.params[a]instanceof Array||(this.params[a]=[this.params[a]]):this.params[a]=[],this._eventWrappers[a]=new b.EventWrapper(this.params[a]));return this._eventWrappers[a]};g.prototype.addGlobalEventHandlers=function(a){for(var b in a)a.hasOwnProperty(b)&&this.addGlobalEventHandler(b,a[b])};g.prototype.addGlobalEventHandler=function(a,b,d,c){void 0===d&&(d=null);void 0===c&&(c="socialize");this._globalEventHandlers[a]||(this._globalEventHandlers[a]=[]);b=this._globalEventsManager.add(a,b,"component",
d,c,this.params);this._globalEventHandlers[a].push(b)};g.prototype.removeGlobalEventHandlers=function(a){for(var b in a)a.hasOwnProperty(b)&&this.removeGlobalEventHandler(b,a[b])};g.prototype.removeGlobalEventHandler=function(b,e,d,c){void 0===d&&(d=null);void 0===c&&(c="socialize");if(b=this._globalEventHandlers[b])d=a.utils.array.firstIndex(b,function(a){return a.handler==e}),-1<d&&(c=b[d],this._globalEventsManager.remove(c.fullEventName,c),b.splice(d,1))};g.prototype.prepareCallback=function(a){var b=
this;return function(){for(var d=[],c=0;c<arguments.length;c++)d[c-0]=arguments[c];if(!b._isDisposed)return a.apply(this,d)}};g.prototype.dispose=function(){for(var a in this._globalEventHandlers)for(var b in this._globalEventHandlers[a]){var d=this._globalEventHandlers[a][b];this._globalEventsManager.remove(d.fullEventName,d)}this._globalEventHandlers={};this._eventWrappers={};this.params={};this._isDisposed=!0};g.instanceCounter=0;g.NOT_IMPLEMENTED_ERROR="Abstract method not implemented";return g}();
b.BaseObject=g})(a._||(a._={}))})(gigya||(gigya={}));(function(a){a=a._||(a._={});a=a.DeviceTypes||(a.DeviceTypes={});a[a._undefined=0]="_undefined";a[a.desktop=1]="desktop";a[a.mobile=2]="mobile";a[a.auto=3]="auto"})(gigya||(gigya={}));
(function(a){(function(a){var g=function(){function a(b){void 0===b&&(b=[]);this._handlers=b}a.prototype.add=function(a){this._handlers.push(a)};a.prototype.remove=function(a){a=this._handlers.indexOf(a);-1<a&&this._handlers.splice(a,1)};return a}();a.EventWrapper=g})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){a.build||(a.build={version:"",time:""});a.providersConfig||(a.providersConfig={});a.isGigya||(a.isGigya=!0);a.partnerSettings||(a.partnerSettings={authMode:"cookie",baseDomains:"",plugins:{apiDomain:"us1.gigya.com"}});a.thisScript;var b;(function(a){a.autoLoginInProgress})(b=a._||(a._={}));var g;(function(g){function f(){if(a.abTesting)for(var b in a.abTesting)if("optimizely"===b){var c=a.abTesting[b];if(c.serviceParams&&c.serviceParams.hasOwnProperty("apiKey")){var d=window.location.pathname,
e=!1;if(c.disabledPaths)for(var f=0;f<c.disabledPaths.length;f++)if(-1<c.disabledPaths[f].indexOf(d)){e=!0;break}if(!e)for(f=0;f<c.enabledPaths.length;f++)-1<d.indexOf(c.enabledPaths[f])&&a.utils.script.load("//cdn.optimizely.com/js/"+c.serviceParams.apiKey+".js")}}}function e(){function b(d){var e=c[d];c[d]=function(){for(var b=[],f=0;f<arguments.length;f++)b[f-0]=arguments[f];b=Array.prototype.slice.apply(b);f=b[0];f="object"===typeof f&&null!=f&&f.hasOwnProperty("message")?f:{message:f};a.log.addLog(d,
f,!1);e&&(e.apply?e.apply(c,b):e(b.join(" ")))}}var c=window.console;c||(c={});var d=a.utils.array.getArrayFromString(a.thisScript.globalConf.consoleLogLevel,",");if(0!=d.length){var e=a.log.CONSOLE_LOG_LEVELS;-1==a.utils.array.indexOf(d,"*")&&(e=a.utils.array.intersect(d,e));a.log.selectedConsoleLogLevels=e;a.utils.array.forEach(e,function(a){return b(a)})}}function d(b){"1"==a.utils.cookie.get("gig_debug")?a.socialize.showDebugUI({ignoreApiQueue:!0,waitForDebug:!1,onLoad:b}):b()}function c(){a.utils.functions.invokeOnPageLoad(function(){"undefined"!=
typeof window.gigya_omniture_conf&&a.utils.script.load(a._.getCdnResource("/js/GenesisExchange_Gigya.min.js"))})}function l(a){a||(a="en-US");a=a.replace("_","-").toLowerCase();var b=a.split("-"),c=b[0],b=1<b.length?b[1]:c,b=b.toUpperCase();switch(a){case "es-mx":b="ES";break;case "pt-br":case "zh-cn":case "zh-hk":case "zh-tw":case "te-st":case "fr-inf":case "de-inf":case "es-inf":case "nl-inf":break;default:a=c}return{full:c+"-"+b,langCode:a,countryCode:b}}function p(b){for(var c=document.getElementsByTagName("script"),
d,e=c.length-1;0<=e;e--){var f=c[e],g=f.src.toLowerCase();if(""!=g&&(-1<g.indexOf("//cdn.gigya.com")||-1<g.indexOf("//cdns.gigya.com")||-1<g.indexOf("?apikey="))&&(-1<g.indexOf("gigya.js")||-1<g.indexOf("socialize.js")||-1<g.indexOf("socialize2.js")||-1<g.indexOf("gsjssdk.js"))){d=f;break}}if(d&&!window.__gig_hidescript){var c=d.src.split("/"),e=a.utils.URL.getParamsFromURL(d.src,!0)||{},h;if(""!=d.innerHTML.replace(/^\s+|\s+$/g,""))try{h=a.utils.JSON.deserialize(d.innerHTML),"object"!=typeof h&&
(h={})}catch(k){alert("Gigya global configuration object parse error")}a.thisScript={scriptElement:d,protocol:a.localInfo.protocol,baseDomain:c[2],APIKey:e.apikey,lang:l(e.lang||(h?h.lang:null)),globalConf:a.utils.object.merge([a.partnerSettings.plugins||{},h||{},window.__gigyaConf||{}]),URLParams:e};!a.thisScript.APIKey&&"object"==typeof console&&console.warn?console.warn("**** WARNING - Loading socialize.js without an APIKey parameter is unsupported and may result in an unexpected behavior. ****"):
a.thisScript.globalConf.APIKey=a.thisScript.APIKey;a.thisScript.globalConf.lang=a.thisScript.lang.langCode;b()}else 10>n?(n++,window.setTimeout(function(){p(b)},200)):(a.thisScript={scriptElement:null,protocol:a.localInfo.protocol,baseDomain:"https"==a.localInfo.protocol?"https://cdns.gigya.com":"http://cdn.gigya.com",APIKey:"",lang:l(""),globalConf:{},URLParams:{}},b())}function q(c){var f="web",g=window.__gigAPIAdapterSettings,h=a.localInfo.supportsLocalStorage,l="__gigAPIAdapterSettings_"+a.thisScript.APIKey+
"_"+a.build.version;if(g&&"mobile"==g.getAdapterName()&&g.getAPIKey()==a.thisScript.APIKey)f="mobile",h&&(h={apiKey:g.getAPIKey?g.getAPIKey():null,adapterName:g.getAdapterName?g.getAdapterName():null,features:g.getFeatures?g.getFeatures():null,settings:g.getSettings?g.getSettings():null},a.utils.localStorage.setItem(l,a.utils.JSON.serialize(h)));else if(h){var k=a.utils.JSON.deserialize(a.utils.localStorage.getItem(l));k&&"mobile"==k.adapterName&&(f="mobile",g={},k.apiKey&&(g.getAPIKey=function(){return k.apiKey}),
k.adapterName&&(g.getAdapterName=function(){return k.adapterName}),k.features&&(g.getFeatures=function(){return k.features}),k.settings&&(g.getSettings=function(){return k.settings}))}b.apiAdapter=b.apiAdapters[f].newApiAdapter(g);a.utils.functions.createAlias("gigya.auth.loginToken.getTokenParam",b.apiAdapter.getTokenParam);e();d(function(){b.apiAdapter.init(c)})}function k(){var c=a.utils.URL.getParamsFromURL(document.location.href);c.errorCode&&c.regToken&&b.checkCompleteRegistration(c,a.thisScript.globalConf,
function(){})}function m(){var c=a.localInfo,d;c.isIE11&&!window.indexedDB?(d=b.MessagingMethod.Flash,a.thisScript.globalConf.legacyCrossSiteMethod="localConnection"):d=c.isIOSChrome?b.MessagingMethod.LocalStorageListener:c.supportsPostMessage?b.MessagingMethod.PostMessage:b.MessagingMethod.Flash;c.messagingMethod=d}function r(){a.utils.queue.queueForExecution("API",function(){a.utils.functions.invokeOnPageLoad(function(){a.providersConfig.facebook&&a.external.facebook.load(!1);a.providersConfig.googlePlus&&
a.external.googlePlus.load()})})}var n=0;(function(){if(window._isAPIProxy)b.apiAdapters.web.APIProxy.init();else{a.utils.queue.hold("bootstrap","API");a.partnerSettings.baseDomain=a._.getPageBaseDomain()||document.location.hostname;a.partnerSettings.plugins.originalApiDomain=a.partnerSettings.plugins.apiDomain;var d=a.partnerSettings.plugins,e;e=a.partnerSettings.customAPIDomainPrefix?a.partnerSettings.customAPIDomainPrefix+"."+a.partnerSettings.baseDomain:a.partnerSettings.plugins.apiDomain;d.apiDomain=
e;(a.localInfo.isIE6||a.localInfo.isIE7||a.localInfo.isIE8)&&"undefined"!=typeof console&&"undefined"!=typeof console.log&&console.log("Gigya: It looks like you're using an old version of Internet Explorer. This browser is not supported. Please upgrade to a newer version of IE.");a.reports.init();p(function(){m();a.thisScript.globalConf.customEventMap&&a.events.addMap(a.thisScript.globalConf.customEventMap);q(function(){a.utils.queue.release("bootstrap","API");r();a._.chat.init();a.thisScript.globalConf.autoLogin&&
(a.external.facebook.autoLogin(),a.external.googlePlus.autoLogin());k();a.reports.trackAddressBarShares();a.utils.functions.invokeOnPageLoad(function(){return window.setTimeout(a.socialize.trackReferrals,1E3)})});c();f();"function"==typeof onGigyaServiceReady&&onGigyaServiceReady("socialize");var b={sref:document.referrer};a.thisScript.globalConf.actionCounterPath&&(b.actionCounterPath=a.thisScript.globalConf.actionCounterPath);a.reports.report("loadc",a.thisScript.APIKey,null,null,null,b)})}})()})(g||
(g={}))})(gigya||(gigya={}));
} else if (typeof console == 'object' && console.warn) {
console.warn('**** Socialize.js loaded twice ****');
}
| HuVas/HuVas.github.io | testClar/Clarin2_files/socialize.js | JavaScript | mit | 163,917 |
// Read the Docs
// http://readthedocs.org/
// Searching as the user types.
(function(){
// Save a reference to the global object.
var root = this;
// Global Search object on which public functions can be added
var Search;
Search = root.Search = {};
// for instituting a delay between keypresses and searches
var timer = null;
var delay = 250;
var lastQuery = null;
var useApi = false;
// Check if the browser supports history manipulation so
// we can change the URL upon instant searches
var replaceStateSupported = (typeof history.replaceState === "function");
// queue of current requests
var xhr = [];
var $input, $button, $results, $title, $selected_facets = null;
function init() {
$input = $('#id_site_search_2');
$button = $('#id_search_button');
$results = $("#id_search_result");
$title = $("#id_search_title");
$selected_facets = $("#id_selected_facets");
// minimum requirements for this script to kick in...
if(!$input.length || !$results.length) {
return false;
} else {
lastQuery = queryString()
bind();
}
}
Search.init = init;
// Setup the bindings for clicking search or keypresses
function bind() {
// Set a delay so not _every_ keystroke sends a search
$input.keyup(function(ev) {
// Don't do anything unless the query has changed
if(lastQuery == queryString()) {
return;
}
if(timer) {
clearTimeout(timer);
}
timer = setTimeout("Search.run()", delay);
});
$button.click(Search.run);
}
// Abort all existing XHR requests, since a new search is starting
function abortCurrentXHR() {
var request = xhr.pop();
while(request) {
request.abort();
request = xhr.pop();
}
}
// Replace the search results HTML with `html` (string)
function replaceResults(html) {
$results.empty();
$results.append(html);
$title.html(getTitle());
$results.show();
}
// Construct the results HTML
// TODO: Use a template!
function buildHTML(results) {
var html = [];
for (var i=0; i<results.length; i++) {
html.push([
'<li class="module-item">',
'<p class="module-item-title">',
'File: <a href="', results[i].absolute_url,
'?highlight=', $("#id_site_search_2").val(), '">',
results[i].project.name,
" - ", results[i].name, "</a>",
"</p>",
"<p>", results[i].text, "</p>",
"</li>"].join('')
);
}
return html.join('');
}
// Pop the last search off the queue and render the `results`
function onResultsReceived(results) {
// remove the request from the queue
xhr.pop();
lastQuery = queryString()
replaceResults(buildHTML(results));
replaceState();
$("#id_remove_facets").attr('href', removeFacetsUrl());
}
// Replace the URL with the one corresponding to the current search
function replaceState() {
if(!replaceStateSupported) {
return;
}
var url = "/search/project/?" + queryString();
var title = getTitle() + ' | Read the Docs';
window.history.replaceState({}, title, url);
}
// Page title
function getTitle() {
return "Results for " + $("#id_site_search_2").val();
}
// Params used in the search
function getSearchData() {
var data = {
q: getKeywords(),
}
var selected_facets = $selected_facets.val() || ''
if(selected_facets) {
data['selected_facets'] = selected_facets;
}
return data;
}
// e.g. q=my+search&selected_facets=project_exact:Read%20The%20Docs
function queryString() {
return jQuery.param(getSearchData());
}
// The active query value
function getKeywords() {
return $input.val()
}
// Url for the current query with any facet filters removed
function removeFacetsUrl() {
return '?' + jQuery.param({q: getKeywords()});
}
// Perform the ajax request to get the search results from the API
function run(ev) {
if(ev) {
ev.preventDefault();
}
abortCurrentXHR();
// Don't do anything if there is no query
if(getKeywords() == '') {
$results.empty();
$results.hide();
$title.html("No search term entered");
return;
}
var data = getSearchData();
if(useApi) {
apiSearch(data);
} else {
htmlSearch(data);
}
}
Search.run = run;
// TODO: The api search is incomplete. It doesn't take into account
// facets nor pagination. It's a partial implemenation.
function apiSearch(data) {
xhr.push(jQuery.ajax({
type: 'GET',
url: "/api/v1/file/search/",
data: data,
dataType: 'jsonp',
success: function(res, text, xhqr) {
onResultsReceived(res.objects);
}
}));
}
// Alternative search implementation not using the API.
function htmlSearch(data) {
xhr.push(jQuery.ajax({
type: 'GET',
url: "/search/project/",
data: data,
success: function(res, text, xhqr) {
onHtmlReceived(res);
}
}));
}
// Alternative implementation not using the API. Receives
// the full HTML including title, pagination, facets, etc.
function onHtmlReceived(html) {
xhr.pop(); // remove the request from the queue
lastQuery = queryString()
$("#search_module").replaceWith(html);
replaceState();
}
}).call(this);
| johncosta/private-readthedocs.org | media/javascript/instantsearch.js | JavaScript | mit | 5,472 |
import * as types from './actionTypes';
export function addNote(newNote) {
return { type: types.ADD_NOTE, newNote };
}
export function deleteNote(id) {
return { type: types.DELETE_NOTE, id };
}
export function updateNote(updatedNote) {
return { type: types.UPDATE_NOTE, updatedNote };
}
export function getNotes(notes) {
return { type: types.GET_NOTES, notes };
}
export function selectNote(id) {
return { type: types.SELECT_NOTE, id };
}
export function login(userEmail, accessToken) {
return { type: types.LOGIN, userEmail, accessToken };
}
export function logout() {
return { type: types.LOGOUT };
}
export function saveAccessToken(userEmail, accessToken) {
return { type: types.SAVE_ACCESS_TOKEN, userEmail, accessToken };
}
export function authFail(userEmail) {
return { type: types.AUTH_FAIL, userEmail };
}
| carlegbert/wholenote | client/app/actions/actions.js | JavaScript | mit | 842 |
(function (module) {
'use strict';
module.service("Dialog", dialogService);
module.constant("dialogMap", dialogMap());
function dialogMap() {
return {
'product-details': {
controller: 'ProductDetailsController',
templateUrl: '/views/widgets/product-details.html'
},
'category-details': {
controller: 'CategoryDetailsController',
templateUrl: '/views/widgets/category-details.html'
}
};
}
dialogService.$inject = ['$rootScope', '$modal', 'dialogMap'];
function dialogService($rootScope, $modal, dialogMap) {
return {
open: function (id, data, options) {
var dialogContext = dialogMap[id];
var scope = ng.extend($rootScope.$new(), {options: options});
return $modal.open({
templateUrl: dialogContext.templateUrl,
controller: dialogContext.controller,
scope: scope,
resolve: {
data: function () {
return ng.copy(data);
}
}
}).result;
}
};
}
})(ng.module('korann.modal', [])); | VanDalkvist/korann.admin | public/js/app/modules/dialog.module.js | JavaScript | mit | 1,317 |
"use strict";
const ID = require("./ID.js");
class Finger{
constructor(node, index){
this.node = node;
this.start = node.id.add(ID.powerOfTwoBuffer(index));
}
}
module.exports = Finger; | FelixMcFelix/conductor-chord | src/Finger.js | JavaScript | mit | 194 |
var $$ = React.createElement;
var Substance = require("substance");
var Scrollbar = require("./scrollbar");
var _ = require("substance/helpers");
var PanelMixin = require("./panel_mixin");
var ContentPanelMixin = _.extend({}, PanelMixin, {
contextTypes: {
app: React.PropTypes.object.isRequired,
componentFactory: React.PropTypes.object.isRequired,
},
// Since component gets rendered multiple times we need to update
// the scrollbar and reattach the scroll event
componentDidMount: function() {
var app = this.context.app;
this.updateScrollbar();
$(window).on('resize', this.updateScrollbar);
var doc = app.doc;
doc.connect(this, {
'document:changed': this.onDocumentChange
});
},
componentWillUnmount: function() {
var app = this.context.app
var doc = app.doc;
doc.disconnect(this);
$(window).off('resize');
},
onDocumentChange: function() {
setTimeout(function() {
this.updateScrollbar();
}.bind(this), 0);
},
componentDidUpdate: function() {
this.updateScrollbar();
},
updateScrollbar: function() {
var scrollbar = this.refs.scrollbar;
var panelContentEl = this.refs.panelContent.getDOMNode();
// We need to await next repaint, otherwise dimensions will be wrong
Substance.delay(function() {
scrollbar.update(panelContentEl);
},0);
// (Re)-Bind scroll event on new panelContentEl
$(panelContentEl).off('scroll');
$(panelContentEl).on('scroll', this._onScroll);
},
_onScroll: function(e) {
var panelContentEl = this.refs.panelContent.getDOMNode();
this.refs.scrollbar.update(panelContentEl);
},
// Rendering
// -----------------
getContentEditor: function() {
var app = this.context.app;
var doc = app.doc;
var componentFactory = this.context.componentFactory;
var ContainerClass = componentFactory.get("container");
return $$(ContainerClass, {
doc: doc,
node: doc.get("content"),
ref: "contentEditor"
});
},
render: function() {
var app = this.context.app;
return $$("div", {className: "panel content-panel-component"}, // usually absolutely positioned
$$(Scrollbar, {
id: "content-scrollbar",
contextId: app.state.contextId,
highlights: app.getHighlightedNodes.bind(app),
ref: "scrollbar"
}),
$$('div', {className: "panel-content", ref: "panelContent"}, // requires absolute positioning, overflow=auto
this.getContentEditor()
)
);
}
});
var ContentPanel = React.createClass({
mixins: [ContentPanelMixin],
displayName: "ContentPanel",
});
module.exports = ContentPanel; | substance/archivist-composer | src/writer/content_panel.js | JavaScript | mit | 2,680 |
'use strict';
/* jshint maxstatements: 30 */
var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var bitcore = require('..');
var PublicKey = bitcore.PublicKey;
var Address = bitcore.Address;
var Script = bitcore.Script;
var Networks = bitcore.Networks;
var validbase58 = require('./data/bitcoind/base58_keys_valid.json');
var invalidbase58 = require('./data/bitcoind/base58_keys_invalid.json');
describe('Address', function() {
var pubkeyhash = Buffer.from('4a0529a63fcc33e4f51688311b89b97371b5c76c', 'hex');
var buf = Buffer.concat([Buffer.from([30]), pubkeyhash]);
var str = 'DBtUjAUFWHqS1y8CgetQtPW6YKDhffyFT4';
it('can\'t build without data', function() {
(function() {
return new Address();
}).should.throw('First argument is required, please include address data.');
});
it('should throw an error because of bad network param', function() {
(function() {
return new Address(PKHLivenet[0], 'main', 'pubkeyhash');
}).should.throw('Second argument must be "livenet" or "testnet".');
});
it('should throw an error because of bad type param', function() {
(function() {
return new Address(PKHLivenet[0], 'livenet', 'pubkey');
}).should.throw('Third argument must be "pubkeyhash" or "scripthash"');
});
describe('bitcoind compliance', function() {
validbase58.map(function(d) {
if (!d[2].isPrivkey) {
it('should describe address ' + d[0] + ' as valid', function() {
var type;
if (d[2].addrType === 'script') {
type = 'scripthash';
} else if (d[2].addrType === 'pubkey') {
type = 'pubkeyhash';
}
var network = 'livenet';
if (d[2].isTestnet) {
network = 'testnet';
}
return new Address(d[0], network, type);
});
}
});
invalidbase58.map(function(d) {
it('should describe input ' + d[0].slice(0, 10) + '... as invalid', function() {
expect(function() {
return new Address(d[0]);
}).to.throw(Error);
});
});
});
// livenet valid
var PKHLivenet = [
'D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC',
'DGYdw7jC17b9SappjsrAsaghhDTS8sV5Mx',
'DExWunrSkF2P9NAzW4JpEeC38uC3z36cCk',
'DMYFDsuFamS4kogsiqxQRXK9diCfmJzNLh',
' DQJXChtyuN3aiU3W6pG4mgnykisHH5hqst \t\n'
];
// livenet p2sh
var P2SHLivenet = [
'A7HRQk3GFCW2QasvdZxXuYj8kkQK5QrYLs',
'A3RHoAQLPDSuBewbuvt5NMqEKasqs9ty3C',
'A3YUuiZjn3FzW2i6KqFVgHaN5r5fjvwEJ1',
'AFVkW8WgPP2rsTdAeyogFK9k8gXJ1LZwrb',
'A2CUbyEtqGUjngAjxpGmM5Nwhrz72gh23v',
'\t \AD21pKoCWcrqrUW4oRv5xUaGwCfXhiyx6y \r'
];
// testnet p2sh
var P2SHTestnet = [
'2MsvyG12kxxipe276Au4zKqvd2xdrBuHWb3',
'2MvY1BBau2C6jRC1hNX5LmviLrpvVG386TM',
'2N22vuiMGhfqD77vPqsXPiALBfn6oUTtFtH',
'2N1Gz97rN7P6VCj9xf64wWFqQZgpUng1mM3'
];
//livenet bad checksums
var badChecksums = [
'461QQ2sYWxU7H2PV4oBwJGNch8XVTYYbZxU',
'461QQ2sYWxASd2PV4oBwJGNch8XVTYYbZxU',
'DRjyUS2uuieEPkhZNdQz8hE5YycxVEqSXA', ///////
];
//livenet non-base58
var nonBase58 = [
'15vkcKf7g#23wLAnZLmb$uMiiVDc3nq4a2',
'1A601ttWnUq1SEQLMr4ttDh24wcbj4w2TT',
'1BpbpfLdY7oBS9gK7aIXgvMgr1DpvNH3B2',
'1Jz2yCRdOST1p2gUqFB5wsSQfdmEJaffg7'
];
//testnet valid
var PKHTestnet = [
'ngbSgr1dhCqsLg6Z5tpsaCspwrH72x2Zk3',
'ngao4q8auS6YuDKYPkzjt7zKYYT8LzkGZS',
'nbo7vyCuiMxiYW4thwwuaTHQdCoqinmzJz',
'nagGnGDKWYpvnphf9rgo3xtQhAxiEM1QGD'
];
describe('validation', function() {
it('getValidationError detects network mismatchs', function() {
var error = Address.getValidationError('D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC', 'testnet');
should.exist(error);
});
it('isValid returns true on a valid address', function() {
var valid = Address.isValid('D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC', 'livenet');
valid.should.equal(true);
});
it('isValid returns false on network mismatch', function() {
var valid = Address.isValid('D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC', 'testnet');
valid.should.equal(false);
});
it('validates correctly the P2PKH test vector', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i]);
should.not.exist(error);
}
});
it('validates correctly the P2SH test vector', function() {
for (var i = 0; i < P2SHLivenet.length; i++) {
var error = Address.getValidationError(P2SHLivenet[i]);
should.not.exist(error);
}
});
it('validates correctly the P2SH testnet test vector', function() {
for (var i = 0; i < P2SHTestnet.length; i++) {
var error = Address.getValidationError(P2SHTestnet[i], 'testnet');
should.not.exist(error);
}
});
it('rejects correctly the P2PKH livenet test vector with "testnet" parameter', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i], 'testnet');
should.exist(error);
}
});
it('validates correctly the P2PKH livenet test vector with "livenet" parameter', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i], 'livenet');
should.not.exist(error);
}
});
it('should not validate if checksum is invalid', function() {
for (var i = 0; i < badChecksums.length; i++) {
var error = Address.getValidationError(badChecksums[i], 'livenet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Checksum mismatch');
}
});
it('should not validate on a network mismatch', function() {
var error, i;
for (i = 0; i < PKHLivenet.length; i++) {
error = Address.getValidationError(PKHLivenet[i], 'testnet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Address has mismatched network type.');
}
for (i = 0; i < PKHTestnet.length; i++) {
error = Address.getValidationError(PKHTestnet[i], 'livenet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Address has mismatched network type.');
}
});
it('should not validate on a type mismatch', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i], 'livenet', 'scripthash');
should.exist(error);
error.message.should.equal('Address has mismatched type.');
}
});
it('should not validate on non-base58 characters', function() {
for (var i = 0; i < nonBase58.length; i++) {
var error = Address.getValidationError(nonBase58[i], 'livenet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Non-base58 character');
}
});
it('testnet addresses are validated correctly', function() {
for (var i = 0; i < PKHTestnet.length; i++) {
var error = Address.getValidationError(PKHTestnet[i], 'testnet');
should.not.exist(error);
}
});
it('addresses with whitespace are validated correctly', function() {
var ws = ' \r \t \n DD4KSSuBJqcjuTcvUg1CgUKeurPUFeEZkE \t \n \r';
var error = Address.getValidationError(ws);
should.not.exist(error);
Address.fromString(ws).toString().should.equal('DD4KSSuBJqcjuTcvUg1CgUKeurPUFeEZkE');
});
});
describe('instantiation', function() {
it('can be instantiated from another address', function() {
var address = Address.fromBuffer(buf);
var address2 = new Address({
hashBuffer: address.hashBuffer,
network: address.network,
type: address.type
});
address.toString().should.equal(address2.toString());
});
});
describe('encodings', function() {
it('should make an address from a buffer', function() {
Address.fromBuffer(buf).toString().should.equal(str);
new Address(buf).toString().should.equal(str);
new Address(buf).toString().should.equal(str);
});
it('should make an address from a string', function() {
Address.fromString(str).toString().should.equal(str);
new Address(str).toString().should.equal(str);
});
it('should make an address using a non-string network', function() {
Address.fromString(str, Networks.livenet).toString().should.equal(str);
});
it('should error because of unrecognized data format', function() {
(function() {
return new Address(new Error());
}).should.throw(bitcore.errors.InvalidArgument);
});
it('should error because of incorrect format for pubkey hash', function() {
(function() {
return new Address.fromPublicKeyHash('notahash');
}).should.throw('Address supplied is not a buffer.');
});
it('should error because of incorrect format for script hash', function() {
(function() {
return new Address.fromScriptHash('notascript');
}).should.throw('Address supplied is not a buffer.');
});
it('should error because of incorrect type for transform buffer', function() {
(function() {
return Address._transformBuffer('notabuffer');
}).should.throw('Address supplied is not a buffer.');
});
it('should error because of incorrect length buffer for transform buffer', function() {
(function() {
return Address._transformBuffer(new Buffer(20));
}).should.throw('Address buffers must be exactly 21 bytes.');
});
it('should error because of incorrect type for pubkey transform', function() {
(function() {
return Address._transformPublicKey(new Buffer(20));
}).should.throw('Address must be an instance of PublicKey.');
});
it('should error because of incorrect type for script transform', function() {
(function() {
return Address._transformScript(new Buffer(20));
}).should.throw('Invalid Argument: script must be a Script instance');
});
it('should error because of incorrect type for string transform', function() {
(function() {
return Address._transformString(new Buffer(20));
}).should.throw('data parameter supplied is not a string.');
});
it('should make an address from a pubkey hash buffer', function() {
var hash = pubkeyhash; //use the same hash
var a = Address.fromPublicKeyHash(hash, 'livenet');
a.network.should.equal(Networks.livenet);
a.toString().should.equal(str);
var b = Address.fromPublicKeyHash(hash, 'testnet');
b.network.should.equal(Networks.testnet);
b.type.should.equal('pubkeyhash');
new Address(hash, 'livenet').toString().should.equal(str);
});
it('should make an address using the default network', function() {
var hash = pubkeyhash; //use the same hash
var network = Networks.defaultNetwork;
Networks.defaultNetwork = Networks.livenet;
var a = Address.fromPublicKeyHash(hash);
a.network.should.equal(Networks.livenet);
// change the default
Networks.defaultNetwork = Networks.testnet;
var b = Address.fromPublicKeyHash(hash);
b.network.should.equal(Networks.testnet);
// restore the default
Networks.defaultNetwork = network;
});
it('should throw an error for invalid length hashBuffer', function() {
(function() {
return Address.fromPublicKeyHash(buf);
}).should.throw('Address hashbuffers must be exactly 20 bytes.');
});
it('should make this address from a compressed pubkey', function() {
var pubkey = new PublicKey('02789418bb8aee5a63471c09d3402b9d06a1c3d7975635a4a5258e89dff3547079');
var address = Address.fromPublicKey(pubkey, 'livenet');
address.toString().should.equal('DKLLdArnsyhkuPhxDbWYEBgLpQDLerRNrZ');
});
it('should use the default network for pubkey', function() {
var pubkey = new PublicKey('02789418bb8aee5a63471c09d3402b9d06a1c3d7975635a4a5258e89dff3547079');
var address = Address.fromPublicKey(pubkey);
address.network.should.equal(Networks.defaultNetwork);
});
it('should make this address from an uncompressed pubkey', function() {
var pubkey = new PublicKey('0450A38BD7F0AC212FEBA77354A9B036A32E0F7C81FC4E0C5ADCA7C549C4505D2522458C2D9AE3CEFD684E039194B72C8A10F9CB9D4764AB26FCC2718D421D3B84');
var a = Address.fromPublicKey(pubkey, 'livenet');
a.toString().should.equal('DFJ1z7FVd8CEodkQ41w54bmCDYhrNd24Dv');
var b = new Address(pubkey, 'livenet', 'pubkeyhash');
b.toString().should.equal('DFJ1z7FVd8CEodkQ41w54bmCDYhrNd24Dv');
});
it('should classify from a custom network', function() {
var custom = {
name: 'customnetwork',
pubkeyhash: 0x1c,
privatekey: 0x1e,
scripthash: 0x28,
xpubkey: 0x02e8de8f,
xprivkey: 0x02e8da54,
networkMagic: 0x0c110907,
port: 7333
};
var addressString = 'CX4WePxBwq1Y6u7VyMJfmmitE7GiTgC9aE';
Networks.add(custom);
var network = Networks.get('customnetwork');
var address = Address.fromString(addressString);
address.type.should.equal(Address.PayToPublicKeyHash);
address.network.should.equal(network);
Networks.remove(network);
});
describe('from a script', function() {
it('should fail to build address from a non p2sh,p2pkh script', function() {
var s = new Script('OP_CHECKMULTISIG');
(function() {
return new Address(s);
}).should.throw('needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out');
});
it('should make this address from a p2pkh output script', function() {
var s = new Script('OP_DUP OP_HASH160 20 ' +
'0xc8e11b0eb0d2ad5362d894f048908341fa61b6e1 OP_EQUALVERIFY OP_CHECKSIG');
var buf = s.toBuffer();
var a = Address.fromScript(s, 'livenet');
a.toString().should.equal('DPTFMF1EYh2tYtGwWJgFqLy37QgLdSSDQW');
var b = new Address(s, 'livenet');
b.toString().should.equal('DPTFMF1EYh2tYtGwWJgFqLy37QgLdSSDQW');
});
it('should make this address from a p2sh input script', function() {
var s = Script.fromString('OP_HASH160 20 0xa6ed4af315271e657ee307828f54a4365fa5d20f OP_EQUAL');
var a = Address.fromScript(s, 'livenet');
a.toString().should.equal('A7eu6dAkyaNZJpjXwSqgUipxxvKTTjJKzY');
var b = new Address(s, 'livenet');
b.toString().should.equal('A7eu6dAkyaNZJpjXwSqgUipxxvKTTjJKzY');
});
it('returns the same address if the script is a pay to public key hash out', function() {
var address = 'D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC';
var script = Script.buildPublicKeyHashOut(new Address(address));
console.log(script);
Address(script, Networks.livenet).toString().should.equal(address);
});
it('returns the same address if the script is a pay to script hash out', function() {
var address = 'A7eu6dAkyaNZJpjXwSqgUipxxvKTTjJKzY';
var script = Script.buildScriptHashOut(new Address(address));
Address(script, Networks.livenet).toString().should.equal(address);
});
});
it('should derive from this known address string livenet', function() {
var address = new Address(str);
var buffer = address.toBuffer();
var slice = buffer.slice(1);
var sliceString = slice.toString('hex');
sliceString.should.equal(pubkeyhash.toString('hex'));
});
it('should derive from this known address string testnet', function() {
var a = new Address(PKHTestnet[0], 'testnet');
var b = new Address(a.toString());
b.toString().should.equal(PKHTestnet[0]);
b.network.should.equal(Networks.testnet);
});
it('should derive from this known address string livenet scripthash', function() {
var a = new Address(P2SHLivenet[0], 'livenet', 'scripthash');
var b = new Address(a.toString());
b.toString().should.equal(P2SHLivenet[0]);
});
it('should derive from this known address string testnet scripthash', function() {
var address = new Address(P2SHTestnet[0], 'testnet', 'scripthash');
address = new Address(address.toString());
address.toString().should.equal(P2SHTestnet[0]);
});
});
describe('#toBuffer', function() {
it('3c3fa3d4adcaf8f52d5b1843975e122548269937 corresponds to hash LQiX3WFFnc6JDULSRRG3Dsjza3VmhJ5pCP', function() {
var address = new Address(str);
address.toBuffer().slice(1).toString('hex').should.equal(pubkeyhash.toString('hex'));
});
});
describe('#object', function() {
it('roundtrip to-from-to', function() {
var obj = new Address(str).toObject();
var address = Address.fromObject(obj);
address.toString().should.equal(str);
});
it('will fail with invalid state', function() {
expect(function() {
return Address.fromObject('¹');
}).to.throw(bitcore.errors.InvalidState);
});
});
describe('#toString', function() {
it('livenet pubkeyhash address', function() {
var address = new Address(str);
address.toString().should.equal(str);
});
it('scripthash address', function() {
var address = new Address(P2SHLivenet[0]);
address.toString().should.equal(P2SHLivenet[0]);
});
it('testnet scripthash address', function() {
var address = new Address(P2SHTestnet[0]);
address.toString().should.equal(P2SHTestnet[0]);
});
it('testnet pubkeyhash address', function() {
var address = new Address(PKHTestnet[0]);
address.toString().should.equal(PKHTestnet[0]);
});
});
describe('#inspect', function() {
it('should output formatted output correctly', function() {
var address = new Address(str);
var output = '<Address: DBtUjAUFWHqS1y8CgetQtPW6YKDhffyFT4, type: pubkeyhash, network: livenet>';
address.inspect().should.equal(output);
});
});
describe('questions about the address', function() {
it('should detect a P2SH address', function() {
new Address(P2SHLivenet[0]).isPayToScriptHash().should.equal(true);
new Address(P2SHLivenet[0]).isPayToPublicKeyHash().should.equal(false);
new Address(P2SHTestnet[0]).isPayToScriptHash().should.equal(true);
new Address(P2SHTestnet[0]).isPayToPublicKeyHash().should.equal(false);
});
it('should detect a Pay To PubkeyHash address', function() {
new Address(PKHLivenet[0]).isPayToPublicKeyHash().should.equal(true);
new Address(PKHLivenet[0]).isPayToScriptHash().should.equal(false);
new Address(PKHTestnet[0]).isPayToPublicKeyHash().should.equal(true);
new Address(PKHTestnet[0]).isPayToScriptHash().should.equal(false);
});
});
it('throws an error if it couldn\'t instantiate', function() {
expect(function() {
return new Address(1);
}).to.throw(TypeError);
});
it('can roundtrip from/to a object', function() {
var address = new Address(P2SHLivenet[0]);
expect(new Address(address.toObject()).toString()).to.equal(P2SHLivenet[0]);
});
it('will use the default network for an object', function() {
var obj = {
hash: '19a7d869032368fd1f1e26e5e73a4ad0e474960e',
type: 'scripthash'
};
var address = new Address(obj);
address.network.should.equal(Networks.defaultNetwork);
});
describe('creating a P2SH address from public keys', function() {
var public1 = '02da5798ed0c055e31339eb9b5cef0d3c0ccdec84a62e2e255eb5c006d4f3e7f5b';
var public2 = '0272073bf0287c4469a2a011567361d42529cd1a72ab0d86aa104ecc89342ffeb0';
var public3 = '02738a516a78355db138e8119e58934864ce222c553a5407cf92b9c1527e03c1a2';
var publics = [public1, public2, public3];
it('can create an address from a set of public keys', function() {
var address = Address.createMultisig(publics, 2, Networks.livenet);
address.toString().should.equal('A6e68GnkmTokZV8xtaRPw7BTBVBCeFFwuT');
address = new Address(publics, 2, Networks.livenet);
address.toString().should.equal('A6e68GnkmTokZV8xtaRPw7BTBVBCeFFwuT');
});
it('works on testnet also', function() {
var address = Address.createMultisig(publics, 2, Networks.testnet);
address.toString().should.equal('2N7T3TAetJrSCruQ39aNrJvYLhG1LJosujf');
});
it('can also be created by Address.createMultisig', function() {
var address = Address.createMultisig(publics, 2);
var address2 = Address.createMultisig(publics, 2);
address.toString().should.equal(address2.toString());
});
it('fails if invalid array is provided', function() {
expect(function() {
return Address.createMultisig([], 3, 'testnet');
}).to.throw('Number of required signatures must be less than or equal to the number of public keys');
});
});
});
| bitpay/bitcore | packages/bitcore-lib-doge/test/address.js | JavaScript | mit | 20,962 |
import $ from "jquery";
import _ from "underscore";
import "bootstrap";
import "jquery-deparam";
import "./configure_datatables";
import View from "../view";
import Cache from "../cache";
import ColumnManager from "./column_manager";
import SelectionManager from "./selection_manager";
import LockManager from "./lock_manager";
import FilterView from "./filter_view";
import { extractColumnCSSClass, toColumnCSSClass } from "../utils/css";
import cidMap from "./cid_map";
import Config from "./config";
class LocalDataTable extends View {
constructor(options) {
super(options);
this.options = options || {};
// copy over certain properties from options to the table itself
_.extend(this, _.pick(this.options, ["selectedIds", "paginate"]));
_.bindAll(this, "_onRowCreated", "_onBulkHeaderClick", "_onBulkRowClick", "_bulkCheckboxAdjust", "_onDraw",
"_onColumnVisibilityChange", "_onColumnReorder");
this._initKeyWithValueOrDefault('urlPagination', this.options.urlPagination, true);
this.urlPagination = this.urlPagination && this.paginate;
this.cache = new Cache();
this.selectionManager = new SelectionManager();
this.rowClass = this.options.rowClass || this._resolveRowClass();
this.config = this.options.config || (this._configFromPlugin && this._configFromPlugin()) || new Config();
this._applyDefaults();
this._columnManager = new ColumnManager(this);
this._lockManager = new LockManager(this);
this.listenTo(this.collection, "add", this._onAdd);
this.listenTo(this.collection, "remove", this._onRemove);
this.listenTo(this.collection, "reset", this._onReset);
}
_initKeyWithValueOrDefault(key, value, defaultValue) {
if (this[key] === undefined) {
if (value !== undefined) {
this[key] = value;
} else {
this[key] = defaultValue;
}
}
}
availableColumnTypes() {
return this.config.columnTypes;
}
// apply filtering
filter(...args) {
this._lockManager.ensureUnlocked("filter");
this.dataTable.fnFilter(...args);
}
// change pagination
page(...args) {
this._lockManager.ensureUnlocked("page");
return this.dataTable.fnPageChange(...args);
}
// sort specific columns
sort(...args) {
this._lockManager.ensureUnlocked("sort");
return this.dataTable.fnSort(...args);
}
selectedModels() {
this._lockManager.ensureUnlocked("bulk");
return this.selectionManager.models();
}
render() {
this.$el.html(this.template);
this._dataTableCreate();
this._initBulkHandling();
this._enableRowHighlight();
this.paginate && this._initPaginationHandling();
this._triggerChangeSelection();
this.urlPagination && this._setupPaginationHistory();
this.trigger("render");
this._afterRender();
return this;
}
renderColumn(id) {
const config = this._columnManager.columnConfigForId(id);
if (!config) {
throw new Error("column not found");
}
this.cache.each(row => {
row.renderColumnByConfig(config);
});
}
selectAllVisible(state) {
this._lockManager.ensureUnlocked("bulk");
this.bulkCheckbox.prop("checked", state);
_.each(this._visibleRowsOnCurrentPage(), function(row) {
this._setRowSelectedState(row.model, row, state);
}, this);
this._triggerChangeSelection({ selectAllVisible: state });
}
selectAllMatching() {
this._lockManager.ensureUnlocked("bulk");
if (!this.paginate) throw new Error("#selectAllMatching can only be used with paginated tables");
_.each(this._allMatchingModels(), function(model) {
this._setRowSelectedState(model, this.cache.get(model), true);
}, this);
this._triggerChangeSelection();
}
matchingCount() {
this._lockManager.ensureUnlocked("bulk");
return this.dataTable.fnSettings().aiDisplay.length;
}
totalRecordsCount() {
this._lockManager.ensureUnlocked("bulk");
return this.dataTable.fnSettings().fnRecordsTotal();
}
pageLimit() {
return this.dataTable.fnSettings()._iDisplayLength;
}
columnRequired(state, id) {
if (!state && this._columnManager.columnConfigForId(id).required) {
throw new Error("can not disable visibility when column is required");
}
}
columnVisibility(attr, state) {
if (arguments.length === 1) {
// getter
return this._columnManager.visibility.get(attr);
} else {
this.columnRequired(state, attr);
this._columnManager.visibility.set(attr, state);
state && this.renderColumn(attr);
}
}
// takes a hash of { columnAttr: columnState, ... }
setColumnVisibilities(columns) {
_.each(columns, this.columnRequired, this);
this._columnManager.visibility.set(columns);
_.each(columns, function(state, attr) {
state && this.renderColumn(attr);
}, this);
}
restoreColumnVisibility() {
_.each(this.columnsConfig(), function(column) {
if (column.id) {
this.columnVisibility(column.id, column.visible);
}
}, this);
}
columnOrder(order) {
if (this._reorderableColumnsEnabled()) {
this._changeColumnOrder(order);
}
}
restoreColumnOrder() {
if (this._reorderableColumnsEnabled()) {
this._changeColumnOrder({ reset: true });
}
}
changeSorting(sorting) {
this._columnManager.changeSorting(sorting);
if (this.dataTable) {
const normalizeSortingColumn = sort => _.first(sort, 2);
sorting = _.map(this._columnManager.dataTableSortingConfig(), normalizeSortingColumn);
let currentSorting = _.map(this.dataTable.fnSettings().aaSorting, normalizeSortingColumn);
if (!_.isEqual(currentSorting, sorting)) {
this.dataTable.fnSort(sorting);
}
}
}
lock(name, state) {
if (arguments.length === 1) {
// getter
return this._lockManager.lock(name);
} else if (arguments.length === 2) {
// setter
this._lockManager.lock(name, state);
} else {
throw new Error("#lock requires a name and/or a state");
}
}
columnsConfig() {
return this._columnManager.columnsConfig();
}
configGenerator() {
return this._columnManager._configGenerator;
}
disableFilters(errorMessage) {
const columns = this.columnsConfig();
for (const c in columns) {
if (!columns[c].filter) continue;
this.child(`filter-${columns[c].id}`).disableFilter(errorMessage);
}
}
enableFilters() {
const columns = this.columnsConfig();
for (const c in columns) {
if (!columns[c].filter) continue;
this.child(`filter-${columns[c].id}`).enableFilter();
}
}
updateAjaxSource() {
// get ajax url
const ajaxURL = this.dataTable.fnSettings().sAjaxSource;
// get the endpoint of ajax url
const splitUrl = ajaxURL.split("?");
const endpoint = splitUrl[0];
// Early exit if no params
if (!splitUrl[1]) {
return;
}
// get parameters of ajax url
const params = $.deparam(splitUrl[1]);
// make ext_filter_json param the same as the current url, now with new filters
params.ext_filter_json = JSON.stringify(this.configGenerator()._getUrlFilterParams());
// Build new url with old endpoint but new params
const newURL = `${endpoint}?${$.param(params)}`;
// Update datatable ajax source
this.dataTable.fnSettings().sAjaxSource = newURL;
// trigger "filter:column" event
this._onColumnFilter();
}
columnElements(selector) {
const selectorString = selector || "";
return this.$("table").find(`thead tr th${selectorString}`);
}
// Private APIs
_enableReorderableColumns() {
const self = this;
self._colReorder = new $.fn.dataTable.ColReorder(this.dataTable, {
fnReorderCallback(fromIndex, toIndex) {
// notify that columns have been externally rearranged
self._columnManager.columnsSwapped(fromIndex, toIndex);
// pass event up
self._onColumnReorder();
},
bAddFixed: false,
bResizeTableWrapper: false,
allowHeaderDoubleClick: false,
allowResize: self.resizableColumns,
// iFixedColumns configures how many columns should be unmovable starting from left
// if the first column is the bulk column we make it unmovable
iFixedColumns: this.$el.find(this.BULK_COLUMN_HEADER_CHECKBOX_SELECTOR).length
});
}
_renderGrandTotalsRow() {
let hasGrandTotalsCell = false;
// if dataTable is available AND we have a totals row
if (this.dataTable && this.totalsRow) {
// If we don't have a footer rendered, render it
if (this.dataTable.find("tfoot").length < 1) {
this.dataTable.append("<tfoot><tr></tr></tfoot>");
}
// Clear the footer
const $grandTotalsRow = this.dataTable.find("tfoot tr");
$grandTotalsRow.html("");
// Iterate over the current columns config
this.columnsConfig().forEach(col => {
if (this.columnVisibility(col.id) || col.bulk) {
const node = $("<td>");
// If column is a non totals column, draw "Grand totals" on the first one and the rest are empty
if (this.isNontotalsColumn && this.isNontotalsColumn(col)) {
if (hasGrandTotalsCell) {
$grandTotalsRow.append(node);
} else {
hasGrandTotalsCell = true;
col.grandTotalRenderer ? col.grandTotalRenderer.apply(this.totalsRow, [node, col]) : node.text("Grand Total");
$grandTotalsRow.append(node);
}
} else {
(col.grandTotalRenderer || col.renderer).apply(this.totalsRow, [node, col]);
$grandTotalsRow.append(node);
}
}
});
}
}
_renderHeaderGroup() {
if (!_.isEmpty(this.rowClass.prototype.columnGroupDefinitions)) {
const columnGroups = this.rowClass.prototype.columnGroupDefinitions;
let tr = this.$("table").find('thead tr.header-groups-row');
if (tr.length === 0) {
tr = $('<tr class="header-groups-row">');
} else {
tr.empty();
}
const uniqueHeaderGroupDataIndex = {};
_.each(this._columnManager._visibilitySummary().visible, col => {
const columnConfig = _.findWhere(this._columnManager.columnsConfig(), { attr: col });
let headerGroupDataIndex = columnConfig.headerGroupDataIndex;
let columnGroupConfig = _.findWhere(columnGroups, { "headerGroupDataIndex": headerGroupDataIndex });
if (!columnGroupConfig || !headerGroupDataIndex) {
console.log(`Unable to find a matching headerGroupDataIndex for ${columnConfig.attr}`);
columnGroupConfig = { colspan: 1, headerName: '' };
headerGroupDataIndex = columnConfig.title;
}
if (columnGroupConfig && !uniqueHeaderGroupDataIndex[headerGroupDataIndex]) {
uniqueHeaderGroupDataIndex[headerGroupDataIndex] = true;
tr.append(`<th colspan="${columnGroupConfig.colspan}" class="header-groups">${columnGroupConfig.headerName}</th>`);
}
});
this.$("table").find('thead').prepend(tr);
}
}
// Changes or resets the column order.
// When called with no args, returns the current order.
// Call with { reset : true } to have it restore column order to initial configuration
// Provide array of indexes as first argument to have it reordered by that
_changeColumnOrder(order) {
if (this._colReorder) {
const columnsOrig = _.clone(this.dataTable.fnSettings().aoColumns);
if (_.isArray(order)) {
this._colReorder.fnOrder(order);
} else if (_.has(order, 'reset') && order.reset) {
this._colReorder.fnReset();
} else {
return this._colReorder.fnOrder();
}
// restore columnsConfig order to match the underlying order from dataTable
const columnsConfig = this.columnsConfig();
const columnsConfigOrig = _.clone(columnsConfig);
// reset config
columnsConfig.splice(0, columnsConfig.length);
// fill in config in correct order
_.each(this.dataTable.fnSettings().aoColumns, tableColumn => {
const oldIndex = columnsOrig.indexOf(tableColumn);
if (oldIndex !== -1) {
columnsConfig.push(columnsConfigOrig[oldIndex]);
}
});
this._columnManager.columnsReordered();
}
}
_allMatchingModels() {
// returns all models matching the current filter criteria, regardless of pagination
// since we are using deferred rendering, the dataTable.$ and dataTable._ methods don't return all
// matching data since some of the rows may not have been rendered yet.
// here we use the the aiDisplay property to get indicies of the data matching the current filtering
// and return the associated models
return _.map(this.dataTable.fnSettings().aiDisplay, function(index) {
return this.collection.at(index);
}, this);
}
_applyDefaults() {
_.defaults(this, {
sorting: [[0, this.paginate ? "desc" : "asc"]]
});
if (!this.objectName.plural) {
throw new Error("plural object name must be provided");
} else if (!this.objectName.singular) {
throw new Error("singular object name must be provided");
}
}
// returns row objects that have not been filtered out and are on the current page
_visibleRowsOnCurrentPage() {
// non-paginated tables will return all rows, ignoring the page param
const visibleRowsCurrentPageArgs = { filter: "applied", page: "current" };
return this.dataTable.$("tr", visibleRowsCurrentPageArgs).map((index, node) => $(node).data("row"));
}
_setRowSelectedState(model, row, state) {
this.selectionManager.process(model, state);
// the row may not exist yet as we utilize deferred rendering. we track the model as
// selected and make the ui reflect this when the row is finally created
row && row.bulkState(state);
}
_dataTableCreate() {
this.dataTable = this.$("table").dataTable(this._dataTableConfig());
this._setupSelect2PaginationAttributes();
this._installSortInterceptors();
this.filteringEnabled && this._setupFiltering();
if (this._reorderableColumnsEnabled()) {
this._enableReorderableColumns();
}
this._columnManager.on("change:visibility", this._onColumnVisibilityChange);
this._columnManager.applyVisibilityPreferences();
this._renderHeaderGroup();
if (this.collection.length) this._onReset(this.collection);
// if resizeable, add resizeable class
if (this._colReorder && this._colReorder.s.allowResize) {
this.$("table").addClass("dataTable-resizeableColumns");
}
if (this.striped) {
this.$("table").addClass("table-striped");
}
}
_areAllVisibleRowsSelected() {
let allSelected;
const visibleRows = this._visibleRowsOnCurrentPage();
if (visibleRows.length) {
allSelected = _.all(visibleRows, row => row.bulkState() === true);
} else {
// have no selections does not count as having all selected
allSelected = false;
}
return allSelected;
}
// when changing between pages / filters we set the header bulk checkbox state based on whether all newly visible rows are selected or not
// note: we defer execution as the "page" and "filter" events are called before new rows are swapped in
// this allows our code to run after the all the new rows are inserted
_bulkCheckboxAdjust() {
if (!this.bulkCheckbox) return;
_.defer(() => {
this.bulkCheckbox.prop("checked", this._areAllVisibleRowsSelected());
});
}
// Do not enable when columnGroupDefinitions is defined and not empty.
_reorderableColumnsEnabled() {
return this.reorderableColumns && _.isEmpty(this.rowClass.prototype.columnGroupDefinitions);
}
_initPaginationHandling() {
this.dataTable.on("page", this._bulkCheckboxAdjust);
}
_setQueryStringPageFromDataTable() {
let page = this.dataTable.fnPagingInfo().iPage;
if (page !== this._parsePageNumberFromQueryString() - 1) {
history.pushState({}, "pagination", this._createQueryStringWithPageNumber(page + 1));
}
}
_setupPaginationHistory() {
this.dataTable.on("page", () => {
this._setQueryStringPageFromDataTable();
});
this.dataTable.on("pageLengthChange", () => {
this._setQueryStringPageFromDataTable();
});
window.onpopstate = () => {
this._goToPageFromQueryString();
};
}
_afterRender() {
if (this.urlPagination) {
this._goToPageFromQueryString();
}
}
_goToPageFromQueryString() {
let pageNumber = this._parsePageNumberFromQueryString() - 1;
if (pageNumber >= 0) {
this.page(pageNumber);
}
}
_urlParameters() {
return $.deparam(window.location.href.split("?")[1] || "");
}
_createQueryStringWithPageNumber(pageNumber) {
let urlParameters = this._urlParameters();
urlParameters.page = pageNumber;
return "?" + $.param(urlParameters);
}
_parsePageNumberFromQueryString() {
let parameters = this._urlParameters();
let page = parseInt(parameters.page);
if (isNaN(page)) {
return 1;
} else {
return page;
}
}
_initBulkHandling() {
const bulkCheckbox = this.$el.find(this.BULK_COLUMN_HEADER_CHECKBOX_SELECTOR);
if (!bulkCheckbox.length) return;
this.bulkCheckbox = bulkCheckbox;
this.bulkCheckbox.click(this._onBulkHeaderClick);
this.dataTable.on("click", this.BULK_COLUMN_CHECKBOXES_SELECTOR, this._onBulkRowClick);
this.dataTable.on("filter", this._bulkCheckboxAdjust);
}
_enableRowHighlight() {
this.dataTable.on("click", this.ROWS_SELECTOR, this._onRowHighlightClick);
}
_onRowHighlightClick(event) {
const el = $(event.target).closest("tr");
const currentState = el.hasClass("highlighted");
$(event.target).closest("tbody").find('tr').toggleClass('highlighted', false);
el.toggleClass("highlighted", !currentState);
}
_dataTableConfig() {
let displayStart, recordTotal;
if (this.urlPagination) {
displayStart = this._getSafeDisplayStartFromPageNumber();
recordTotal = displayStart + this.paginateLength;
}
return {
sDom: this.layout,
bDeferRender: true,
bPaginate: this.paginate,
aLengthMenu: this.paginateLengthMenu,
iDisplayLength: this.paginateLength,
iDisplayStart: displayStart,
iRecordsTotal: recordTotal,
iRecordsDisplay: recordTotal,
bInfo: true,
fnCreatedRow: this._onRowCreated,
aoColumns: this._columnManager.dataTableColumnsConfig(),
aaSorting: this._columnManager.dataTableSortingConfig(),
fnDrawCallback: this._onDraw,
oLanguage: {
sEmptyTable: this.emptyText
}
};
}
_getSafeDisplayStartFromPageNumber() {
let pageIndex = this._parsePageNumberFromQueryString() - 1;
if (pageIndex < 0) {
return 0;
} else {
return pageIndex * this.paginateLength;
}
}
_triggerChangeSelection(extraData) {
const data = _.extend(extraData || {}, { count: this.selectionManager.count() });
this.trigger("change:selected", data);
}
_setupSelect2PaginationAttributes() {
this.$('select')
.attr('data-plugin', 'select2')
.css('width', '5em');
}
// DataTables does not provide a good way to programmatically disable sorting, so we:
// 1) remove the default sorting event handler that dataTables adds
// 2) Create a div and put the header in it. We need to do this so sorting doesn't conflict with filtering
// on the click events.
// 3) insert our own event handler on the div that stops the event if we are locked
// 4) re-insert the dataTables sort event handler
_installSortInterceptors() {
const self = this;
this.dataTable.find("thead th").each(function(index) {
$(this).off("click.DT");
$(this).off("keypress.DT");
const wrapper = $("<div class='DataTables_sort_wrapper'><div class='DataTables_sort_interceptor'></div></div>");
$(this).contents().appendTo(wrapper.find(".DataTables_sort_interceptor"));
$(this).append(wrapper);
// handle clicking on div as sorting
$('.DataTables_sort_interceptor', this).on("click", event => {
if (self.lock("sort")) {
event.stopImmediatePropagation();
} else {
history.pushState({}, "pagination", self._createQueryStringWithPageNumber(1));
}
});
// default sort handler for column with index
self.dataTable.fnSortListener($('.DataTables_sort_wrapper', this), index);
});
}
// Sets up filtering for the dataTable
_setupFiltering() {
const table = this;
const cg = table.configGenerator();
// Close active filter menu if user clicks on document
$("body").on("click", e => {
$("[data-toggle='filter-popover']").each(function() {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $(".popover").has(e.target).length === 0) {
$(this).popover("hide");
}
});
});
// We make a filter for each column header
table.dataTable.find("thead th").each(function(index) {
// here we use the CSS in the header to get the column config by attr
// there isn't a better way to do this currently
let col;
const columnClassName = extractColumnCSSClass(this.className);
if (columnClassName) {
cg.columnsConfig.forEach(currentColConfig => {
if (currentColConfig.id && toColumnCSSClass(currentColConfig.id) === columnClassName) {
col = currentColConfig;
}
});
} else {
// TODO: FAIL!!!
}
if (col) {
// We only make the filter controls if there's a filter element in the column manager
if (col.filter) {
table.child(`filter-${col.id}`, new FilterView({
column: col,
table,
head: this,
className: "dropdown DataTables_filter_wrapper"
}));
$(this).append(table.child(`filter-${col.id}`).render().$el);
}
}
});
}
// events
_onColumnReorder() {
this.trigger("reorder");
this._renderGrandTotalsRow();
}
_onDraw() {
this.trigger("draw", arguments);
this._renderGrandTotalsRow();
this._renderHeaderGroup();
}
_onColumnVisibilityChange(summary) {
this.dataTable.find(".dataTables_empty").attr("colspan", summary.visible.length);
this._renderGrandTotalsRow();
this._renderHeaderGroup();
}
_onBulkHeaderClick(event) {
const state = this.bulkCheckbox.prop("checked");
this.selectAllVisible(state);
// don't let dataTables sort this column on the click of checkbox
event.stopPropagation();
}
_onBulkRowClick(event) {
const checkbox = $(event.target);
const row = checkbox.closest("tr").data("row");
const checked = checkbox.prop("checked");
// ensure that when a single row checkbox is unchecked, we uncheck the header bulk checkbox
if (!checked) this.bulkCheckbox.prop("checked", false);
this._setRowSelectedState(row.model, row, checked);
this._triggerChangeSelection();
event.stopPropagation();
}
_onRowCreated(node, data) {
const model = this.collection.get(data);
// eslint-disable-next-line new-cap
const row = new this.rowClass({
el: node,
model,
columnsConfig: this.columnsConfig()
});
this.cache.set(model, row);
this.child(`child${row.cid}`, row).render();
// due to deferred rendering, the model associated with the row may have already been selected, but not rendered yet.
this.selectionManager.has(model) && row.bulkState(true);
}
_onAdd(model) {
if (!this.dataTable) return;
this.dataTable.fnAddData({ cid: model.cid });
this._triggerChangeSelection();
}
_onRemove(model) {
if (!this.dataTable) return;
const cache = this.cache;
const row = cache.get(model);
this.dataTable.fnDeleteRow(row.el, () => {
cache.unset(model);
row.close();
});
this.selectionManager.process(model, false);
this._triggerChangeSelection();
}
_onReset(collection) {
if (!this.dataTable) return;
this.dataTable.fnClearTable();
this.cache.each(row => {
row.close();
});
this.cache.reset();
// populate with preselected items
this.selectionManager = new SelectionManager();
_.each(this.selectedIds, function(id) {
// its possible that a selected id is provided for a model that doesn't actually exist in the table, ignore it
const selectedModel = this.collection.get(id);
selectedModel && this._setRowSelectedState(selectedModel, null, true);
}, this);
// add new data
this.dataTable.fnAddData(cidMap(collection));
this._triggerChangeSelection();
}
_onColumnFilter() {
this.trigger("filter:column");
}
}
_.extend(LocalDataTable.prototype, {
BULK_COLUMN_HEADER_CHECKBOX_SELECTOR: "th:first.bulk :checkbox",
BULK_COLUMN_CHECKBOXES_SELECTOR: "td:first-child.bulk :checkbox",
ROWS_SELECTOR: "tbody tr",
template: '<table cellpadding="0" class="table"></table>',
paginate: true,
paginateLengthMenu: [10, 25, 50, 100],
paginateLength: 10,
selectedIds: [],
filteringEnabled: false,
layout: "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
striped: true,
reorderableColumns: true,
resizableColumns: false,
objectName: {
singular: "row",
plural: "rows"
}
});
export default LocalDataTable;
| Invoca/backdraft | src/data_table/local_data_table.js | JavaScript | mit | 25,506 |
var s = document.createElement('script');
s.src = chrome.extension.getURL('flourish.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s); | mrwillis21/flourish | extension.js | JavaScript | mit | 213 |
import PropTypes from 'prop-types';
import Element from './Element';
export default class Rect extends Element {
static displayName = 'Rect';
static propTypes = {
x: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
y: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
width: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
};
static defaultProps = {
...Element.defaultProps,
};
defaultComponent='rect'
}
| finnfiddle/number-picture | packages/element/src/Rect.js | JavaScript | mit | 531 |
'use strict';
// var Boom = require('boom');
var BPromise = require('bluebird');
module.exports = function (handler) {
return function (req, res) {
return new BPromise(function (resolve) {
resolve(handler(req, res));
})
.then(function (response) {
if (response === undefined) {
// [KE] assume the response is handled, eg in a res.redirect
return;
}
if (response.isBoom) {
res.error(response);
return;
}
res.json(response);
}, res.error).catch(res.error);
};
};
| swccg/api | middleware/resPromise.js | JavaScript | mit | 556 |
(function() {
if (typeof module === "undefined") self.queue = queue;
else module.exports = queue;
queue.version = "1.0.1";
function queue(parallelism) {
var queue = {},
active = 0, // number of in-flight deferrals
remaining = 0, // number of deferrals remaining
head, tail, // singly-linked list of deferrals
error = null,
results = [],
await = noop,
awaitAll;
if (arguments.length < 1) parallelism = Infinity;
queue.defer = function() {
if (!error) {
var node = arguments;
node.index = results.push(undefined) - 1;
if (tail) tail.next = node, tail = tail.next;
else head = tail = node;
++remaining;
pop();
}
return queue;
};
queue.await = function(f) {
await = f;
awaitAll = false;
if (!remaining) notify();
return queue;
};
queue.awaitAll = function(f) {
await = f;
awaitAll = true;
if (!remaining) notify();
return queue;
};
function pop() {
if (head && active < parallelism) {
var node = head,
f = node[0],
a = Array.prototype.slice.call(node, 1),
i = node.index;
if (head === tail) head = tail = null;
else head = head.next;
++active;
a.push(function(e, r) {
--active;
if (error != null) return;
if (e != null) {
// clearing remaining cancels subsequent callbacks
// clearing head stops queued tasks from being executed
// setting error ignores subsequent calls to defer
error = e;
remaining = results = head = tail = null;
notify();
} else {
results[i] = r;
if (--remaining) pop();
else notify();
}
});
f.apply(null, a);
}
}
function notify() {
if (error != null) await(error);
else if (awaitAll) await(null, results);
else await.apply(null, [null].concat(results));
}
return queue;
}
function noop() {}
})(); | ddsc/webclient | app/scripts/vendor/queue.js | JavaScript | mit | 2,139 |
/*globals define, WebGMEGlobal, requirejs*/
/*jshint browser: true*/
/**
* @author rkereskenyi / https://github.com/rkereskenyi
* @author lattmann / https://github.com/lattmann
* @author pmeijer / https://github.com/pmeijer
*/
define([
'common/core/coreQ',
'plugin/PluginManagerBase',
'plugin/PluginResult',
'plugin/PluginMessage',
'blob/BlobClient',
'js/Dialogs/PluginConfig/PluginConfigDialog',
'js/logger'
], function (Core, PluginManagerBase, PluginResult, PluginMessage, BlobClient, PluginConfigDialog, Logger) {
'use strict';
var InterpreterManager = function (client, gmeConfig) {
this._client = client;
//this._manager = new PluginManagerBase();
this.gmeConfig = gmeConfig;
this._savedConfigs = {};
this.logger = Logger.create('gme:InterpreterManager', gmeConfig.client.log);
this.logger.debug('InterpreterManager ctor');
};
var getPlugin = function (name, callback) {
if (WebGMEGlobal && WebGMEGlobal.plugins && WebGMEGlobal.plugins.hasOwnProperty(name)) {
callback(null, WebGMEGlobal.plugins[name]);
} else {
requirejs(['/plugin/' + name + '/' + name + '/' + name],
function (InterpreterClass) {
callback(null, InterpreterClass);
},
function (err) {
callback(err, null);
}
);
}
};
function getPluginErrorResult(pluginName, message, startTime, projectId) {
var pluginResult = new PluginResult(),
pluginMessage = new PluginMessage();
pluginMessage.severity = 'error';
pluginMessage.message = message;
pluginResult.setSuccess(false);
pluginResult.setPluginName(pluginName);
pluginResult.setProjectId(projectId || 'N/A');
pluginResult.addMessage(pluginMessage);
pluginResult.setStartTime(startTime);
pluginResult.setFinishTime((new Date()).toISOString());
pluginResult.setError(pluginMessage.message);
return pluginResult;
}
/**
*
* @param {string} name - name of plugin to be executed.
* @param {object} silentPluginCfg - if falsy dialog window will be shown.
* @param {object.string} silentPluginCfg.activeNode - Path to activeNode.
* @param {object.Array.<string>} silentPluginCfg.activeSelection - Paths to nodes in activeSelection.
* @param {object.boolean} silentPluginCfg.runOnServer - Whether to run the plugin on the server or not.
* @param {object.object} silentPluginCfg.pluginConfig - Plugin specific options.
* @param callback
*/
InterpreterManager.prototype.run = function (name, silentPluginCfg, callback) {
var self = this,
projectId = self._client.getProjectObject().projectId,
startTime = (new Date()).toISOString();
getPlugin(name, function (err, plugin) {
self.logger.debug('Getting getPlugin in run.');
if (!err && plugin) {
var plugins = {},
runWithConfiguration;
plugins[name] = plugin;
var pluginManager = new PluginManagerBase(self._client.getProjectObject(), Core, self.logger, plugins,
self.gmeConfig);
pluginManager.notificationHandlers = [function (data, callback) {
self._client.dispatchPluginNotification(data);
callback(null);
}];
pluginManager.initialize(null, function (pluginConfigs, configSaveCallback) {
//#1: display config to user
var serverAllowedGlobal = self.gmeConfig.plugin.allowServerExecution === true,
serverAllowedPlugin = !plugin.disableServerExecution,
browserAllowedGlobal = self.gmeConfig.plugin.allowBrowserExecution === true,
browserAllowedPlugin = !plugin.disableBrowserExecution,
runOptions = {
name: 'runOnServer',
displayName: 'Execute on Server',
description: '',
value: false,
valueType: 'boolean',
readOnly: false
},
hackedConfig = {
'Global Options': [runOptions]
},
i, j, d, len;
if (serverAllowedGlobal === false && browserAllowedGlobal === false) {
callback(getPluginErrorResult(name, 'Plugin execution is disabled!', startTime, projectId));
return;
}
if (serverAllowedPlugin === false && browserAllowedPlugin === false) {
callback(getPluginErrorResult(name, 'This plugin cannot run on the server nor in the browser!?',
startTime, projectId));
return;
}
if (browserAllowedGlobal) {
if (serverAllowedGlobal) {
if (browserAllowedPlugin) {
if (serverAllowedPlugin) {
// This is the default
} else {
runOptions.readOnly = true;
runOptions.description = 'This plugin can not run on the server.';
}
} else {
runOptions.readOnly = true;
runOptions.value = true;
runOptions.description = 'This plugin can not run in the browser.';
}
} else {
if (browserAllowedPlugin) {
runOptions.readOnly = true;
runOptions.description = 'Server execution is disabled.';
} else {
callback(getPluginErrorResult(name,
'This plugin can only run on the server which is disabled!', startTime, projectId));
return;
}
}
} else {
if (browserAllowedPlugin) {
runOptions.readOnly = true;
runOptions.value = true;
runOptions.description = 'Browser execution is disabled.';
} else {
callback(getPluginErrorResult(name,
'This plugin can only run on the server which is disabled!', startTime, projectId));
return;
}
}
for (i in pluginConfigs) {
if (pluginConfigs.hasOwnProperty(i)) {
hackedConfig[i] = pluginConfigs[i];
// retrieve user settings from previous run
if (self._savedConfigs.hasOwnProperty(i)) {
var iConfig = self._savedConfigs[i];
len = hackedConfig[i].length;
while (len--) {
if (iConfig.hasOwnProperty(hackedConfig[i][len].name)) {
hackedConfig[i][len].value = iConfig[hackedConfig[i][len].name];
}
}
}
}
}
runWithConfiguration = function (updatedConfig) {
//when Save&Run is clicked in the dialog (or silentPluginCfg was passed)
var globalconfig = updatedConfig['Global Options'],
activeNode,
errMessage,
activeSelection;
delete updatedConfig['Global Options'];
activeNode = silentPluginCfg.activeNode;
if (!activeNode && WebGMEGlobal && WebGMEGlobal.State) {
activeNode = WebGMEGlobal.State.getActiveObject();
}
activeSelection = silentPluginCfg.activeSelection;
if (!activeSelection && WebGMEGlobal && WebGMEGlobal.State) {
activeSelection = WebGMEGlobal.State.getActiveSelection();
}
// save config from user
for (i in updatedConfig) {
self._savedConfigs[i] = updatedConfig[i];
}
//#2: save it back and run the plugin
if (configSaveCallback) {
configSaveCallback(updatedConfig);
if (self._client.getBranchStatus() &&
self._client.getBranchStatus() !== self._client.CONSTANTS.BRANCH_STATUS.SYNC) {
errMessage = 'Not allowed to invoke plugin while local branch is AHEAD or ' +
'PULLING changes from server.';
self.logger.error(errMessage);
callback(getPluginErrorResult(name, errMessage, startTime, projectId));
return;
}
// TODO: If global config says try to merge branch then we
// TODO: should pass the name of the branch.
var config = {
project: self._client.getActiveProjectId(),
token: '',
activeNode: activeNode, // active object in the editor
activeSelection: activeSelection || [],
commit: self._client.getActiveCommitHash(), //#668b3babcdf2ddcd7ba38b51acb62d63da859d90,
// This will get loaded too which will provide a sanity check on the client state.
rootHash: self._client.getActiveRootHash(),
branchName: self._client.getActiveBranchName()
};
if (globalconfig.runOnServer === true || silentPluginCfg.runOnServer === true) {
var context = {
managerConfig: config,
pluginConfig: updatedConfig[name]
};
self._client.runServerPlugin(name, context, function (err, result) {
if (err) {
self.logger.error(err);
if (result) {
callback(new PluginResult(result));
} else {
errMessage = 'Plugin execution resulted in error, err: ' + err;
callback(getPluginErrorResult(name, errMessage, startTime, projectId));
}
} else {
var resultObject = new PluginResult(result);
callback(resultObject);
}
});
} else {
config.blobClient = new BlobClient({logger: self.logger.fork('BlobClient')});
pluginManager.executePlugin(name, config, function (err, result) {
if (err) {
self.logger.error(err);
}
callback(result);
});
}
}
};
if (silentPluginCfg) {
var updatedConfig = {};
for (i in hackedConfig) {
updatedConfig[i] = {};
len = hackedConfig[i].length;
while (len--) {
updatedConfig[i][hackedConfig[i][len].name] = hackedConfig[i][len].value;
}
if (silentPluginCfg && silentPluginCfg.pluginConfig) {
for (j in silentPluginCfg.pluginConfig) {
updatedConfig[i][j] = silentPluginCfg.pluginConfig[j];
}
}
}
runWithConfiguration(updatedConfig);
} else {
d = new PluginConfigDialog();
silentPluginCfg = {};
d.show(hackedConfig, plugin, runWithConfiguration);
}
});
} else {
self.logger.error(err);
self.logger.error('Unable to load plugin');
callback(getPluginErrorResult(name, 'Unable to load plugin, err:' + err, startTime, projectId));
}
});
};
//TODO: Somehow it would feel more right if we do run in async mode, but if not then we should provide getState and
//TODO: getResult synchronous functions as well.
return InterpreterManager;
});
| pillforge/webgme | src/client/js/Utils/InterpreterManager.js | JavaScript | mit | 14,117 |
module.exports = function (grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
jshint: {
options: {
"expr": true,
"laxcomma": true,
"smarttabs": true,
"curly": true,
"eqeqeq": false,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"es5": true,
"undef": true,
"eqnull": true,
"browser": true,
"regexdash": true,
"loopfunc": true,
"mootools": true,
"node": true,
globals: {
"Mousetrap": true,
"Modernizr": true,
"mootools": true,
"nsUtil": true,
"resource": true,
"define": true,
"debugMode": true,
"rendererModel": true,
"viewMode": true,
"WixGoogleAnalytics": true,
"siteHeader": true,
"editorModel": true,
"siteId": true,
"LOG": true,
"PHASES": true,
"wixLogLegend": true,
"wixEvents": true,
"WixLogger": true,
"wixErrors": true,
"WixBILogger": true,
"managers": true,
"classDefinition": true,
"Utils": true,
"UtilsClass": true,
"WClass": true,
"W": true,
"e": true,
"l": true,
"s": true,
"m": true,
"g": true,
"d": true,
"f": true,
"t": true,
"after": true,
"unescape": true,
"alert": true,
"missingItems": true,
"hex_sha256": true,
"XDomainRequest": true,
"_userAnalyticsAccount": true,
"getCookieInfo": true,
"creationSource": true,
"ActiveXObject": true,
"Test": true,
"main": true,
"Async": true,
"console": true,
"Request": true,
"getAsyncExpects": true,
"fail": true,
"pageTracker": true,
"_gat": true,
"Constants": true,
"expect": true,
"describe": true,
"beforeEach": true,
"it": true,
"waits": true,
"runs": true,
"waitsFor": true,
"afterEach": true,
"spyOn": true,
"sleep": true,
"jasmine": true,
"getPlayGround": true,
"Element": true,
"typeOf": true,
"getSpy": true,
"MockBuilder": true,
"Define": true,
"instanceOf": true,
"xdescribe": true,
"merge": true,
"clone": true
}
},
all: [
'Gruntfile.js',
'tasks/**/*.js',
'test/javascript/**/*.js'
]
},
jasmine_node: {
specNameMatcher: "spec",
projectRoot: ".",
requirejs: false,
forceExit: true,
jUnit: {
report: false,
savePath: "./build/reports/jasmine/",
useDotNotation: true,
consolidate: true
}
},
aggregate: {
"ordered-list": {
src: "test/resources/ordered-list.json",
manifest: "target/ordered-list.json"
},
main: {
src: "test/resources/aggregations.json",
manifest: "target/manifest.json"
},
'no-min': {
src: "test/resources/no-min.json",
manifest: 'target/no-min.json',
min: false
},
'no-copy': {
src: "test/resources/no-copy.json",
manifest: 'target/no-copy.json',
copy: false
},
list: {
src: "test/resources/list.json",
manifest: 'target/list.json',
manifestCopy: 'target/list.copy.json',
min: false,
copy: false
},
exclude: {
src: "test/resources/exclude.json",
manifest: 'target/exclude.json',
manifestCopy: 'target/exclude.copy.json'
},
css: {
src: "test/resources/css.json",
manifest: 'target/css.json'
},
manymin: {
src: "test/resources/manymin.json",
manifest: "target/manymin.json",
min: false,
manymin: true,
copy: false
}
},
modify: {
json: {
base: 'test/resources',
src: ['dir*/**/*.json'],
dest: 'target/mod',
modifier: function (name, content) {
return {
name: name.search('subdir1_2') !== -1 ? 'genereated.name.json' : name,
content: '[' + content + ']'
};
}
}
},
clean: {
test: "target"
},
copy: {
target: {
files: {
'target/aggregations/greatescape/escaped.js': ['test/greatescape/original.js']
}
}
},
greatescape: {
all: 'target/aggregations/greatescape/escaped.js'
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// By default, lint and run all tests.
grunt.registerTask('default', ['clean', 'jshint', 'modify', 'aggregate']);
};
| omryn/grunt-aggregator | Gruntfile.js | JavaScript | mit | 6,809 |
/*!
CSSLint
Copyright (c) 2011 Nicole Sullivan and Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Build time: 20-August-2012 10:49:54 */
var CSSLint = (function(){
/*!
Parser-Lib
Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Version v0.1.9, Build time: 23-July-2012 10:52:31 */
var parserlib = {};
(function(){
/**
* A generic base to inherit from for any object
* that needs event handling.
* @class EventTarget
* @constructor
*/
function EventTarget(){
/**
* The array of listeners for various events.
* @type Object
* @property _listeners
* @private
*/
this._listeners = {};
}
EventTarget.prototype = {
//restore constructor
constructor: EventTarget,
/**
* Adds a listener for a given event type.
* @param {String} type The type of event to add a listener for.
* @param {Function} listener The function to call when the event occurs.
* @return {void}
* @method addListener
*/
addListener: function(type, listener){
if (!this._listeners[type]){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
/**
* Fires an event based on the passed-in object.
* @param {Object|String} event An object with at least a 'type' attribute
* or a string indicating the event name.
* @return {void}
* @method fire
*/
fire: function(event){
if (typeof event == "string"){
event = { type: event };
}
if (typeof event.target != "undefined"){
event.target = this;
}
if (typeof event.type == "undefined"){
throw new Error("Event object missing 'type' property.");
}
if (this._listeners[event.type]){
//create a copy of the array and use that so listeners can't chane
var listeners = this._listeners[event.type].concat();
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].call(this, event);
}
}
},
/**
* Removes a listener for a given event type.
* @param {String} type The type of event to remove a listener from.
* @param {Function} listener The function to remove from the event.
* @return {void}
* @method removeListener
*/
removeListener: function(type, listener){
if (this._listeners[type]){
var listeners = this._listeners[type];
for (var i=0, len=listeners.length; i < len; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
break;
}
}
}
}
};
/**
* Convenient way to read through strings.
* @namespace parserlib.util
* @class StringReader
* @constructor
* @param {String} text The text to read.
*/
function StringReader(text){
/**
* The input text with line endings normalized.
* @property _input
* @type String
* @private
*/
this._input = text.replace(/\n\r?/g, "\n");
/**
* The row for the character to be read next.
* @property _line
* @type int
* @private
*/
this._line = 1;
/**
* The column for the character to be read next.
* @property _col
* @type int
* @private
*/
this._col = 1;
/**
* The index of the character in the input to be read next.
* @property _cursor
* @type int
* @private
*/
this._cursor = 0;
}
StringReader.prototype = {
//restore constructor
constructor: StringReader,
//-------------------------------------------------------------------------
// Position info
//-------------------------------------------------------------------------
/**
* Returns the column of the character to be read next.
* @return {int} The column of the character to be read next.
* @method getCol
*/
getCol: function(){
return this._col;
},
/**
* Returns the row of the character to be read next.
* @return {int} The row of the character to be read next.
* @method getLine
*/
getLine: function(){
return this._line ;
},
/**
* Determines if you're at the end of the input.
* @return {Boolean} True if there's no more input, false otherwise.
* @method eof
*/
eof: function(){
return (this._cursor == this._input.length);
},
//-------------------------------------------------------------------------
// Basic reading
//-------------------------------------------------------------------------
/**
* Reads the next character without advancing the cursor.
* @param {int} count How many characters to look ahead (default is 1).
* @return {String} The next character or null if there is no next character.
* @method peek
*/
peek: function(count){
var c = null;
count = (typeof count == "undefined" ? 1 : count);
//if we're not at the end of the input...
if (this._cursor < this._input.length){
//get character and increment cursor and column
c = this._input.charAt(this._cursor + count - 1);
}
return c;
},
/**
* Reads the next character from the input and adjusts the row and column
* accordingly.
* @return {String} The next character or null if there is no next character.
* @method read
*/
read: function(){
var c = null;
//if we're not at the end of the input...
if (this._cursor < this._input.length){
//if the last character was a newline, increment row count
//and reset column count
if (this._input.charAt(this._cursor) == "\n"){
this._line++;
this._col=1;
} else {
this._col++;
}
//get character and increment cursor and column
c = this._input.charAt(this._cursor++);
}
return c;
},
//-------------------------------------------------------------------------
// Misc
//-------------------------------------------------------------------------
/**
* Saves the current location so it can be returned to later.
* @method mark
* @return {void}
*/
mark: function(){
this._bookmark = {
cursor: this._cursor,
line: this._line,
col: this._col
};
},
reset: function(){
if (this._bookmark){
this._cursor = this._bookmark.cursor;
this._line = this._bookmark.line;
this._col = this._bookmark.col;
delete this._bookmark;
}
},
//-------------------------------------------------------------------------
// Advanced reading
//-------------------------------------------------------------------------
/**
* Reads up to and including the given string. Throws an error if that
* string is not found.
* @param {String} pattern The string to read.
* @return {String} The string when it is found.
* @throws Error when the string pattern is not found.
* @method readTo
*/
readTo: function(pattern){
var buffer = "",
c;
/*
* First, buffer must be the same length as the pattern.
* Then, buffer must end with the pattern or else reach the
* end of the input.
*/
while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) != buffer.length - pattern.length){
c = this.read();
if (c){
buffer += c;
} else {
throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + ".");
}
}
return buffer;
},
/**
* Reads characters while each character causes the given
* filter function to return true. The function is passed
* in each character and either returns true to continue
* reading or false to stop.
* @param {Function} filter The function to read on each character.
* @return {String} The string made up of all characters that passed the
* filter check.
* @method readWhile
*/
readWhile: function(filter){
var buffer = "",
c = this.read();
while(c !== null && filter(c)){
buffer += c;
c = this.read();
}
return buffer;
},
/**
* Reads characters that match either text or a regular expression and
* returns those characters. If a match is found, the row and column
* are adjusted; if no match is found, the reader's state is unchanged.
* reading or false to stop.
* @param {String|RegExp} matchter If a string, then the literal string
* value is searched for. If a regular expression, then any string
* matching the pattern is search for.
* @return {String} The string made up of all characters that matched or
* null if there was no match.
* @method readMatch
*/
readMatch: function(matcher){
var source = this._input.substring(this._cursor),
value = null;
//if it's a string, just do a straight match
if (typeof matcher == "string"){
if (source.indexOf(matcher) === 0){
value = this.readCount(matcher.length);
}
} else if (matcher instanceof RegExp){
if (matcher.test(source)){
value = this.readCount(RegExp.lastMatch.length);
}
}
return value;
},
/**
* Reads a given number of characters. If the end of the input is reached,
* it reads only the remaining characters and does not throw an error.
* @param {int} count The number of characters to read.
* @return {String} The string made up the read characters.
* @method readCount
*/
readCount: function(count){
var buffer = "";
while(count--){
buffer += this.read();
}
return buffer;
}
};
/**
* Type to use when a syntax error occurs.
* @class SyntaxError
* @namespace parserlib.util
* @constructor
* @param {String} message The error message.
* @param {int} line The line at which the error occurred.
* @param {int} col The column at which the error occurred.
*/
function SyntaxError(message, line, col){
/**
* The column at which the error occurred.
* @type int
* @property col
*/
this.col = col;
/**
* The line at which the error occurred.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.message = message;
}
//inherit from Error
SyntaxError.prototype = new Error();
/**
* Base type to represent a single syntactic unit.
* @class SyntaxUnit
* @namespace parserlib.util
* @constructor
* @param {String} text The text of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SyntaxUnit(text, line, col, type){
/**
* The column of text on which the unit resides.
* @type int
* @property col
*/
this.col = col;
/**
* The line of text on which the unit resides.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.text = text;
/**
* The type of syntax unit.
* @type int
* @property type
*/
this.type = type;
}
/**
* Create a new syntax unit based solely on the given token.
* Convenience method for creating a new syntax unit when
* it represents a single token instead of multiple.
* @param {Object} token The token object to represent.
* @return {parserlib.util.SyntaxUnit} The object representing the token.
* @static
* @method fromToken
*/
SyntaxUnit.fromToken = function(token){
return new SyntaxUnit(token.value, token.startLine, token.startCol);
};
SyntaxUnit.prototype = {
//restore constructor
constructor: SyntaxUnit,
/**
* Returns the text representation of the unit.
* @return {String} The text representation of the unit.
* @method valueOf
*/
valueOf: function(){
return this.toString();
},
/**
* Returns the text representation of the unit.
* @return {String} The text representation of the unit.
* @method toString
*/
toString: function(){
return this.text;
}
};
/*global StringReader, SyntaxError*/
/**
* Generic TokenStream providing base functionality.
* @class TokenStreamBase
* @namespace parserlib.util
* @constructor
* @param {String|StringReader} input The text to tokenize or a reader from
* which to read the input.
*/
function TokenStreamBase(input, tokenData){
/**
* The string reader for easy access to the text.
* @type StringReader
* @property _reader
* @private
*/
this._reader = input ? new StringReader(input.toString()) : null;
/**
* Token object for the last consumed token.
* @type Token
* @property _token
* @private
*/
this._token = null;
/**
* The array of token information.
* @type Array
* @property _tokenData
* @private
*/
this._tokenData = tokenData;
/**
* Lookahead token buffer.
* @type Array
* @property _lt
* @private
*/
this._lt = [];
/**
* Lookahead token buffer index.
* @type int
* @property _ltIndex
* @private
*/
this._ltIndex = 0;
this._ltIndexCache = [];
}
/**
* Accepts an array of token information and outputs
* an array of token data containing key-value mappings
* and matching functions that the TokenStream needs.
* @param {Array} tokens An array of token descriptors.
* @return {Array} An array of processed token data.
* @method createTokenData
* @static
*/
TokenStreamBase.createTokenData = function(tokens){
var nameMap = [],
typeMap = {},
tokenData = tokens.concat([]),
i = 0,
len = tokenData.length+1;
tokenData.UNKNOWN = -1;
tokenData.unshift({name:"EOF"});
for (; i < len; i++){
nameMap.push(tokenData[i].name);
tokenData[tokenData[i].name] = i;
if (tokenData[i].text){
typeMap[tokenData[i].text] = i;
}
}
tokenData.name = function(tt){
return nameMap[tt];
};
tokenData.type = function(c){
return typeMap[c];
};
return tokenData;
};
TokenStreamBase.prototype = {
//restore constructor
constructor: TokenStreamBase,
//-------------------------------------------------------------------------
// Matching methods
//-------------------------------------------------------------------------
/**
* Determines if the next token matches the given token type.
* If so, that token is consumed; if not, the token is placed
* back onto the token stream. You can pass in any number of
* token types and this will return true if any of the token
* types is found.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token might be. If an array is passed,
* it's assumed that the token can be any of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {Boolean} True if the token type matches, false if not.
* @method match
*/
match: function(tokenTypes, channel){
//always convert to an array, makes things easier
if (!(tokenTypes instanceof Array)){
tokenTypes = [tokenTypes];
}
var tt = this.get(channel),
i = 0,
len = tokenTypes.length;
while(i < len){
if (tt == tokenTypes[i++]){
return true;
}
}
//no match found, put the token back
this.unget();
return false;
},
/**
* Determines if the next token matches the given token type.
* If so, that token is consumed; if not, an error is thrown.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token should be. If an array is passed,
* it's assumed that the token must be one of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {void}
* @method mustMatch
*/
mustMatch: function(tokenTypes, channel){
var token;
//always convert to an array, makes things easier
if (!(tokenTypes instanceof Array)){
tokenTypes = [tokenTypes];
}
if (!this.match.apply(this, arguments)){
token = this.LT(1);
throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name +
" at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
}
},
//-------------------------------------------------------------------------
// Consuming methods
//-------------------------------------------------------------------------
/**
* Keeps reading from the token stream until either one of the specified
* token types is found or until the end of the input is reached.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token should be. If an array is passed,
* it's assumed that the token must be one of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {void}
* @method advance
*/
advance: function(tokenTypes, channel){
while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){
this.get();
}
return this.LA(0);
},
/**
* Consumes the next token from the token stream.
* @return {int} The token type of the token that was just consumed.
* @method get
*/
get: function(channel){
var tokenInfo = this._tokenData,
reader = this._reader,
value,
i =0,
len = tokenInfo.length,
found = false,
token,
info;
//check the lookahead buffer first
if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){
i++;
this._token = this._lt[this._ltIndex++];
info = tokenInfo[this._token.type];
//obey channels logic
while((info.channel !== undefined && channel !== info.channel) &&
this._ltIndex < this._lt.length){
this._token = this._lt[this._ltIndex++];
info = tokenInfo[this._token.type];
i++;
}
//here be dragons
if ((info.channel === undefined || channel === info.channel) &&
this._ltIndex <= this._lt.length){
this._ltIndexCache.push(i);
return this._token.type;
}
}
//call token retriever method
token = this._getToken();
//if it should be hidden, don't save a token
if (token.type > -1 && !tokenInfo[token.type].hide){
//apply token channel
token.channel = tokenInfo[token.type].channel;
//save for later
this._token = token;
this._lt.push(token);
//save space that will be moved (must be done before array is truncated)
this._ltIndexCache.push(this._lt.length - this._ltIndex + i);
//keep the buffer under 5 items
if (this._lt.length > 5){
this._lt.shift();
}
//also keep the shift buffer under 5 items
if (this._ltIndexCache.length > 5){
this._ltIndexCache.shift();
}
//update lookahead index
this._ltIndex = this._lt.length;
}
/*
* Skip to the next token if:
* 1. The token type is marked as hidden.
* 2. The token type has a channel specified and it isn't the current channel.
*/
info = tokenInfo[token.type];
if (info &&
(info.hide ||
(info.channel !== undefined && channel !== info.channel))){
return this.get(channel);
} else {
//return just the type
return token.type;
}
},
/**
* Looks ahead a certain number of tokens and returns the token type at
* that position. This will throw an error if you lookahead past the
* end of input, past the size of the lookahead buffer, or back past
* the first token in the lookahead buffer.
* @param {int} The index of the token type to retrieve. 0 for the
* current token, 1 for the next, -1 for the previous, etc.
* @return {int} The token type of the token in the given position.
* @method LA
*/
LA: function(index){
var total = index,
tt;
if (index > 0){
//TODO: Store 5 somewhere
if (index > 5){
throw new Error("Too much lookahead.");
}
//get all those tokens
while(total){
tt = this.get();
total--;
}
//unget all those tokens
while(total < index){
this.unget();
total++;
}
} else if (index < 0){
if(this._lt[this._ltIndex+index]){
tt = this._lt[this._ltIndex+index].type;
} else {
throw new Error("Too much lookbehind.");
}
} else {
tt = this._token.type;
}
return tt;
},
/**
* Looks ahead a certain number of tokens and returns the token at
* that position. This will throw an error if you lookahead past the
* end of input, past the size of the lookahead buffer, or back past
* the first token in the lookahead buffer.
* @param {int} The index of the token type to retrieve. 0 for the
* current token, 1 for the next, -1 for the previous, etc.
* @return {Object} The token of the token in the given position.
* @method LA
*/
LT: function(index){
//lookahead first to prime the token buffer
this.LA(index);
//now find the token, subtract one because _ltIndex is already at the next index
return this._lt[this._ltIndex+index-1];
},
/**
* Returns the token type for the next token in the stream without
* consuming it.
* @return {int} The token type of the next token in the stream.
* @method peek
*/
peek: function(){
return this.LA(1);
},
/**
* Returns the actual token object for the last consumed token.
* @return {Token} The token object for the last consumed token.
* @method token
*/
token: function(){
return this._token;
},
/**
* Returns the name of the token for the given token type.
* @param {int} tokenType The type of token to get the name of.
* @return {String} The name of the token or "UNKNOWN_TOKEN" for any
* invalid token type.
* @method tokenName
*/
tokenName: function(tokenType){
if (tokenType < 0 || tokenType > this._tokenData.length){
return "UNKNOWN_TOKEN";
} else {
return this._tokenData[tokenType].name;
}
},
/**
* Returns the token type value for the given token name.
* @param {String} tokenName The name of the token whose value should be returned.
* @return {int} The token type value for the given token name or -1
* for an unknown token.
* @method tokenName
*/
tokenType: function(tokenName){
return this._tokenData[tokenName] || -1;
},
/**
* Returns the last consumed token to the token stream.
* @method unget
*/
unget: function(){
//if (this._ltIndex > -1){
if (this._ltIndexCache.length){
this._ltIndex -= this._ltIndexCache.pop();//--;
this._token = this._lt[this._ltIndex - 1];
} else {
throw new Error("Too much lookahead.");
}
}
};
parserlib.util = {
StringReader: StringReader,
SyntaxError : SyntaxError,
SyntaxUnit : SyntaxUnit,
EventTarget : EventTarget,
TokenStreamBase : TokenStreamBase
};
})();
/*
Parser-Lib
Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Version v0.1.9, Build time: 23-July-2012 10:52:31 */
(function(){
var EventTarget = parserlib.util.EventTarget,
TokenStreamBase = parserlib.util.TokenStreamBase,
StringReader = parserlib.util.StringReader,
SyntaxError = parserlib.util.SyntaxError,
SyntaxUnit = parserlib.util.SyntaxUnit;
var Colors = {
aliceblue :"#f0f8ff",
antiquewhite :"#faebd7",
aqua :"#00ffff",
aquamarine :"#7fffd4",
azure :"#f0ffff",
beige :"#f5f5dc",
bisque :"#ffe4c4",
black :"#000000",
blanchedalmond :"#ffebcd",
blue :"#0000ff",
blueviolet :"#8a2be2",
brown :"#a52a2a",
burlywood :"#deb887",
cadetblue :"#5f9ea0",
chartreuse :"#7fff00",
chocolate :"#d2691e",
coral :"#ff7f50",
cornflowerblue :"#6495ed",
cornsilk :"#fff8dc",
crimson :"#dc143c",
cyan :"#00ffff",
darkblue :"#00008b",
darkcyan :"#008b8b",
darkgoldenrod :"#b8860b",
darkgray :"#a9a9a9",
darkgreen :"#006400",
darkkhaki :"#bdb76b",
darkmagenta :"#8b008b",
darkolivegreen :"#556b2f",
darkorange :"#ff8c00",
darkorchid :"#9932cc",
darkred :"#8b0000",
darksalmon :"#e9967a",
darkseagreen :"#8fbc8f",
darkslateblue :"#483d8b",
darkslategray :"#2f4f4f",
darkturquoise :"#00ced1",
darkviolet :"#9400d3",
deeppink :"#ff1493",
deepskyblue :"#00bfff",
dimgray :"#696969",
dodgerblue :"#1e90ff",
firebrick :"#b22222",
floralwhite :"#fffaf0",
forestgreen :"#228b22",
fuchsia :"#ff00ff",
gainsboro :"#dcdcdc",
ghostwhite :"#f8f8ff",
gold :"#ffd700",
goldenrod :"#daa520",
gray :"#808080",
green :"#008000",
greenyellow :"#adff2f",
honeydew :"#f0fff0",
hotpink :"#ff69b4",
indianred :"#cd5c5c",
indigo :"#4b0082",
ivory :"#fffff0",
khaki :"#f0e68c",
lavender :"#e6e6fa",
lavenderblush :"#fff0f5",
lawngreen :"#7cfc00",
lemonchiffon :"#fffacd",
lightblue :"#add8e6",
lightcoral :"#f08080",
lightcyan :"#e0ffff",
lightgoldenrodyellow :"#fafad2",
lightgray :"#d3d3d3",
lightgreen :"#90ee90",
lightpink :"#ffb6c1",
lightsalmon :"#ffa07a",
lightseagreen :"#20b2aa",
lightskyblue :"#87cefa",
lightslategray :"#778899",
lightsteelblue :"#b0c4de",
lightyellow :"#ffffe0",
lime :"#00ff00",
limegreen :"#32cd32",
linen :"#faf0e6",
magenta :"#ff00ff",
maroon :"#800000",
mediumaquamarine:"#66cdaa",
mediumblue :"#0000cd",
mediumorchid :"#ba55d3",
mediumpurple :"#9370d8",
mediumseagreen :"#3cb371",
mediumslateblue :"#7b68ee",
mediumspringgreen :"#00fa9a",
mediumturquoise :"#48d1cc",
mediumvioletred :"#c71585",
midnightblue :"#191970",
mintcream :"#f5fffa",
mistyrose :"#ffe4e1",
moccasin :"#ffe4b5",
navajowhite :"#ffdead",
navy :"#000080",
oldlace :"#fdf5e6",
olive :"#808000",
olivedrab :"#6b8e23",
orange :"#ffa500",
orangered :"#ff4500",
orchid :"#da70d6",
palegoldenrod :"#eee8aa",
palegreen :"#98fb98",
paleturquoise :"#afeeee",
palevioletred :"#d87093",
papayawhip :"#ffefd5",
peachpuff :"#ffdab9",
peru :"#cd853f",
pink :"#ffc0cb",
plum :"#dda0dd",
powderblue :"#b0e0e6",
purple :"#800080",
red :"#ff0000",
rosybrown :"#bc8f8f",
royalblue :"#4169e1",
saddlebrown :"#8b4513",
salmon :"#fa8072",
sandybrown :"#f4a460",
seagreen :"#2e8b57",
seashell :"#fff5ee",
sienna :"#a0522d",
silver :"#c0c0c0",
skyblue :"#87ceeb",
slateblue :"#6a5acd",
slategray :"#708090",
snow :"#fffafa",
springgreen :"#00ff7f",
steelblue :"#4682b4",
tan :"#d2b48c",
teal :"#008080",
thistle :"#d8bfd8",
tomato :"#ff6347",
turquoise :"#40e0d0",
violet :"#ee82ee",
wheat :"#f5deb3",
white :"#ffffff",
whitesmoke :"#f5f5f5",
yellow :"#ffff00",
yellowgreen :"#9acd32"
};
/*global SyntaxUnit, Parser*/
/**
* Represents a selector combinator (whitespace, +, >).
* @namespace parserlib.css
* @class Combinator
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function Combinator(text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE);
/**
* The type of modifier.
* @type String
* @property type
*/
this.type = "unknown";
//pretty simple
if (/^\s+$/.test(text)){
this.type = "descendant";
} else if (text == ">"){
this.type = "child";
} else if (text == "+"){
this.type = "adjacent-sibling";
} else if (text == "~"){
this.type = "sibling";
}
}
Combinator.prototype = new SyntaxUnit();
Combinator.prototype.constructor = Combinator;
/*global SyntaxUnit, Parser*/
/**
* Represents a media feature, such as max-width:500.
* @namespace parserlib.css
* @class MediaFeature
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {SyntaxUnit} name The name of the feature.
* @param {SyntaxUnit} value The value of the feature or null if none.
*/
function MediaFeature(name, value){
SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE);
/**
* The name of the media feature
* @type String
* @property name
*/
this.name = name;
/**
* The value for the feature or null if there is none.
* @type SyntaxUnit
* @property value
*/
this.value = value;
}
MediaFeature.prototype = new SyntaxUnit();
MediaFeature.prototype.constructor = MediaFeature;
/*global SyntaxUnit, Parser*/
/**
* Represents an individual media query.
* @namespace parserlib.css
* @class MediaQuery
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} modifier The modifier "not" or "only" (or null).
* @param {String} mediaType The type of media (i.e., "print").
* @param {Array} parts Array of selectors parts making up this selector.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function MediaQuery(modifier, mediaType, features, line, col){
SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType + " " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE);
/**
* The media modifier ("not" or "only")
* @type String
* @property modifier
*/
this.modifier = modifier;
/**
* The mediaType (i.e., "print")
* @type String
* @property mediaType
*/
this.mediaType = mediaType;
/**
* The parts that make up the selector.
* @type Array
* @property features
*/
this.features = features;
}
MediaQuery.prototype = new SyntaxUnit();
MediaQuery.prototype.constructor = MediaQuery;
/*global Tokens, TokenStream, SyntaxError, Properties, Validation, ValidationError, SyntaxUnit,
PropertyValue, PropertyValuePart, SelectorPart, SelectorSubPart, Selector,
PropertyName, Combinator, MediaFeature, MediaQuery, EventTarget */
/**
* A CSS3 parser.
* @namespace parserlib.css
* @class Parser
* @constructor
* @param {Object} options (Optional) Various options for the parser:
* starHack (true|false) to allow IE6 star hack as valid,
* underscoreHack (true|false) to interpret leading underscores
* as IE6-7 targeting for known properties, ieFilters (true|false)
* to indicate that IE < 8 filters should be accepted and not throw
* syntax errors.
*/
function Parser(options){
//inherit event functionality
EventTarget.call(this);
this.options = options || {};
this._tokenStream = null;
}
//Static constants
Parser.DEFAULT_TYPE = 0;
Parser.COMBINATOR_TYPE = 1;
Parser.MEDIA_FEATURE_TYPE = 2;
Parser.MEDIA_QUERY_TYPE = 3;
Parser.PROPERTY_NAME_TYPE = 4;
Parser.PROPERTY_VALUE_TYPE = 5;
Parser.PROPERTY_VALUE_PART_TYPE = 6;
Parser.SELECTOR_TYPE = 7;
Parser.SELECTOR_PART_TYPE = 8;
Parser.SELECTOR_SUB_PART_TYPE = 9;
Parser.prototype = function(){
var proto = new EventTarget(), //new prototype
prop,
additions = {
//restore constructor
constructor: Parser,
//instance constants - yuck
DEFAULT_TYPE : 0,
COMBINATOR_TYPE : 1,
MEDIA_FEATURE_TYPE : 2,
MEDIA_QUERY_TYPE : 3,
PROPERTY_NAME_TYPE : 4,
PROPERTY_VALUE_TYPE : 5,
PROPERTY_VALUE_PART_TYPE : 6,
SELECTOR_TYPE : 7,
SELECTOR_PART_TYPE : 8,
SELECTOR_SUB_PART_TYPE : 9,
//-----------------------------------------------------------------
// Grammar
//-----------------------------------------------------------------
_stylesheet: function(){
/*
* stylesheet
* : [ CHARSET_SYM S* STRING S* ';' ]?
* [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
* [ namespace [S|CDO|CDC]* ]*
* [ [ ruleset | media | page | font_face | keyframes ] [S|CDO|CDC]* ]*
* ;
*/
var tokenStream = this._tokenStream,
charset = null,
count,
token,
tt;
this.fire("startstylesheet");
//try to read character set
this._charset();
this._skipCruft();
//try to read imports - may be more than one
while (tokenStream.peek() == Tokens.IMPORT_SYM){
this._import();
this._skipCruft();
}
//try to read namespaces - may be more than one
while (tokenStream.peek() == Tokens.NAMESPACE_SYM){
this._namespace();
this._skipCruft();
}
//get the next token
tt = tokenStream.peek();
//try to read the rest
while(tt > Tokens.EOF){
try {
switch(tt){
case Tokens.MEDIA_SYM:
this._media();
this._skipCruft();
break;
case Tokens.PAGE_SYM:
this._page();
this._skipCruft();
break;
case Tokens.FONT_FACE_SYM:
this._font_face();
this._skipCruft();
break;
case Tokens.KEYFRAMES_SYM:
this._keyframes();
this._skipCruft();
break;
case Tokens.UNKNOWN_SYM: //unknown @ rule
tokenStream.get();
if (!this.options.strict){
//fire error event
this.fire({
type: "error",
error: null,
message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
line: tokenStream.LT(0).startLine,
col: tokenStream.LT(0).startCol
});
//skip braces
count=0;
while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){
count++; //keep track of nesting depth
}
while(count){
tokenStream.advance([Tokens.RBRACE]);
count--;
}
} else {
//not a syntax error, rethrow it
throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol);
}
break;
case Tokens.S:
this._readWhitespace();
break;
default:
if(!this._ruleset()){
//error handling for known issues
switch(tt){
case Tokens.CHARSET_SYM:
token = tokenStream.LT(1);
this._charset(false);
throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol);
case Tokens.IMPORT_SYM:
token = tokenStream.LT(1);
this._import(false);
throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
case Tokens.NAMESPACE_SYM:
token = tokenStream.LT(1);
this._namespace(false);
throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
default:
tokenStream.get(); //get the last token
this._unexpectedToken(tokenStream.token());
}
}
}
} catch(ex) {
if (ex instanceof SyntaxError && !this.options.strict){
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
} else {
throw ex;
}
}
tt = tokenStream.peek();
}
if (tt != Tokens.EOF){
this._unexpectedToken(tokenStream.token());
}
this.fire("endstylesheet");
},
_charset: function(emit){
var tokenStream = this._tokenStream,
charset,
token,
line,
col;
if (tokenStream.match(Tokens.CHARSET_SYM)){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
tokenStream.mustMatch(Tokens.STRING);
token = tokenStream.token();
charset = token.value;
this._readWhitespace();
tokenStream.mustMatch(Tokens.SEMICOLON);
if (emit !== false){
this.fire({
type: "charset",
charset:charset,
line: line,
col: col
});
}
}
},
_import: function(emit){
/*
* import
* : IMPORT_SYM S*
* [STRING|URI] S* media_query_list? ';' S*
*/
var tokenStream = this._tokenStream,
tt,
uri,
importToken,
mediaList = [];
//read import symbol
tokenStream.mustMatch(Tokens.IMPORT_SYM);
importToken = tokenStream.token();
this._readWhitespace();
tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
//grab the URI value
uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
this._readWhitespace();
mediaList = this._media_query_list();
//must end with a semicolon
tokenStream.mustMatch(Tokens.SEMICOLON);
this._readWhitespace();
if (emit !== false){
this.fire({
type: "import",
uri: uri,
media: mediaList,
line: importToken.startLine,
col: importToken.startCol
});
}
},
_namespace: function(emit){
/*
* namespace
* : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
*/
var tokenStream = this._tokenStream,
line,
col,
prefix,
uri;
//read import symbol
tokenStream.mustMatch(Tokens.NAMESPACE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
//it's a namespace prefix - no _namespace_prefix() method because it's just an IDENT
if (tokenStream.match(Tokens.IDENT)){
prefix = tokenStream.token().value;
this._readWhitespace();
}
tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
/*if (!tokenStream.match(Tokens.STRING)){
tokenStream.mustMatch(Tokens.URI);
}*/
//grab the URI value
uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
this._readWhitespace();
//must end with a semicolon
tokenStream.mustMatch(Tokens.SEMICOLON);
this._readWhitespace();
if (emit !== false){
this.fire({
type: "namespace",
prefix: prefix,
uri: uri,
line: line,
col: col
});
}
},
_media: function(){
/*
* media
* : MEDIA_SYM S* media_query_list S* '{' S* ruleset* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
mediaList;// = [];
//look for @media
tokenStream.mustMatch(Tokens.MEDIA_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
mediaList = this._media_query_list();
tokenStream.mustMatch(Tokens.LBRACE);
this._readWhitespace();
this.fire({
type: "startmedia",
media: mediaList,
line: line,
col: col
});
while(true) {
if (tokenStream.peek() == Tokens.PAGE_SYM){
this._page();
} else if (!this._ruleset()){
break;
}
}
tokenStream.mustMatch(Tokens.RBRACE);
this._readWhitespace();
this.fire({
type: "endmedia",
media: mediaList,
line: line,
col: col
});
},
//CSS3 Media Queries
_media_query_list: function(){
/*
* media_query_list
* : S* [media_query [ ',' S* media_query ]* ]?
* ;
*/
var tokenStream = this._tokenStream,
mediaList = [];
this._readWhitespace();
if (tokenStream.peek() == Tokens.IDENT || tokenStream.peek() == Tokens.LPAREN){
mediaList.push(this._media_query());
}
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
mediaList.push(this._media_query());
}
return mediaList;
},
/*
* Note: "expression" in the grammar maps to the _media_expression
* method.
*/
_media_query: function(){
/*
* media_query
* : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
* | expression [ AND S* expression ]*
* ;
*/
var tokenStream = this._tokenStream,
type = null,
ident = null,
token = null,
expressions = [];
if (tokenStream.match(Tokens.IDENT)){
ident = tokenStream.token().value.toLowerCase();
//since there's no custom tokens for these, need to manually check
if (ident != "only" && ident != "not"){
tokenStream.unget();
ident = null;
} else {
token = tokenStream.token();
}
}
this._readWhitespace();
if (tokenStream.peek() == Tokens.IDENT){
type = this._media_type();
if (token === null){
token = tokenStream.token();
}
} else if (tokenStream.peek() == Tokens.LPAREN){
if (token === null){
token = tokenStream.LT(1);
}
expressions.push(this._media_expression());
}
if (type === null && expressions.length === 0){
return null;
} else {
this._readWhitespace();
while (tokenStream.match(Tokens.IDENT)){
if (tokenStream.token().value.toLowerCase() != "and"){
this._unexpectedToken(tokenStream.token());
}
this._readWhitespace();
expressions.push(this._media_expression());
}
}
return new MediaQuery(ident, type, expressions, token.startLine, token.startCol);
},
//CSS3 Media Queries
_media_type: function(){
/*
* media_type
* : IDENT
* ;
*/
return this._media_feature();
},
/**
* Note: in CSS3 Media Queries, this is called "expression".
* Renamed here to avoid conflict with CSS3 Selectors
* definition of "expression". Also note that "expr" in the
* grammar now maps to "expression" from CSS3 selectors.
* @method _media_expression
* @private
*/
_media_expression: function(){
/*
* expression
* : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
* ;
*/
var tokenStream = this._tokenStream,
feature = null,
token,
expression = null;
tokenStream.mustMatch(Tokens.LPAREN);
feature = this._media_feature();
this._readWhitespace();
if (tokenStream.match(Tokens.COLON)){
this._readWhitespace();
token = tokenStream.LT(1);
expression = this._expression();
}
tokenStream.mustMatch(Tokens.RPAREN);
this._readWhitespace();
return new MediaFeature(feature, (expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null));
},
//CSS3 Media Queries
_media_feature: function(){
/*
* media_feature
* : IDENT
* ;
*/
var tokenStream = this._tokenStream;
tokenStream.mustMatch(Tokens.IDENT);
return SyntaxUnit.fromToken(tokenStream.token());
},
//CSS3 Paged Media
_page: function(){
/*
* page:
* PAGE_SYM S* IDENT? pseudo_page? S*
* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
identifier = null,
pseudoPage = null;
//look for @page
tokenStream.mustMatch(Tokens.PAGE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
if (tokenStream.match(Tokens.IDENT)){
identifier = tokenStream.token().value;
//The value 'auto' may not be used as a page name and MUST be treated as a syntax error.
if (identifier.toLowerCase() === "auto"){
this._unexpectedToken(tokenStream.token());
}
}
//see if there's a colon upcoming
if (tokenStream.peek() == Tokens.COLON){
pseudoPage = this._pseudo_page();
}
this._readWhitespace();
this.fire({
type: "startpage",
id: identifier,
pseudo: pseudoPage,
line: line,
col: col
});
this._readDeclarations(true, true);
this.fire({
type: "endpage",
id: identifier,
pseudo: pseudoPage,
line: line,
col: col
});
},
//CSS3 Paged Media
_margin: function(){
/*
* margin :
* margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
marginSym = this._margin_sym();
if (marginSym){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this.fire({
type: "startpagemargin",
margin: marginSym,
line: line,
col: col
});
this._readDeclarations(true);
this.fire({
type: "endpagemargin",
margin: marginSym,
line: line,
col: col
});
return true;
} else {
return false;
}
},
//CSS3 Paged Media
_margin_sym: function(){
/*
* margin_sym :
* TOPLEFTCORNER_SYM |
* TOPLEFT_SYM |
* TOPCENTER_SYM |
* TOPRIGHT_SYM |
* TOPRIGHTCORNER_SYM |
* BOTTOMLEFTCORNER_SYM |
* BOTTOMLEFT_SYM |
* BOTTOMCENTER_SYM |
* BOTTOMRIGHT_SYM |
* BOTTOMRIGHTCORNER_SYM |
* LEFTTOP_SYM |
* LEFTMIDDLE_SYM |
* LEFTBOTTOM_SYM |
* RIGHTTOP_SYM |
* RIGHTMIDDLE_SYM |
* RIGHTBOTTOM_SYM
* ;
*/
var tokenStream = this._tokenStream;
if(tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM,
Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM,
Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM,
Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM,
Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM,
Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM,
Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM]))
{
return SyntaxUnit.fromToken(tokenStream.token());
} else {
return null;
}
},
_pseudo_page: function(){
/*
* pseudo_page
* : ':' IDENT
* ;
*/
var tokenStream = this._tokenStream;
tokenStream.mustMatch(Tokens.COLON);
tokenStream.mustMatch(Tokens.IDENT);
//TODO: CSS3 Paged Media says only "left", "center", and "right" are allowed
return tokenStream.token().value;
},
_font_face: function(){
/*
* font_face
* : FONT_FACE_SYM S*
* '{' S* declaration [ ';' S* declaration ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col;
//look for @page
tokenStream.mustMatch(Tokens.FONT_FACE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
this.fire({
type: "startfontface",
line: line,
col: col
});
this._readDeclarations(true);
this.fire({
type: "endfontface",
line: line,
col: col
});
},
_operator: function(){
/*
* operator
* : '/' S* | ',' S* | /( empty )/
* ;
*/
var tokenStream = this._tokenStream,
token = null;
if (tokenStream.match([Tokens.SLASH, Tokens.COMMA])){
token = tokenStream.token();
this._readWhitespace();
}
return token ? PropertyValuePart.fromToken(token) : null;
},
_combinator: function(){
/*
* combinator
* : PLUS S* | GREATER S* | TILDE S* | S+
* ;
*/
var tokenStream = this._tokenStream,
value = null,
token;
if(tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])){
token = tokenStream.token();
value = new Combinator(token.value, token.startLine, token.startCol);
this._readWhitespace();
}
return value;
},
_unary_operator: function(){
/*
* unary_operator
* : '-' | '+'
* ;
*/
var tokenStream = this._tokenStream;
if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){
return tokenStream.token().value;
} else {
return null;
}
},
_property: function(){
/*
* property
* : IDENT S*
* ;
*/
var tokenStream = this._tokenStream,
value = null,
hack = null,
tokenValue,
token,
line,
col;
//check for star hack - throws error if not allowed
if (tokenStream.peek() == Tokens.STAR && this.options.starHack){
tokenStream.get();
token = tokenStream.token();
hack = token.value;
line = token.startLine;
col = token.startCol;
}
if(tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
tokenValue = token.value;
//check for underscore hack - no error if not allowed because it's valid CSS syntax
if (tokenValue.charAt(0) == "_" && this.options.underscoreHack){
hack = "_";
tokenValue = tokenValue.substring(1);
}
value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol));
this._readWhitespace();
}
return value;
},
//Augmented with CSS3 Selectors
_ruleset: function(){
/*
* ruleset
* : selectors_group
* '{' S* declaration? [ ';' S* declaration? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
tt,
selectors;
/*
* Error Recovery: If even a single selector fails to parse,
* then the entire ruleset should be thrown away.
*/
try {
selectors = this._selectors_group();
} catch (ex){
if (ex instanceof SyntaxError && !this.options.strict){
//fire error event
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
//skip over everything until closing brace
tt = tokenStream.advance([Tokens.RBRACE]);
if (tt == Tokens.RBRACE){
//if there's a right brace, the rule is finished so don't do anything
} else {
//otherwise, rethrow the error because it wasn't handled properly
throw ex;
}
} else {
//not a syntax error, rethrow it
throw ex;
}
//trigger parser to continue
return true;
}
//if it got here, all selectors parsed
if (selectors){
this.fire({
type: "startrule",
selectors: selectors,
line: selectors[0].line,
col: selectors[0].col
});
this._readDeclarations(true);
this.fire({
type: "endrule",
selectors: selectors,
line: selectors[0].line,
col: selectors[0].col
});
}
return selectors;
},
//CSS3 Selectors
_selectors_group: function(){
/*
* selectors_group
* : selector [ COMMA S* selector ]*
* ;
*/
var tokenStream = this._tokenStream,
selectors = [],
selector;
selector = this._selector();
if (selector !== null){
selectors.push(selector);
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
selector = this._selector();
if (selector !== null){
selectors.push(selector);
} else {
this._unexpectedToken(tokenStream.LT(1));
}
}
}
return selectors.length ? selectors : null;
},
//CSS3 Selectors
_selector: function(){
/*
* selector
* : simple_selector_sequence [ combinator simple_selector_sequence ]*
* ;
*/
var tokenStream = this._tokenStream,
selector = [],
nextSelector = null,
combinator = null,
ws = null;
//if there's no simple selector, then there's no selector
nextSelector = this._simple_selector_sequence();
if (nextSelector === null){
return null;
}
selector.push(nextSelector);
do {
//look for a combinator
combinator = this._combinator();
if (combinator !== null){
selector.push(combinator);
nextSelector = this._simple_selector_sequence();
//there must be a next selector
if (nextSelector === null){
this._unexpectedToken(this.LT(1));
} else {
//nextSelector is an instance of SelectorPart
selector.push(nextSelector);
}
} else {
//if there's not whitespace, we're done
if (this._readWhitespace()){
//add whitespace separator
ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol);
//combinator is not required
combinator = this._combinator();
//selector is required if there's a combinator
nextSelector = this._simple_selector_sequence();
if (nextSelector === null){
if (combinator !== null){
this._unexpectedToken(tokenStream.LT(1));
}
} else {
if (combinator !== null){
selector.push(combinator);
} else {
selector.push(ws);
}
selector.push(nextSelector);
}
} else {
break;
}
}
} while(true);
return new Selector(selector, selector[0].line, selector[0].col);
},
//CSS3 Selectors
_simple_selector_sequence: function(){
/*
* simple_selector_sequence
* : [ type_selector | universal ]
* [ HASH | class | attrib | pseudo | negation ]*
* | [ HASH | class | attrib | pseudo | negation ]+
* ;
*/
var tokenStream = this._tokenStream,
//parts of a simple selector
elementName = null,
modifiers = [],
//complete selector text
selectorText= "",
//the different parts after the element name to search for
components = [
//HASH
function(){
return tokenStream.match(Tokens.HASH) ?
new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
null;
},
this._class,
this._attrib,
this._pseudo,
this._negation
],
i = 0,
len = components.length,
component = null,
found = false,
line,
col;
//get starting line and column for the selector
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
elementName = this._type_selector();
if (!elementName){
elementName = this._universal();
}
if (elementName !== null){
selectorText += elementName;
}
while(true){
//whitespace means we're done
if (tokenStream.peek() === Tokens.S){
break;
}
//check for each component
while(i < len && component === null){
component = components[i++].call(this);
}
if (component === null){
//we don't have a selector
if (selectorText === ""){
return null;
} else {
break;
}
} else {
i = 0;
modifiers.push(component);
selectorText += component.toString();
component = null;
}
}
return selectorText !== "" ?
new SelectorPart(elementName, modifiers, selectorText, line, col) :
null;
},
//CSS3 Selectors
_type_selector: function(){
/*
* type_selector
* : [ namespace_prefix ]? element_name
* ;
*/
var tokenStream = this._tokenStream,
ns = this._namespace_prefix(),
elementName = this._element_name();
if (!elementName){
/*
* Need to back out the namespace that was read due to both
* type_selector and universal reading namespace_prefix
* first. Kind of hacky, but only way I can figure out
* right now how to not change the grammar.
*/
if (ns){
tokenStream.unget();
if (ns.length > 1){
tokenStream.unget();
}
}
return null;
} else {
if (ns){
elementName.text = ns + elementName.text;
elementName.col -= ns.length;
}
return elementName;
}
},
//CSS3 Selectors
_class: function(){
/*
* class
* : '.' IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.DOT)){
tokenStream.mustMatch(Tokens.IDENT);
token = tokenStream.token();
return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1);
} else {
return null;
}
},
//CSS3 Selectors
_element_name: function(){
/*
* element_name
* : IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol);
} else {
return null;
}
},
//CSS3 Selectors
_namespace_prefix: function(){
/*
* namespace_prefix
* : [ IDENT | '*' ]? '|'
* ;
*/
var tokenStream = this._tokenStream,
value = "";
//verify that this is a namespace prefix
if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE){
if(tokenStream.match([Tokens.IDENT, Tokens.STAR])){
value += tokenStream.token().value;
}
tokenStream.mustMatch(Tokens.PIPE);
value += "|";
}
return value.length ? value : null;
},
//CSS3 Selectors
_universal: function(){
/*
* universal
* : [ namespace_prefix ]? '*'
* ;
*/
var tokenStream = this._tokenStream,
value = "",
ns;
ns = this._namespace_prefix();
if(ns){
value += ns;
}
if(tokenStream.match(Tokens.STAR)){
value += "*";
}
return value.length ? value : null;
},
//CSS3 Selectors
_attrib: function(){
/*
* attrib
* : '[' S* [ namespace_prefix ]? IDENT S*
* [ [ PREFIXMATCH |
* SUFFIXMATCH |
* SUBSTRINGMATCH |
* '=' |
* INCLUDES |
* DASHMATCH ] S* [ IDENT | STRING ] S*
* ]? ']'
* ;
*/
var tokenStream = this._tokenStream,
value = null,
ns,
token;
if (tokenStream.match(Tokens.LBRACKET)){
token = tokenStream.token();
value = token.value;
value += this._readWhitespace();
ns = this._namespace_prefix();
if (ns){
value += ns;
}
tokenStream.mustMatch(Tokens.IDENT);
value += tokenStream.token().value;
value += this._readWhitespace();
if(tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH,
Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])){
value += tokenStream.token().value;
value += this._readWhitespace();
tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
value += tokenStream.token().value;
value += this._readWhitespace();
}
tokenStream.mustMatch(Tokens.RBRACKET);
return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol);
} else {
return null;
}
},
//CSS3 Selectors
_pseudo: function(){
/*
* pseudo
* : ':' ':'? [ IDENT | functional_pseudo ]
* ;
*/
var tokenStream = this._tokenStream,
pseudo = null,
colons = ":",
line,
col;
if (tokenStream.match(Tokens.COLON)){
if (tokenStream.match(Tokens.COLON)){
colons += ":";
}
if (tokenStream.match(Tokens.IDENT)){
pseudo = tokenStream.token().value;
line = tokenStream.token().startLine;
col = tokenStream.token().startCol - colons.length;
} else if (tokenStream.peek() == Tokens.FUNCTION){
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol - colons.length;
pseudo = this._functional_pseudo();
}
if (pseudo){
pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col);
}
}
return pseudo;
},
//CSS3 Selectors
_functional_pseudo: function(){
/*
* functional_pseudo
* : FUNCTION S* expression ')'
* ;
*/
var tokenStream = this._tokenStream,
value = null;
if(tokenStream.match(Tokens.FUNCTION)){
value = tokenStream.token().value;
value += this._readWhitespace();
value += this._expression();
tokenStream.mustMatch(Tokens.RPAREN);
value += ")";
}
return value;
},
//CSS3 Selectors
_expression: function(){
/*
* expression
* : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
* ;
*/
var tokenStream = this._tokenStream,
value = "";
while(tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION,
Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH,
Tokens.FREQ, Tokens.ANGLE, Tokens.TIME,
Tokens.RESOLUTION])){
value += tokenStream.token().value;
value += this._readWhitespace();
}
return value.length ? value : null;
},
//CSS3 Selectors
_negation: function(){
/*
* negation
* : NOT S* negation_arg S* ')'
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
value = "",
arg,
subpart = null;
if (tokenStream.match(Tokens.NOT)){
value = tokenStream.token().value;
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
value += this._readWhitespace();
arg = this._negation_arg();
value += arg;
value += this._readWhitespace();
tokenStream.match(Tokens.RPAREN);
value += tokenStream.token().value;
subpart = new SelectorSubPart(value, "not", line, col);
subpart.args.push(arg);
}
return subpart;
},
//CSS3 Selectors
_negation_arg: function(){
/*
* negation_arg
* : type_selector | universal | HASH | class | attrib | pseudo
* ;
*/
var tokenStream = this._tokenStream,
args = [
this._type_selector,
this._universal,
function(){
return tokenStream.match(Tokens.HASH) ?
new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
null;
},
this._class,
this._attrib,
this._pseudo
],
arg = null,
i = 0,
len = args.length,
elementName,
line,
col,
part;
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
while(i < len && arg === null){
arg = args[i].call(this);
i++;
}
//must be a negation arg
if (arg === null){
this._unexpectedToken(tokenStream.LT(1));
}
//it's an element name
if (arg.type == "elementName"){
part = new SelectorPart(arg, [], arg.toString(), line, col);
} else {
part = new SelectorPart(null, [arg], arg.toString(), line, col);
}
return part;
},
_declaration: function(){
/*
* declaration
* : property ':' S* expr prio?
* | /( empty )/
* ;
*/
var tokenStream = this._tokenStream,
property = null,
expr = null,
prio = null,
error = null,
invalid = null,
propertyName= "";
property = this._property();
if (property !== null){
tokenStream.mustMatch(Tokens.COLON);
this._readWhitespace();
expr = this._expr();
//if there's no parts for the value, it's an error
if (!expr || expr.length === 0){
this._unexpectedToken(tokenStream.LT(1));
}
prio = this._prio();
/*
* If hacks should be allowed, then only check the root
* property. If hacks should not be allowed, treat
* _property or *property as invalid properties.
*/
propertyName = property.toString();
if (this.options.starHack && property.hack == "*" ||
this.options.underscoreHack && property.hack == "_") {
propertyName = property.text;
}
try {
this._validateProperty(propertyName, expr);
} catch (ex) {
invalid = ex;
}
this.fire({
type: "property",
property: property,
value: expr,
important: prio,
line: property.line,
col: property.col,
invalid: invalid
});
return true;
} else {
return false;
}
},
_prio: function(){
/*
* prio
* : IMPORTANT_SYM S*
* ;
*/
var tokenStream = this._tokenStream,
result = tokenStream.match(Tokens.IMPORTANT_SYM);
this._readWhitespace();
return result;
},
_expr: function(){
/*
* expr
* : term [ operator term ]*
* ;
*/
var tokenStream = this._tokenStream,
values = [],
//valueParts = [],
value = null,
operator = null;
value = this._term();
if (value !== null){
values.push(value);
do {
operator = this._operator();
//if there's an operator, keep building up the value parts
if (operator){
values.push(operator);
} /*else {
//if there's not an operator, you have a full value
values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
valueParts = [];
}*/
value = this._term();
if (value === null){
break;
} else {
values.push(value);
}
} while(true);
}
//cleanup
/*if (valueParts.length){
values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
}*/
return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null;
},
_term: function(){
/*
* term
* : unary_operator?
* [ NUMBER S* | PERCENTAGE S* | LENGTH S* | ANGLE S* |
* TIME S* | FREQ S* | function | ie_function ]
* | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor
* ;
*/
var tokenStream = this._tokenStream,
unary = null,
value = null,
token,
line,
col;
//returns the operator or null
unary = this._unary_operator();
if (unary !== null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
//exception for IE filters
if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){
value = this._ie_function();
if (unary === null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
//see if there's a simple match
} else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
Tokens.ANGLE, Tokens.TIME,
Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])){
value = tokenStream.token().value;
if (unary === null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
this._readWhitespace();
} else {
//see if it's a color
token = this._hexcolor();
if (token === null){
//if there's no unary, get the start of the next token for line/col info
if (unary === null){
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
}
//has to be a function
if (value === null){
/*
* This checks for alpha(opacity=0) style of IE
* functions. IE_FUNCTION only presents progid: style.
*/
if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){
value = this._ie_function();
} else {
value = this._function();
}
}
/*if (value === null){
return null;
//throw new Error("Expected identifier at line " + tokenStream.token().startLine + ", character " + tokenStream.token().startCol + ".");
}*/
} else {
value = token.value;
if (unary === null){
line = token.startLine;
col = token.startCol;
}
}
}
return value !== null ?
new PropertyValuePart(unary !== null ? unary + value : value, line, col) :
null;
},
_function: function(){
/*
* function
* : FUNCTION S* expr ')' S*
* ;
*/
var tokenStream = this._tokenStream,
functionText = null,
expr = null,
lt;
if (tokenStream.match(Tokens.FUNCTION)){
functionText = tokenStream.token().value;
this._readWhitespace();
expr = this._expr();
functionText += expr;
//START: Horrible hack in case it's an IE filter
if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){
do {
if (this._readWhitespace()){
functionText += tokenStream.token().value;
}
//might be second time in the loop
if (tokenStream.LA(0) == Tokens.COMMA){
functionText += tokenStream.token().value;
}
tokenStream.match(Tokens.IDENT);
functionText += tokenStream.token().value;
tokenStream.match(Tokens.EQUALS);
functionText += tokenStream.token().value;
//functionText += this._term();
lt = tokenStream.peek();
while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
tokenStream.get();
functionText += tokenStream.token().value;
lt = tokenStream.peek();
}
} while(tokenStream.match([Tokens.COMMA, Tokens.S]));
}
//END: Horrible Hack
tokenStream.match(Tokens.RPAREN);
functionText += ")";
this._readWhitespace();
}
return functionText;
},
_ie_function: function(){
/* (My own extension)
* ie_function
* : IE_FUNCTION S* IDENT '=' term [S* ','? IDENT '=' term]+ ')' S*
* ;
*/
var tokenStream = this._tokenStream,
functionText = null,
expr = null,
lt;
//IE function can begin like a regular function, too
if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){
functionText = tokenStream.token().value;
do {
if (this._readWhitespace()){
functionText += tokenStream.token().value;
}
//might be second time in the loop
if (tokenStream.LA(0) == Tokens.COMMA){
functionText += tokenStream.token().value;
}
tokenStream.match(Tokens.IDENT);
functionText += tokenStream.token().value;
tokenStream.match(Tokens.EQUALS);
functionText += tokenStream.token().value;
//functionText += this._term();
lt = tokenStream.peek();
while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
tokenStream.get();
functionText += tokenStream.token().value;
lt = tokenStream.peek();
}
} while(tokenStream.match([Tokens.COMMA, Tokens.S]));
tokenStream.match(Tokens.RPAREN);
functionText += ")";
this._readWhitespace();
}
return functionText;
},
_hexcolor: function(){
/*
* There is a constraint on the color that it must
* have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
* after the "#"; e.g., "#000" is OK, but "#abcd" is not.
*
* hexcolor
* : HASH S*
* ;
*/
var tokenStream = this._tokenStream,
token = null,
color;
if(tokenStream.match(Tokens.HASH)){
//need to do some validation here
token = tokenStream.token();
color = token.value;
if (!/#[a-f0-9]{3,6}/i.test(color)){
throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
}
this._readWhitespace();
}
return token;
},
//-----------------------------------------------------------------
// Animations methods
//-----------------------------------------------------------------
_keyframes: function(){
/*
* keyframes:
* : KEYFRAMES_SYM S* keyframe_name S* '{' S* keyframe_rule* '}' {
* ;
*/
var tokenStream = this._tokenStream,
token,
tt,
name,
prefix = "";
tokenStream.mustMatch(Tokens.KEYFRAMES_SYM);
token = tokenStream.token();
if (/^@\-([^\-]+)\-/.test(token.value)) {
prefix = RegExp.$1;
}
this._readWhitespace();
name = this._keyframe_name();
this._readWhitespace();
tokenStream.mustMatch(Tokens.LBRACE);
this.fire({
type: "startkeyframes",
name: name,
prefix: prefix,
line: token.startLine,
col: token.startCol
});
this._readWhitespace();
tt = tokenStream.peek();
//check for key
while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) {
this._keyframe_rule();
this._readWhitespace();
tt = tokenStream.peek();
}
this.fire({
type: "endkeyframes",
name: name,
prefix: prefix,
line: token.startLine,
col: token.startCol
});
this._readWhitespace();
tokenStream.mustMatch(Tokens.RBRACE);
},
_keyframe_name: function(){
/*
* keyframe_name:
* : IDENT
* | STRING
* ;
*/
var tokenStream = this._tokenStream,
token;
tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
return SyntaxUnit.fromToken(tokenStream.token());
},
_keyframe_rule: function(){
/*
* keyframe_rule:
* : key_list S*
* '{' S* declaration [ ';' S* declaration ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
token,
keyList = this._key_list();
this.fire({
type: "startkeyframerule",
keys: keyList,
line: keyList[0].line,
col: keyList[0].col
});
this._readDeclarations(true);
this.fire({
type: "endkeyframerule",
keys: keyList,
line: keyList[0].line,
col: keyList[0].col
});
},
_key_list: function(){
/*
* key_list:
* : key [ S* ',' S* key]*
* ;
*/
var tokenStream = this._tokenStream,
token,
key,
keyList = [];
//must be least one key
keyList.push(this._key());
this._readWhitespace();
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
keyList.push(this._key());
this._readWhitespace();
}
return keyList;
},
_key: function(){
/*
* There is a restriction that IDENT can be only "from" or "to".
*
* key
* : PERCENTAGE
* | IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.PERCENTAGE)){
return SyntaxUnit.fromToken(tokenStream.token());
} else if (tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
if (/from|to/i.test(token.value)){
return SyntaxUnit.fromToken(token);
}
tokenStream.unget();
}
//if it gets here, there wasn't a valid token, so time to explode
this._unexpectedToken(tokenStream.LT(1));
},
//-----------------------------------------------------------------
// Helper methods
//-----------------------------------------------------------------
/**
* Not part of CSS grammar, but useful for skipping over
* combination of white space and HTML-style comments.
* @return {void}
* @method _skipCruft
* @private
*/
_skipCruft: function(){
while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){
//noop
}
},
/**
* Not part of CSS grammar, but this pattern occurs frequently
* in the official CSS grammar. Split out here to eliminate
* duplicate code.
* @param {Boolean} checkStart Indicates if the rule should check
* for the left brace at the beginning.
* @param {Boolean} readMargins Indicates if the rule should check
* for margin patterns.
* @return {void}
* @method _readDeclarations
* @private
*/
_readDeclarations: function(checkStart, readMargins){
/*
* Reads the pattern
* S* '{' S* declaration [ ';' S* declaration ]* '}' S*
* or
* S* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
* Note that this is how it is described in CSS3 Paged Media, but is actually incorrect.
* A semicolon is only necessary following a delcaration is there's another declaration
* or margin afterwards.
*/
var tokenStream = this._tokenStream,
tt;
this._readWhitespace();
if (checkStart){
tokenStream.mustMatch(Tokens.LBRACE);
}
this._readWhitespace();
try {
while(true){
if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){
//noop
} else if (this._declaration()){
if (!tokenStream.match(Tokens.SEMICOLON)){
break;
}
} else {
break;
}
//if ((!this._margin() && !this._declaration()) || !tokenStream.match(Tokens.SEMICOLON)){
// break;
//}
this._readWhitespace();
}
tokenStream.mustMatch(Tokens.RBRACE);
this._readWhitespace();
} catch (ex) {
if (ex instanceof SyntaxError && !this.options.strict){
//fire error event
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
//see if there's another declaration
tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]);
if (tt == Tokens.SEMICOLON){
//if there's a semicolon, then there might be another declaration
this._readDeclarations(false, readMargins);
} else if (tt != Tokens.RBRACE){
//if there's a right brace, the rule is finished so don't do anything
//otherwise, rethrow the error because it wasn't handled properly
throw ex;
}
} else {
//not a syntax error, rethrow it
throw ex;
}
}
},
/**
* In some cases, you can end up with two white space tokens in a
* row. Instead of making a change in every function that looks for
* white space, this function is used to match as much white space
* as necessary.
* @method _readWhitespace
* @return {String} The white space if found, empty string if not.
* @private
*/
_readWhitespace: function(){
var tokenStream = this._tokenStream,
ws = "";
while(tokenStream.match(Tokens.S)){
ws += tokenStream.token().value;
}
return ws;
},
/**
* Throws an error when an unexpected token is found.
* @param {Object} token The token that was found.
* @method _unexpectedToken
* @return {void}
* @private
*/
_unexpectedToken: function(token){
throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
},
/**
* Helper method used for parsing subparts of a style sheet.
* @return {void}
* @method _verifyEnd
* @private
*/
_verifyEnd: function(){
if (this._tokenStream.LA(1) != Tokens.EOF){
this._unexpectedToken(this._tokenStream.LT(1));
}
},
//-----------------------------------------------------------------
// Validation methods
//-----------------------------------------------------------------
_validateProperty: function(property, value){
Validation.validate(property, value);
},
//-----------------------------------------------------------------
// Parsing methods
//-----------------------------------------------------------------
parse: function(input){
this._tokenStream = new TokenStream(input, Tokens);
this._stylesheet();
},
parseStyleSheet: function(input){
//just passthrough
return this.parse(input);
},
parseMediaQuery: function(input){
this._tokenStream = new TokenStream(input, Tokens);
var result = this._media_query();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a property value (everything after the semicolon).
* @return {parserlib.css.PropertyValue} The property value.
* @throws parserlib.util.SyntaxError If an unexpected token is found.
* @method parserPropertyValue
*/
parsePropertyValue: function(input){
this._tokenStream = new TokenStream(input, Tokens);
this._readWhitespace();
var result = this._expr();
//okay to have a trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a complete CSS rule, including selectors and
* properties.
* @param {String} input The text to parser.
* @return {Boolean} True if the parse completed successfully, false if not.
* @method parseRule
*/
parseRule: function(input){
this._tokenStream = new TokenStream(input, Tokens);
//skip any leading white space
this._readWhitespace();
var result = this._ruleset();
//skip any trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a single CSS selector (no comma)
* @param {String} input The text to parse as a CSS selector.
* @return {Selector} An object representing the selector.
* @throws parserlib.util.SyntaxError If an unexpected token is found.
* @method parseSelector
*/
parseSelector: function(input){
this._tokenStream = new TokenStream(input, Tokens);
//skip any leading white space
this._readWhitespace();
var result = this._selector();
//skip any trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses an HTML style attribute: a set of CSS declarations
* separated by semicolons.
* @param {String} input The text to parse as a style attribute
* @return {void}
* @method parseStyleAttribute
*/
parseStyleAttribute: function(input){
input += "}"; // for error recovery in _readDeclarations()
this._tokenStream = new TokenStream(input, Tokens);
this._readDeclarations();
}
};
//copy over onto prototype
for (prop in additions){
if (additions.hasOwnProperty(prop)){
proto[prop] = additions[prop];
}
}
return proto;
}();
/*
nth
: S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? |
['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S*
;
*/
/*global Validation, ValidationTypes, ValidationError*/
var Properties = {
//A
"alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>",
"alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"animation" : 1,
"animation-delay" : { multi: "<time>", comma: true },
"animation-direction" : { multi: "normal | alternate", comma: true },
"animation-duration" : { multi: "<time>", comma: true },
"animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"animation-name" : { multi: "none | <ident>", comma: true },
"animation-play-state" : { multi: "running | paused", comma: true },
"animation-timing-function" : 1,
//vendor prefixed
"-moz-animation-delay" : { multi: "<time>", comma: true },
"-moz-animation-direction" : { multi: "normal | alternate", comma: true },
"-moz-animation-duration" : { multi: "<time>", comma: true },
"-moz-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-moz-animation-name" : { multi: "none | <ident>", comma: true },
"-moz-animation-play-state" : { multi: "running | paused", comma: true },
"-ms-animation-delay" : { multi: "<time>", comma: true },
"-ms-animation-direction" : { multi: "normal | alternate", comma: true },
"-ms-animation-duration" : { multi: "<time>", comma: true },
"-ms-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-ms-animation-name" : { multi: "none | <ident>", comma: true },
"-ms-animation-play-state" : { multi: "running | paused", comma: true },
"-webkit-animation-delay" : { multi: "<time>", comma: true },
"-webkit-animation-direction" : { multi: "normal | alternate", comma: true },
"-webkit-animation-duration" : { multi: "<time>", comma: true },
"-webkit-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-webkit-animation-name" : { multi: "none | <ident>", comma: true },
"-webkit-animation-play-state" : { multi: "running | paused", comma: true },
"-o-animation-delay" : { multi: "<time>", comma: true },
"-o-animation-direction" : { multi: "normal | alternate", comma: true },
"-o-animation-duration" : { multi: "<time>", comma: true },
"-o-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-o-animation-name" : { multi: "none | <ident>", comma: true },
"-o-animation-play-state" : { multi: "running | paused", comma: true },
"appearance" : "icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | inherit",
"azimuth" : function (expression) {
var simple = "<angle> | leftwards | rightwards | inherit",
direction = "left-side | far-left | left | center-left | center | center-right | right | far-right | right-side",
behind = false,
valid = false,
part;
if (!ValidationTypes.isAny(expression, simple)) {
if (ValidationTypes.isAny(expression, "behind")) {
behind = true;
valid = true;
}
if (ValidationTypes.isAny(expression, direction)) {
valid = true;
if (!behind) {
ValidationTypes.isAny(expression, "behind");
}
}
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (<'azimuth'>) but found '" + part + "'.", part.line, part.col);
}
}
},
//B
"backface-visibility" : "visible | hidden",
"background" : 1,
"background-attachment" : { multi: "<attachment>", comma: true },
"background-clip" : { multi: "<box>", comma: true },
"background-color" : "<color> | inherit",
"background-image" : { multi: "<bg-image>", comma: true },
"background-origin" : { multi: "<box>", comma: true },
"background-position" : { multi: "<bg-position>", comma: true },
"background-repeat" : { multi: "<repeat-style>" },
"background-size" : { multi: "<bg-size>", comma: true },
"baseline-shift" : "baseline | sub | super | <percentage> | <length>",
"behavior" : 1,
"binding" : 1,
"bleed" : "<length>",
"bookmark-label" : "<content> | <attr> | <string>",
"bookmark-level" : "none | <integer>",
"bookmark-state" : "open | closed",
"bookmark-target" : "none | <uri> | <attr>",
"border" : "<border-width> || <border-style> || <color>",
"border-bottom" : "<border-width> || <border-style> || <color>",
"border-bottom-color" : "<color>",
"border-bottom-left-radius" : "<x-one-radius>",
"border-bottom-right-radius" : "<x-one-radius>",
"border-bottom-style" : "<border-style>",
"border-bottom-width" : "<border-width>",
"border-collapse" : "collapse | separate | inherit",
"border-color" : { multi: "<color> | inherit", max: 4 },
"border-image" : 1,
"border-image-outset" : { multi: "<length> | <number>", max: 4 },
"border-image-repeat" : { multi: "stretch | repeat | round", max: 2 },
"border-image-slice" : function(expression) {
var valid = false,
numeric = "<number> | <percentage>",
fill = false,
count = 0,
max = 4,
part;
if (ValidationTypes.isAny(expression, "fill")) {
fill = true;
valid = true;
}
while (expression.hasNext() && count < max) {
valid = ValidationTypes.isAny(expression, numeric);
if (!valid) {
break;
}
count++;
}
if (!fill) {
ValidationTypes.isAny(expression, "fill");
} else {
valid = true;
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '" + part + "'.", part.line, part.col);
}
}
},
"border-image-source" : "<image> | none",
"border-image-width" : { multi: "<length> | <percentage> | <number> | auto", max: 4 },
"border-left" : "<border-width> || <border-style> || <color>",
"border-left-color" : "<color> | inherit",
"border-left-style" : "<border-style>",
"border-left-width" : "<border-width>",
"border-radius" : function(expression) {
var valid = false,
numeric = "<length> | <percentage>",
slash = false,
fill = false,
count = 0,
max = 8,
part;
while (expression.hasNext() && count < max) {
valid = ValidationTypes.isAny(expression, numeric);
if (!valid) {
if (expression.peek() == "/" && count > 1 && !slash) {
slash = true;
max = count + 5;
expression.next();
} else {
break;
}
}
count++;
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (<'border-radius'>) but found '" + part + "'.", part.line, part.col);
}
}
},
"border-right" : "<border-width> || <border-style> || <color>",
"border-right-color" : "<color> | inherit",
"border-right-style" : "<border-style>",
"border-right-width" : "<border-width>",
"border-spacing" : { multi: "<length> | inherit", max: 2 },
"border-style" : { multi: "<border-style>", max: 4 },
"border-top" : "<border-width> || <border-style> || <color>",
"border-top-color" : "<color> | inherit",
"border-top-left-radius" : "<x-one-radius>",
"border-top-right-radius" : "<x-one-radius>",
"border-top-style" : "<border-style>",
"border-top-width" : "<border-width>",
"border-width" : { multi: "<border-width>", max: 4 },
"bottom" : "<margin-width> | inherit",
"box-align" : "start | end | center | baseline | stretch", //http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/
"box-decoration-break" : "slice |clone",
"box-direction" : "normal | reverse | inherit",
"box-flex" : "<number>",
"box-flex-group" : "<integer>",
"box-lines" : "single | multiple",
"box-ordinal-group" : "<integer>",
"box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit",
"box-pack" : "start | end | center | justify",
"box-shadow" : function (expression) {
var result = false,
part;
if (!ValidationTypes.isAny(expression, "none")) {
Validation.multiProperty("<shadow>", expression, true, Infinity);
} else {
if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
},
"box-sizing" : "content-box | border-box | inherit",
"break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
"break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
"break-inside" : "auto | avoid | avoid-page | avoid-column",
//C
"caption-side" : "top | bottom | inherit",
"clear" : "none | right | left | both | inherit",
"clip" : 1,
"color" : "<color> | inherit",
"color-profile" : 1,
"column-count" : "<integer> | auto", //http://www.w3.org/TR/css3-multicol/
"column-fill" : "auto | balance",
"column-gap" : "<length> | normal",
"column-rule" : "<border-width> || <border-style> || <color>",
"column-rule-color" : "<color>",
"column-rule-style" : "<border-style>",
"column-rule-width" : "<border-width>",
"column-span" : "none | all",
"column-width" : "<length> | auto",
"columns" : 1,
"content" : 1,
"counter-increment" : 1,
"counter-reset" : 1,
"crop" : "<shape> | auto",
"cue" : "cue-after | cue-before | inherit",
"cue-after" : 1,
"cue-before" : 1,
"cursor" : 1,
//D
"direction" : "ltr | rtl | inherit",
"display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | box | inline-box | grid | inline-grid | none | inherit | -webkit-box",
"dominant-baseline" : 1,
"drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>",
"drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>",
"drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"drop-initial-size" : "auto | line | <length> | <percentage>",
"drop-initial-value" : "initial | <integer>",
//E
"elevation" : "<angle> | below | level | above | higher | lower | inherit",
"empty-cells" : "show | hide | inherit",
//F
"filter" : 1,
"fit" : "fill | hidden | meet | slice",
"fit-position" : 1,
"float" : "left | right | none | inherit",
"float-offset" : 1,
"font" : 1,
"font-family" : 1,
"font-size" : "<absolute-size> | <relative-size> | <length> | <percentage> | inherit",
"font-size-adjust" : "<number> | none | inherit",
"font-stretch" : "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit",
"font-style" : "normal | italic | oblique | inherit",
"font-variant" : "normal | small-caps | inherit",
"font-weight" : "normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit",
//G
"grid-cell-stacking" : "columns | rows | layer",
"grid-column" : 1,
"grid-columns" : 1,
"grid-column-align" : "start | end | center | stretch",
"grid-column-sizing" : 1,
"grid-column-span" : "<integer>",
"grid-flow" : "none | rows | columns",
"grid-layer" : "<integer>",
"grid-row" : 1,
"grid-rows" : 1,
"grid-row-align" : "start | end | center | stretch",
"grid-row-span" : "<integer>",
"grid-row-sizing" : 1,
//H
"hanging-punctuation" : 1,
"height" : "<margin-width> | inherit",
"hyphenate-after" : "<integer> | auto",
"hyphenate-before" : "<integer> | auto",
"hyphenate-character" : "<string> | auto",
"hyphenate-lines" : "no-limit | <integer>",
"hyphenate-resource" : 1,
"hyphens" : "none | manual | auto",
//I
"icon" : 1,
"image-orientation" : "angle | auto",
"image-rendering" : 1,
"image-resolution" : 1,
"inline-box-align" : "initial | last | <integer>",
//L
"left" : "<margin-width> | inherit",
"letter-spacing" : "<length> | normal | inherit",
"line-height" : "<number> | <length> | <percentage> | normal | inherit",
"line-break" : "auto | loose | normal | strict",
"line-stacking" : 1,
"line-stacking-ruby" : "exclude-ruby | include-ruby",
"line-stacking-shift" : "consider-shifts | disregard-shifts",
"line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height",
"list-style" : 1,
"list-style-image" : "<uri> | none | inherit",
"list-style-position" : "inside | outside | inherit",
"list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit",
//M
"margin" : { multi: "<margin-width> | inherit", max: 4 },
"margin-bottom" : "<margin-width> | inherit",
"margin-left" : "<margin-width> | inherit",
"margin-right" : "<margin-width> | inherit",
"margin-top" : "<margin-width> | inherit",
"mark" : 1,
"mark-after" : 1,
"mark-before" : 1,
"marks" : 1,
"marquee-direction" : 1,
"marquee-play-count" : 1,
"marquee-speed" : 1,
"marquee-style" : 1,
"max-height" : "<length> | <percentage> | none | inherit",
"max-width" : "<length> | <percentage> | none | inherit",
"min-height" : "<length> | <percentage> | inherit",
"min-width" : "<length> | <percentage> | inherit",
"move-to" : 1,
//N
"nav-down" : 1,
"nav-index" : 1,
"nav-left" : 1,
"nav-right" : 1,
"nav-up" : 1,
//O
"opacity" : "<number> | inherit",
"orphans" : "<integer> | inherit",
"outline" : 1,
"outline-color" : "<color> | invert | inherit",
"outline-offset" : 1,
"outline-style" : "<border-style> | inherit",
"outline-width" : "<border-width> | inherit",
"overflow" : "visible | hidden | scroll | auto | inherit",
"overflow-style" : 1,
"overflow-x" : 1,
"overflow-y" : 1,
//P
"padding" : { multi: "<padding-width> | inherit", max: 4 },
"padding-bottom" : "<padding-width> | inherit",
"padding-left" : "<padding-width> | inherit",
"padding-right" : "<padding-width> | inherit",
"padding-top" : "<padding-width> | inherit",
"page" : 1,
"page-break-after" : "auto | always | avoid | left | right | inherit",
"page-break-before" : "auto | always | avoid | left | right | inherit",
"page-break-inside" : "auto | avoid | inherit",
"page-policy" : 1,
"pause" : 1,
"pause-after" : 1,
"pause-before" : 1,
"perspective" : 1,
"perspective-origin" : 1,
"phonemes" : 1,
"pitch" : 1,
"pitch-range" : 1,
"play-during" : 1,
"pointer-events" : "auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | inherit",
"position" : "static | relative | absolute | fixed | inherit",
"presentation-level" : 1,
"punctuation-trim" : 1,
//Q
"quotes" : 1,
//R
"rendering-intent" : 1,
"resize" : 1,
"rest" : 1,
"rest-after" : 1,
"rest-before" : 1,
"richness" : 1,
"right" : "<margin-width> | inherit",
"rotation" : 1,
"rotation-point" : 1,
"ruby-align" : 1,
"ruby-overhang" : 1,
"ruby-position" : 1,
"ruby-span" : 1,
//S
"size" : 1,
"speak" : "normal | none | spell-out | inherit",
"speak-header" : "once | always | inherit",
"speak-numeral" : "digits | continuous | inherit",
"speak-punctuation" : "code | none | inherit",
"speech-rate" : 1,
"src" : 1,
"stress" : 1,
"string-set" : 1,
"table-layout" : "auto | fixed | inherit",
"tab-size" : "<integer> | <length>",
"target" : 1,
"target-name" : 1,
"target-new" : 1,
"target-position" : 1,
"text-align" : "left | right | center | justify | inherit" ,
"text-align-last" : 1,
"text-decoration" : 1,
"text-emphasis" : 1,
"text-height" : 1,
"text-indent" : "<length> | <percentage> | inherit",
"text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida",
"text-outline" : 1,
"text-overflow" : 1,
"text-rendering" : "auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit",
"text-shadow" : 1,
"text-transform" : "capitalize | uppercase | lowercase | none | inherit",
"text-wrap" : "normal | none | avoid",
"top" : "<margin-width> | inherit",
"transform" : 1,
"transform-origin" : 1,
"transform-style" : 1,
"transition" : 1,
"transition-delay" : 1,
"transition-duration" : 1,
"transition-property" : 1,
"transition-timing-function" : 1,
//U
"unicode-bidi" : "normal | embed | bidi-override | inherit",
"user-modify" : "read-only | read-write | write-only | inherit",
"user-select" : "none | text | toggle | element | elements | all | inherit",
//V
"vertical-align" : "<percentage> | <length> | baseline | sub | super | top | text-top | middle | bottom | text-bottom | inherit",
"visibility" : "visible | hidden | collapse | inherit",
"voice-balance" : 1,
"voice-duration" : 1,
"voice-family" : 1,
"voice-pitch" : 1,
"voice-pitch-range" : 1,
"voice-rate" : 1,
"voice-stress" : 1,
"voice-volume" : 1,
"volume" : 1,
//W
"white-space" : "normal | pre | nowrap | pre-wrap | pre-line | inherit",
"white-space-collapse" : 1,
"widows" : "<integer> | inherit",
"width" : "<length> | <percentage> | auto | inherit" ,
"word-break" : "normal | keep-all | break-all",
"word-spacing" : "<length> | normal | inherit",
"word-wrap" : 1,
//Z
"z-index" : "<integer> | auto | inherit",
"zoom" : "<number> | <percentage> | normal"
};
/*global SyntaxUnit, Parser*/
/**
* Represents a selector combinator (whitespace, +, >).
* @namespace parserlib.css
* @class PropertyName
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {String} hack The type of IE hack applied ("*", "_", or null).
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function PropertyName(text, hack, line, col){
SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE);
/**
* The type of IE hack applied ("*", "_", or null).
* @type String
* @property hack
*/
this.hack = hack;
}
PropertyName.prototype = new SyntaxUnit();
PropertyName.prototype.constructor = PropertyName;
PropertyName.prototype.toString = function(){
return (this.hack ? this.hack : "") + this.text;
};
/*global SyntaxUnit, Parser*/
/**
* Represents a single part of a CSS property value, meaning that it represents
* just everything single part between ":" and ";". If there are multiple values
* separated by commas, this type represents just one of the values.
* @param {String[]} parts An array of value parts making up this value.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
* @namespace parserlib.css
* @class PropertyValue
* @extends parserlib.util.SyntaxUnit
* @constructor
*/
function PropertyValue(parts, line, col){
SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE);
/**
* The parts that make up the selector.
* @type Array
* @property parts
*/
this.parts = parts;
}
PropertyValue.prototype = new SyntaxUnit();
PropertyValue.prototype.constructor = PropertyValue;
/*global SyntaxUnit, Parser*/
/**
* A utility class that allows for easy iteration over the various parts of a
* property value.
* @param {parserlib.css.PropertyValue} value The property value to iterate over.
* @namespace parserlib.css
* @class PropertyValueIterator
* @constructor
*/
function PropertyValueIterator(value){
/**
* Iterator value
* @type int
* @property _i
* @private
*/
this._i = 0;
/**
* The parts that make up the value.
* @type Array
* @property _parts
* @private
*/
this._parts = value.parts;
/**
* Keeps track of bookmarks along the way.
* @type Array
* @property _marks
* @private
*/
this._marks = [];
/**
* Holds the original property value.
* @type parserlib.css.PropertyValue
* @property value
*/
this.value = value;
}
/**
* Returns the total number of parts in the value.
* @return {int} The total number of parts in the value.
* @method count
*/
PropertyValueIterator.prototype.count = function(){
return this._parts.length;
};
/**
* Indicates if the iterator is positioned at the first item.
* @return {Boolean} True if positioned at first item, false if not.
* @method isFirst
*/
PropertyValueIterator.prototype.isFirst = function(){
return this._i === 0;
};
/**
* Indicates if there are more parts of the property value.
* @return {Boolean} True if there are more parts, false if not.
* @method hasNext
*/
PropertyValueIterator.prototype.hasNext = function(){
return (this._i < this._parts.length);
};
/**
* Marks the current spot in the iteration so it can be restored to
* later on.
* @return {void}
* @method mark
*/
PropertyValueIterator.prototype.mark = function(){
this._marks.push(this._i);
};
/**
* Returns the next part of the property value or null if there is no next
* part. Does not move the internal counter forward.
* @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next
* part.
* @method peek
*/
PropertyValueIterator.prototype.peek = function(count){
return this.hasNext() ? this._parts[this._i + (count || 0)] : null;
};
/**
* Returns the next part of the property value or null if there is no next
* part.
* @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next
* part.
* @method next
*/
PropertyValueIterator.prototype.next = function(){
return this.hasNext() ? this._parts[this._i++] : null;
};
/**
* Returns the previous part of the property value or null if there is no
* previous part.
* @return {parserlib.css.PropertyValuePart} The previous part of the
* property value or null if there is no next part.
* @method previous
*/
PropertyValueIterator.prototype.previous = function(){
return this._i > 0 ? this._parts[--this._i] : null;
};
/**
* Restores the last saved bookmark.
* @return {void}
* @method restore
*/
PropertyValueIterator.prototype.restore = function(){
if (this._marks.length){
this._i = this._marks.pop();
}
};
/*global SyntaxUnit, Parser, Colors*/
/**
* Represents a single part of a CSS property value, meaning that it represents
* just one part of the data between ":" and ";".
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
* @namespace parserlib.css
* @class PropertyValuePart
* @extends parserlib.util.SyntaxUnit
* @constructor
*/
function PropertyValuePart(text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE);
/**
* Indicates the type of value unit.
* @type String
* @property type
*/
this.type = "unknown";
//figure out what type of data it is
var temp;
//it is a measurement?
if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){ //dimension
this.type = "dimension";
this.value = +RegExp.$1;
this.units = RegExp.$2;
//try to narrow down
switch(this.units.toLowerCase()){
case "em":
case "rem":
case "ex":
case "px":
case "cm":
case "mm":
case "in":
case "pt":
case "pc":
case "ch":
this.type = "length";
break;
case "deg":
case "rad":
case "grad":
this.type = "angle";
break;
case "ms":
case "s":
this.type = "time";
break;
case "hz":
case "khz":
this.type = "frequency";
break;
case "dpi":
case "dpcm":
this.type = "resolution";
break;
//default
}
} else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
this.type = "percentage";
this.value = +RegExp.$1;
} else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
this.type = "percentage";
this.value = +RegExp.$1;
} else if (/^([+\-]?\d+)$/i.test(text)){ //integer
this.type = "integer";
this.value = +RegExp.$1;
} else if (/^([+\-]?[\d\.]+)$/i.test(text)){ //number
this.type = "number";
this.value = +RegExp.$1;
} else if (/^#([a-f0-9]{3,6})/i.test(text)){ //hexcolor
this.type = "color";
temp = RegExp.$1;
if (temp.length == 3){
this.red = parseInt(temp.charAt(0)+temp.charAt(0),16);
this.green = parseInt(temp.charAt(1)+temp.charAt(1),16);
this.blue = parseInt(temp.charAt(2)+temp.charAt(2),16);
} else {
this.red = parseInt(temp.substring(0,2),16);
this.green = parseInt(temp.substring(2,4),16);
this.blue = parseInt(temp.substring(4,6),16);
}
} else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)){ //rgb() color with absolute numbers
this.type = "color";
this.red = +RegExp.$1;
this.green = +RegExp.$2;
this.blue = +RegExp.$3;
} else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //rgb() color with percentages
this.type = "color";
this.red = +RegExp.$1 * 255 / 100;
this.green = +RegExp.$2 * 255 / 100;
this.blue = +RegExp.$3 * 255 / 100;
} else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with absolute numbers
this.type = "color";
this.red = +RegExp.$1;
this.green = +RegExp.$2;
this.blue = +RegExp.$3;
this.alpha = +RegExp.$4;
} else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with percentages
this.type = "color";
this.red = +RegExp.$1 * 255 / 100;
this.green = +RegExp.$2 * 255 / 100;
this.blue = +RegExp.$3 * 255 / 100;
this.alpha = +RegExp.$4;
} else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //hsl()
this.type = "color";
this.hue = +RegExp.$1;
this.saturation = +RegExp.$2 / 100;
this.lightness = +RegExp.$3 / 100;
} else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //hsla() color with percentages
this.type = "color";
this.hue = +RegExp.$1;
this.saturation = +RegExp.$2 / 100;
this.lightness = +RegExp.$3 / 100;
this.alpha = +RegExp.$4;
} else if (/^url\(["']?([^\)"']+)["']?\)/i.test(text)){ //URI
this.type = "uri";
this.uri = RegExp.$1;
} else if (/^([^\(]+)\(/i.test(text)){
this.type = "function";
this.name = RegExp.$1;
this.value = text;
} else if (/^["'][^"']*["']/.test(text)){ //string
this.type = "string";
this.value = eval(text);
} else if (Colors[text.toLowerCase()]){ //named color
this.type = "color";
temp = Colors[text.toLowerCase()].substring(1);
this.red = parseInt(temp.substring(0,2),16);
this.green = parseInt(temp.substring(2,4),16);
this.blue = parseInt(temp.substring(4,6),16);
} else if (/^[\,\/]$/.test(text)){
this.type = "operator";
this.value = text;
} else if (/^[a-z\-\u0080-\uFFFF][a-z0-9\-\u0080-\uFFFF]*$/i.test(text)){
this.type = "identifier";
this.value = text;
}
}
PropertyValuePart.prototype = new SyntaxUnit();
PropertyValuePart.prototype.constructor = PropertyValuePart;
/**
* Create a new syntax unit based solely on the given token.
* Convenience method for creating a new syntax unit when
* it represents a single token instead of multiple.
* @param {Object} token The token object to represent.
* @return {parserlib.css.PropertyValuePart} The object representing the token.
* @static
* @method fromToken
*/
PropertyValuePart.fromToken = function(token){
return new PropertyValuePart(token.value, token.startLine, token.startCol);
};
var Pseudos = {
":first-letter": 1,
":first-line": 1,
":before": 1,
":after": 1
};
Pseudos.ELEMENT = 1;
Pseudos.CLASS = 2;
Pseudos.isElement = function(pseudo){
return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] == Pseudos.ELEMENT;
};
/*global SyntaxUnit, Parser, Specificity*/
/**
* Represents an entire single selector, including all parts but not
* including multiple selectors (those separated by commas).
* @namespace parserlib.css
* @class Selector
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {Array} parts Array of selectors parts making up this selector.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function Selector(parts, line, col){
SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE);
/**
* The parts that make up the selector.
* @type Array
* @property parts
*/
this.parts = parts;
/**
* The specificity of the selector.
* @type parserlib.css.Specificity
* @property specificity
*/
this.specificity = Specificity.calculate(this);
}
Selector.prototype = new SyntaxUnit();
Selector.prototype.constructor = Selector;
/*global SyntaxUnit, Parser*/
/**
* Represents a single part of a selector string, meaning a single set of
* element name and modifiers. This does not include combinators such as
* spaces, +, >, etc.
* @namespace parserlib.css
* @class SelectorPart
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} elementName The element name in the selector or null
* if there is no element name.
* @param {Array} modifiers Array of individual modifiers for the element.
* May be empty if there are none.
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SelectorPart(elementName, modifiers, text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE);
/**
* The tag name of the element to which this part
* of the selector affects.
* @type String
* @property elementName
*/
this.elementName = elementName;
/**
* The parts that come after the element name, such as class names, IDs,
* pseudo classes/elements, etc.
* @type Array
* @property modifiers
*/
this.modifiers = modifiers;
}
SelectorPart.prototype = new SyntaxUnit();
SelectorPart.prototype.constructor = SelectorPart;
/*global SyntaxUnit, Parser*/
/**
* Represents a selector modifier string, meaning a class name, element name,
* element ID, pseudo rule, etc.
* @namespace parserlib.css
* @class SelectorSubPart
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {String} type The type of selector modifier.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SelectorSubPart(text, type, line, col){
SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE);
/**
* The type of modifier.
* @type String
* @property type
*/
this.type = type;
/**
* Some subparts have arguments, this represents them.
* @type Array
* @property args
*/
this.args = [];
}
SelectorSubPart.prototype = new SyntaxUnit();
SelectorSubPart.prototype.constructor = SelectorSubPart;
/*global Pseudos, SelectorPart*/
/**
* Represents a selector's specificity.
* @namespace parserlib.css
* @class Specificity
* @constructor
* @param {int} a Should be 1 for inline styles, zero for stylesheet styles
* @param {int} b Number of ID selectors
* @param {int} c Number of classes and pseudo classes
* @param {int} d Number of element names and pseudo elements
*/
function Specificity(a, b, c, d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
Specificity.prototype = {
constructor: Specificity,
/**
* Compare this specificity to another.
* @param {Specificity} other The other specificity to compare to.
* @return {int} -1 if the other specificity is larger, 1 if smaller, 0 if equal.
* @method compare
*/
compare: function(other){
var comps = ["a", "b", "c", "d"],
i, len;
for (i=0, len=comps.length; i < len; i++){
if (this[comps[i]] < other[comps[i]]){
return -1;
} else if (this[comps[i]] > other[comps[i]]){
return 1;
}
}
return 0;
},
/**
* Creates a numeric value for the specificity.
* @return {int} The numeric value for the specificity.
* @method valueOf
*/
valueOf: function(){
return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d;
},
/**
* Returns a string representation for specificity.
* @return {String} The string representation of specificity.
* @method toString
*/
toString: function(){
return this.a + "," + this.b + "," + this.c + "," + this.d;
}
};
/**
* Calculates the specificity of the given selector.
* @param {parserlib.css.Selector} The selector to calculate specificity for.
* @return {parserlib.css.Specificity} The specificity of the selector.
* @static
* @method calculate
*/
Specificity.calculate = function(selector){
var i, len,
part,
b=0, c=0, d=0;
function updateValues(part){
var i, j, len, num,
elementName = part.elementName ? part.elementName.text : "",
modifier;
if (elementName && elementName.charAt(elementName.length-1) != "*") {
d++;
}
for (i=0, len=part.modifiers.length; i < len; i++){
modifier = part.modifiers[i];
switch(modifier.type){
case "class":
case "attribute":
c++;
break;
case "id":
b++;
break;
case "pseudo":
if (Pseudos.isElement(modifier.text)){
d++;
} else {
c++;
}
break;
case "not":
for (j=0, num=modifier.args.length; j < num; j++){
updateValues(modifier.args[j]);
}
}
}
}
for (i=0, len=selector.parts.length; i < len; i++){
part = selector.parts[i];
if (part instanceof SelectorPart){
updateValues(part);
}
}
return new Specificity(0, b, c, d);
};
/*global Tokens, TokenStreamBase*/
var h = /^[0-9a-fA-F]$/,
nonascii = /^[\u0080-\uFFFF]$/,
nl = /\n|\r\n|\r|\f/;
//-----------------------------------------------------------------------------
// Helper functions
//-----------------------------------------------------------------------------
function isHexDigit(c){
return c !== null && h.test(c);
}
function isDigit(c){
return c !== null && /\d/.test(c);
}
function isWhitespace(c){
return c !== null && /\s/.test(c);
}
function isNewLine(c){
return c !== null && nl.test(c);
}
function isNameStart(c){
return c !== null && (/[a-z_\u0080-\uFFFF\\]/i.test(c));
}
function isNameChar(c){
return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c));
}
function isIdentStart(c){
return c !== null && (isNameStart(c) || /\-\\/.test(c));
}
function mix(receiver, supplier){
for (var prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return receiver;
}
//-----------------------------------------------------------------------------
// CSS Token Stream
//-----------------------------------------------------------------------------
/**
* A token stream that produces CSS tokens.
* @param {String|Reader} input The source of text to tokenize.
* @constructor
* @class TokenStream
* @namespace parserlib.css
*/
function TokenStream(input){
TokenStreamBase.call(this, input, Tokens);
}
TokenStream.prototype = mix(new TokenStreamBase(), {
/**
* Overrides the TokenStreamBase method of the same name
* to produce CSS tokens.
* @param {variant} channel The name of the channel to use
* for the next token.
* @return {Object} A token object representing the next token.
* @method _getToken
* @private
*/
_getToken: function(channel){
var c,
reader = this._reader,
token = null,
startLine = reader.getLine(),
startCol = reader.getCol();
c = reader.read();
while(c){
switch(c){
/*
* Potential tokens:
* - COMMENT
* - SLASH
* - CHAR
*/
case "/":
if(reader.peek() == "*"){
token = this.commentToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - DASHMATCH
* - INCLUDES
* - PREFIXMATCH
* - SUFFIXMATCH
* - SUBSTRINGMATCH
* - CHAR
*/
case "|":
case "~":
case "^":
case "$":
case "*":
if(reader.peek() == "="){
token = this.comparisonToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - STRING
* - INVALID
*/
case "\"":
case "'":
token = this.stringToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - HASH
* - CHAR
*/
case "#":
if (isNameChar(reader.peek())){
token = this.hashToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - DOT
* - NUMBER
* - DIMENSION
* - PERCENTAGE
*/
case ".":
if (isDigit(reader.peek())){
token = this.numberToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - CDC
* - MINUS
* - NUMBER
* - DIMENSION
* - PERCENTAGE
*/
case "-":
if (reader.peek() == "-"){ //could be closing HTML-style comment
token = this.htmlCommentEndToken(c, startLine, startCol);
} else if (isNameStart(reader.peek())){
token = this.identOrFunctionToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - IMPORTANT_SYM
* - CHAR
*/
case "!":
token = this.importantToken(c, startLine, startCol);
break;
/*
* Any at-keyword or CHAR
*/
case "@":
token = this.atRuleToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - NOT
* - CHAR
*/
case ":":
token = this.notToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - CDO
* - CHAR
*/
case "<":
token = this.htmlCommentStartToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - UNICODE_RANGE
* - URL
* - CHAR
*/
case "U":
case "u":
if (reader.peek() == "+"){
token = this.unicodeRangeToken(c, startLine, startCol);
break;
}
/* falls through */
default:
/*
* Potential tokens:
* - NUMBER
* - DIMENSION
* - LENGTH
* - FREQ
* - TIME
* - EMS
* - EXS
* - ANGLE
*/
if (isDigit(c)){
token = this.numberToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - S
*/
if (isWhitespace(c)){
token = this.whitespaceToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - IDENT
*/
if (isIdentStart(c)){
token = this.identOrFunctionToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - CHAR
* - PLUS
*/
{
token = this.charToken(c, startLine, startCol);
}
}
//make sure this token is wanted
//TODO: check channel
break;
}
if (!token && c === null){
token = this.createToken(Tokens.EOF,null,startLine,startCol);
}
return token;
},
//-------------------------------------------------------------------------
// Methods to create tokens
//-------------------------------------------------------------------------
/**
* Produces a token based on available data and the current
* reader position information. This method is called by other
* private methods to create tokens and is never called directly.
* @param {int} tt The token type.
* @param {String} value The text value of the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @param {Object} options (Optional) Specifies a channel property
* to indicate that a different channel should be scanned
* and/or a hide property indicating that the token should
* be hidden.
* @return {Object} A token object.
* @method createToken
*/
createToken: function(tt, value, startLine, startCol, options){
var reader = this._reader;
options = options || {};
return {
value: value,
type: tt,
channel: options.channel,
hide: options.hide || false,
startLine: startLine,
startCol: startCol,
endLine: reader.getLine(),
endCol: reader.getCol()
};
},
//-------------------------------------------------------------------------
// Methods to create specific tokens
//-------------------------------------------------------------------------
/**
* Produces a token for any at-rule. If the at-rule is unknown, then
* the token is for a single "@" character.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method atRuleToken
*/
atRuleToken: function(first, startLine, startCol){
var rule = first,
reader = this._reader,
tt = Tokens.CHAR,
valid = false,
ident,
c;
/*
* First, mark where we are. There are only four @ rules,
* so anything else is really just an invalid token.
* Basically, if this doesn't match one of the known @
* rules, just return '@' as an unknown token and allow
* parsing to continue after that point.
*/
reader.mark();
//try to find the at-keyword
ident = this.readName();
rule = first + ident;
tt = Tokens.type(rule.toLowerCase());
//if it's not valid, use the first character only and reset the reader
if (tt == Tokens.CHAR || tt == Tokens.UNKNOWN){
if (rule.length > 1){
tt = Tokens.UNKNOWN_SYM;
} else {
tt = Tokens.CHAR;
rule = first;
reader.reset();
}
}
return this.createToken(tt, rule, startLine, startCol);
},
/**
* Produces a character token based on the given character
* and location in the stream. If there's a special (non-standard)
* token name, this is used; otherwise CHAR is used.
* @param {String} c The character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method charToken
*/
charToken: function(c, startLine, startCol){
var tt = Tokens.type(c);
if (tt == -1){
tt = Tokens.CHAR;
}
return this.createToken(tt, c, startLine, startCol);
},
/**
* Produces a character token based on the given character
* and location in the stream. If there's a special (non-standard)
* token name, this is used; otherwise CHAR is used.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method commentToken
*/
commentToken: function(first, startLine, startCol){
var reader = this._reader,
comment = this.readComment(first);
return this.createToken(Tokens.COMMENT, comment, startLine, startCol);
},
/**
* Produces a comparison token based on the given character
* and location in the stream. The next character must be
* read and is already known to be an equals sign.
* @param {String} c The character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method comparisonToken
*/
comparisonToken: function(c, startLine, startCol){
var reader = this._reader,
comparison = c + reader.read(),
tt = Tokens.type(comparison) || Tokens.CHAR;
return this.createToken(tt, comparison, startLine, startCol);
},
/**
* Produces a hash token based on the specified information. The
* first character provided is the pound sign (#) and then this
* method reads a name afterward.
* @param {String} first The first character (#) in the hash name.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method hashToken
*/
hashToken: function(first, startLine, startCol){
var reader = this._reader,
name = this.readName(first);
return this.createToken(Tokens.HASH, name, startLine, startCol);
},
/**
* Produces a CDO or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method htmlCommentStartToken
*/
htmlCommentStartToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(3);
if (text == "<!--"){
return this.createToken(Tokens.CDO, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces a CDC or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method htmlCommentEndToken
*/
htmlCommentEndToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(2);
if (text == "-->"){
return this.createToken(Tokens.CDC, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces an IDENT or FUNCTION token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the identifier.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method identOrFunctionToken
*/
identOrFunctionToken: function(first, startLine, startCol){
var reader = this._reader,
ident = this.readName(first),
tt = Tokens.IDENT;
//if there's a left paren immediately after, it's a URI or function
if (reader.peek() == "("){
ident += reader.read();
if (ident.toLowerCase() == "url("){
tt = Tokens.URI;
ident = this.readURI(ident);
//didn't find a valid URL or there's no closing paren
if (ident.toLowerCase() == "url("){
tt = Tokens.FUNCTION;
}
} else {
tt = Tokens.FUNCTION;
}
} else if (reader.peek() == ":"){ //might be an IE function
//IE-specific functions always being with progid:
if (ident.toLowerCase() == "progid"){
ident += reader.readTo("(");
tt = Tokens.IE_FUNCTION;
}
}
return this.createToken(tt, ident, startLine, startCol);
},
/**
* Produces an IMPORTANT_SYM or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method importantToken
*/
importantToken: function(first, startLine, startCol){
var reader = this._reader,
important = first,
tt = Tokens.CHAR,
temp,
c;
reader.mark();
c = reader.read();
while(c){
//there can be a comment in here
if (c == "/"){
//if the next character isn't a star, then this isn't a valid !important token
if (reader.peek() != "*"){
break;
} else {
temp = this.readComment(c);
if (temp === ""){ //broken!
break;
}
}
} else if (isWhitespace(c)){
important += c + this.readWhitespace();
} else if (/i/i.test(c)){
temp = reader.readCount(8);
if (/mportant/i.test(temp)){
important += c + temp;
tt = Tokens.IMPORTANT_SYM;
}
break; //we're done
} else {
break;
}
c = reader.read();
}
if (tt == Tokens.CHAR){
reader.reset();
return this.charToken(first, startLine, startCol);
} else {
return this.createToken(tt, important, startLine, startCol);
}
},
/**
* Produces a NOT or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method notToken
*/
notToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(4);
if (text.toLowerCase() == ":not("){
return this.createToken(Tokens.NOT, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces a number token based on the given character
* and location in the stream. This may return a token of
* NUMBER, EMS, EXS, LENGTH, ANGLE, TIME, FREQ, DIMENSION,
* or PERCENTAGE.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method numberToken
*/
numberToken: function(first, startLine, startCol){
var reader = this._reader,
value = this.readNumber(first),
ident,
tt = Tokens.NUMBER,
c = reader.peek();
if (isIdentStart(c)){
ident = this.readName(reader.read());
value += ident;
if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vm$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)){
tt = Tokens.LENGTH;
} else if (/^deg|^rad$|^grad$/i.test(ident)){
tt = Tokens.ANGLE;
} else if (/^ms$|^s$/i.test(ident)){
tt = Tokens.TIME;
} else if (/^hz$|^khz$/i.test(ident)){
tt = Tokens.FREQ;
} else if (/^dpi$|^dpcm$/i.test(ident)){
tt = Tokens.RESOLUTION;
} else {
tt = Tokens.DIMENSION;
}
} else if (c == "%"){
value += reader.read();
tt = Tokens.PERCENTAGE;
}
return this.createToken(tt, value, startLine, startCol);
},
/**
* Produces a string token based on the given character
* and location in the stream. Since strings may be indicated
* by single or double quotes, a failure to match starting
* and ending quotes results in an INVALID token being generated.
* The first character in the string is passed in and then
* the rest are read up to and including the final quotation mark.
* @param {String} first The first character in the string.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method stringToken
*/
stringToken: function(first, startLine, startCol){
var delim = first,
string = first,
reader = this._reader,
prev = first,
tt = Tokens.STRING,
c = reader.read();
while(c){
string += c;
//if the delimiter is found with an escapement, we're done.
if (c == delim && prev != "\\"){
break;
}
//if there's a newline without an escapement, it's an invalid string
if (isNewLine(reader.peek()) && c != "\\"){
tt = Tokens.INVALID;
break;
}
//save previous and get next
prev = c;
c = reader.read();
}
//if c is null, that means we're out of input and the string was never closed
if (c === null){
tt = Tokens.INVALID;
}
return this.createToken(tt, string, startLine, startCol);
},
unicodeRangeToken: function(first, startLine, startCol){
var reader = this._reader,
value = first,
temp,
tt = Tokens.CHAR;
//then it should be a unicode range
if (reader.peek() == "+"){
reader.mark();
value += reader.read();
value += this.readUnicodeRangePart(true);
//ensure there's an actual unicode range here
if (value.length == 2){
reader.reset();
} else {
tt = Tokens.UNICODE_RANGE;
//if there's a ? in the first part, there can't be a second part
if (value.indexOf("?") == -1){
if (reader.peek() == "-"){
reader.mark();
temp = reader.read();
temp += this.readUnicodeRangePart(false);
//if there's not another value, back up and just take the first
if (temp.length == 1){
reader.reset();
} else {
value += temp;
}
}
}
}
}
return this.createToken(tt, value, startLine, startCol);
},
/**
* Produces a S token based on the specified information. Since whitespace
* may have multiple characters, this consumes all whitespace characters
* into a single token.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method whitespaceToken
*/
whitespaceToken: function(first, startLine, startCol){
var reader = this._reader,
value = first + this.readWhitespace();
return this.createToken(Tokens.S, value, startLine, startCol);
},
//-------------------------------------------------------------------------
// Methods to read values from the string stream
//-------------------------------------------------------------------------
readUnicodeRangePart: function(allowQuestionMark){
var reader = this._reader,
part = "",
c = reader.peek();
//first read hex digits
while(isHexDigit(c) && part.length < 6){
reader.read();
part += c;
c = reader.peek();
}
//then read question marks if allowed
if (allowQuestionMark){
while(c == "?" && part.length < 6){
reader.read();
part += c;
c = reader.peek();
}
}
//there can't be any other characters after this point
return part;
},
readWhitespace: function(){
var reader = this._reader,
whitespace = "",
c = reader.peek();
while(isWhitespace(c)){
reader.read();
whitespace += c;
c = reader.peek();
}
return whitespace;
},
readNumber: function(first){
var reader = this._reader,
number = first,
hasDot = (first == "."),
c = reader.peek();
while(c){
if (isDigit(c)){
number += reader.read();
} else if (c == "."){
if (hasDot){
break;
} else {
hasDot = true;
number += reader.read();
}
} else {
break;
}
c = reader.peek();
}
return number;
},
readString: function(){
var reader = this._reader,
delim = reader.read(),
string = delim,
prev = delim,
c = reader.peek();
while(c){
c = reader.read();
string += c;
//if the delimiter is found with an escapement, we're done.
if (c == delim && prev != "\\"){
break;
}
//if there's a newline without an escapement, it's an invalid string
if (isNewLine(reader.peek()) && c != "\\"){
string = "";
break;
}
//save previous and get next
prev = c;
c = reader.peek();
}
//if c is null, that means we're out of input and the string was never closed
if (c === null){
string = "";
}
return string;
},
readURI: function(first){
var reader = this._reader,
uri = first,
inner = "",
c = reader.peek();
reader.mark();
//skip whitespace before
while(c && isWhitespace(c)){
reader.read();
c = reader.peek();
}
//it's a string
if (c == "'" || c == "\""){
inner = this.readString();
} else {
inner = this.readURL();
}
c = reader.peek();
//skip whitespace after
while(c && isWhitespace(c)){
reader.read();
c = reader.peek();
}
//if there was no inner value or the next character isn't closing paren, it's not a URI
if (inner === "" || c != ")"){
uri = first;
reader.reset();
} else {
uri += inner + reader.read();
}
return uri;
},
readURL: function(){
var reader = this._reader,
url = "",
c = reader.peek();
//TODO: Check for escape and nonascii
while (/^[!#$%&\\*-~]$/.test(c)){
url += reader.read();
c = reader.peek();
}
return url;
},
readName: function(first){
var reader = this._reader,
ident = first || "",
c = reader.peek();
while(true){
if (c == "\\"){
ident += this.readEscape(reader.read());
c = reader.peek();
} else if(c && isNameChar(c)){
ident += reader.read();
c = reader.peek();
} else {
break;
}
}
return ident;
},
readEscape: function(first){
var reader = this._reader,
cssEscape = first || "",
i = 0,
c = reader.peek();
if (isHexDigit(c)){
do {
cssEscape += reader.read();
c = reader.peek();
} while(c && isHexDigit(c) && ++i < 6);
}
if (cssEscape.length == 3 && /\s/.test(c) ||
cssEscape.length == 7 || cssEscape.length == 1){
reader.read();
} else {
c = "";
}
return cssEscape + c;
},
readComment: function(first){
var reader = this._reader,
comment = first || "",
c = reader.read();
if (c == "*"){
while(c){
comment += c;
//look for end of comment
if (comment.length > 2 && c == "*" && reader.peek() == "/"){
comment += reader.read();
break;
}
c = reader.read();
}
return comment;
} else {
return "";
}
}
});
var Tokens = [
/*
* The following token names are defined in CSS3 Grammar: http://www.w3.org/TR/css3-syntax/#lexical
*/
//HTML-style comments
{ name: "CDO"},
{ name: "CDC"},
//ignorables
{ name: "S", whitespace: true/*, channel: "ws"*/},
{ name: "COMMENT", comment: true, hide: true, channel: "comment" },
//attribute equality
{ name: "INCLUDES", text: "~="},
{ name: "DASHMATCH", text: "|="},
{ name: "PREFIXMATCH", text: "^="},
{ name: "SUFFIXMATCH", text: "$="},
{ name: "SUBSTRINGMATCH", text: "*="},
//identifier types
{ name: "STRING"},
{ name: "IDENT"},
{ name: "HASH"},
//at-keywords
{ name: "IMPORT_SYM", text: "@import"},
{ name: "PAGE_SYM", text: "@page"},
{ name: "MEDIA_SYM", text: "@media"},
{ name: "FONT_FACE_SYM", text: "@font-face"},
{ name: "CHARSET_SYM", text: "@charset"},
{ name: "NAMESPACE_SYM", text: "@namespace"},
{ name: "UNKNOWN_SYM" },
//{ name: "ATKEYWORD"},
//CSS3 animations
{ name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-o-keyframes" ] },
//important symbol
{ name: "IMPORTANT_SYM"},
//measurements
{ name: "LENGTH"},
{ name: "ANGLE"},
{ name: "TIME"},
{ name: "FREQ"},
{ name: "DIMENSION"},
{ name: "PERCENTAGE"},
{ name: "NUMBER"},
//functions
{ name: "URI"},
{ name: "FUNCTION"},
//Unicode ranges
{ name: "UNICODE_RANGE"},
/*
* The following token names are defined in CSS3 Selectors: http://www.w3.org/TR/css3-selectors/#selector-syntax
*/
//invalid string
{ name: "INVALID"},
//combinators
{ name: "PLUS", text: "+" },
{ name: "GREATER", text: ">"},
{ name: "COMMA", text: ","},
{ name: "TILDE", text: "~"},
//modifier
{ name: "NOT"},
/*
* Defined in CSS3 Paged Media
*/
{ name: "TOPLEFTCORNER_SYM", text: "@top-left-corner"},
{ name: "TOPLEFT_SYM", text: "@top-left"},
{ name: "TOPCENTER_SYM", text: "@top-center"},
{ name: "TOPRIGHT_SYM", text: "@top-right"},
{ name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner"},
{ name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner"},
{ name: "BOTTOMLEFT_SYM", text: "@bottom-left"},
{ name: "BOTTOMCENTER_SYM", text: "@bottom-center"},
{ name: "BOTTOMRIGHT_SYM", text: "@bottom-right"},
{ name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner"},
{ name: "LEFTTOP_SYM", text: "@left-top"},
{ name: "LEFTMIDDLE_SYM", text: "@left-middle"},
{ name: "LEFTBOTTOM_SYM", text: "@left-bottom"},
{ name: "RIGHTTOP_SYM", text: "@right-top"},
{ name: "RIGHTMIDDLE_SYM", text: "@right-middle"},
{ name: "RIGHTBOTTOM_SYM", text: "@right-bottom"},
/*
* The following token names are defined in CSS3 Media Queries: http://www.w3.org/TR/css3-mediaqueries/#syntax
*/
/*{ name: "MEDIA_ONLY", state: "media"},
{ name: "MEDIA_NOT", state: "media"},
{ name: "MEDIA_AND", state: "media"},*/
{ name: "RESOLUTION", state: "media"},
/*
* The following token names are not defined in any CSS specification but are used by the lexer.
*/
//not a real token, but useful for stupid IE filters
{ name: "IE_FUNCTION" },
//part of CSS3 grammar but not the Flex code
{ name: "CHAR" },
//TODO: Needed?
//Not defined as tokens, but might as well be
{
name: "PIPE",
text: "|"
},
{
name: "SLASH",
text: "/"
},
{
name: "MINUS",
text: "-"
},
{
name: "STAR",
text: "*"
},
{
name: "LBRACE",
text: "{"
},
{
name: "RBRACE",
text: "}"
},
{
name: "LBRACKET",
text: "["
},
{
name: "RBRACKET",
text: "]"
},
{
name: "EQUALS",
text: "="
},
{
name: "COLON",
text: ":"
},
{
name: "SEMICOLON",
text: ";"
},
{
name: "LPAREN",
text: "("
},
{
name: "RPAREN",
text: ")"
},
{
name: "DOT",
text: "."
}
];
(function(){
var nameMap = [],
typeMap = {};
Tokens.UNKNOWN = -1;
Tokens.unshift({name:"EOF"});
for (var i=0, len = Tokens.length; i < len; i++){
nameMap.push(Tokens[i].name);
Tokens[Tokens[i].name] = i;
if (Tokens[i].text){
if (Tokens[i].text instanceof Array){
for (var j=0; j < Tokens[i].text.length; j++){
typeMap[Tokens[i].text[j]] = i;
}
} else {
typeMap[Tokens[i].text] = i;
}
}
}
Tokens.name = function(tt){
return nameMap[tt];
};
Tokens.type = function(c){
return typeMap[c] || -1;
};
})();
//This file will likely change a lot! Very experimental!
/*global Properties, ValidationTypes, ValidationError, PropertyValueIterator */
var Validation = {
validate: function(property, value){
//normalize name
var name = property.toString().toLowerCase(),
parts = value.parts,
expression = new PropertyValueIterator(value),
spec = Properties[name],
part,
valid,
j, count,
msg,
types,
last,
literals,
max, multi, group;
if (!spec) {
if (name.indexOf("-") !== 0){ //vendor prefixed are ok
throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
}
} else if (typeof spec != "number"){
//initialization
if (typeof spec == "string"){
if (spec.indexOf("||") > -1) {
this.groupProperty(spec, expression);
} else {
this.singleProperty(spec, expression, 1);
}
} else if (spec.multi) {
this.multiProperty(spec.multi, expression, spec.comma, spec.max || Infinity);
} else if (typeof spec == "function") {
spec(expression);
}
}
},
singleProperty: function(types, expression, max, partial) {
var result = false,
value = expression.value,
count = 0,
part;
while (expression.hasNext() && count < max) {
result = ValidationTypes.isAny(expression, types);
if (!result) {
break;
}
count++;
}
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
},
multiProperty: function (types, expression, comma, max) {
var result = false,
value = expression.value,
count = 0,
sep = false,
part;
while(expression.hasNext() && !result && count < max) {
if (ValidationTypes.isAny(expression, types)) {
count++;
if (!expression.hasNext()) {
result = true;
} else if (comma) {
if (expression.peek() == ",") {
part = expression.next();
} else {
break;
}
}
} else {
break;
}
}
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
part = expression.previous();
if (comma && part == ",") {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
},
groupProperty: function (types, expression, comma) {
var result = false,
value = expression.value,
typeCount = types.split("||").length,
groups = { count: 0 },
partial = false,
name,
part;
while(expression.hasNext() && !result) {
name = ValidationTypes.isAnyOfGroup(expression, types);
if (name) {
//no dupes
if (groups[name]) {
break;
} else {
groups[name] = 1;
groups.count++;
partial = true;
if (groups.count == typeCount || !expression.hasNext()) {
result = true;
}
}
} else {
break;
}
}
if (!result) {
if (partial && expression.hasNext()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
};
/**
* Type to use when a validation error occurs.
* @class ValidationError
* @namespace parserlib.util
* @constructor
* @param {String} message The error message.
* @param {int} line The line at which the error occurred.
* @param {int} col The column at which the error occurred.
*/
function ValidationError(message, line, col){
/**
* The column at which the error occurred.
* @type int
* @property col
*/
this.col = col;
/**
* The line at which the error occurred.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.message = message;
}
//inherit from Error
ValidationError.prototype = new Error();
//This file will likely change a lot! Very experimental!
/*global Properties, Validation, ValidationError, PropertyValueIterator, console*/
var ValidationTypes = {
isLiteral: function (part, literals) {
var text = part.text.toString().toLowerCase(),
args = literals.split(" | "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found; i++){
if (text == args[i].toLowerCase()){
found = true;
}
}
return found;
},
isSimple: function(type) {
return !!this.simple[type];
},
isComplex: function(type) {
return !!this.complex[type];
},
/**
* Determines if the next part(s) of the given expression
* are any of the given types.
*/
isAny: function (expression, types) {
var args = types.split(" | "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found && expression.hasNext(); i++){
found = this.isType(expression, args[i]);
}
return found;
},
/**
* Determines if the next part(s) of the given expresion
* are one of a group.
*/
isAnyOfGroup: function(expression, types) {
var args = types.split(" || "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found; i++){
found = this.isType(expression, args[i]);
}
return found ? args[i-1] : false;
},
/**
* Determines if the next part(s) of the given expression
* are of a given type.
*/
isType: function (expression, type) {
var part = expression.peek(),
result = false;
if (type.charAt(0) != "<") {
result = this.isLiteral(part, type);
if (result) {
expression.next();
}
} else if (this.simple[type]) {
result = this.simple[type](part);
if (result) {
expression.next();
}
} else {
result = this.complex[type](expression);
}
return result;
},
simple: {
"<absolute-size>": function(part){
return ValidationTypes.isLiteral(part, "xx-small | x-small | small | medium | large | x-large | xx-large");
},
"<attachment>": function(part){
return ValidationTypes.isLiteral(part, "scroll | fixed | local");
},
"<attr>": function(part){
return part.type == "function" && part.name == "attr";
},
"<bg-image>": function(part){
return this["<image>"](part) || this["<gradient>"](part) || part == "none";
},
"<gradient>": function(part) {
return part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(part);
},
"<box>": function(part){
return ValidationTypes.isLiteral(part, "padding-box | border-box | content-box");
},
"<content>": function(part){
return part.type == "function" && part.name == "content";
},
"<relative-size>": function(part){
return ValidationTypes.isLiteral(part, "smaller | larger");
},
//any identifier
"<ident>": function(part){
return part.type == "identifier";
},
"<length>": function(part){
return part.type == "length" || part.type == "number" || part.type == "integer" || part == "0";
},
"<color>": function(part){
return part.type == "color" || part == "transparent";
},
"<number>": function(part){
return part.type == "number" || this["<integer>"](part);
},
"<integer>": function(part){
return part.type == "integer";
},
"<line>": function(part){
return part.type == "integer";
},
"<angle>": function(part){
return part.type == "angle";
},
"<uri>": function(part){
return part.type == "uri";
},
"<image>": function(part){
return this["<uri>"](part);
},
"<percentage>": function(part){
return part.type == "percentage" || part == "0";
},
"<border-width>": function(part){
return this["<length>"](part) || ValidationTypes.isLiteral(part, "thin | medium | thick");
},
"<border-style>": function(part){
return ValidationTypes.isLiteral(part, "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset");
},
"<margin-width>": function(part){
return this["<length>"](part) || this["<percentage>"](part) || ValidationTypes.isLiteral(part, "auto");
},
"<padding-width>": function(part){
return this["<length>"](part) || this["<percentage>"](part);
},
"<shape>": function(part){
return part.type == "function" && (part.name == "rect" || part.name == "inset-rect");
},
"<time>": function(part) {
return part.type == "time";
}
},
complex: {
"<bg-position>": function(expression){
var types = this,
result = false,
numeric = "<percentage> | <length>",
xDir = "left | center | right",
yDir = "top | center | bottom",
part,
i, len;
/*
<position> = [
[ left | center | right | top | bottom | <percentage> | <length> ]
|
[ left | center | right | <percentage> | <length> ]
[ top | center | bottom | <percentage> | <length> ]
|
[ center | [ left | right ] [ <percentage> | <length> ]? ] &&
[ center | [ top | bottom ] [ <percentage> | <length> ]? ]
]
*/
if (ValidationTypes.isAny(expression, "top | bottom")) {
result = true;
} else {
//must be two-part
if (ValidationTypes.isAny(expression, numeric)){
if (expression.hasNext()){
result = ValidationTypes.isAny(expression, numeric + " | " + yDir);
}
} else if (ValidationTypes.isAny(expression, xDir)){
if (expression.hasNext()){
//two- or three-part
if (ValidationTypes.isAny(expression, yDir)){
result = true;
ValidationTypes.isAny(expression, numeric);
} else if (ValidationTypes.isAny(expression, numeric)){
//could also be two-part, so check the next part
if (ValidationTypes.isAny(expression, yDir)){
ValidationTypes.isAny(expression, numeric);
}
result = true;
}
}
}
}
return result;
},
"<bg-size>": function(expression){
//<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain
var types = this,
result = false,
numeric = "<percentage> | <length> | auto",
part,
i, len;
if (ValidationTypes.isAny(expression, "cover | contain")) {
result = true;
} else if (ValidationTypes.isAny(expression, numeric)) {
result = true;
ValidationTypes.isAny(expression, numeric);
}
return result;
},
"<repeat-style>": function(expression){
//repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2}
var result = false,
values = "repeat | space | round | no-repeat",
part;
if (expression.hasNext()){
part = expression.next();
if (ValidationTypes.isLiteral(part, "repeat-x | repeat-y")) {
result = true;
} else if (ValidationTypes.isLiteral(part, values)) {
result = true;
if (expression.hasNext() && ValidationTypes.isLiteral(expression.peek(), values)) {
expression.next();
}
}
}
return result;
},
"<shadow>": function(expression) {
//inset? && [ <length>{2,4} && <color>? ]
var result = false,
count = 0,
inset = false,
color = false,
part;
if (expression.hasNext()) {
if (ValidationTypes.isAny(expression, "inset")){
inset = true;
}
if (ValidationTypes.isAny(expression, "<color>")) {
color = true;
}
while (ValidationTypes.isAny(expression, "<length>") && count < 4) {
count++;
}
if (expression.hasNext()) {
if (!color) {
ValidationTypes.isAny(expression, "<color>");
}
if (!inset) {
ValidationTypes.isAny(expression, "inset");
}
}
result = (count >= 2 && count <= 4);
}
return result;
},
"<x-one-radius>": function(expression) {
//[ <length> | <percentage> ] [ <length> | <percentage> ]?
var result = false,
count = 0,
numeric = "<length> | <percentage>",
part;
if (ValidationTypes.isAny(expression, numeric)){
result = true;
ValidationTypes.isAny(expression, numeric);
}
return result;
}
}
};
parserlib.css = {
Colors :Colors,
Combinator :Combinator,
Parser :Parser,
PropertyName :PropertyName,
PropertyValue :PropertyValue,
PropertyValuePart :PropertyValuePart,
MediaFeature :MediaFeature,
MediaQuery :MediaQuery,
Selector :Selector,
SelectorPart :SelectorPart,
SelectorSubPart :SelectorSubPart,
Specificity :Specificity,
TokenStream :TokenStream,
Tokens :Tokens,
ValidationError :ValidationError
};
})();
/**
* Main CSSLint object.
* @class CSSLint
* @static
* @extends parserlib.util.EventTarget
*/
/*global parserlib, Reporter*/
var CSSLint = (function(){
var rules = [],
formatters = [],
api = new parserlib.util.EventTarget();
api.version = "0.9.8";
//-------------------------------------------------------------------------
// Rule Management
//-------------------------------------------------------------------------
/**
* Adds a new rule to the engine.
* @param {Object} rule The rule to add.
* @method addRule
*/
api.addRule = function(rule){
rules.push(rule);
rules[rule.id] = rule;
};
/**
* Clears all rule from the engine.
* @method clearRules
*/
api.clearRules = function(){
rules = [];
};
/**
* Returns the rule objects.
* @return An array of rule objects.
* @method getRules
*/
api.getRules = function(){
return [].concat(rules).sort(function(a,b){
return a.id > b.id ? 1 : 0;
});
};
/**
* Returns a ruleset configuration object with all current rules.
* @return A ruleset object.
* @method getRuleset
*/
api.getRuleset = function() {
var ruleset = {},
i = 0,
len = rules.length;
while (i < len){
ruleset[rules[i++].id] = 1; //by default, everything is a warning
}
return ruleset;
};
//-------------------------------------------------------------------------
// Formatters
//-------------------------------------------------------------------------
/**
* Adds a new formatter to the engine.
* @param {Object} formatter The formatter to add.
* @method addFormatter
*/
api.addFormatter = function(formatter) {
// formatters.push(formatter);
formatters[formatter.id] = formatter;
};
/**
* Retrieves a formatter for use.
* @param {String} formatId The name of the format to retrieve.
* @return {Object} The formatter or undefined.
* @method getFormatter
*/
api.getFormatter = function(formatId){
return formatters[formatId];
};
/**
* Formats the results in a particular format for a single file.
* @param {Object} result The results returned from CSSLint.verify().
* @param {String} filename The filename for which the results apply.
* @param {String} formatId The name of the formatter to use.
* @param {Object} options (Optional) for special output handling.
* @return {String} A formatted string for the results.
* @method format
*/
api.format = function(results, filename, formatId, options) {
var formatter = this.getFormatter(formatId),
result = null;
if (formatter){
result = formatter.startFormat();
result += formatter.formatResults(results, filename, options || {});
result += formatter.endFormat();
}
return result;
};
/**
* Indicates if the given format is supported.
* @param {String} formatId The ID of the format to check.
* @return {Boolean} True if the format exists, false if not.
* @method hasFormat
*/
api.hasFormat = function(formatId){
return formatters.hasOwnProperty(formatId);
};
//-------------------------------------------------------------------------
// Verification
//-------------------------------------------------------------------------
/**
* Starts the verification process for the given CSS text.
* @param {String} text The CSS text to verify.
* @param {Object} ruleset (Optional) List of rules to apply. If null, then
* all rules are used. If a rule has a value of 1 then it's a warning,
* a value of 2 means it's an error.
* @return {Object} Results of the verification.
* @method verify
*/
api.verify = function(text, ruleset){
var i = 0,
len = rules.length,
reporter,
lines,
report,
parser = new parserlib.css.Parser({ starHack: true, ieFilters: true,
underscoreHack: true, strict: false });
// normalize line endings
lines = text.replace(/\n\r?/g, "$split$").split('$split$');
if (!ruleset){
ruleset = this.getRuleset();
}
reporter = new Reporter(lines, ruleset);
ruleset.errors = 2; //always report parsing errors as errors
for (i in ruleset){
if(ruleset.hasOwnProperty(i)){
if (rules[i]){
rules[i].init(parser, reporter);
}
}
}
//capture most horrible error type
try {
parser.parse(text);
} catch (ex) {
reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
}
report = {
messages : reporter.messages,
stats : reporter.stats
};
//sort by line numbers, rollups at the bottom
report.messages.sort(function (a, b){
if (a.rollup && !b.rollup){
return 1;
} else if (!a.rollup && b.rollup){
return -1;
} else {
return a.line - b.line;
}
});
return report;
};
//-------------------------------------------------------------------------
// Publish the API
//-------------------------------------------------------------------------
return api;
})();
/*global CSSLint*/
/**
* An instance of Report is used to report results of the
* verification back to the main API.
* @class Reporter
* @constructor
* @param {String[]} lines The text lines of the source.
* @param {Object} ruleset The set of rules to work with, including if
* they are errors or warnings.
*/
function Reporter(lines, ruleset){
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
}
Reporter.prototype = {
//restore constructor
constructor: Reporter,
/**
* Report an error.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method error
*/
error: function(message, line, col, rule){
this.messages.push({
type : "error",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule || {}
});
},
/**
* Report an warning.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method warn
* @deprecated Use report instead.
*/
warn: function(message, line, col, rule){
this.report(message, line, col, rule);
},
/**
* Report an issue.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method report
*/
report: function(message, line, col, rule){
this.messages.push({
type : this.ruleset[rule.id] == 2 ? "error" : "warning",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some informational text.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method info
*/
info: function(message, line, col, rule){
this.messages.push({
type : "info",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some rollup error information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupError
*/
rollupError: function(message, rule){
this.messages.push({
type : "error",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report some rollup warning information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupWarn
*/
rollupWarn: function(message, rule){
this.messages.push({
type : "warning",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report a statistic.
* @param {String} name The name of the stat to store.
* @param {Variant} value The value of the stat.
* @method stat
*/
stat: function(name, value){
this.stats[name] = value;
}
};
//expose for testing purposes
CSSLint._Reporter = Reporter;
/*global CSSLint*/
/*
* Utility functions that make life easier.
*/
CSSLint.Util = {
/*
* Adds all properties from supplier onto receiver,
* overwriting if the same name already exists on
* reciever.
* @param {Object} The object to receive the properties.
* @param {Object} The object to provide the properties.
* @return {Object} The receiver
*/
mix: function(receiver, supplier){
var prop;
for (prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return prop;
},
/*
* Polyfill for array indexOf() method.
* @param {Array} values The array to search.
* @param {Variant} value The value to search for.
* @return {int} The index of the value if found, -1 if not.
*/
indexOf: function(values, value){
if (values.indexOf){
return values.indexOf(value);
} else {
for (var i=0, len=values.length; i < len; i++){
if (values[i] === value){
return i;
}
}
return -1;
}
},
/*
* Polyfill for array forEach() method.
* @param {Array} values The array to operate on.
* @param {Function} func The function to call on each item.
* @return {void}
*/
forEach: function(values, func) {
if (values.forEach){
return values.forEach(func);
} else {
for (var i=0, len=values.length; i < len; i++){
func(values[i], i, values);
}
}
}
};
/*global CSSLint*/
/*
* Rule: Don't use adjoining classes (.foo.bar).
*/
CSSLint.addRule({
//rule information
id: "adjoining-classes",
name: "Disallow adjoining classes",
desc: "Don't use adjoining classes.",
browsers: "IE6",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
classCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
classCount = 0;
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "class"){
classCount++;
}
if (classCount > 1){
reporter.report("Don't use adjoining classes.", part.line, part.col, rule);
}
}
}
}
}
});
}
});
/*global CSSLint*/
/*
* Rule: Don't use width or height when using padding or border.
*/
CSSLint.addRule({
//rule information
id: "box-model",
name: "Beware of broken box size",
desc: "Don't use width or height when using padding or border.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
widthProperties = {
border: 1,
"border-left": 1,
"border-right": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1
},
heightProperties = {
border: 1,
"border-bottom": 1,
"border-top": 1,
padding: 1,
"padding-bottom": 1,
"padding-top": 1
},
properties;
function startRule(){
properties = {};
}
function endRule(){
var prop, value;
if (properties.height){
for (prop in heightProperties){
if (heightProperties.hasOwnProperty(prop) && properties[prop]){
value = properties[prop].value;
//special case for padding
if (!(prop == "padding" && value.parts.length === 2 && value.parts[0].value === 0)){
reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
if (properties.width){
for (prop in widthProperties){
if (widthProperties.hasOwnProperty(prop) && properties[prop]){
value = properties[prop].value;
if (!(prop == "padding" && value.parts.length === 2 && value.parts[1].value === 0)){
reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (heightProperties[name] || widthProperties[name]){
if (!/^0\S*$/.test(event.value) && !(name == "border" && event.value == "none")){
properties[name] = { line: event.property.line, col: event.property.col, value: event.value };
}
} else {
if (/^(width|height)/i.test(name) && /^(length|percentage)/.test(event.value.parts[0].type)){
properties[name] = 1;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*global CSSLint*/
/*
* Rule: box-sizing doesn't work in IE6 and IE7.
*/
CSSLint.addRule({
//rule information
id: "box-sizing",
name: "Disallow use of box-sizing",
desc: "The box-sizing properties isn't supported in IE6 and IE7.",
browsers: "IE6, IE7",
tags: ["Compatibility"],
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (name == "box-sizing"){
reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule);
}
});
}
});
/*
* Rule: Include all compatible vendor prefixes to reach a wider
* range of users.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "compatible-vendor-prefixes",
name: "Require compatible vendor prefixes",
desc: "Include all compatible vendor prefixes to reach a wider range of users.",
browsers: "All",
//initialization
init: function (parser, reporter) {
var rule = this,
compatiblePrefixes,
properties,
prop,
variations,
prefixed,
i,
len,
inKeyFrame = false,
arrayPush = Array.prototype.push,
applyTo = [];
// See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details
compatiblePrefixes = {
"animation" : "webkit moz",
"animation-delay" : "webkit moz",
"animation-direction" : "webkit moz",
"animation-duration" : "webkit moz",
"animation-fill-mode" : "webkit moz",
"animation-iteration-count" : "webkit moz",
"animation-name" : "webkit moz",
"animation-play-state" : "webkit moz",
"animation-timing-function" : "webkit moz",
"appearance" : "webkit moz",
"border-end" : "webkit moz",
"border-end-color" : "webkit moz",
"border-end-style" : "webkit moz",
"border-end-width" : "webkit moz",
"border-image" : "webkit moz o",
"border-radius" : "webkit moz",
"border-start" : "webkit moz",
"border-start-color" : "webkit moz",
"border-start-style" : "webkit moz",
"border-start-width" : "webkit moz",
"box-align" : "webkit moz ms",
"box-direction" : "webkit moz ms",
"box-flex" : "webkit moz ms",
"box-lines" : "webkit ms",
"box-ordinal-group" : "webkit moz ms",
"box-orient" : "webkit moz ms",
"box-pack" : "webkit moz ms",
"box-sizing" : "webkit moz",
"box-shadow" : "webkit moz",
"column-count" : "webkit moz ms",
"column-gap" : "webkit moz ms",
"column-rule" : "webkit moz ms",
"column-rule-color" : "webkit moz ms",
"column-rule-style" : "webkit moz ms",
"column-rule-width" : "webkit moz ms",
"column-width" : "webkit moz ms",
"hyphens" : "epub moz",
"line-break" : "webkit ms",
"margin-end" : "webkit moz",
"margin-start" : "webkit moz",
"marquee-speed" : "webkit wap",
"marquee-style" : "webkit wap",
"padding-end" : "webkit moz",
"padding-start" : "webkit moz",
"tab-size" : "moz o",
"text-size-adjust" : "webkit ms",
"transform" : "webkit moz ms o",
"transform-origin" : "webkit moz ms o",
"transition" : "webkit moz o",
"transition-delay" : "webkit moz o",
"transition-duration" : "webkit moz o",
"transition-property" : "webkit moz o",
"transition-timing-function" : "webkit moz o",
"user-modify" : "webkit moz",
"user-select" : "webkit moz ms",
"word-break" : "epub ms",
"writing-mode" : "epub ms"
};
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = [];
prefixed = compatiblePrefixes[prop].split(' ');
for (i = 0, len = prefixed.length; i < len; i++) {
variations.push('-' + prefixed[i] + '-' + prop);
}
compatiblePrefixes[prop] = variations;
arrayPush.apply(applyTo, variations);
}
}
parser.addListener("startrule", function () {
properties = [];
});
parser.addListener("startkeyframes", function (event) {
inKeyFrame = event.prefix || true;
});
parser.addListener("endkeyframes", function (event) {
inKeyFrame = false;
});
parser.addListener("property", function (event) {
var name = event.property;
if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {
// e.g., -moz-transform is okay to be alone in @-moz-keyframes
if (!inKeyFrame || typeof inKeyFrame != "string" ||
name.text.indexOf("-" + inKeyFrame + "-") !== 0) {
properties.push(name);
}
}
});
parser.addListener("endrule", function (event) {
if (!properties.length) {
return;
}
var propertyGroups = {},
i,
len,
name,
prop,
variations,
value,
full,
actual,
item,
propertiesSpecified;
for (i = 0, len = properties.length; i < len; i++) {
name = properties[i];
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = compatiblePrefixes[prop];
if (CSSLint.Util.indexOf(variations, name.text) > -1) {
if (!propertyGroups[prop]) {
propertyGroups[prop] = {
full : variations.slice(0),
actual : [],
actualNodes: []
};
}
if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
propertyGroups[prop].actual.push(name.text);
propertyGroups[prop].actualNodes.push(name);
}
}
}
}
}
for (prop in propertyGroups) {
if (propertyGroups.hasOwnProperty(prop)) {
value = propertyGroups[prop];
full = value.full;
actual = value.actual;
if (full.length > actual.length) {
for (i = 0, len = full.length; i < len; i++) {
item = full[i];
if (CSSLint.Util.indexOf(actual, item) === -1) {
propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length == 2) ? actual.join(" and ") : actual.join(", ");
reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
}
}
}
}
}
});
}
});
/*
* Rule: Certain properties don't play well with certain display values.
* - float should not be used with inline-block
* - height, width, margin-top, margin-bottom, float should not be used with inline
* - vertical-align should not be used with block
* - margin, float should not be used with table-*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "display-property-grouping",
name: "Require properties appropriate for display",
desc: "Certain properties shouldn't be used with certain display property values.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var propertiesToCheck = {
display: 1,
"float": "none",
height: 1,
width: 1,
margin: 1,
"margin-left": 1,
"margin-right": 1,
"margin-bottom": 1,
"margin-top": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1,
"padding-bottom": 1,
"padding-top": 1,
"vertical-align": 1
},
properties;
function reportProperty(name, display, msg){
if (properties[name]){
if (typeof propertiesToCheck[name] != "string" || properties[name].value.toLowerCase() != propertiesToCheck[name]){
reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule);
}
}
}
function startRule(){
properties = {};
}
function endRule(){
var display = properties.display ? properties.display.value : null;
if (display){
switch(display){
case "inline":
//height, width, margin-top, margin-bottom, float should not be used with inline
reportProperty("height", display);
reportProperty("width", display);
reportProperty("margin", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");
break;
case "block":
//vertical-align should not be used with block
reportProperty("vertical-align", display);
break;
case "inline-block":
//float should not be used with inline-block
reportProperty("float", display);
break;
default:
//margin, float should not be used with table
if (display.indexOf("table-") === 0){
reportProperty("margin", display);
reportProperty("margin-left", display);
reportProperty("margin-right", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display);
}
//otherwise do nothing
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startpage", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (propertiesToCheck[name]){
properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col };
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endpage", endRule);
}
});
/*
* Rule: Disallow duplicate background-images (using url).
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "duplicate-background-images",
name: "Disallow duplicate background images",
desc: "Every background-image should be unique. Use a common class for e.g. sprites.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
stack = {};
parser.addListener("property", function(event){
var name = event.property.text,
value = event.value,
i, len;
if (name.match(/background/i)) {
for (i=0, len=value.parts.length; i < len; i++) {
if (value.parts[i].type == 'uri') {
if (typeof stack[value.parts[i].uri] === 'undefined') {
stack[value.parts[i].uri] = event;
}
else {
reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule);
}
}
}
}
});
}
});
/*
* Rule: Duplicate properties must appear one after the other. If an already-defined
* property appears somewhere else in the rule, then it's likely an error.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "duplicate-properties",
name: "Disallow duplicate properties",
desc: "Duplicate properties must appear one after the other.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties,
lastProperty;
function startRule(event){
properties = {};
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase();
if (properties[name] && (lastProperty != name || properties[name] == event.value.text)){
reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule);
}
properties[name] = event.value.text;
lastProperty = name;
});
}
});
/*
* Rule: Style rules without any properties defined should be removed.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "empty-rules",
name: "Disallow empty rules",
desc: "Rules without any properties specified should be removed.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
parser.addListener("startrule", function(){
count=0;
});
parser.addListener("property", function(){
count++;
});
parser.addListener("endrule", function(event){
var selectors = event.selectors;
if (count === 0){
reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule);
}
});
}
});
/*
* Rule: There should be no syntax errors. (Duh.)
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "errors",
name: "Parsing Errors",
desc: "This rule looks for recoverable syntax errors.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("error", function(event){
reporter.error(event.message, event.line, event.col, rule);
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "fallback-colors",
name: "Require fallback colors",
desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",
browsers: "IE6,IE7,IE8",
//initialization
init: function(parser, reporter){
var rule = this,
lastProperty,
propertiesToCheck = {
color: 1,
background: 1,
"background-color": 1
},
properties;
function startRule(event){
properties = {};
lastProperty = null;
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase(),
parts = event.value.parts,
i = 0,
colorType = "",
len = parts.length;
if(propertiesToCheck[name]){
while(i < len){
if (parts[i].type == "color"){
if ("alpha" in parts[i] || "hue" in parts[i]){
if (/([^\)]+)\(/.test(parts[i])){
colorType = RegExp.$1.toUpperCase();
}
if (!lastProperty || (lastProperty.property.text.toLowerCase() != name || lastProperty.colorType != "compat")){
reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule);
}
} else {
event.colorType = "compat";
}
}
i++;
}
}
lastProperty = event;
});
}
});
/*
* Rule: You shouldn't use more than 10 floats. If you do, there's probably
* room for some abstraction.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "floats",
name: "Disallow too many floats",
desc: "This rule tests if the float property is used too many times",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var count = 0;
//count how many times "float" is used
parser.addListener("property", function(event){
if (event.property.text.toLowerCase() == "float" &&
event.value.text.toLowerCase() != "none"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("floats", count);
if (count >= 10){
reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule);
}
});
}
});
/*
* Rule: Avoid too many @font-face declarations in the same stylesheet.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "font-faces",
name: "Don't use too many web fonts",
desc: "Too many different web fonts in the same stylesheet.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
parser.addListener("startfontface", function(){
count++;
});
parser.addListener("endstylesheet", function(){
if (count > 5){
reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule);
}
});
}
});
/*
* Rule: You shouldn't need more than 9 font-size declarations.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "font-sizes",
name: "Disallow too many font sizes",
desc: "Checks the number of font-size declarations.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//check for use of "font-size"
parser.addListener("property", function(event){
if (event.property == "font-size"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("font-sizes", count);
if (count >= 10){
reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule);
}
});
}
});
/*
* Rule: When using a vendor-prefixed gradient, make sure to use them all.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "gradients",
name: "Require all gradient definitions",
desc: "When using a vendor-prefixed gradient, make sure to use them all.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
gradients;
parser.addListener("startrule", function(){
gradients = {
moz: 0,
webkit: 0,
oldWebkit: 0,
ms: 0,
o: 0
};
});
parser.addListener("property", function(event){
if (/\-(moz|ms|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){
gradients[RegExp.$1] = 1;
} else if (/\-webkit\-gradient/i.test(event.value)){
gradients.oldWebkit = 1;
}
});
parser.addListener("endrule", function(event){
var missing = [];
if (!gradients.moz){
missing.push("Firefox 3.6+");
}
if (!gradients.webkit){
missing.push("Webkit (Safari 5+, Chrome)");
}
if (!gradients.oldWebkit){
missing.push("Old Webkit (Safari 4+, Chrome)");
}
if (!gradients.ms){
missing.push("Internet Explorer 10+");
}
if (!gradients.o){
missing.push("Opera 11.1+");
}
if (missing.length && missing.length < 5){
reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule);
}
});
}
});
/*
* Rule: Don't use IDs for selectors.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "ids",
name: "Disallow IDs in selectors",
desc: "Selectors should not contain IDs.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
idCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
idCount = 0;
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "id"){
idCount++;
}
}
}
}
if (idCount == 1){
reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule);
} else if (idCount > 1){
reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule);
}
}
});
}
});
/*
* Rule: Don't use @import, use <link> instead.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "import",
name: "Disallow @import",
desc: "Don't use @import, use <link> instead.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("import", function(event){
reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule);
});
}
});
/*
* Rule: Make sure !important is not overused, this could lead to specificity
* war. Display a warning on !important declarations, an error if it's
* used more at least 10 times.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "important",
name: "Disallow !important",
desc: "Be careful when using !important declaration",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//warn that important is used and increment the declaration counter
parser.addListener("property", function(event){
if (event.important === true){
count++;
reporter.report("Use of !important", event.line, event.col, rule);
}
});
//if there are more than 10, show an error
parser.addListener("endstylesheet", function(){
reporter.stat("important", count);
if (count >= 10){
reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specificity issues.", rule);
}
});
}
});
/*
* Rule: Properties should be known (listed in CSS3 specification) or
* be a vendor-prefixed property.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "known-properties",
name: "Require use of known properties",
desc: "Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
// the check is handled entirely by the parser-lib (https://github.com/nzakas/parser-lib)
if (event.invalid) {
reporter.report(event.invalid.message, event.line, event.col, rule);
}
});
}
});
/*
* Rule: outline: none or outline: 0 should only be used in a :focus rule
* and only if there are other properties in the same rule.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "outline-none",
name: "Disallow outline: none",
desc: "Use of outline: none or outline: 0 should be limited to :focus rules.",
browsers: "All",
tags: ["Accessibility"],
//initialization
init: function(parser, reporter){
var rule = this,
lastRule;
function startRule(event){
if (event.selectors){
lastRule = {
line: event.line,
col: event.col,
selectors: event.selectors,
propCount: 0,
outline: false
};
} else {
lastRule = null;
}
}
function endRule(event){
if (lastRule){
if (lastRule.outline){
if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") == -1){
reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule);
} else if (lastRule.propCount == 1) {
reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase(),
value = event.value;
if (lastRule){
lastRule.propCount++;
if (name == "outline" && (value == "none" || value == "0")){
lastRule.outline = true;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*
* Rule: Don't use classes or IDs with elements (a.foo or a#foo).
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "overqualified-elements",
name: "Disallow overqualified elements",
desc: "Don't use classes or IDs with elements (a.foo or a#foo).",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
classes = {};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (part.elementName && modifier.type == "id"){
reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule);
} else if (modifier.type == "class"){
if (!classes[modifier]){
classes[modifier] = [];
}
classes[modifier].push({ modifier: modifier, part: part });
}
}
}
}
}
});
parser.addListener("endstylesheet", function(){
var prop;
for (prop in classes){
if (classes.hasOwnProperty(prop)){
//one use means that this is overqualified
if (classes[prop].length == 1 && classes[prop][0].part.elementName){
reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule);
}
}
}
});
}
});
/*
* Rule: Headings (h1-h6) should not be qualified (namespaced).
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "qualified-headings",
name: "Disallow qualified headings",
desc: "Headings should not be qualified (namespaced).",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){
reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule);
}
}
}
}
});
}
});
/*
* Rule: Selectors that look like regular expressions are slow and should be avoided.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "regex-selectors",
name: "Disallow selectors that look like regexs",
desc: "Selectors that look like regular expressions are slow and should be avoided.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "attribute"){
if (/([\~\|\^\$\*]=)/.test(modifier)){
reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule);
}
}
}
}
}
}
});
}
});
/*
* Rule: Total number of rules should not exceed x.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "rules-count",
name: "Rules Count",
desc: "Track how many rules there are.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//count each rule
parser.addListener("startrule", function(){
count++;
});
parser.addListener("endstylesheet", function(){
reporter.stat("rule-count", count);
});
}
});
/*
* Rule: Use shorthand properties where possible.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "shorthand",
name: "Require shorthand properties",
desc: "Use shorthand properties where possible.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
prop, i, len,
propertiesToCheck = {},
properties,
mapping = {
"margin": [
"margin-top",
"margin-bottom",
"margin-left",
"margin-right"
],
"padding": [
"padding-top",
"padding-bottom",
"padding-left",
"padding-right"
]
};
//initialize propertiesToCheck
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
for (i=0, len=mapping[prop].length; i < len; i++){
propertiesToCheck[mapping[prop][i]] = prop;
}
}
}
function startRule(event){
properties = {};
}
//event handler for end of rules
function endRule(event){
var prop, i, len, total;
//check which properties this rule has
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
total=0;
for (i=0, len=mapping[prop].length; i < len; i++){
total += properties[mapping[prop][i]] ? 1 : 0;
}
if (total == mapping[prop].length){
reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value.parts[0].value;
if (propertiesToCheck[name]){
properties[name] = 1;
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*
* Rule: Don't use properties with a star prefix.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "star-property-hack",
name: "Disallow properties with a star prefix",
desc: "Checks for the star property hack (targets IE6/7)",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//check if property name starts with "*"
parser.addListener("property", function(event){
var property = event.property;
if (property.hack == "*") {
reporter.report("Property with star prefix found.", event.property.line, event.property.col, rule);
}
});
}
});
/*
* Rule: Don't use text-indent for image replacement if you need to support rtl.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "text-indent",
name: "Disallow negative text-indent",
desc: "Checks for text indent less than -99px",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
textIndent,
direction;
function startRule(event){
textIndent = false;
direction = "inherit";
}
//event handler for end of rules
function endRule(event){
if (textIndent && direction != "ltr"){
reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule);
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value;
if (name == "text-indent" && value.parts[0].value < -99){
textIndent = event.property;
} else if (name == "direction" && value == "ltr"){
direction = "ltr";
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*
* Rule: Don't use properties with a underscore prefix.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "underscore-property-hack",
name: "Disallow properties with an underscore prefix",
desc: "Checks for the underscore property hack (targets IE6)",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//check if property name starts with "_"
parser.addListener("property", function(event){
var property = event.property;
if (property.hack == "_") {
reporter.report("Property with underscore prefix found.", event.property.line, event.property.col, rule);
}
});
}
});
/*
* Rule: Headings (h1-h6) should be defined only once.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "unique-headings",
name: "Headings should only be defined once",
desc: "Headings should be defined only once.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var headings = {
h1: 0,
h2: 0,
h3: 0,
h4: 0,
h5: 0,
h6: 0
};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
pseudo,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){
for (j=0; j < part.modifiers.length; j++){
if (part.modifiers[j].type == "pseudo"){
pseudo = true;
break;
}
}
if (!pseudo){
headings[RegExp.$1]++;
if (headings[RegExp.$1] > 1) {
reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule);
}
}
}
}
});
parser.addListener("endstylesheet", function(event){
var prop,
messages = [];
for (prop in headings){
if (headings.hasOwnProperty(prop)){
if (headings[prop] > 1){
messages.push(headings[prop] + " " + prop + "s");
}
}
}
if (messages.length){
reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule);
}
});
}
});
/*
* Rule: Don't use universal selector because it's slow.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "universal-selector",
name: "Disallow universal selector",
desc: "The universal selector (*) is known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName == "*"){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
});
}
});
/*
* Rule: Don't use unqualified attribute selectors because they're just like universal selectors.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "unqualified-attributes",
name: "Disallow unqualified attribute selectors",
desc: "Unqualified attribute selectors are known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "attribute" && (!part.elementName || part.elementName == "*")){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
}
}
});
}
});
/*
* Rule: When using a vendor-prefixed property, make sure to
* include the standard one.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "vendor-prefix",
name: "Require standard property with vendor prefix",
desc: "When using a vendor-prefixed property, make sure to include the standard one.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties,
num,
propertiesToCheck = {
"-webkit-border-radius": "border-radius",
"-webkit-border-top-left-radius": "border-top-left-radius",
"-webkit-border-top-right-radius": "border-top-right-radius",
"-webkit-border-bottom-left-radius": "border-bottom-left-radius",
"-webkit-border-bottom-right-radius": "border-bottom-right-radius",
"-o-border-radius": "border-radius",
"-o-border-top-left-radius": "border-top-left-radius",
"-o-border-top-right-radius": "border-top-right-radius",
"-o-border-bottom-left-radius": "border-bottom-left-radius",
"-o-border-bottom-right-radius": "border-bottom-right-radius",
"-moz-border-radius": "border-radius",
"-moz-border-radius-topleft": "border-top-left-radius",
"-moz-border-radius-topright": "border-top-right-radius",
"-moz-border-radius-bottomleft": "border-bottom-left-radius",
"-moz-border-radius-bottomright": "border-bottom-right-radius",
"-moz-column-count": "column-count",
"-webkit-column-count": "column-count",
"-moz-column-gap": "column-gap",
"-webkit-column-gap": "column-gap",
"-moz-column-rule": "column-rule",
"-webkit-column-rule": "column-rule",
"-moz-column-rule-style": "column-rule-style",
"-webkit-column-rule-style": "column-rule-style",
"-moz-column-rule-color": "column-rule-color",
"-webkit-column-rule-color": "column-rule-color",
"-moz-column-rule-width": "column-rule-width",
"-webkit-column-rule-width": "column-rule-width",
"-moz-column-width": "column-width",
"-webkit-column-width": "column-width",
"-webkit-column-span": "column-span",
"-webkit-columns": "columns",
"-moz-box-shadow": "box-shadow",
"-webkit-box-shadow": "box-shadow",
"-moz-transform" : "transform",
"-webkit-transform" : "transform",
"-o-transform" : "transform",
"-ms-transform" : "transform",
"-moz-transform-origin" : "transform-origin",
"-webkit-transform-origin" : "transform-origin",
"-o-transform-origin" : "transform-origin",
"-ms-transform-origin" : "transform-origin",
"-moz-box-sizing" : "box-sizing",
"-webkit-box-sizing" : "box-sizing",
"-moz-user-select" : "user-select",
"-khtml-user-select" : "user-select",
"-webkit-user-select" : "user-select"
};
//event handler for beginning of rules
function startRule(){
properties = {};
num=1;
}
//event handler for end of rules
function endRule(event){
var prop,
i, len,
standard,
needed,
actual,
needsStandard = [];
for (prop in properties){
if (propertiesToCheck[prop]){
needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]});
}
}
for (i=0, len=needsStandard.length; i < len; i++){
needed = needsStandard[i].needed;
actual = needsStandard[i].actual;
if (!properties[needed]){
reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
} else {
//make sure standard property is last
if (properties[needed][0].pos < properties[actual][0].pos){
reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (!properties[name]){
properties[name] = [];
}
properties[name].push({ name: event.property, value : event.value, pos:num++ });
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*
* Rule: You don't need to specify units when a value is 0.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "zero-units",
name: "Disallow units for 0 values",
desc: "You don't need to specify units when a value is 0.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//count how many times "float" is used
parser.addListener("property", function(event){
var parts = event.value.parts,
i = 0,
len = parts.length;
while(i < len){
if ((parts[i].units || parts[i].type == "percentage") && parts[i].value === 0 && parts[i].type != "time"){
reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule);
}
i++;
}
});
}
});
/*global CSSLint*/
(function() {
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var xmlEscape = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/[\"&><]/g, function(match) {
switch (match) {
case "\"":
return """;
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
}
});
};
CSSLint.addFormatter({
//format information
id: "checkstyle-xml",
name: "Checkstyle XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</checkstyle>";
},
/**
* Returns message when there is a file read error.
* @param {String} filename The name of the file that caused the error.
* @param {String} message The error message
* @return {String} The error message.
*/
readError: function(filename, message) {
return "<file name=\"" + xmlEscape(filename) + "\"><error line=\"0\" column=\"0\" severty=\"error\" message=\"" + xmlEscape(message) + "\"></error></file>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
/**
* Generate a source string for a rule.
* Checkstyle source strings usually resemble Java class names e.g
* net.csslint.SomeRuleName
* @param {Object} rule
* @return rule source as {String}
*/
var generateSource = function(rule) {
if (!rule || !('name' in rule)) {
return "";
}
return 'net.csslint.' + rule.name.replace(/\s/g,'');
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
//ignore rollups for now
if (!message.rollup) {
output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" message=\"" + xmlEscape(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
}());
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "compact",
name: "Compact, 'porcelain' format",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = "";
options = options || {};
/**
* Capitalize and return given string.
* @param str {String} to capitalize
* @return {String} capitalized
*/
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
if (messages.length === 0) {
return options.quiet ? "" : filename + ": Lint Free!";
}
CSSLint.Util.forEach(messages, function(message, i) {
if (message.rollup) {
output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n";
} else {
output += filename + ": " + "line " + message.line +
", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + "\n";
}
});
return output;
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "csslint-xml",
name: "CSSLint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</csslint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "junit-xml",
name: "JUNIT XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><testsuites>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function() {
return "</testsuites>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [],
tests = {
'error': 0,
'failure': 0
};
/**
* Generate a source string for a rule.
* JUNIT source strings usually resemble Java class names e.g
* net.csslint.SomeRuleName
* @param {Object} rule
* @return rule source as {String}
*/
var generateSource = function(rule) {
if (!rule || !('name' in rule)) {
return "";
}
return 'net.csslint.' + rule.name.replace(/\s/g,'');
};
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
messages.forEach(function (message, i) {
// since junit has no warning class
// all issues as errors
var type = message.type === 'warning' ? 'error' : message.type;
//ignore rollups for now
if (!message.rollup) {
// build the test case seperately, once joined
// we'll add it to a custom array filtered by type
output.push("<testcase time=\"0\" name=\"" + generateSource(message.rule) + "\">");
output.push("<" + type + " message=\"" + escapeSpecialCharacters(message.message) + "\"><![CDATA[" + message.line + ':' + message.col + ':' + escapeSpecialCharacters(message.evidence) + "]]></" + type + ">");
output.push("</testcase>");
tests[type] += 1;
}
});
output.unshift("<testsuite time=\"0\" tests=\"" + messages.length + "\" skipped=\"0\" errors=\"" + tests.error + "\" failures=\"" + tests.failure + "\" package=\"net.csslint\" name=\"" + filename + "\">");
output.push("</testsuite>");
}
return output.join("");
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "lint-xml",
name: "Lint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</lint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "text",
name: "Plain Text",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = "";
options = options || {};
if (messages.length === 0) {
return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + ".";
}
output = "\n\ncsslint: There are " + messages.length + " problems in " + filename + ".";
var pos = filename.lastIndexOf("/"),
shortFilename = filename;
if (pos === -1){
pos = filename.lastIndexOf("\\");
}
if (pos > -1){
shortFilename = filename.substring(pos+1);
}
CSSLint.Util.forEach(messages, function (message, i) {
output = output + "\n\n" + shortFilename;
if (message.rollup) {
output += "\n" + (i+1) + ": " + message.type;
output += "\n" + message.message;
} else {
output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col;
output += "\n" + message.message;
output += "\n" + message.evidence;
}
});
return output;
}
});
return CSSLint;
})();
| blackberry-webworks/csslint | release/csslint.js | JavaScript | mit | 306,601 |
const exec = require('child_process').exec;
module.exports = {
onLivingRoomLightOn,
onLivingRoomLightOff,
};
function onLivingRoomLightOn() {
return exec(`sudo ${__dirname}/../../lib/scripts/Emetteur 3 ${__dirname}/../../lib/actions/livingRoom/LightOn.csv`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
function onLivingRoomLightOff() {
return exec(`sudo ${__dirname}/../../lib/scripts/Emetteur 3 ${__dirname}/../../lib/actions/livingRoom/LightOff.csv`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
| SurionA/home-center-radio-frequence-control | handler/livingRoom/index.js | JavaScript | mit | 882 |
import {StyleSheet} from 'react-native'
const styles = StyleSheet.create({
container: {
flex: 1
}
})
export default styles
| huxinmin/PracticeMakesPerfect | reactNative/GitterMobile-master/app/screens/RoomUsers/RoomUsersList/styles.js | JavaScript | mit | 133 |
/* eslint-disable */
() => {
const filterOptions = [
{ id: 'In Stock, Out Of Stock', value: 'In Stock, Out Of Stock' },
{ id: 'In Stock', value: 'In Stock' },
{ id: 'Out Of Stock', value: 'Out Of Stock' },
];
const [activeFilter, setActiveFilter] = React.useState(filterOptions[0].id);
const [searchTerm, setSearchTerm] = React.useState('');
const [records, setRecords] = React.useState([
{
name: 'Red Slippers',
SKU: '0231664667',
price: '$14.00',
inventory: 'In Stock',
},
{
name: 'Velvet Hat',
SKU: '0231664669',
price: '$23.00',
inventory: 'In Stock',
},
{
name: 'Silver Jeans',
SKU: '0231664667',
price: '$69.00',
inventory: 'In Stock',
},
{
name: 'Orange Stocks',
SKU: '0231664671',
price: '$9.00',
inventory: 'Out Of Stock',
},
{
name: 'Black T-shirts',
SKU: '0231664672',
price: '$19.00',
inventory: 'In Stock',
},
]);
const columns = [
{
title: 'Name',
render: row => <Highlighter match={searchTerm}>{row.name}</Highlighter>,
width: '30%',
},
{
title: 'SKU',
render: row => row.SKU,
width: '20%',
},
{
title: 'Price',
render: row => row.price,
width: '20%',
},
{
title: 'Inventory',
render: row => row.inventory,
width: '20%',
},
];
const _getFilteredData = () => {
let filteredData = records.concat(records);
if (activeFilter !== 'In Stock, Out Of Stock') {
filteredData = filteredData.filter(row => row.inventory === activeFilter);
}
if (searchTerm !== '') {
filteredData = filteredData.filter(row =>
row.name.toUpperCase().includes(searchTerm.toUpperCase()),
);
}
return filteredData;
};
const filteredData = _getFilteredData();
const _clearSearch = () => {
setSearchTerm('');
};
const _renderSearch = expandable => {
return (
<Search
expandable={expandable}
onChange={e => {
setSearchTerm(e.target.value);
}}
value={searchTerm}
onClear={_clearSearch}
/>
);
};
const _renderEmptyState = () => (
<Table.EmptyState
title="You haven't added any items yet"
subtitle="Add items to your website so people can buy them"
image={
<Box
height={120}
width={120}
backgroundColor="#dfe5eb"
borderRadius="50%"
/>
}
>
<TextButton suffixIcon={<Icons.ExternalLink />}>
Learn how to add items
</TextButton>
</Table.EmptyState>
);
const _renderMainToolbar = () => {
return (
<Card>
<TableToolbar>
<TableToolbar.ItemGroup position="start">
<TableToolbar.Item>
<TableToolbar.Label>
Status
<span style={{ width: '150px' }}>
<Dropdown
options={filterOptions}
selectedId={activeFilter}
onSelect={selectedOption => {
console.log(selectedOption);
setActiveFilter(selectedOption.value);
}}
roundInput
/>
</span>
</TableToolbar.Label>
</TableToolbar.Item>
<TableToolbar.Item>
<TableToolbar.Label>
Category
<span style={{ width: '150px' }}>
<Dropdown
options={[{ id: 0, value: 'All categories' }]}
selectedId={0}
roundInput
/>
</span>
</TableToolbar.Label>
</TableToolbar.Item>
</TableToolbar.ItemGroup>
<TableToolbar.ItemGroup position="end">
<TableToolbar.Item>{_renderSearch(false)}</TableToolbar.Item>
</TableToolbar.ItemGroup>
</TableToolbar>
</Card>
);
};
return (
<Page height="600px">
<Page.Header
title="Products"
actionsBar={
<Box>
<Box padding="SP1">
<IconButton skin="inverted">
<Icons.More />
</IconButton>{' '}
</Box>
<Box padding="SP1">
<Button prefixIcon={<Icons.Add />}>Add Product</Button>{' '}
</Box>
</Box>
}
/>
<Page.Content>
<Table
data={filteredData}
columns={columns}
onSelectionChange={selectedIds =>
console.log('Table.onSelectionChange(): selectedIds=', selectedIds)
}
showSelection
>
<Page.Sticky>
<Card>
<Table.ToolbarContainer>
{selectionContext =>
selectionContext.selectedCount === 0
? _renderMainToolbar()
: this._renderActionsToolbar({ ...selectionContext })
}
</Table.ToolbarContainer>
<Table.SubToolbar>
<FormField label="Filtered by:" labelPlacement="left">
<TagList
tags={[
{ id: '1', children: 'In Stock' },
{ id: '2', children: 'Out Of Stock' },
]}
maxVisibleTags={2}
actionButton={{ label: 'Clear All', onClick: () => {} }}
/>
</FormField>
</Table.SubToolbar>
{filteredData.length ? <Table.Titlebar /> : _renderEmptyState()}
</Card>
</Page.Sticky>
<Card>
<Table.Content titleBarVisible={false} />
</Card>
</Table>
</Page.Content>
</Page>
);
const _renderActionsToolbar = ({ selectedCount, getSelectedIds }) => {
return (
<TableToolbar>
<TableToolbar.ItemGroup position="start">
<TableToolbar.Item>
<TableToolbar.SelectedCount>{`${selectedCount} Selected`}</TableToolbar.SelectedCount>
</TableToolbar.Item>
</TableToolbar.ItemGroup>
<TableToolbar.ItemGroup position="end">
<TableToolbar.Item layout="button">
<Button
skin="light"
priority="primary"
prefixIcon={<Icons.Upload />}
onClick={() =>
window.alert(`Exporting selectedIds=${getSelectedIds()}`)
}
>
Export
</Button>
</TableToolbar.Item>
<TableToolbar.Item layout="button">
<Button
skin="light"
priority="primary"
prefixIcon={<Icons.Duplicate />}
onClick={() =>
window.alert(`Duplicating selectedIds=${getSelectedIds()}`)
}
>
Duplicate
</Button>
</TableToolbar.Item>
<TableToolbar.Item layout="button">
<Button
skin="light"
priority="primary"
prefixIcon={<Icons.Edit />}
onClick={() =>
window.alert(`Editing selectedIds=${getSelectedIds()}`)
}
>
Edit
</Button>
</TableToolbar.Item>
<TableToolbar.Divider />
<TableToolbar.Item>{this._renderSearch(true)}</TableToolbar.Item>
</TableToolbar.ItemGroup>
</TableToolbar>
);
};
};
| wix/wix-style-react | packages/wix-style-react/src/Table/docs/examples/19_TableStickyToolbarExample.js | JavaScript | mit | 7,606 |
module.exports = {
test: {
src: [
'test/vendor/assert.js',
'test/test-adapter.js',
'transpiled/tests.cjs.js'
],
options: {
reporter: 'spec'
}
}
}; | ramybenaroya/es6-modules-packager | tasks/options/mochaTest.js | JavaScript | mit | 190 |
import { Map } from 'immutable';
const BLOCK_MAP = Map({
'header-one': {
element: 'h1',
},
'header-two': {
element: 'h2',
},
'header-three': {
element: 'h3',
},
'header-four': {
element: 'h4',
},
'header-five': {
element: 'h5',
},
'header-six': {
element: 'h6',
},
blockquote: {
element: 'blockquote',
},
'code-block': {
element: 'pre',
},
atomic: {
element: 'figure',
},
'unordered-list-item': {
element: 'li',
},
'ordered-list-item': {
element: 'li',
},
unstyled: {
element: 'div',
},
});
export default BLOCK_MAP;
| SLedunois/personal-website | public/src/admin/editor/blockRenderMap.js | JavaScript | mit | 615 |
var _base = require('./bog.domain.repositories._base.js');
var StatusDataRepo = require('../../data/repositories/bog.data.repositories.status');
var StatusRepository = function (current_user) {
var self = this;
var user = current_user;
// Return All Items
var All = function (callback) {
var dataRepo = new StatusDataRepo();
dataRepo.all(function (err, coll) {
if (err) {
callback(self.err.wrap(1001, null, err));
} else {
callback(null, coll);
}
});
};
return {
all: All
};
};
StatusRepository.prototype = new _base();
module.exports = StatusRepository; | BankOfGiving/Bog.io | server/domain/repositories/bog.domain.repositories.status.js | JavaScript | mit | 689 |
/* */
"format cjs";
;
(function(factory) {
var objectTypes = {
'function': true,
'object': true
};
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
if (typeof define === 'function' && define.amd) {
define(['./rx'], function(Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('./rx'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function(root, exp, Rx, undefined) {
var Observable = Rx.Observable,
observableProto = Observable.prototype,
AnonymousObservable = Rx.AnonymousObservable,
ObservableBase = Rx.ObservableBase,
Subject = Rx.Subject,
AsyncSubject = Rx.AsyncSubject,
Observer = Rx.Observer,
ScheduledObserver = Rx.internals.ScheduledObserver,
disposableCreate = Rx.Disposable.create,
disposableEmpty = Rx.Disposable.empty,
BinaryDisposable = Rx.BinaryDisposable,
currentThreadScheduler = Rx.Scheduler.currentThread,
isFunction = Rx.helpers.isFunction,
inherits = Rx.internals.inherits,
addProperties = Rx.internals.addProperties,
checkDisposed = Rx.Disposable.checkDisposed;
function cloneArray(arr) {
var len = arr.length,
a = new Array(len);
for (var i = 0; i < len; i++) {
a[i] = arr[i];
}
return a;
}
var MulticastObservable = (function(__super__) {
inherits(MulticastObservable, __super__);
function MulticastObservable(source, fn1, fn2) {
this.source = source;
this._fn1 = fn1;
this._fn2 = fn2;
__super__.call(this);
}
MulticastObservable.prototype.subscribeCore = function(o) {
var connectable = this.source.multicast(this._fn1());
return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
};
return MulticastObservable;
}(ObservableBase));
observableProto.multicast = function(subjectOrSubjectSelector, selector) {
return isFunction(subjectOrSubjectSelector) ? new MulticastObservable(this, subjectOrSubjectSelector, selector) : new ConnectableObservable(this, subjectOrSubjectSelector);
};
observableProto.publish = function(selector) {
return selector && isFunction(selector) ? this.multicast(function() {
return new Subject();
}, selector) : this.multicast(new Subject());
};
observableProto.share = function() {
return this.publish().refCount();
};
observableProto.publishLast = function(selector) {
return selector && isFunction(selector) ? this.multicast(function() {
return new AsyncSubject();
}, selector) : this.multicast(new AsyncSubject());
};
observableProto.publishValue = function(initialValueOrSelector, initialValue) {
return arguments.length === 2 ? this.multicast(function() {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector));
};
observableProto.shareValue = function(initialValue) {
return this.publishValue(initialValue).refCount();
};
observableProto.replay = function(selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ? this.multicast(function() {
return new ReplaySubject(bufferSize, windowSize, scheduler);
}, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
observableProto.shareReplay = function(bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function(s, o) {
this._s = s;
this._o = o;
};
InnerSubscription.prototype.dispose = function() {
if (!this._s.isDisposed && this._o !== null) {
var idx = this._s.observers.indexOf(this._o);
this._s.observers.splice(idx, 1);
this._o = null;
}
};
var BehaviorSubject = Rx.BehaviorSubject = (function(__super__) {
inherits(BehaviorSubject, __super__);
function BehaviorSubject(value) {
__super__.call(this);
this.value = value;
this.observers = [];
this.isDisposed = false;
this.isStopped = false;
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer.prototype, {
_subscribe: function(o) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(o);
o.onNext(this.value);
return new InnerSubscription(this, o);
}
if (this.hasError) {
o.onError(this.error);
} else {
o.onCompleted();
}
return disposableEmpty;
},
getValue: function() {
checkDisposed(this);
if (this.hasError) {
thrower(this.error);
}
return this.value;
},
hasObservers: function() {
return this.observers.length > 0;
},
onCompleted: function() {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
onError: function(error) {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
onNext: function(value) {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.value = value;
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
dispose: function() {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.error = null;
}
});
return BehaviorSubject;
}(Observable));
var ReplaySubject = Rx.ReplaySubject = (function(__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function() {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
inherits(ReplaySubject, __super__);
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
_subscribe: function(o) {
checkDisposed(this);
var so = new ScheduledObserver(this.scheduler, o),
subscription = createRemovableDisposable(this, so);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0,
len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
},
hasObservers: function() {
return this.observers.length > 0;
},
_trim: function(now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
onNext: function(value) {
checkDisposed(this);
if (this.isStopped) {
return;
}
var now = this.scheduler.now();
this.q.push({
interval: now,
value: value
});
this._trim(now);
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
onError: function(error) {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
onCompleted: function() {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
dispose: function() {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var RefCountObservable = (function(__super__) {
inherits(RefCountObservable, __super__);
function RefCountObservable(source) {
this.source = source;
this._count = 0;
this._connectableSubscription = null;
__super__.call(this);
}
RefCountObservable.prototype.subscribeCore = function(o) {
var subscription = this.source.subscribe(o);
++this._count === 1 && (this._connectableSubscription = this.source.connect());
return new RefCountDisposable(this, subscription);
};
function RefCountDisposable(p, s) {
this._p = p;
this._s = s;
this.isDisposed = false;
}
RefCountDisposable.prototype.dispose = function() {
if (!this.isDisposed) {
this.isDisposed = true;
this._s.dispose();
--this._p._count === 0 && this._p._connectableSubscription.dispose();
}
};
return RefCountObservable;
}(ObservableBase));
var ConnectableObservable = Rx.ConnectableObservable = (function(__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
this.source = source;
this._connection = null;
this._source = source.asObservable();
this._subject = subject;
__super__.call(this);
}
function ConnectDisposable(parent, subscription) {
this._p = parent;
this._s = subscription;
}
ConnectDisposable.prototype.dispose = function() {
if (this._s) {
this._s.dispose();
this._s = null;
this._p._connection = null;
}
};
ConnectableObservable.prototype.connect = function() {
if (!this._connection) {
var subscription = this._source.subscribe(this._subject);
this._connection = new ConnectDisposable(this, subscription);
}
return this._connection;
};
ConnectableObservable.prototype._subscribe = function(o) {
return this._subject.subscribe(o);
};
ConnectableObservable.prototype.refCount = function() {
return new RefCountObservable(this);
};
return ConnectableObservable;
}(Observable));
observableProto.singleInstance = function() {
var source = this,
hasObservable = false,
observable;
function getObservable() {
if (!hasObservable) {
hasObservable = true;
observable = source['finally'](function() {
hasObservable = false;
}).publish().refCount();
}
return observable;
}
return new AnonymousObservable(function(o) {
return getObservable().subscribe(o);
});
};
return Rx;
}));
| staab/staab.github.io | jspm_packages/npm/rx@4.0.7/dist/rx.binding.js | JavaScript | mit | 13,153 |
var utils = {
handleError: function(dataToLogToConsole, errorMessage, errorObj) {
console.log(dataToLogToConsole || errorMessage);
if (errorMessage) {
var alertMessage = errorMessage;
// if error object is passed, then append error message in the error object
if (errorObj && errorObj.hasOwnProperty('message')) {
// message returned from the server is actually stringified json. Try to parse it as json
// It contains code and message
var errorJSON = JSON.parse(errorObj.message);
if (errorJSON.hasOwnProperty('message')) {
alertMessage += ". " + errorJSON.message;
}
else {
alertMessage += ". " + errorObj.message;
}
}
alert(alertMessage);
}
}
}
module.exports = utils;
| typekit/platform-demo-browse | js/modules/utils.js | JavaScript | mit | 795 |
(function($){
$(function(){
triggerNavigation();
triggerScrollTop();
triggerTooltips();
initMQ();
});
function autoplayVideo(video, autoplay) {
autoplay = autoplay || false;
var $carousel = $('.carousel');
$carousel.on('slide.bs.carousel', function(e) {
video.pause();
});
$(video).on('ended', function (e) {
setTimeout(function () {
$carousel.carousel('next');
$carousel.carousel('cycle');
}, 1000);
});
if (autoplay) {
$(window).on('scroll.video.trigger resize.video.trigger', function () {
if ($(video).isOnScreen(0.8)) {
$(window).off('scroll.video.trigger resize.video.trigger');
video.play();
}
});
}
}
function triggerNavigation() {
var $nav_trigger = $('.js-navi-trigger');
$nav_trigger.on('mouseenter', function (e) {
$('#'+$(this).data('trigger')).addClass('navi-open-icons');
});
$nav_trigger.on('mouseleave', function (e) {
$('#'+$(this).data('trigger')).removeClass('navi-open-icons');
});
$nav = $('.js-nav');
$nav.on('mouseenter', function (e) {
$(this).addClass('navi-open-full');
});
$nav.on('mouseleave', function (e) {
$(this).removeClass('navi-open-full');
});
}
function triggerScrollTop() {
var $up_trigger = $('.js-up-trigger');
$up_trigger.hide().on('click', function (e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, 500);
});
$(window).on('scroll.up.trigger resize.up.trigger', function () {
if ($(this).scrollTop() > $(this).outerHeight() / 2) {
$up_trigger.fadeIn();
} else {
$up_trigger.fadeOut();
}
});
}
function triggerTooltips() {
$('[data-toggle="tooltip"]').tooltip();
}
function initMQ() {
var queries = [
{
context: 'default',
match: function() {
$('img').each(function() {
if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src'));
var small = $(this).data('default');
if (small) $(this).attr('src', small);
});
}
},
{
context: 'medium',
match: function() {
$('img').each(function() {
if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src'));
var medium = $(this).data('medium');
if (medium) $(this).attr('src', medium);
});
}
},
{
context: 'wide',
match: function() {
$('img').each(function() {
if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src'));
var large = $(this).data('large');
if (large) $(this).attr('src', large);
});
}
}
];
MQ.init(queries);
}
$.fn.isOnScreen = function(percentage) {
percentage = percentage || 0;
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
var height = this.outerHeight();
var width = this.outerWidth();
bounds.right = bounds.left + height;
bounds.bottom = bounds.top + width;
return (!(
viewport.right < bounds.left + width * percentage ||
viewport.left > bounds.right - width * percentage ||
viewport.bottom < bounds.top + height * percentage ||
viewport.top > bounds.bottom - height * percentage
));
};
})(window.jQuery); | michalochman/bild | js/main.js | JavaScript | mit | 4,375 |
module.exports = MnInputCustomElement()
function MnInputCustomElement() {
const supportsCustomElements = 'customElements' in window
if (!supportsCustomElements) {
require('@webcomponents/custom-elements')
}
if (!window.customElements.get('mn-input')) {
window.customElements.define('mn-input', require('./input.class.js'))
}
return window.customElements.get('mn-input')
}
| reserva-facil/minimalist | webcomponents/input/input.webcomponent.js | JavaScript | mit | 396 |
( function () { 'use strict';
function isPlainObject(stuff) {
if (
typeof stuff !== 'object' || stuff === null // Не объект
|| stuff === stuff.window // window
|| stuff.nodeType // DOM node
|| !stuff.constructor
|| !stuff.constructor.prototype.hasOwnProperty('isPrototypeOf')
// Проверка, что прототип объекта равняется "Object.prototype"
) {
return false;
} else {
return true;
}
}
Object.defineProperty( Object, 'isPlainObject', { value: isPlainObject } );
} () );
| kahless/fructose.js | lib/object/isPlainObject.js | JavaScript | mit | 600 |
global.SETTINGS = require('./settings');
global.log = require('./lib/log');
let app = require('./lib/server');
app.listen(SETTINGS.PORT, () => {
log.info(`#server Listening on port ${SETTINGS.PORT}`);
});
| sgmonda/api-koa | index.js | JavaScript | mit | 208 |
define(['underscore', 'util', 'collection/abstract'],
function(_, Util, AbstractCollection)
{
'use strict';
var _parent = AbstractCollection.prototype;
var ArrayCollection = Util.extend(AbstractCollection, {
_registry: null,
create: function() {
var me = this;
_parent.create.apply(me, arguments);
me._registry = [];
},
add: function(item) {
var me = this;
if (arguments.length > 1) {
_.each(arguments, function(arg) {
me.add(arg)
});
return;
}
if (!_.contains(me._registry, item)) {
me._registry.push(item);
_parent.add.apply(me, arguments);
}
},
remove: function(item) {
var me = this;
if (arguments.length > 1) {
_.each(arguments, function(arg) {
me.remove(arg);
});
return;
}
var index = _.indexOf(me._registry, item);
if (index >= 0) {
me._registry.splice(index, 1);
_parent.remove.apply(me, arguments);
}
},
each: function(iterator) {
_.each(this._registry, iterator);
},
some: function(iterator) {
return _.some(this._registry, iterator);
},
count: function() {
return this._registry.length;
},
getAll: function() {
return this._map.slice();
}
});
return ArrayCollection;
}); | DirtyHairy/mayrogue-deathmatch | goldmine/shared/collection/array.js | JavaScript | mit | 1,858 |
(function(global) {
var LiteGraph = global.LiteGraph;
function GamepadInput() {
this.addOutput("left_x_axis", "number");
this.addOutput("left_y_axis", "number");
this.addOutput("button_pressed", LiteGraph.EVENT);
this.properties = { gamepad_index: 0, threshold: 0.1 };
this._left_axis = new Float32Array(2);
this._right_axis = new Float32Array(2);
this._triggers = new Float32Array(2);
this._previous_buttons = new Uint8Array(17);
this._current_buttons = new Uint8Array(17);
}
GamepadInput.title = "Gamepad";
GamepadInput.desc = "gets the input of the gamepad";
GamepadInput.CENTER = 0;
GamepadInput.LEFT = 1;
GamepadInput.RIGHT = 2;
GamepadInput.UP = 4;
GamepadInput.DOWN = 8;
GamepadInput.zero = new Float32Array(2);
GamepadInput.buttons = [
"a",
"b",
"x",
"y",
"lb",
"rb",
"lt",
"rt",
"back",
"start",
"ls",
"rs",
"home"
];
GamepadInput.prototype.onExecute = function() {
//get gamepad
var gamepad = this.getGamepad();
var threshold = this.properties.threshold || 0.0;
if (gamepad) {
this._left_axis[0] =
Math.abs(gamepad.xbox.axes["lx"]) > threshold
? gamepad.xbox.axes["lx"]
: 0;
this._left_axis[1] =
Math.abs(gamepad.xbox.axes["ly"]) > threshold
? gamepad.xbox.axes["ly"]
: 0;
this._right_axis[0] =
Math.abs(gamepad.xbox.axes["rx"]) > threshold
? gamepad.xbox.axes["rx"]
: 0;
this._right_axis[1] =
Math.abs(gamepad.xbox.axes["ry"]) > threshold
? gamepad.xbox.axes["ry"]
: 0;
this._triggers[0] =
Math.abs(gamepad.xbox.axes["ltrigger"]) > threshold
? gamepad.xbox.axes["ltrigger"]
: 0;
this._triggers[1] =
Math.abs(gamepad.xbox.axes["rtrigger"]) > threshold
? gamepad.xbox.axes["rtrigger"]
: 0;
}
if (this.outputs) {
for (var i = 0; i < this.outputs.length; i++) {
var output = this.outputs[i];
if (!output.links || !output.links.length) {
continue;
}
var v = null;
if (gamepad) {
switch (output.name) {
case "left_axis":
v = this._left_axis;
break;
case "right_axis":
v = this._right_axis;
break;
case "left_x_axis":
v = this._left_axis[0];
break;
case "left_y_axis":
v = this._left_axis[1];
break;
case "right_x_axis":
v = this._right_axis[0];
break;
case "right_y_axis":
v = this._right_axis[1];
break;
case "trigger_left":
v = this._triggers[0];
break;
case "trigger_right":
v = this._triggers[1];
break;
case "a_button":
v = gamepad.xbox.buttons["a"] ? 1 : 0;
break;
case "b_button":
v = gamepad.xbox.buttons["b"] ? 1 : 0;
break;
case "x_button":
v = gamepad.xbox.buttons["x"] ? 1 : 0;
break;
case "y_button":
v = gamepad.xbox.buttons["y"] ? 1 : 0;
break;
case "lb_button":
v = gamepad.xbox.buttons["lb"] ? 1 : 0;
break;
case "rb_button":
v = gamepad.xbox.buttons["rb"] ? 1 : 0;
break;
case "ls_button":
v = gamepad.xbox.buttons["ls"] ? 1 : 0;
break;
case "rs_button":
v = gamepad.xbox.buttons["rs"] ? 1 : 0;
break;
case "hat_left":
v = gamepad.xbox.hatmap & GamepadInput.LEFT;
break;
case "hat_right":
v = gamepad.xbox.hatmap & GamepadInput.RIGHT;
break;
case "hat_up":
v = gamepad.xbox.hatmap & GamepadInput.UP;
break;
case "hat_down":
v = gamepad.xbox.hatmap & GamepadInput.DOWN;
break;
case "hat":
v = gamepad.xbox.hatmap;
break;
case "start_button":
v = gamepad.xbox.buttons["start"] ? 1 : 0;
break;
case "back_button":
v = gamepad.xbox.buttons["back"] ? 1 : 0;
break;
case "button_pressed":
for (
var j = 0;
j < this._current_buttons.length;
++j
) {
if (
this._current_buttons[j] &&
!this._previous_buttons[j]
) {
this.triggerSlot(
i,
GamepadInput.buttons[j]
);
}
}
break;
default:
break;
}
} else {
//if no gamepad is connected, output 0
switch (output.name) {
case "button_pressed":
break;
case "left_axis":
case "right_axis":
v = GamepadInput.zero;
break;
default:
v = 0;
}
}
this.setOutputData(i, v);
}
}
};
GamepadInput.mapping = {a:0,b:1,x:2,y:3,lb:4,rb:5,lt:6,rt:7,back:8,start:9,ls:10,rs:11 };
GamepadInput.mapping_array = ["a","b","x","y","lb","rb","lt","rt","back","start","ls","rs"];
GamepadInput.prototype.getGamepad = function() {
var getGamepads =
navigator.getGamepads ||
navigator.webkitGetGamepads ||
navigator.mozGetGamepads;
if (!getGamepads) {
return null;
}
var gamepads = getGamepads.call(navigator);
var gamepad = null;
this._previous_buttons.set(this._current_buttons);
//pick the first connected
for (var i = this.properties.gamepad_index; i < 4; i++) {
if (!gamepads[i]) {
continue;
}
gamepad = gamepads[i];
//xbox controller mapping
var xbox = this.xbox_mapping;
if (!xbox) {
xbox = this.xbox_mapping = {
axes: [],
buttons: {},
hat: "",
hatmap: GamepadInput.CENTER
};
}
xbox.axes["lx"] = gamepad.axes[0];
xbox.axes["ly"] = gamepad.axes[1];
xbox.axes["rx"] = gamepad.axes[2];
xbox.axes["ry"] = gamepad.axes[3];
xbox.axes["ltrigger"] = gamepad.buttons[6].value;
xbox.axes["rtrigger"] = gamepad.buttons[7].value;
xbox.hat = "";
xbox.hatmap = GamepadInput.CENTER;
for (var j = 0; j < gamepad.buttons.length; j++) {
this._current_buttons[j] = gamepad.buttons[j].pressed;
if(j < 12)
{
xbox.buttons[ GamepadInput.mapping_array[j] ] = gamepad.buttons[j].pressed;
if(gamepad.buttons[j].was_pressed)
this.trigger( GamepadInput.mapping_array[j] + "_button_event" );
}
else //mapping of XBOX
switch ( j ) //I use a switch to ensure that a player with another gamepad could play
{
case 12:
if (gamepad.buttons[j].pressed) {
xbox.hat += "up";
xbox.hatmap |= GamepadInput.UP;
}
break;
case 13:
if (gamepad.buttons[j].pressed) {
xbox.hat += "down";
xbox.hatmap |= GamepadInput.DOWN;
}
break;
case 14:
if (gamepad.buttons[j].pressed) {
xbox.hat += "left";
xbox.hatmap |= GamepadInput.LEFT;
}
break;
case 15:
if (gamepad.buttons[j].pressed) {
xbox.hat += "right";
xbox.hatmap |= GamepadInput.RIGHT;
}
break;
case 16:
xbox.buttons["home"] = gamepad.buttons[j].pressed;
break;
default:
}
}
gamepad.xbox = xbox;
return gamepad;
}
};
GamepadInput.prototype.onDrawBackground = function(ctx) {
if (this.flags.collapsed) {
return;
}
//render gamepad state?
var la = this._left_axis;
var ra = this._right_axis;
ctx.strokeStyle = "#88A";
ctx.strokeRect(
(la[0] + 1) * 0.5 * this.size[0] - 4,
(la[1] + 1) * 0.5 * this.size[1] - 4,
8,
8
);
ctx.strokeStyle = "#8A8";
ctx.strokeRect(
(ra[0] + 1) * 0.5 * this.size[0] - 4,
(ra[1] + 1) * 0.5 * this.size[1] - 4,
8,
8
);
var h = this.size[1] / this._current_buttons.length;
ctx.fillStyle = "#AEB";
for (var i = 0; i < this._current_buttons.length; ++i) {
if (this._current_buttons[i]) {
ctx.fillRect(0, h * i, 6, h);
}
}
};
GamepadInput.prototype.onGetOutputs = function() {
return [
["left_axis", "vec2"],
["right_axis", "vec2"],
["left_x_axis", "number"],
["left_y_axis", "number"],
["right_x_axis", "number"],
["right_y_axis", "number"],
["trigger_left", "number"],
["trigger_right", "number"],
["a_button", "number"],
["b_button", "number"],
["x_button", "number"],
["y_button", "number"],
["lb_button", "number"],
["rb_button", "number"],
["ls_button", "number"],
["rs_button", "number"],
["start_button", "number"],
["back_button", "number"],
["a_button_event", LiteGraph.EVENT ],
["b_button_event", LiteGraph.EVENT ],
["x_button_event", LiteGraph.EVENT ],
["y_button_event", LiteGraph.EVENT ],
["lb_button_event", LiteGraph.EVENT ],
["rb_button_event", LiteGraph.EVENT ],
["ls_button_event", LiteGraph.EVENT ],
["rs_button_event", LiteGraph.EVENT ],
["start_button_event", LiteGraph.EVENT ],
["back_button_event", LiteGraph.EVENT ],
["hat_left", "number"],
["hat_right", "number"],
["hat_up", "number"],
["hat_down", "number"],
["hat", "number"],
["button_pressed", LiteGraph.EVENT]
];
};
LiteGraph.registerNodeType("input/gamepad", GamepadInput);
})(this);
| jagenjo/litegraph.js | src/nodes/input.js | JavaScript | mit | 12,882 |
var ViewportContainers = function ( editor ) {
var container = new UI.Panel();
container.setId( 'ViewportContainers' );
return container;
};
| adarshk/storyblocks | js/render/ViewportContainers.js | JavaScript | mit | 149 |
import view from './views/home'
export { view }
| vshao/webapp | src/pages/home/lazy.js | JavaScript | mit | 49 |
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
moduloEstado.controller('EstadoViewController', ['$scope', '$routeParams', 'serverService', '$location', 'estadoService', '$uibModal',
function ($scope, $routeParams, serverService, $location, estadoService, $uibModal) {
$scope.fields = estadoService.getFields();
$scope.obtitle = estadoService.getObTitle();
$scope.icon = estadoService.getIcon();
$scope.ob = estadoService.getTitle();
$scope.title = "Vista de " + $scope.obtitle;
$scope.id = $routeParams.id;
$scope.status = null;
$scope.debugging = serverService.debugging();
serverService.promise_getOne($scope.ob, $scope.id).then(function (response) {
if (response.status == 200) {
if (response.data.status == 200) {
$scope.status = null;
$scope.bean = response.data.message;
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
$scope.close = function () {
$location.path('/home');
};
$scope.plist = function () {
$location.path('/' + $scope.ob + '/plist');
};
$scope.back = function () {
window.history.back();
};
}]); | rafaelaznar/andamio-client | public_html/js/estado/view.js | JavaScript | mit | 2,950 |
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var DebugLogtron = require('debug-logtron');
var fs = require('fs');
var crypto = require('crypto');
var HyperbahnClient = require('tchannel/hyperbahn/index.js');
module.exports = runTests;
if (require.main === module) {
runTests(require('../lib/hyperbahn-cluster.js'));
}
function runTests(HyperbahnCluster) {
HyperbahnCluster.test('can advertise', {
size: 5
}, function t(cluster, assert) {
var bob = cluster.remotes.bob;
var client = new HyperbahnClient({
serviceName: 'hello-bob',
callerName: 'hello-bob-test',
hostPortList: cluster.hostPortList,
tchannel: bob.channel,
logger: DebugLogtron('hyperbahnClient')
});
client.once('advertised', onResponse);
client.advertise();
function onResponse() {
var result = client.latestAdvertisementResult;
cluster.checkExitPeers(assert, {
serviceName: 'hello-bob',
hostPort: bob.channel.hostPort
});
assert.equal(result.head, null);
// Because of duplicates in a size 5 cluster we know
// that we have at most 5 kValues
assert.ok(result.body.connectionCount <= 5,
'expect to have at most 5 advertise results');
client.destroy();
assert.end();
}
});
HyperbahnCluster.test('can advertise using hostPortFile', {
size: 5
}, function t(cluster, assert) {
var bob = cluster.remotes.bob;
var hostPortFile;
do {
hostPortFile = '/tmp/host-' + crypto.randomBytes(4).readUInt32LE(0) + '.json';
} while (fs.existsSync(hostPortFile));
fs.writeFileSync(hostPortFile, JSON.stringify(cluster.hostPortList), 'utf8');
var client = new HyperbahnClient({
serviceName: 'hello-bob',
callerName: 'hello-bob-test',
hostPortFile: hostPortFile,
tchannel: bob.channel,
logger: DebugLogtron('hyperbahnClient')
});
assert.once('end', function cleanup() {
client.destroy();
if (fs.existsSync(hostPortFile)) {
fs.unlinkSync(hostPortFile);
}
});
client.once('advertised', onResponse);
client.advertise();
function onResponse() {
var result = client.latestAdvertisementResult;
cluster.checkExitPeers(assert, {
serviceName: 'hello-bob',
hostPort: bob.channel.hostPort
});
assert.equal(result.head, null);
// Because of duplicates in a size 5 cluster we know
// that we have at most 5 kValues
assert.ok(result.body.connectionCount <= 5,
'expect to have at most 5 advertise results');
assert.end();
}
});
}
| savaki/tchannel | hyperbahn/test/hyperbahn-client/advertise.js | JavaScript | mit | 4,058 |
module.exports = {
_id: '5731eb718dc033bc69d9660f',
email: 'register_user@test.com',
name: 'New Test User',
password: '09a3fcee233197960eb1bafe82e20021ad2807e8b12c79e9822ba0d5addfdcb7f786a365b2e8de0419f24cf671f2bd8bac9e6aacd5ff5bece1e5e7346fc19c1741e0286659e39577aaa4a6fd4fe0eab30b95d4437f3821838e27f311bda42a70ae47656eea65afd65a856c9079c866d591df466538cfe7abff4578f3d93fb9e6',
passwordSalt: 'a6a465b8c1baf79bb9423c249ef8a523bd7e34600b3b2215562870a35895fdab'
};
| Honkyoku/miez | tests/fixtures/user.js | JavaScript | mit | 472 |
//you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate input
function configureParams() {
var nameRequest = event["body-json"];
hash.update(event["context"]["source-ip"]);
var hashedIpAddress = hash.digest('hex');
var blocking_string = hashedIpAddress;
var session_expiry = 3600;
if (nameRequest.vname) {
var v1ValidationFilter = /^The ([a-z]|[A-Z])+ ([a-z]|[A-Z])+ of ([a-z]|[A-Z]|[0-9]|-| )+([a-z]|[A-Z]|[0-9])$/i;
if (v1ValidationFilter.test(nameRequest.vname)) {
var vname_components = [];
var vname_version = 'v1';
var vnameMacroParts = nameRequest.vname.split(' of ');
var vnameCity = vnameMacroParts[1];
var vnameColorAndAnimal = vnameMacroParts[0];
var vnameMicroParts = vnameColorAndAnimal.split(' ');
var vnameColor = vnameMicroParts[1];
var vnameAnimal = vnameMicroParts[2];
vname_components = [vnameColor, vnameAnimal, vnameCity];
}
else {
context.done(null, { "error": "vname doesn't match current versions" });
return null;
}
/* SAMPLE DATA, uncomment if you want to use it
vname_version = 'v1';
vname_components = ['brown','bear','Chicago'];
blocking_string = 0383176601762cf74cb95607034b9c7712a431325074396e073d7eb4e5206edc; //just a hash of the user's IP address, you could use a cookie or deviceId as well
session_expiry = 600; // 10 minute connection
*/
sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry);
}
else {
return null;
}
return null;
}
function sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry) {
var payload = { "vname_version": vname_version, "vname_components": vname_components, "blocking_string": blocking_string, "session_expiry_sec": session_expiry };
payload = JSON.stringify(payload);
console.log(payload);
const options = {
hostname: 'api.voicesignin.com',
port: 443,
path: '/ask',
method: 'POST',
headers: {
'Content-Type': 'application/json',
//********************************************************************
'Authorization': '' // add your API key here
//********************************************************************
}
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
// console.log('data:',res.data);
var rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
var requestResponse = JSON.parse(rawData);
console.log('reqresp: ' + JSON.stringify(requestResponse));
if (requestResponse.request_id !== undefined) {
context.done(null, requestResponse);
return null;
}
else {
context.done(null, { "error": "invalid request" });
return null;
}
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(payload);
req.end();
}
};
| SteveBowden/voicesignin | basic-lambda-integration/nodejs/ask.js | JavaScript | mit | 3,864 |
const path = require('path');
const nodeExternals = require('webpack-node-externals'); // 외부 Node.js 모듈들을 포함하지 않기 위해 로드.
const WebpackShellPlugin = require('webpack-shell-plugin');
const OutputFileName = 'aether.agent.package.js';
var serverCfg = {
context: path.resolve(__dirname, 'src'),
entry: './app.js',
target: 'node',
externals: [nodeExternals()],//node_modules는 무시하도록 설정
output: {
path: path.resolve(__dirname, 'dist'),
filename: OutputFileName
},
module: {
rules:[{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
['es2016']
],
plugins: [require('babel-plugin-transform-strict-mode')]// 'use strict'가 없어도 별다른 경고 뱉지 않도록 빌드시 페이지마다 'use strict' 자동삽입
}
}]
}]
},
plugins: [
new WebpackShellPlugin({
onBuildStart:['echo "Webpack Start"'],
onBuildEnd:['echo "Build End: ' + path.resolve(__dirname, 'dist') + '/' + OutputFileName + '"'],
})
]
};
module.exports = serverCfg; | hakoiko/ws-monitor-agent | webpack.config.js | JavaScript | mit | 1,143 |
com.chanjet.gzq.aflow.Canvas = draw2d.Canvas.extend({
canvasName: "com.chanjet.gzq.aflow.Canvas",
init: function(id){
this._super(id);
this.setScrollArea("#"+id);
this.id = id;
var MyInterceptorPolicy = draw2d.policy.canvas.ConnectionInterceptorPolicy.extend({
init : function()
{
this._super();
},
delegateDrop: function(draggedFigure, dropTarget){
return this._super(draggedFigure, dropTarget);
}
});
this.installEditPolicy(new MyInterceptorPolicy());
this.userData = {
name: "流程模版",
id: this.id,
type: "FlowDefinition",
formTemplateId: 'uuid',
formTemplateName: '表单模版名称',
};
},
insertTask: function (connection, taskType) {
var shape = eval("new com.chanjet.gzq.aflow."+taskType+"()");
var x = connection.getBoundingBox().getTopLeft().getX() + (connection.getBoundingBox().getWidth() / 2) - 48;
var y = connection.getBoundingBox().getCenter().getY() - shape.getHeight() / 2;
var sourcePort = connection.getSource();
var targetPort = connection.getTarget();
var cmd = new draw2d.command.CommandDelete(connection);
this.getCommandStack().execute(cmd);
var command = new draw2d.command.CommandAdd(this, shape, x, y);
this.getCommandStack().execute(command);
var cmd = new draw2d.command.CommandConnect(this, sourcePort, shape.inputPorts.data[0]);
// cmd.execute();
this.getCommandStack().execute(cmd);
if (sourcePort.parent.cssClass == 'BranchTask') {
connection.showExpression();
}
cmd = new draw2d.command.CommandConnect(this, shape.outputPorts.data[0], targetPort);
// cmd.execute();
this.getCommandStack().execute(cmd);
},
appendTask: function (thisTask, taskType, value, xPos, yPos) {
var emptyPort = null;
thisTask.outputPorts.data.forEach(function (e, i) {
if(e.connections.data.length == 0) {
emptyPort = e;
}
});
if(emptyPort == null) {
return;
}
var x = xPos != null? xPos : thisTask.getBoundingBox().getTopLeft().getX() + 96 + 100;
var y = yPos != null? yPos : thisTask.getBoundingBox().getCenter().getY();
var shape = eval("new com.chanjet.gzq.aflow."+taskType+"()");
if(taskType == "UserTask") {
shape.userData['userIds'] = value;
}
else if(taskType == "RoleTask") {
shape.userData['roleIds'] = value;
}
else {
console.log(value);
}
var command = new draw2d.command.CommandAdd(this, shape, x, y - shape.getHeight() / 2);
this.getCommandStack().execute(command);
var cmd = new draw2d.command.CommandConnect(this, emptyPort, shape.inputPorts.data[0]);
// cmd.execute();
this.getCommandStack().execute(cmd);
if (thisTask.cssClass == 'BranchTask') {
cmd.connection.showExpression();
}
return shape;
},
convertTaskType: function (thisTask, newTaskType, value) {
var shape = eval("new com.chanjet.gzq.aflow."+newTaskType+"()");
if(newTaskType == "UserTask") {
shape.userData['userIds'] = value;
}
else if(newTaskType == "RoleTask") {
shape.userData['roleIds'] = value;
}
else {
console.log(value);
}
var command = new draw2d.command.CommandAdd(this, shape, thisTask.x, thisTask.y);
this.getCommandStack().execute(command);
thisTask.inputPorts.data.forEach(function (port, index) {
port.connections.data.forEach(function (connection, i) {
command = new draw2d.command.CommandReconnect(connection);
command.setNewPorts(connection.sourcePort, shape.inputPorts.data[0]);
app.canvas.getCommandStack().execute(command);
});
});
command = new draw2d.command.CommandDelete(thisTask);
this.getCommandStack().execute(command);
return shape;
},
appendBranchTaskFromWizard: function (thisTask, value) {
var padding = 50;
var heightOfTaskFigure = 32;
var shape = new com.chanjet.gzq.aflow.BranchTask();
var emptyPort = null;
thisTask.outputPorts.data.forEach(function (e, i) {
if(e.connections.data.length == 0) {
emptyPort = e;
}
});
if(emptyPort == null) {
return;
}
var x = thisTask.getBoundingBox().getTopLeft().getX() + 96 + 150;
var y = thisTask.getBoundingBox().getCenter().getY();
var command = new draw2d.command.CommandAdd(this, shape, x, y - shape.getHeight()/2);
this.getCommandStack().execute(command);
var cmd = new draw2d.command.CommandConnect(this, emptyPort, shape.inputPorts.data[0]);
// cmd.execute();
this.getCommandStack().execute(cmd);
if (thisTask.cssClass == 'BranchTask') {
cmd.connection.showExpression();
}
for(var i = value.length - 2; i > 0; i--) {
shape.addCase();
}
var totalHeight = (heightOfTaskFigure + padding) * value.length;
value.forEach(function (element, index) {
app.canvas.appendTask(shape, 'UserTask', "", shape.getBoundingBox().getTopLeft().getX() + 250,
shape.getBoundingBox().getTopLeft().getY() + totalHeight/2 - (heightOfTaskFigure + padding) * index);
});
shape.outputPorts.data.forEach(function (port, index) {
port.connections.data.forEach(function (connection, i) {
connection.userData['expression'] = value[index];
connection.showExpression();
return;
});
});
return shape;
},
getLastTask: function () {
var sourcePort;
app.canvas.figures.data.forEach(function (e, i) {
if (e.cssClass != "Connection") {
e.getOutputPorts().each( function (i, p) {
p.setMaxFanOut(1);
if(p.connections.data.length==0) {
sourcePort = p;
}
});
}
});
return sourcePort.parent;
},
}); | hitdavid/workflow-designer-web | designer/canvas/Canvas.js | JavaScript | mit | 6,417 |
import explicitElementToString from './elementToString';
import * as util from './util';
/**
* converts an explicit dataSet to a javascript object
* @param dataSet
* @param options
*/
export default function explicitDataSetToJS (dataSet, options) {
if (dataSet === undefined) {
throw 'dicomParser.explicitDataSetToJS: missing required parameter dataSet';
}
options = options || {
omitPrivateAttibutes: true, // true if private elements should be omitted
maxElementLength: 128 // maximum element length to try and convert to string format
};
var result = {
};
for (var tag in dataSet.elements) {
var element = dataSet.elements[tag];
// skip this element if it a private element and our options specify that we should
if (options.omitPrivateAttibutes === true && util.isPrivateTag(tag)) {
continue;
}
if (element.items) {
// handle sequences
var sequenceItems = [];
for (var i = 0; i < element.items.length; i++) {
sequenceItems.push(explicitDataSetToJS(element.items[i].dataSet, options));
}
result[tag] = sequenceItems;
} else {
var asString;
asString = undefined;
if (element.length < options.maxElementLength) {
asString = explicitElementToString(dataSet, element);
}
if (asString !== undefined) {
result[tag] = asString;
} else {
result[tag] = {
dataOffset: element.dataOffset,
length: element.length
};
}
}
}
return result;
}
| chafey/byozfwv | node_modules/dicom-parser/src/util/dataSetToJS.js | JavaScript | mit | 1,556 |
'use strict';
var _ = require('lodash');
var Bacon = require('baconjs');
var logger = require('./logger');
var bus = new Bacon.Bus();
var dirtyStores = [];
var dispatching = false;
function dispatch(type, payload) {
if (dispatching) {
return Promise.reject('Cascading dispatches are prohibited. Fix your flux.');
}
return new Promise(function (resolve, reject) {
dispatching = true;
logger.logMessage(type, payload);
try {
bus.push({type: type, payload: payload});
pushChanges();
resolve();
} finally {
logger.logMessageEnd();
dispatching = false;
}
});
}
function input(type) {
var payloads = bus.filter(function (msg) {
return msg.type === type;
}).map('.payload');
return payloads;
}
function markStoreAsDirty(store) {
if (!_.contains(dirtyStores, store)) {
dirtyStores.push(store);
}
}
function pushChangesOnce() {
var stores = dirtyStores;
dirtyStores = [];
_.each(stores, function (store) {
store.changes.push(store.output);
});
}
function pushChanges() {
if (!dirtyStores.length) {
logger.logNoDirtyStores();
return;
}
var also = false;
while(dirtyStores.length > 0) {
logger.logDirtyStores(dirtyStores, also);
pushChangesOnce();
also = true;
}
}
module.exports = {
dispatch: dispatch,
input: input,
markStoreAsDirty: markStoreAsDirty
};
| songsterr/harukaze | lib/dispatcher.js | JavaScript | mit | 1,392 |
import * as React from 'react';
// import of a small, pure module in a private demo
// bundle size and module duplication is negligible
/* eslint-disable-next-line no-restricted-imports */
import { convertLength } from '@mui/material/styles/cssUtils';
import { createTheme, responsiveFontSizes } from '@mui/material/styles';
import Box from '@mui/material/Box';
import {
Legend,
Tooltip,
LineChart,
Line,
XAxis,
YAxis,
Label,
ResponsiveContainer,
} from 'recharts';
let theme = createTheme();
theme = responsiveFontSizes(theme);
const colors = [
'#443dc2',
'#2060df',
'#277e91',
'#378153',
'#4d811d',
'#63780d',
'#996600',
];
const variants = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1'];
export default function ResponsiveFontSizes() {
const convert = convertLength(theme.typography.htmlFontSize);
const toPx = (rem) => parseFloat(convert(rem, 'px'));
const series = variants.map((variantName) => {
const variant = theme.typography[variantName];
const data = [];
data.push({
viewport: 0,
fontSize: toPx(variant.fontSize),
});
theme.breakpoints.keys.forEach((key) => {
const viewport = theme.breakpoints.values[key];
const value = theme.breakpoints.up(key);
if (variant[value]) {
data.push({
viewport: viewport - 1,
fontSize: data[data.length - 1].fontSize,
});
data.push({
viewport,
fontSize: toPx(variant[value].fontSize),
});
} else if (key === 'xl') {
data.push({
viewport,
fontSize: data[data.length - 1].fontSize,
});
}
});
return {
name: variantName,
data,
};
});
return (
<Box sx={{ height: 380, width: '100%', color: 'black' }}>
<ResponsiveContainer>
<LineChart
margin={{
top: 50,
right: 140,
bottom: 0,
left: 30,
}}
>
<XAxis dataKey="viewport" type="number">
<Label position="right" offset={30}>
viewport (px)
</Label>
</XAxis>
<YAxis dataKey="fontSize" type="number">
<Label position="top" offset={20}>
font-size (rem)
</Label>
</YAxis>
<Tooltip />
<Legend />
{series.map((serie, index) => (
<Line
dataKey="fontSize"
stroke={colors[index % colors.length]}
data={serie.data}
name={serie.name}
key={serie.name}
/>
))}
</LineChart>
</ResponsiveContainer>
</Box>
);
}
| oliviertassinari/material-ui | docs/data/material/customization/typography/ResponsiveFontSizesChart.js | JavaScript | mit | 2,687 |
import Mirage from 'ember-cli-mirage';
import Schema from 'ember-cli-mirage/orm/schema';
import Model from 'ember-cli-mirage/orm/model';
import Db from 'ember-cli-mirage/db';
export default {
setup() {
let db = new Db();
this.schema = new Schema(db);
this.schema.registerModels({
wordSmith: Model.extend({
blogPosts: Mirage.hasMany()
}),
blogPost: Model.extend({
wordSmith: Mirage.belongsTo(),
fineComments: Mirage.hasMany()
}),
fineComment: Model.extend({
blogPost: Mirage.belongsTo()
}),
greatPhoto: Model,
foo: Model.extend({
bar: Mirage.belongsTo()
}),
bar: Model.extend({
baz: Mirage.belongsTo()
}),
baz: Model.extend({
quuxes: Mirage.hasMany()
}),
quux: Model.extend({
zomgs: Mirage.hasMany()
}),
zomg: Model.extend({
lol: Mirage.belongsTo()
}),
lol: Model,
roflCopter: Model
});
return this.schema;
}
};
| ballPointPenguin/ember-cli-mirage | tests/integration/serializers/schema-helper.js | JavaScript | mit | 1,026 |
define([
'webgl/createProgram',
'webgl/shader/compileShaderFromFile'
], function(
createProgram,
compileShaderFromFile
) {
/**
* Creates a program from 2 script tags.
*
* @param {!WebGLRenderingContext} gl The WebGL Context.
* @param {string} vertexShaderFileName The file name of the vertex shader.
* @param {string} fragmentShaderFileName The file name of the fragment shader.
* @return {!WebGLProgram} A program
*/
return function createProgramFromScripts(gl, vertexShaderFileName, fragmentShaderFileName, callback) {
var async = !!callback;
if(async) {
compileShaderFromFile(gl, vertexShaderFileName, 'vertex', function(vertexShader) {
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment', function(fragmentShader) {
callback(createProgram(gl, vertexShader, fragmentShader));
});
});
}
else {
return createProgram(gl,
compileShaderFromFile(gl, vertexShaderFileName, 'vertex'),
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment'));
}
};
}); | bridgs/messing-with-webgl | javascripts/client/webgl/createProgramFromFiles.js | JavaScript | mit | 1,022 |