code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Currency code map.
*/
/**
* Namespace for locale number format functions
*/
goog.provide('goog.i18n.currencyCodeMap');
goog.provide('goog.i18n.currencyCodeMapTier2');
/**
* The mapping of currency symbol through intl currency code.
* The source of information is mostly from wikipedia and CLDR. Since there is
* no authoritive source, items are judged by personal perception.
* If an application need currency support that available in tier2, it
* should extend currencyCodeMap to include tier2 data by doing this:
* goog.object.extend(goog.i18n.currencyCodeMap,
* goog.i18n.currencyCodeMapTier2);
*
* @type {Object}
* @const
*/
goog.i18n.currencyCodeMap = {
'AED': '\u062F\u002e\u0625',
'ARS': '$',
'AUD': '$',
'BDT': '\u09F3',
'BRL': 'R$',
'CAD': '$',
'CHF': 'Fr.',
'CLP': '$',
'CNY': '\u00a5',
'COP': '$',
'CRC': '\u20a1',
'CUP': '$',
'CZK': 'K\u010d',
'DKK': 'kr',
'DOP': '$',
'EGP': '\u00a3',
'EUR': '\u20ac',
'GBP': '\u00a3',
'HKD': '$',
'HRK': 'kn',
'HUF': 'Ft',
'IDR': 'Rp',
'ILS': '\u20AA',
'INR': 'Rs',
'IQD': '\u0639\u062F',
'ISK': 'kr',
'JMD': '$',
'JPY': '\u00a5',
'KRW': '\u20A9',
'KWD': '\u062F\u002e\u0643',
'LKR': 'Rs',
'LVL': 'Ls',
'MNT': '\u20AE',
'MXN': '$',
'MYR': 'RM',
'NOK': 'kr',
'NZD': '$',
'PAB': 'B/.',
'PEN': 'S/.',
'PHP': 'P',
'PKR': 'Rs.',
'PLN': 'z\u0142',
'RON': 'L',
'RUB': '\u0440\u0443\u0431',
'SAR': '\u0633\u002E\u0631',
'SEK': 'kr',
'SGD': '$',
'SKK': 'Sk',
'SYP': 'SYP',
'THB': '\u0e3f',
'TRY': 'TL',
'TWD': 'NT$',
'USD': '$',
'UYU': '$',
'VEF': 'Bs.F',
'VND': '\u20AB',
'XAF': 'FCFA',
'XCD': '$',
'YER': 'YER',
'ZAR': 'R'
};
/**
* This group of currency data is unlikely to be used. In case they are,
* program need to merge it into goog.locale.CurrencyCodeMap.
*
* @type {Object}
* @const
*/
goog.i18n.currencyCodeMapTier2 = {
'AFN': '\u060b',
'ALL': 'Lek',
'AMD': '\u0564\u0580\u002e',
'ANG': '\u0083',
'AOA': 'Kz',
'AWG': '\u0192',
'AZN': 'm',
'BAM': '\u041a\u041c',
'BBD': '$',
'BGN': '\u043b\u0432',
'BHD': '\u0628\u002e\u062f\u002e',
'BIF': 'FBu',
'BMD': '$',
'BND': '$',
'BOB': 'B$',
'BSD': '$',
'BTN': 'Nu.',
'BWP': 'P',
'BYR': 'Br',
'BZD': '$',
'CDF': 'F',
'CVE': '$',
'DJF': 'Fdj',
'DZD': '\u062f\u062C',
'EEK': 'EEK',
'ERN': 'Nfk',
'ETB': 'Br',
'FJD': '$',
'FKP': '\u00a3',
'GEL': 'GEL',
'GHS': '\u20B5',
'GIP': '\u00a3',
'GMD': 'D',
'GNF': 'FG',
'GTQ': 'Q',
'GYD': '$',
'HNL': 'L',
'HTG': 'G',
'IRR': '\ufdfc',
'JOD': 'JOD',
'KES': 'KSh',
'KGS': 'som',
'KHR': '\u17DB',
'KMF': 'KMF',
'KPW': '\u20A9',
'KYD': '$',
'KZT': 'KZT',
'LAK': '\u20AD',
'LBP': '\u0644\u002e\u0644',
'LRD': '$',
'LSL': 'L',
'LTL': 'Lt',
'LYD': '\u0644\u002e\u062F',
'MAD': '\u0645\u002E\u062F\u002E',
'MDL': 'MDL',
'MGA': 'MGA',
'MKD': 'MKD',
'MMK': 'K',
'MOP': 'MOP$',
'MRO': 'UM',
'MUR': 'Rs',
'MVR': 'Rf',
'MWK': 'MK',
'MZN': 'MTn',
'NAD': '$',
'NGN': '\u20A6',
'NIO': 'C$',
'NPR': 'Rs',
'OMR': '\u0639\u002E\u062F\u002E',
'PGK': 'K',
'PYG': '\u20b2',
'QAR': '\u0642\u002E\u0631',
'RSD': '\u0420\u0421\u0414',
'RWF': 'RF',
'SBD': '$',
'SCR': 'SR',
'SDG': 'SDG',
'SHP': '\u00a3',
'SLL': 'Le',
'SOS': 'So. Sh.',
'SRD': '$',
'STD': 'Db',
'SZL': 'L',
'TJS': 'TJS',
'TMM': 'm',
'TND': '\u062F\u002e\u062A ',
'TOP': 'T$',
'TTD': '$',
'TZS': 'TZS',
'UAH': 'UAH',
'UGX': 'USh',
'UZS': 'UZS',
'VUV': 'Vt',
'WST': 'WS$',
'XOF': 'CFA',
'XPF': 'F',
'ZMK': 'ZK',
'ZWD': '$'
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A utility to get better currency format pattern.
*
* This module implements a new currency format representation model. It
* provides 3 currency representation forms: global, portable and local. Local
* format is the most popular format people use to represent currency in its
* circulating country without worrying about how it should be distinguished
* from other currencies. Global format is a formal representation in context
* of multiple currencies in same page, it is ISO 4217 currency code. Portable
* format is a compromise between global and local. It looks similar to how
* people would like to see how their currency is being represented in other
* media. While at the same time, it should be distinguishable to world's
* popular currencies (like USD, EUR) and currencies somewhat relevant in the
* area (like CNY in HK, though native currency is HKD). There is no guarantee
* of uniqueness.
*
*/
goog.provide('goog.i18n.currency');
/**
* The mask of precision field.
* @private
*/
goog.i18n.currency.PRECISION_MASK_ = 0x07;
/**
* Whether the currency sign should be positioned after the number.
* @private
*/
goog.i18n.currency.POSITION_FLAG_ = 0x08;
/**
* Whether a space should be inserted between the number and currency sign.
* @private
*/
goog.i18n.currency.SPACE_FLAG_ = 0x20;
/**
* This function will add tier2 currency support. Be default, only tier1
* (most popular currencies) are supported. If an application really needs
* to support some of the rarely used currencies, it should call this function
* before any other functions in this namespace.
*/
goog.i18n.currency.addTier2Support = function() {
for (var key in goog.i18n.currency.CurrencyInfoTier2) {
goog.i18n.currency.CurrencyInfo[key] =
goog.i18n.currency.CurrencyInfoTier2[key];
}
};
/**
* Global currency pattern always uses ISO-4217 currency code as prefix. Local
* currency sign is added if it is different from currency code. Each currency
* is unique in this form. The negative side is that ISO code looks weird in
* some countries as people normally do not use it. Local currency sign
* alleviates the problem, but also makes it a little verbose.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {string} Global currency pattern string for given currency.
*/
goog.i18n.currency.getGlobalCurrencyPattern = function(currencyCode) {
var info = goog.i18n.currency.CurrencyInfo[currencyCode];
var patternNum = info[0];
if (currencyCode == info[1]) {
return goog.i18n.currency.getCurrencyPattern_(patternNum, info[1]);
}
return currencyCode + ' ' +
goog.i18n.currency.getCurrencyPattern_(patternNum, info[1]);
};
/**
* Return global currency sign string for those applications
* that want to handle currency sign themselves.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {string} Global currency sign for given currency.
*/
goog.i18n.currency.getGlobalCurrencySign = function(currencyCode) {
var info = goog.i18n.currency.CurrencyInfo[currencyCode];
return (currencyCode == info[1]) ? currencyCode :
currencyCode + ' ' + info[1];
};
/**
* Local currency pattern is the most frequently used pattern in currency's
* native region. It does not care about how it is distinguished from other
* currencies.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {string} Local currency pattern string for given currency.
*/
goog.i18n.currency.getLocalCurrencyPattern = function(currencyCode) {
var info = goog.i18n.currency.CurrencyInfo[currencyCode];
return goog.i18n.currency.getCurrencyPattern_(info[0], info[1]);
};
/**
* Returns local currency sign string for those applications that need to
* handle currency sign separately.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {string} Local currency sign for given currency.
*/
goog.i18n.currency.getLocalCurrencySign = function(currencyCode) {
return goog.i18n.currency.CurrencyInfo[currencyCode][1];
};
/**
* Portable currency pattern is a compromise between local and global. It is
* not a mere blend or mid-way between the two. Currency sign is chosen so that
* it looks familiar to native users. It also has enough information to
* distinguish itself from other popular currencies in its native region.
* In this pattern, currency sign symbols that has availability problem in
* popular fonts are also avoided.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {string} Portable currency pattern string for given currency.
*/
goog.i18n.currency.getPortableCurrencyPattern = function(currencyCode) {
var info = goog.i18n.currency.CurrencyInfo[currencyCode];
return goog.i18n.currency.getCurrencyPattern_(info[0], info[2]);
};
/**
* Return portable currency sign string for those applications that need to
* handle currency sign themselves.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {string} Portable currency sign for given currency.
*/
goog.i18n.currency.getPortableCurrencySign = function(currencyCode) {
return goog.i18n.currency.CurrencyInfo[currencyCode][2];
};
/**
* This function returns the default currency sign position. Some applications
* may want to handle currency sign and currency amount separately. This
* function can be used in such situations to correctly position the currency
* sign relative to the amount.
*
* To match the behavior of ICU, position is not determined by display locale.
*
* @param {string} currencyCode ISO-4217 3-letter currency code.
* @return {boolean} true if currency should be positioned before amount field.
*/
goog.i18n.currency.isPrefixSignPosition = function(currencyCode) {
return (goog.i18n.currency.CurrencyInfo[currencyCode][0] &
goog.i18n.currency.POSITION_FLAG_) == 0;
};
/**
* This function constructs the currency pattern. Currency sign is provided. The
* pattern information is encoded in patternNum.
*
* @param {number} patternNum Encoded pattern number that has
* currency pattern information.
* @param {string} sign The currency sign that will be used in pattern.
* @return {string} currency pattern string.
* @private
*/
goog.i18n.currency.getCurrencyPattern_ = function(patternNum, sign) {
var strParts = ['#,##0'];
var precision = patternNum & goog.i18n.currency.PRECISION_MASK_;
if (precision > 0) {
strParts.push('.');
for (var i = 0; i < precision; i++) {
strParts.push('0');
}
}
if ((patternNum & goog.i18n.currency.POSITION_FLAG_) == 0) {
strParts.unshift((patternNum & goog.i18n.currency.SPACE_FLAG_) ?
"' " : "'");
strParts.unshift(sign);
strParts.unshift("'");
} else {
strParts.push((patternNum & goog.i18n.currency.SPACE_FLAG_) ? " '" : "'",
sign, "'");
}
return strParts.join('');
};
/**
* Modify currency pattern string by adjusting precision for given currency.
* Standard currency pattern will have 2 digit after decimal point.
* Examples:
* $#,##0.00 -> $#,##0 (precision == 0)
* $#,##0.00 -> $#,##0.0 (precision == 1)
* $#,##0.00 -> $#,##0.000 (precision == 3)
*
* @param {string} pattern currency pattern string.
* @param {string} currencyCode 3-letter currency code.
* @return {string} modified currency pattern string.
*/
goog.i18n.currency.adjustPrecision = function(pattern, currencyCode) {
var strParts = ['0'];
var info = goog.i18n.currency.CurrencyInfo[currencyCode];
var precision = info[0] & goog.i18n.currency.PRECISION_MASK_;
if (precision > 0) {
strParts.push('.');
for (var i = 0; i < precision; i++) {
strParts.push('0');
}
}
return pattern.replace(/0.00/g, strParts.join(''));
};
/**
* Tier 1 currency information.
*
* The first number in the array is a combination of the precision mask and
* other flags. The precision mask indicates how many decimal places to show for
* the currency. Valid values are [0..7]. The position flag indicates whether
* the currency sign should be positioned after the number. Valid values are 0
* (before the number) or 16 (after the number). The space flag indicates
* whether a space should be inserted between the currency sign and number.
* Valid values are 0 (no space) and 24 (space).
*
* The number in the array is calculated by adding together the mask and flag
* values. For example:
*
* 0: no precision (0), currency sign first (0), no space (0)
* 2: two decimals precision (2), currency sign first (0), no space (0)
* 18: two decimals precision (2), currency sign last (16), no space (0)
* 42: two decimals precision (2), currency sign last (16), space (24)
*
* @type {!Object.<!Array>}
*/
goog.i18n.currency.CurrencyInfo = {
'AED': [2, 'dh', '\u062f.\u0625.', 'DH'],
'AUD': [2, '$', 'AU$'],
'BDT': [2, '\u09F3', 'Tk'],
'BRL': [2, 'R$', 'R$'],
'CAD': [2, '$', 'C$'],
'CHF': [2, 'CHF', 'CHF'],
'CLP': [0, '$', 'CL$'],
'CNY': [2, '¥', 'RMB¥'],
'COP': [0, '$', 'COL$'],
'CRC': [0, '\u20a1', 'CR\u20a1'],
'CZK': [2, 'K\u010d', 'K\u010d'],
'DKK': [18, 'kr', 'kr'],
'DOP': [2, '$', 'RD$'],
'EGP': [2, '£', 'LE'],
'EUR': [18, '€', '€'],
'GBP': [2, '£', 'GB£'],
'HKD': [2, '$', 'HK$'],
'ILS': [2, '\u20AA', 'IL\u20AA'],
'INR': [2, '\u20B9', 'Rs'],
'ISK': [0, 'kr', 'kr'],
'JMD': [2, '$', 'JA$'],
'JPY': [0, '¥', 'JP¥'],
'KRW': [0, '\u20A9', 'KR₩'],
'LKR': [2, 'Rs', 'SLRs'],
'MNT': [0, '\u20AE', 'MN₮'],
'MXN': [2, '$', 'Mex$'],
'MYR': [2, 'RM', 'RM'],
'NOK': [18, 'kr', 'NOkr'],
'PAB': [2, 'B/.', 'B/.'],
'PEN': [2, 'S/.', 'S/.'],
'PHP': [2, '\u20B1', 'Php'],
'PKR': [0, 'Rs', 'PKRs.'],
'RUB': [42, 'руб.', 'руб.'],
'SAR': [2, 'Rial', 'Rial'],
'SEK': [2, 'kr', 'kr'],
'SGD': [2, '$', 'S$'],
'THB': [2, '\u0e3f', 'THB'],
'TRY': [2, 'TL', 'YTL'],
'TWD': [2, 'NT$', 'NT$'],
'USD': [2, '$', 'US$'],
'UYU': [2, '$', 'UY$'],
'VND': [0, '\u20AB', 'VN\u20AB'],
'YER': [0, 'Rial', 'Rial'],
'ZAR': [2, 'R', 'ZAR']
};
/**
* Tier 2 currency information.
* @type {!Object.<!Array>}
*/
goog.i18n.currency.CurrencyInfoTier2 = {
'AFN': [16, 'Af.', 'AFN'],
'ALL': [0, 'Lek', 'Lek'],
'AMD': [0, 'Dram', 'dram'],
'AOA': [2, 'Kz', 'Kz'],
'ARS': [2, '$', 'AR$'],
'AWG': [2, 'Afl.', 'Afl.'],
'AZN': [2, 'man.', 'man.'],
'BAM': [18, 'KM', 'KM'],
'BBD': [2, '$', 'Bds$'],
'BGN': [2, 'lev', 'lev'],
'BHD': [3, 'din', 'din'],
'BIF': [0, 'FBu', 'FBu'],
'BMD': [2, '$', 'BD$'],
'BND': [2, '$', 'B$'],
'BOB': [2, 'Bs', 'Bs'],
'BSD': [2, '$', 'BS$'],
'BTN': [2, 'Nu.', 'Nu.'],
'BWP': [2, 'P', 'pula'],
'BYR': [0, 'BYR', 'BYR'],
'BZD': [2, '$', 'BZ$'],
'CDF': [2, 'FrCD', 'CDF'],
'CUC': [1, '$', 'CUC$'],
'CUP': [2, '$', 'CU$'],
'CVE': [2, 'CVE', 'Esc'],
'DJF': [0, 'Fdj', 'Fdj'],
'DZD': [2, 'din', 'din'],
'ERN': [2, 'Nfk', 'Nfk'],
'ETB': [2, 'Birr', 'Birr'],
'FJD': [2, '$', 'FJ$'],
'FKP': [2, '£', 'FK£'],
'GEL': [2, 'GEL', 'GEL'],
'GHS': [2, 'GHS', 'GHS'],
'GIP': [2, '£', 'GI£'],
'GMD': [2, 'GMD', 'GMD'],
'GNF': [0, 'FG', 'FG'],
'GTQ': [2, 'Q', 'GTQ'],
'GYD': [0, '$', 'GY$'],
'HNL': [2, 'L', 'HNL'],
'HRK': [2, 'kn', 'kn'],
'HTG': [2, 'HTG', 'HTG'],
'HUF': [0, 'Ft', 'Ft'],
'IDR': [0, 'Rp', 'Rp'],
'IQD': [0, 'din', 'IQD'],
'IRR': [0, 'Rial', 'IRR'],
'JOD': [3, 'din', 'JOD'],
'KES': [2, 'Ksh', 'Ksh'],
'KGS': [2, 'KGS', 'KGS'],
'KHR': [2, 'Riel', 'KHR'],
'KMF': [0, 'CF', 'KMF'],
'KPW': [0, '\u20A9KP', 'KPW'],
'KWD': [3, 'din', 'KWD'],
'KYD': [2, '$', 'KY$'],
'KZT': [2, '\u20B8', 'KZT'],
'LAK': [0, '\u20AD', '\u20AD'],
'LBP': [0, 'L£', 'LBP'],
'LRD': [2, '$', 'L$'],
'LSL': [2, 'LSL', 'LSL'],
'LTL': [2, 'Lt', 'Lt'],
'LVL': [2, 'Ls', 'Ls'],
'LYD': [3, 'din', 'LD'],
'MAD': [2, 'dh', 'MAD'],
'MDL': [2, 'MDL', 'MDL'],
'MGA': [0, 'Ar', 'MGA'],
'MKD': [2, 'din', 'MKD'],
'MMK': [0, 'K', 'MMK'],
'MOP': [2, 'MOP', 'MOP$'],
'MRO': [0, 'MRO', 'MRO'],
'MUR': [0, 'MURs', 'MURs'],
'MWK': [2, 'MWK', 'MWK'],
'MZN': [2, 'MTn', 'MTn'],
'NAD': [2, '$', 'N$'],
'NGN': [2, '\u20A6', 'NG\u20A6'],
'NIO': [2, 'C$', 'C$'],
'NPR': [2, 'Rs', 'NPRs'],
'NZD': [2, '$', 'NZ$'],
'OMR': [3, 'Rial', 'OMR'],
'PGK': [2, 'PGK', 'PGK'],
'PLN': [2, 'z\u0142', 'z\u0142'],
'PYG': [0, 'Gs', 'PYG'],
'QAR': [2, 'Rial', 'QR'],
'RON': [2, 'RON', 'RON'],
'RSD': [0, 'din', 'RSD'],
'RWF': [0, 'RF', 'RF'],
'SBD': [2, '$', 'SI$'],
'SCR': [2, 'SCR', 'SCR'],
'SDG': [2, 'SDG', 'SDG'],
'SHP': [2, '£', 'SH£'],
'SLL': [0, 'SLL', 'SLL'],
'SOS': [0, 'SOS', 'SOS'],
'SRD': [2, '$', 'SR$'],
'STD': [0, 'Db', 'Db'],
'SYP': [16, '£', 'SY£'],
'SZL': [2, 'SZL', 'SZL'],
'TJS': [2, 'Som', 'TJS'],
'TND': [3, 'din', 'DT'],
'TOP': [2, 'T$', 'T$'],
'TTD': [2, '$', 'TT$'],
'TZS': [0, 'TSh', 'TSh'],
'UAH': [2, '\u20B4', 'UAH'],
'UGX': [0, 'UGX', 'UGX'],
'UYU': [1, '$', '$U'],
'UZS': [0, 'so\u02bcm', 'UZS'],
'VEF': [2, 'Bs', 'Bs'],
'VUV': [0, 'VUV', 'VUV'],
'WST': [2, 'WST', 'WST'],
'XAF': [0, 'FCFA', 'FCFA'],
'XCD': [2, '$', 'EC$'],
'XOF': [0, 'CFA', 'CFA'],
'XPF': [0, 'FCFP', 'FCFP'],
'ZMK': [0, 'ZMK', 'ZMK']
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides functions to parse and pretty-print HTML strings.
*
*/
goog.provide('goog.format.HtmlPrettyPrinter');
goog.provide('goog.format.HtmlPrettyPrinter.Buffer');
goog.require('goog.object');
goog.require('goog.string.StringBuffer');
/**
* This class formats HTML to be more human-readable.
* TODO(user): Add hierarchical indentation.
* @param {number=} opt_timeOutMillis Max # milliseconds to spend on #format. If
* this time is exceeded, return partially formatted. 0 or negative number
* indicates no timeout.
* @constructor
*/
goog.format.HtmlPrettyPrinter = function(opt_timeOutMillis) {
/**
* Max # milliseconds to spend on #format.
* @type {number}
* @private
*/
this.timeOutMillis_ = opt_timeOutMillis && opt_timeOutMillis > 0 ?
opt_timeOutMillis : 0;
};
/**
* Singleton.
* @type {goog.format.HtmlPrettyPrinter?}
* @private
*/
goog.format.HtmlPrettyPrinter.instance_ = null;
/**
* Singleton lazy initializer.
* @return {goog.format.HtmlPrettyPrinter} Singleton.
* @private
*/
goog.format.HtmlPrettyPrinter.getInstance_ = function() {
if (!goog.format.HtmlPrettyPrinter.instance_) {
goog.format.HtmlPrettyPrinter.instance_ =
new goog.format.HtmlPrettyPrinter();
}
return goog.format.HtmlPrettyPrinter.instance_;
};
/**
* Static utility function. See prototype #format.
* @param {string} html The HTML text to pretty print.
* @return {string} Formatted result.
*/
goog.format.HtmlPrettyPrinter.format = function(html) {
return goog.format.HtmlPrettyPrinter.getInstance_().format(html);
};
/**
* List of patterns used to tokenize HTML for pretty printing. Cache
* subexpression for tag name.
* comment|meta-tag|tag|text|other-less-than-characters
* @type {RegExp}
* @private
*/
goog.format.HtmlPrettyPrinter.TOKEN_REGEX_ =
/(?:<!--.*?-->|<!.*?>|<(\/?)(\w+)[^>]*>|[^<]+|<)/g;
/**
* Tags whose contents we don't want pretty printed.
* @type {Object}
* @private
*/
goog.format.HtmlPrettyPrinter.NON_PRETTY_PRINTED_TAGS_ = goog.object.createSet(
'script',
'style',
'pre',
'xmp');
/**
* 'Block' tags. We should add newlines before and after these tags during
* pretty printing. Tags drawn mostly from HTML4 definitions for block and other
* non-online tags, excepting the ones in
* #goog.format.HtmlPrettyPrinter.NON_PRETTY_PRINTED_TAGS_.
*
* @type {Object}
* @private
*/
goog.format.HtmlPrettyPrinter.BLOCK_TAGS_ = goog.object.createSet(
'address',
'applet',
'area',
'base',
'basefont',
'blockquote',
'body',
'caption',
'center',
'col',
'colgroup',
'dir',
'div',
'dl',
'fieldset',
'form',
'frame',
'frameset',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'head',
'hr',
'html',
'iframe',
'isindex',
'legend',
'link',
'menu',
'meta',
'noframes',
'noscript',
'ol',
'optgroup',
'option',
'p',
'param',
'table',
'tbody',
'td',
'tfoot',
'th',
'thead',
'title',
'tr',
'ul');
/**
* Non-block tags that break flow. We insert a line break after, but not before
* these. Tags drawn from HTML4 definitions.
* @type {Object}
* @private
*/
goog.format.HtmlPrettyPrinter.BREAKS_FLOW_TAGS_ = goog.object.createSet(
'br',
'dd',
'dt',
'br',
'li',
'noframes');
/**
* Empty tags. These are treated as both start and end tags.
* @type {Object}
* @private
*/
goog.format.HtmlPrettyPrinter.EMPTY_TAGS_ = goog.object.createSet(
'br',
'hr',
'isindex');
/**
* Breaks up HTML so it's easily readable by the user.
* @param {string} html The HTML text to pretty print.
* @return {string} Formatted result.
* @throws {Error} Regex error, data loss, or endless loop detected.
*/
goog.format.HtmlPrettyPrinter.prototype.format = function(html) {
// Trim leading whitespace, but preserve first indent; in other words, keep
// any spaces immediately before the first non-whitespace character (that's
// what $1 is), but remove all other leading whitespace. This adjustment
// historically had been made in Docs. The motivation is that some
// browsers prepend several line breaks in designMode.
html = html.replace(/^\s*?( *\S)/, '$1');
// Trim trailing whitespace.
html = html.replace(/\s+$/, '');
// Keep track of how much time we've used.
var timeOutMillis = this.timeOutMillis_;
var startMillis = timeOutMillis ? goog.now() : 0;
// Handles concatenation of the result and required line breaks.
var buffer = new goog.format.HtmlPrettyPrinter.Buffer();
// Declare these for efficiency since we access them in a loop.
var tokenRegex = goog.format.HtmlPrettyPrinter.TOKEN_REGEX_;
var nonPpTags = goog.format.HtmlPrettyPrinter.NON_PRETTY_PRINTED_TAGS_;
var blockTags = goog.format.HtmlPrettyPrinter.BLOCK_TAGS_;
var breaksFlowTags = goog.format.HtmlPrettyPrinter.BREAKS_FLOW_TAGS_;
var emptyTags = goog.format.HtmlPrettyPrinter.EMPTY_TAGS_;
// Used to verify we're making progress through our regex tokenization.
var lastIndex = 0;
// Use this to track non-pretty-printed tags and childen.
var nonPpTagStack = [];
// Loop through each matched token.
var match;
while (match = tokenRegex.exec(html)) {
// Get token.
var token = match[0];
// Is this token a tag? match.length == 3 for tags, 1 for all others.
if (match.length == 3) {
var tagName = match[2];
if (tagName) {
tagName = tagName.toLowerCase();
}
// Non-pretty-printed tags?
if (nonPpTags.hasOwnProperty(tagName)) {
// End tag?
if (match[1] == '/') {
// Do we have a matching start tag?
var stackSize = nonPpTagStack.length;
var startTagName = stackSize ? nonPpTagStack[stackSize - 1] : null;
if (startTagName == tagName) {
// End of non-pretty-printed block. Line break after.
nonPpTagStack.pop();
buffer.pushToken(false, token, !nonPpTagStack.length);
} else {
// Malformed HTML. No line breaks.
buffer.pushToken(false, token, false);
}
} else {
// Start of non-pretty-printed block. Line break before.
buffer.pushToken(!nonPpTagStack.length, token, false);
nonPpTagStack.push(tagName);
}
} else if (nonPpTagStack.length) {
// Inside non-pretty-printed block, no new line breaks.
buffer.pushToken(false, token, false);
} else if (blockTags.hasOwnProperty(tagName)) {
// Put line break before start block and after end block tags.
var isEmpty = emptyTags.hasOwnProperty(tagName);
var isEndTag = match[1] == '/';
buffer.pushToken(isEmpty || !isEndTag, token, isEmpty || isEndTag);
} else if (breaksFlowTags.hasOwnProperty(tagName)) {
var isEmpty = emptyTags.hasOwnProperty(tagName);
var isEndTag = match[1] == '/';
// Put line break after end flow-breaking tags.
buffer.pushToken(false, token, isEndTag || isEmpty);
} else {
// All other tags, no line break.
buffer.pushToken(false, token, false);
}
} else {
// Non-tags, no line break.
buffer.pushToken(false, token, false);
}
// Double check that we're making progress.
var newLastIndex = tokenRegex.lastIndex;
if (!token || newLastIndex <= lastIndex) {
throw Error('Regex failed to make progress through source html.');
}
lastIndex = newLastIndex;
// Out of time?
if (timeOutMillis) {
if (goog.now() - startMillis > timeOutMillis) {
// Push unprocessed data as one big token and reset regex object.
buffer.pushToken(false, html.substring(tokenRegex.lastIndex), false);
tokenRegex.lastIndex = 0;
break;
}
}
}
// Ensure we end in a line break.
buffer.lineBreak();
// Construct result string.
var result = String(buffer);
// Length should be original length plus # line breaks added.
var expectedLength = html.length + buffer.breakCount;
if (result.length != expectedLength) {
throw Error('Lost data pretty printing html.');
}
return result;
};
/**
* This class is a buffer to which we push our output. It tracks line breaks to
* make sure we don't add unnecessary ones.
* @constructor
*/
goog.format.HtmlPrettyPrinter.Buffer = function() {
/**
* Tokens to be output in #toString.
* @type {goog.string.StringBuffer}
* @private
*/
this.out_ = new goog.string.StringBuffer();
};
/**
* Tracks number of line breaks added.
* @type {number}
*/
goog.format.HtmlPrettyPrinter.Buffer.prototype.breakCount = 0;
/**
* Tracks if we are at the start of a new line.
* @type {boolean}
* @private
*/
goog.format.HtmlPrettyPrinter.Buffer.prototype.isBeginningOfNewLine_ = true;
/**
* Tracks if we need a new line before the next token.
* @type {boolean}
* @private
*/
goog.format.HtmlPrettyPrinter.Buffer.prototype.needsNewLine_ = false;
/**
* Adds token and necessary line breaks to output buffer.
* @param {boolean} breakBefore If true, add line break before token if
* necessary.
* @param {string} token Token to push.
* @param {boolean} breakAfter If true, add line break after token if
* necessary.
*/
goog.format.HtmlPrettyPrinter.Buffer.prototype.pushToken = function(
breakBefore, token, breakAfter) {
// If this token needs a preceeding line break, and
// we haven't already added a line break, and
// this token does not start with a line break,
// then add line break.
// Due to FF3.0 bug with lists, we don't insert a /n
// right before </ul>. See bug 1520665.
if ((this.needsNewLine_ || breakBefore) &&
!/^\r?\n/.test(token) &&
!/\/ul/i.test(token)) {
this.lineBreak();
}
// Token.
this.out_.append(token);
// Remember if this string ended with a line break so we know we don't have to
// insert another one before the next token.
this.isBeginningOfNewLine_ = /\r?\n$/.test(token);
// Remember if this token requires a line break after it. We don't insert it
// here because we might not have to if the next token starts with a line
// break.
this.needsNewLine_ = breakAfter && !this.isBeginningOfNewLine_;
};
/**
* Append line break if we need one.
*/
goog.format.HtmlPrettyPrinter.Buffer.prototype.lineBreak = function() {
if (!this.isBeginningOfNewLine_) {
this.out_.append('\n');
++this.breakCount;
}
};
/**
* @return {string} String representation of tokens.
* @override
*/
goog.format.HtmlPrettyPrinter.Buffer.prototype.toString = function() {
return this.out_.toString();
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Creates a string of a JSON object, properly indented for
* display.
*
*/
goog.provide('goog.format.JsonPrettyPrinter');
goog.provide('goog.format.JsonPrettyPrinter.HtmlDelimiters');
goog.provide('goog.format.JsonPrettyPrinter.TextDelimiters');
goog.require('goog.json');
goog.require('goog.json.Serializer');
goog.require('goog.string');
goog.require('goog.string.StringBuffer');
goog.require('goog.string.format');
/**
* Formats a JSON object as a string, properly indented for display. Supports
* displaying the string as text or html. Users can also specify their own
* set of delimiters for different environments. For example, the JSON object:
*
* <code>{"a": 1, "b": {"c": null, "d": true, "e": [1, 2]}}</code>
*
* Will be displayed like this:
*
* <code>{
* "a": 1,
* "b": {
* "c": null,
* "d": true,
* "e": [
* 1,
* 2
* ]
* }
* }</code>
* @param {goog.format.JsonPrettyPrinter.TextDelimiters} delimiters Container
* for the various strings to use to delimit objects, arrays, newlines, and
* other pieces of the output.
* @constructor
*/
goog.format.JsonPrettyPrinter = function(delimiters) {
/**
* The set of characters to use as delimiters.
* @type {goog.format.JsonPrettyPrinter.TextDelimiters}
* @private
*/
this.delimiters_ = delimiters ||
new goog.format.JsonPrettyPrinter.TextDelimiters();
/**
* Used to serialize property names and values.
* @type {goog.json.Serializer}
* @private
*/
this.jsonSerializer_ = new goog.json.Serializer();
};
/**
* Formats a JSON object as a string, properly indented for display.
* @param {*} json The object to pretty print. It could be a JSON object, a
* string representing a JSON object, or any other type.
* @return {string} Returns a string of the JSON object, properly indented for
* display.
*/
goog.format.JsonPrettyPrinter.prototype.format = function(json) {
// If input is undefined, null, or empty, return an empty string.
if (!goog.isDefAndNotNull(json)) {
return '';
}
if (goog.isString(json)) {
if (goog.string.isEmpty(json)) {
return '';
}
// Try to coerce a string into a JSON object.
json = goog.json.parse(json);
}
var outputBuffer = new goog.string.StringBuffer();
this.printObject_(json, outputBuffer, 0);
return outputBuffer.toString();
};
/**
* Formats a property value based on the type of the propery.
* @param {*} val The object to format.
* @param {goog.string.StringBuffer} outputBuffer The buffer to write the
* response to.
* @param {number} indent The number of spaces to indent each line of the
* output.
* @private
*/
goog.format.JsonPrettyPrinter.prototype.printObject_ = function(val,
outputBuffer, indent) {
var typeOf = goog.typeOf(val);
switch (typeOf) {
case 'null':
case 'boolean':
case 'number':
case 'string':
// "null", "boolean", "number" and "string" properties are printed
// directly to the output.
this.printValue_(
/** @type {null|string|boolean|number} */ (val),
typeOf, outputBuffer);
break;
case 'array':
// Example of how an array looks when formatted
// (using the default delimiters):
// [
// 1,
// 2,
// 3
// ]
outputBuffer.append(this.delimiters_.arrayStart);
var i = 0;
// Iterate through the array and format each element.
for (i = 0; i < val.length; i++) {
if (i > 0) {
// There are multiple elements, add a comma to separate them.
outputBuffer.append(this.delimiters_.propertySeparator);
}
outputBuffer.append(this.delimiters_.lineBreak);
this.printSpaces_(indent + this.delimiters_.indent, outputBuffer);
this.printObject_(val[i], outputBuffer,
indent + this.delimiters_.indent);
}
// If there are no properties in this object, don't put a line break
// between the beginning "[" and ending "]", so the output of an empty
// array looks like <code>[]</code>.
if (i > 0) {
outputBuffer.append(this.delimiters_.lineBreak);
this.printSpaces_(indent, outputBuffer);
}
outputBuffer.append(this.delimiters_.arrayEnd);
break;
case 'object':
// Example of how an object looks when formatted
// (using the default delimiters):
// {
// "a": 1,
// "b": 2,
// "c": "3"
// }
outputBuffer.append(this.delimiters_.objectStart);
var propertyCount = 0;
// Iterate through the object and display each property.
for (var name in val) {
if (!val.hasOwnProperty(name)) {
continue;
}
if (propertyCount > 0) {
// There are multiple properties, add a comma to separate them.
outputBuffer.append(this.delimiters_.propertySeparator);
}
outputBuffer.append(this.delimiters_.lineBreak);
this.printSpaces_(indent + this.delimiters_.indent, outputBuffer);
this.printName_(name, outputBuffer);
outputBuffer.append(this.delimiters_.nameValueSeparator,
this.delimiters_.space);
this.printObject_(val[name], outputBuffer,
indent + this.delimiters_.indent);
propertyCount++;
}
// If there are no properties in this object, don't put a line break
// between the beginning "{" and ending "}", so the output of an empty
// object looks like <code>{}</code>.
if (propertyCount > 0) {
outputBuffer.append(this.delimiters_.lineBreak);
this.printSpaces_(indent, outputBuffer);
}
outputBuffer.append(this.delimiters_.objectEnd);
break;
// Other types, such as "function", aren't expected in JSON, and their
// behavior is undefined. In these cases, just print an empty string to the
// output buffer. This allows the pretty printer to continue while still
// outputing well-formed JSON.
default:
this.printValue_('', 'unknown', outputBuffer);
}
};
/**
* Prints a property name to the output.
* @param {string} name The property name.
* @param {goog.string.StringBuffer} outputBuffer The buffer to write the
* response to.
* @private
*/
goog.format.JsonPrettyPrinter.prototype.printName_ = function(name,
outputBuffer) {
outputBuffer.append(this.delimiters_.preName,
this.jsonSerializer_.serialize(name), this.delimiters_.postName);
};
/**
* Prints a property name to the output.
* @param {string|boolean|number|null} val The property value.
* @param {string} typeOf The type of the value. Used to customize
* value-specific css in the display. This allows clients to distinguish
* between different types in css. For example, the client may define two
* classes: "goog-jsonprettyprinter-propertyvalue-string" and
* "goog-jsonprettyprinter-propertyvalue-number" to assign a different color
* to string and number values.
* @param {goog.string.StringBuffer} outputBuffer The buffer to write the
* response to.
* @private
*/
goog.format.JsonPrettyPrinter.prototype.printValue_ = function(val,
typeOf, outputBuffer) {
outputBuffer.append(goog.string.format(this.delimiters_.preValue, typeOf),
this.jsonSerializer_.serialize(val),
goog.string.format(this.delimiters_.postValue, typeOf));
};
/**
* Print a number of space characters to the output.
* @param {number} indent The number of spaces to indent the line.
* @param {goog.string.StringBuffer} outputBuffer The buffer to write the
* response to.
* @private
*/
goog.format.JsonPrettyPrinter.prototype.printSpaces_ = function(indent,
outputBuffer) {
outputBuffer.append(goog.string.repeat(this.delimiters_.space, indent));
};
/**
* A container for the delimiting characters used to display the JSON string
* to a text display. Each delimiter is a publicly accessible property of
* the object, which makes it easy to tweak delimiters to specific environments.
* @constructor
*/
goog.format.JsonPrettyPrinter.TextDelimiters = function() {
};
/**
* Represents a space character in the output. Used to indent properties a
* certain number of spaces, and to separate property names from property
* values.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.space = ' ';
/**
* Represents a newline character in the output. Used to begin a new line.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.lineBreak = '\n';
/**
* Represents the start of an object in the output.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.objectStart = '{';
/**
* Represents the end of an object in the output.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.objectEnd = '}';
/**
* Represents the start of an array in the output.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.arrayStart = '[';
/**
* Represents the end of an array in the output.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.arrayEnd = ']';
/**
* Represents the string used to separate properties in the output.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.propertySeparator = ',';
/**
* Represents the string used to separate property names from property values in
* the output.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.nameValueSeparator = ':';
/**
* A string that's placed before a property name in the output. Useful for
* wrapping a property name in an html tag.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.preName = '';
/**
* A string that's placed after a property name in the output. Useful for
* wrapping a property name in an html tag.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.postName = '';
/**
* A string that's placed before a property value in the output. Useful for
* wrapping a property value in an html tag.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.preValue = '';
/**
* A string that's placed after a property value in the output. Useful for
* wrapping a property value in an html tag.
* @type {string}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.postValue = '';
/**
* Represents the number of spaces to indent each sub-property of the JSON.
* @type {number}
*/
goog.format.JsonPrettyPrinter.TextDelimiters.prototype.indent = 2;
/**
* A container for the delimiting characters used to display the JSON string
* to an HTML <code><pre></code> or <code><code></code> element.
* @constructor
* @extends {goog.format.JsonPrettyPrinter.TextDelimiters}
*/
goog.format.JsonPrettyPrinter.HtmlDelimiters = function() {
goog.format.JsonPrettyPrinter.TextDelimiters.call(this);
};
goog.inherits(goog.format.JsonPrettyPrinter.HtmlDelimiters,
goog.format.JsonPrettyPrinter.TextDelimiters);
/**
* A <code>span</code> tag thats placed before a property name. Used to style
* property names with CSS.
* @type {string}
* @override
*/
goog.format.JsonPrettyPrinter.HtmlDelimiters.prototype.preName =
'<span class="' +
goog.getCssName('goog-jsonprettyprinter-propertyname') +
'">';
/**
* A closing <code>span</code> tag that's placed after a property name.
* @type {string}
* @override
*/
goog.format.JsonPrettyPrinter.HtmlDelimiters.prototype.postName = '</span>';
/**
* A <code>span</code> tag thats placed before a property value. Used to style
* property value with CSS. The span tag's class is in the format
* goog-jsonprettyprinter-propertyvalue-{TYPE}, where {TYPE} is the JavaScript
* type of the object (the {TYPE} parameter is obtained from goog.typeOf). This
* can be used to style different value types.
* @type {string}
* @override
*/
goog.format.JsonPrettyPrinter.HtmlDelimiters.prototype.preValue =
'<span class="' +
goog.getCssName('goog-jsonprettyprinter-propertyvalue') +
'-%s">';
/**
* A closing <code>span</code> tag that's placed after a property value.
* @type {string}
* @override
*/
goog.format.JsonPrettyPrinter.HtmlDelimiters.prototype.postValue = '</span>';
| JavaScript |
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides functions to parse and manipulate email addresses.
*
*/
goog.provide('goog.format.EmailAddress');
goog.require('goog.string');
/**
* Formats an email address string for display, and allows for extraction of
* The individual componants of the address.
* @param {string=} opt_address The email address.
* @param {string=} opt_name The name associated with the email address.
* @constructor
*/
goog.format.EmailAddress = function(opt_address, opt_name) {
/**
* The name or personal string associated with the address.
* @type {string}
* @private
*/
this.name_ = opt_name || '';
/**
* The email address.
* @type {string}
* @private
*/
this.address_ = opt_address || '';
};
/**
* Match string for opening tokens.
* @type {string}
* @private
*/
goog.format.EmailAddress.OPENERS_ = '"<([';
/**
* Match string for closing tokens.
* @type {string}
* @private
*/
goog.format.EmailAddress.CLOSERS_ = '">)]';
/**
* A RegExp to check special characters to be quoted. Used in cleanAddress().
* @type {RegExp}
* @private
*/
goog.format.EmailAddress.SPECIAL_CHARS_RE_ = /[()<>@,;:\\\".\[\]]/;
/**
* A RegExp to match all double quotes. Used in cleanAddress().
* @type {RegExp}
* @private
*/
goog.format.EmailAddress.ALL_DOUBLE_QUOTES_ = /\"/g;
/**
* A RegExp to match escaped double quotes. Used in parse().
* @type {RegExp}
* @private
*/
goog.format.EmailAddress.ESCAPED_DOUBLE_QUOTES_ = /\\\"/g;
/**
* A RegExp to match all backslashes. Used in cleanAddress().
* @type {RegExp}
* @private
*/
goog.format.EmailAddress.ALL_BACKSLASHES_ = /\\/g;
/**
* A RegExp to match escaped backslashes. Used in parse().
* @type {RegExp}
* @private
*/
goog.format.EmailAddress.ESCAPED_BACKSLASHES_ = /\\\\/g;
/**
* Get the name associated with the email address.
* @return {string} The name or personal portion of the address.
*/
goog.format.EmailAddress.prototype.getName = function() {
return this.name_;
};
/**
* Get the email address.
* @return {string} The email address.
*/
goog.format.EmailAddress.prototype.getAddress = function() {
return this.address_;
};
/**
* Set the name associated with the email address.
* @param {string} name The name to associate.
*/
goog.format.EmailAddress.prototype.setName = function(name) {
this.name_ = name;
};
/**
* Set the email address.
* @param {string} address The email address.
*/
goog.format.EmailAddress.prototype.setAddress = function(address) {
this.address_ = address;
};
/**
* Return the address in a standard format:
* - remove extra spaces.
* - Surround name with quotes if it contains special characters.
* @return {string} The cleaned address.
* @override
*/
goog.format.EmailAddress.prototype.toString = function() {
var name = this.getName();
// We intentionally remove double quotes in the name because escaping
// them to \" looks ugly.
name = name.replace(goog.format.EmailAddress.ALL_DOUBLE_QUOTES_, '');
// If the name has special characters, we need to quote it and escape \'s.
var quoteNeeded = goog.format.EmailAddress.SPECIAL_CHARS_RE_.test(name);
if (quoteNeeded) {
name = '"' +
name.replace(goog.format.EmailAddress.ALL_BACKSLASHES_, '\\\\') + '"';
}
if (name == '') {
return this.address_;
}
if (this.address_ == '') {
return name;
}
return name + ' <' + this.address_ + '>';
};
/**
* Determines is the current object is a valid email address.
* @return {boolean} Whether the email address is valid.
*/
goog.format.EmailAddress.prototype.isValid = function() {
return goog.format.EmailAddress.isValidAddrSpec(this.address_);
};
/**
* Checks if the provided string is a valid email address. Supports both
* simple email addresses (address specs) and addresses that contain display
* names.
* @param {string} str The email address to check.
* @return {boolean} Whether the provided string is a valid address.
*/
goog.format.EmailAddress.isValidAddress = function(str) {
return goog.format.EmailAddress.parse(str).isValid();
};
/**
* Checks if the provided string is a valid address spec (local@domain.com).
* @param {string} str The email address to check.
* @return {boolean} Whether the provided string is a valid address spec.
*/
goog.format.EmailAddress.isValidAddrSpec = function(str) {
// This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name
var filter =
/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,6}$/;
return filter.test(str);
};
/**
* Parse an email address of the form "name" <address> into
* an email address.
* @param {string} addr The address string.
* @return {goog.format.EmailAddress} The parsed address.
*/
goog.format.EmailAddress.parse = function(addr) {
// TODO(ecattell): Strip bidi markers.
var name = '';
var address = '';
for (var i = 0; i < addr.length;) {
var token = goog.format.EmailAddress.getToken_(addr, i);
if (token.charAt(0) == '<' && token.indexOf('>') != -1) {
var end = token.indexOf('>');
address = token.substring(1, end);
} else if (address == '') {
name += token;
}
i += token.length;
}
// Check if it's a simple email address of the form "jlim@google.com".
if (address == '' && name.indexOf('@') != -1) {
address = name;
name = '';
}
name = goog.string.collapseWhitespace(name);
name = goog.string.stripQuotes(name, '\'');
name = goog.string.stripQuotes(name, '"');
// Replace escaped quotes and slashes.
name = name.replace(goog.format.EmailAddress.ESCAPED_DOUBLE_QUOTES_, '"');
name = name.replace(goog.format.EmailAddress.ESCAPED_BACKSLASHES_, '\\');
address = goog.string.collapseWhitespace(address);
return new goog.format.EmailAddress(address, name);
};
/**
* Parse a string containing email addresses of the form
* "name" <address> into an array of email addresses.
* @param {string} str The address list.
* @return {Array.<goog.format.EmailAddress>} The parsed emails.
*/
goog.format.EmailAddress.parseList = function(str) {
var result = [];
var email = '';
var token;
for (var i = 0; i < str.length; ) {
token = goog.format.EmailAddress.getToken_(str, i);
if (token == ',' || token == ';' ||
(token == ' ' && goog.format.EmailAddress.parse(email).isValid())) {
if (!goog.string.isEmpty(email)) {
result.push(goog.format.EmailAddress.parse(email));
}
email = '';
i++;
continue;
}
email += token;
i += token.length;
}
// Add the final token.
if (!goog.string.isEmpty(email)) {
result.push(goog.format.EmailAddress.parse(email));
}
return result;
};
/**
* Get the next token from a position in an address string.
* @param {string} str the string.
* @param {number} pos the position.
* @return {string} the token.
* @private
*/
goog.format.EmailAddress.getToken_ = function(str, pos) {
var ch = str.charAt(pos);
var p = goog.format.EmailAddress.OPENERS_.indexOf(ch);
if (p == -1) {
return ch;
}
if (goog.format.EmailAddress.isEscapedDlQuote_(str, pos)) {
// If an opener is an escaped quote we do not treat it as a real opener
// and keep accumulating the token.
return ch;
}
var closerChar = goog.format.EmailAddress.CLOSERS_.charAt(p);
var endPos = str.indexOf(closerChar, pos + 1);
// If the closer is a quote we go forward skipping escaped quotes until we
// hit the real closing one.
while (endPos >= 0 &&
goog.format.EmailAddress.isEscapedDlQuote_(str, endPos)) {
endPos = str.indexOf(closerChar, endPos + 1);
}
var token = (endPos >= 0) ? str.substring(pos, endPos + 1) : ch;
return token;
};
/**
* Checks if the character in the current position is an escaped double quote
* ( \" ).
* @param {string} str the string.
* @param {number} pos the position.
* @return {boolean} true if the char is escaped double quote.
* @private
*/
goog.format.EmailAddress.isEscapedDlQuote_ = function(str, pos) {
if (str.charAt(pos) != '"') {
return false;
}
var slashCount = 0;
for (var idx = pos - 1; idx >= 0 && str.charAt(idx) == '\\'; idx--) {
slashCount++;
}
return ((slashCount % 2) != 0);
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides utility functions for formatting strings, numbers etc.
*
*/
goog.provide('goog.format');
goog.require('goog.i18n.GraphemeBreak');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* Formats a number of bytes in human readable form.
* 54, 450K, 1.3M, 5G etc.
* @param {number} bytes The number of bytes to show.
* @param {number=} opt_decimals The number of decimals to use. Defaults to 2.
* @return {string} The human readable form of the byte size.
*/
goog.format.fileSize = function(bytes, opt_decimals) {
return goog.format.numBytesToString(bytes, opt_decimals, false);
};
/**
* Checks whether string value containing scaling units (K, M, G, T, P, m,
* u, n) can be converted to a number.
*
* Where there is a decimal, there must be a digit to the left of the
* decimal point.
*
* Negative numbers are valid.
*
* Examples:
* 0, 1, 1.0, 10.4K, 2.3M, -0.3P, 1.2m
*
* @param {string} val String value to check.
* @return {boolean} True if string could be converted to a numeric value.
*/
goog.format.isConvertableScaledNumber = function(val) {
return goog.format.SCALED_NUMERIC_RE_.test(val);
};
/**
* Converts a string to numeric value, taking into account the units.
* If string ends in 'B', use binary conversion.
* @param {string} stringValue String to be converted to numeric value.
* @return {number} Numeric value for string.
*/
goog.format.stringToNumericValue = function(stringValue) {
if (goog.string.endsWith(stringValue, 'B')) {
return goog.format.stringToNumericValue_(
stringValue, goog.format.NUMERIC_SCALES_BINARY_);
}
return goog.format.stringToNumericValue_(
stringValue, goog.format.NUMERIC_SCALES_SI_);
};
/**
* Converts a string to number of bytes, taking into account the units.
* Binary conversion.
* @param {string} stringValue String to be converted to numeric value.
* @return {number} Numeric value for string.
*/
goog.format.stringToNumBytes = function(stringValue) {
return goog.format.stringToNumericValue_(
stringValue, goog.format.NUMERIC_SCALES_BINARY_);
};
/**
* Converts a numeric value to string representation. SI conversion.
* @param {number} val Value to be converted.
* @param {number=} opt_decimals The number of decimals to use. Defaults to 2.
* @return {string} String representation of number.
*/
goog.format.numericValueToString = function(val, opt_decimals) {
return goog.format.numericValueToString_(
val, goog.format.NUMERIC_SCALES_SI_, opt_decimals);
};
/**
* Converts number of bytes to string representation. Binary conversion.
* Default is to return the additional 'B' suffix, e.g. '10.5KB' to minimize
* confusion with counts that are scaled by powers of 1000.
* @param {number} val Value to be converted.
* @param {number=} opt_decimals The number of decimals to use. Defaults to 2.
* @param {boolean=} opt_suffix If true, include trailing 'B' in returned
* string. Default is true.
* @return {string} String representation of number of bytes.
*/
goog.format.numBytesToString = function(val, opt_decimals, opt_suffix) {
var suffix = '';
if (!goog.isDef(opt_suffix) || opt_suffix) {
suffix = 'B';
}
return goog.format.numericValueToString_(
val, goog.format.NUMERIC_SCALES_BINARY_, opt_decimals, suffix);
};
/**
* Converts a string to numeric value, taking into account the units.
* @param {string} stringValue String to be converted to numeric value.
* @param {Object} conversion Dictionary of conversion scales.
* @return {number} Numeric value for string. If it cannot be converted,
* returns NaN.
* @private
*/
goog.format.stringToNumericValue_ = function(stringValue, conversion) {
var match = stringValue.match(goog.format.SCALED_NUMERIC_RE_);
if (!match) {
return NaN;
}
var val = match[1] * conversion[match[2]];
return val;
};
/**
* Converts a numeric value to string, using specified conversion
* scales.
* @param {number} val Value to be converted.
* @param {Object} conversion Dictionary of scaling factors.
* @param {number=} opt_decimals The number of decimals to use. Default is 2.
* @param {string=} opt_suffix Optional suffix to append.
* @return {string} The human readable form of the byte size.
* @private
*/
goog.format.numericValueToString_ = function(val, conversion,
opt_decimals, opt_suffix) {
var prefixes = goog.format.NUMERIC_SCALE_PREFIXES_;
var orig_val = val;
var symbol = '';
var scale = 1;
if (val < 0) {
val = -val;
}
for (var i = 0; i < prefixes.length; i++) {
var unit = prefixes[i];
scale = conversion[unit];
if (val >= scale || (scale <= 1 && val > 0.1 * scale)) {
// Treat values less than 1 differently, allowing 0.5 to be "0.5" rather
// than "500m"
symbol = unit;
break;
}
}
if (!symbol) {
scale = 1;
} else if (opt_suffix) {
symbol += opt_suffix;
}
var ex = Math.pow(10, goog.isDef(opt_decimals) ? opt_decimals : 2);
return Math.round(orig_val / scale * ex) / ex + symbol;
};
/**
* Regular expression for detecting scaling units, such as K, M, G, etc. for
* converting a string representation to a numeric value.
*
* Also allow 'k' to be aliased to 'K'. These could be used for SI (powers
* of 1000) or Binary (powers of 1024) conversions.
*
* Also allow final 'B' to be interpreted as byte-count, implicitly triggering
* binary conversion (e.g., '10.2MB').
*
* @type {RegExp}
* @private
*/
goog.format.SCALED_NUMERIC_RE_ = /^([-]?\d+\.?\d*)([K,M,G,T,P,k,m,u,n]?)[B]?$/;
/**
* Ordered list of scaling prefixes in decreasing order.
* @type {Array}
* @private
*/
goog.format.NUMERIC_SCALE_PREFIXES_ = [
'P', 'T', 'G', 'M', 'K', '', 'm', 'u', 'n'
];
/**
* Scaling factors for conversion of numeric value to string. SI conversion.
* @type {Object}
* @private
*/
goog.format.NUMERIC_SCALES_SI_ = {
'': 1,
'n': 1e-9,
'u': 1e-6,
'm': 1e-3,
'k': 1e3,
'K': 1e3,
'M': 1e6,
'G': 1e9,
'T': 1e12,
'P': 1e15
};
/**
* Scaling factors for conversion of numeric value to string. Binary
* conversion.
* @type {Object}
* @private
*/
goog.format.NUMERIC_SCALES_BINARY_ = {
'': 1,
'n': Math.pow(1024, -3),
'u': Math.pow(1024, -2),
'm': 1.0 / 1024,
'k': 1024,
'K': 1024,
'M': Math.pow(1024, 2),
'G': Math.pow(1024, 3),
'T': Math.pow(1024, 4),
'P': Math.pow(1024, 5)
};
/**
* First Unicode code point that has the Mark property.
* @type {number}
* @private
*/
goog.format.FIRST_GRAPHEME_EXTEND_ = 0x300;
/**
* Returns true if and only if given character should be treated as a breaking
* space. All ASCII control characters, the main Unicode range of spacing
* characters (U+2000 to U+200B inclusive except for U+2007), and several other
* Unicode space characters are treated as breaking spaces.
* @param {number} charCode The character code under consideration.
* @return {boolean} True if the character is a breaking space.
* @private
*/
goog.format.isTreatedAsBreakingSpace_ = function(charCode) {
return (charCode <= goog.format.WbrToken_.SPACE) ||
(charCode >= 0x1000 &&
((charCode >= 0x2000 && charCode <= 0x2006) ||
(charCode >= 0x2008 && charCode <= 0x200B) ||
charCode == 0x1680 ||
charCode == 0x180E ||
charCode == 0x2028 ||
charCode == 0x2029 ||
charCode == 0x205f ||
charCode == 0x3000));
};
/**
* Returns true if and only if given character is an invisible formatting
* character.
* @param {number} charCode The character code under consideration.
* @return {boolean} True if the character is an invisible formatting character.
* @private
*/
goog.format.isInvisibleFormattingCharacter_ = function(charCode) {
// See: http://unicode.org/charts/PDF/U2000.pdf
return (charCode >= 0x200C && charCode <= 0x200F) ||
(charCode >= 0x202A && charCode <= 0x202E);
};
/**
* Inserts word breaks into an HTML string at a given interval. The counter is
* reset if a space or a character which behaves like a space is encountered,
* but it isn't incremented if an invisible formatting character is encountered.
* WBRs aren't inserted into HTML tags or entities. Entities count towards the
* character count, HTML tags do not.
*
* With common strings aliased, objects allocations are constant based on the
* length of the string: N + 3. This guarantee does not hold if the string
* contains an element >= U+0300 and hasGraphemeBreak is non-trivial.
*
* @param {string} str HTML to insert word breaks into.
* @param {function(number, number, boolean): boolean} hasGraphemeBreak A
* function determining if there is a grapheme break between two characters,
* in the same signature as goog.i18n.GraphemeBreak.hasGraphemeBreak.
* @param {number=} opt_maxlen Maximum length after which to ensure
* there is a break. Default is 10 characters.
* @return {string} The string including word breaks.
* @private
*/
goog.format.insertWordBreaksGeneric_ = function(str, hasGraphemeBreak,
opt_maxlen) {
var maxlen = opt_maxlen || 10;
if (maxlen > str.length) return str;
var rv = [];
var n = 0; // The length of the current token
// This will contain the ampersand or less-than character if one of the
// two has been seen; otherwise, the value is zero.
var nestingCharCode = 0;
// First character position from input string that has not been outputted.
var lastDumpPosition = 0;
var charCode = 0;
for (var i = 0; i < str.length; i++) {
// Using charCodeAt versus charAt avoids allocating new string objects.
var lastCharCode = charCode;
charCode = str.charCodeAt(i);
// Don't add a WBR before characters that might be grapheme extending.
var isPotentiallyGraphemeExtending =
charCode >= goog.format.FIRST_GRAPHEME_EXTEND_ &&
!hasGraphemeBreak(lastCharCode, charCode, true);
// Don't add a WBR at the end of a word. For the purposes of determining
// work breaks, all ASCII control characters and some commonly encountered
// Unicode spacing characters are treated as breaking spaces.
if (n >= maxlen &&
!goog.format.isTreatedAsBreakingSpace_(charCode) &&
!isPotentiallyGraphemeExtending) {
// Flush everything seen so far, and append a word break.
rv.push(str.substring(lastDumpPosition, i), goog.format.WORD_BREAK_HTML);
lastDumpPosition = i;
n = 0;
}
if (!nestingCharCode) {
// Not currently within an HTML tag or entity
if (charCode == goog.format.WbrToken_.LT ||
charCode == goog.format.WbrToken_.AMP) {
// Entering an HTML Entity '&' or open tag '<'
nestingCharCode = charCode;
} else if (goog.format.isTreatedAsBreakingSpace_(charCode)) {
// A space or control character -- reset the token length
n = 0;
} else if (!goog.format.isInvisibleFormattingCharacter_(charCode)) {
// A normal flow character - increment. For grapheme extending
// characters, this is not *technically* a new character. However,
// since the grapheme break detector might be overly conservative,
// we have to continue incrementing, or else we won't even be able
// to add breaks when we get to things like punctuation. For the
// case where we have a full grapheme break detector, it is okay if
// we occasionally break slightly early.
n++;
}
} else if (charCode == goog.format.WbrToken_.GT &&
nestingCharCode == goog.format.WbrToken_.LT) {
// Leaving an HTML tag, treat the tag as zero-length
nestingCharCode = 0;
} else if (charCode == goog.format.WbrToken_.SEMI_COLON &&
nestingCharCode == goog.format.WbrToken_.AMP) {
// Leaving an HTML entity, treat it as length one
nestingCharCode = 0;
n++;
}
}
// Take care of anything we haven't flushed so far.
rv.push(str.substr(lastDumpPosition));
return rv.join('');
};
/**
* Inserts word breaks into an HTML string at a given interval.
*
* This method is as aggressive as possible, using a full table of Unicode
* characters where it is legal to insert word breaks; however, this table
* comes at a 2.5k pre-gzip (~1k post-gzip) size cost. Consider using
* insertWordBreaksBasic to minimize the size impact.
*
* @param {string} str HTML to insert word breaks into.
* @param {number=} opt_maxlen Maximum length after which to ensure there is a
* break. Default is 10 characters.
* @return {string} The string including word breaks.
*/
goog.format.insertWordBreaks = function(str, opt_maxlen) {
return goog.format.insertWordBreaksGeneric_(str,
goog.i18n.GraphemeBreak.hasGraphemeBreak, opt_maxlen);
};
/**
* Determines conservatively if a character has a Grapheme break.
*
* Conforms to a similar signature as goog.i18n.GraphemeBreak, but is overly
* conservative, returning true only for characters in common scripts that
* are simple to account for.
*
* @param {number} lastCharCode The previous character code. Ignored.
* @param {number} charCode The character code under consideration. It must be
* at least \u0300 as a precondition -- this case is covered by
* insertWordBreaksGeneric_.
* @param {boolean=} opt_extended Ignored, to conform with the interface.
* @return {boolean} Whether it is one of the recognized subsets of characters
* with a grapheme break.
* @private
*/
goog.format.conservativelyHasGraphemeBreak_ = function(
lastCharCode, charCode, opt_extended) {
// Return false for everything except the most common Cyrillic characters.
// Don't worry about Latin characters, because insertWordBreaksGeneric_
// itself already handles those.
// TODO(gboyer): Also account for Greek, Armenian, and Georgian if it is
// simple to do so.
return charCode >= 0x400 && charCode < 0x523;
};
// TODO(gboyer): Consider using a compile-time flag to switch implementations
// rather than relying on the developers to toggle implementations.
/**
* Inserts word breaks into an HTML string at a given interval.
*
* This method is less aggressive than insertWordBreaks, only inserting
* breaks next to punctuation and between Latin or Cyrillic characters.
* However, this is good enough for the common case of URLs. It also
* works for all Latin and Cyrillic languages, plus CJK has no need for word
* breaks. When this method is used, goog.i18n.GraphemeBreak may be dead
* code eliminated.
*
* @param {string} str HTML to insert word breaks into.
* @param {number=} opt_maxlen Maximum length after which to ensure there is a
* break. Default is 10 characters.
* @return {string} The string including word breaks.
*/
goog.format.insertWordBreaksBasic = function(str, opt_maxlen) {
return goog.format.insertWordBreaksGeneric_(str,
goog.format.conservativelyHasGraphemeBreak_, opt_maxlen);
};
/**
* True iff the current userAgent is IE8 or above.
* @type {boolean}
* @private
*/
goog.format.IS_IE8_OR_ABOVE_ = goog.userAgent.IE &&
goog.userAgent.isVersion(8);
/**
* Constant for the WBR replacement used by insertWordBreaks. Safari requires
* <wbr></wbr>, Opera needs the ­ entity, though this will give a visible
* hyphen at breaks. IE8 uses a zero width space.
* Other browsers just use <wbr>.
* @type {string}
*/
goog.format.WORD_BREAK_HTML =
goog.userAgent.WEBKIT ?
'<wbr></wbr>' : goog.userAgent.OPERA ?
'­' : goog.format.IS_IE8_OR_ABOVE_ ?
'​' : '<wbr>';
/**
* Tokens used within insertWordBreaks.
* @private
* @enum {number}
*/
goog.format.WbrToken_ = {
LT: 60, // '<'.charCodeAt(0)
GT: 62, // '>'.charCodeAt(0)
AMP: 38, // '&'.charCodeAt(0)
SEMI_COLON: 59, // ';'.charCodeAt(0)
SPACE: 32 // ' '.charCodeAt(0)
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper for a IndexedDB key range.
*
*/
goog.provide('goog.db.KeyRange');
/**
* Creates a new IDBKeyRange wrapper object. Should not be created directly,
* instead use one of the static factory methods. For example:
* @see goog.db.KeyRange.bound
* @see goog.db.KeyRange.lowerBound
*
* @param {!IDBKeyRange} range Underlying IDBKeyRange object.
* @constructor
*/
goog.db.KeyRange = function(range) {
/**
* Underlying IDBKeyRange object.
*
* @type {!IDBKeyRange}
* @private
*/
this.range_ = range;
};
/**
* The IDBKeyRange.
* @type {!Object}
* @private
*/
goog.db.KeyRange.IDB_KEY_RANGE_ = goog.global.IDBKeyRange ||
goog.global.webkitIDBKeyRange;
/**
* Creates a new key range for a single value.
*
* @param {IDBKeyType} key The single value in the range.
* @return {!goog.db.KeyRange} The key range.
*/
goog.db.KeyRange.only = function(key) {
return new goog.db.KeyRange(goog.db.KeyRange.IDB_KEY_RANGE_.only(key));
};
/**
* Creates a key range with upper and lower bounds.
*
* @param {IDBKeyType} lower The value of the lower bound.
* @param {IDBKeyType} upper The value of the upper bound.
* @param {boolean=} opt_lowerOpen If true, the range excludes the lower bound
* value.
* @param {boolean=} opt_upperOpen If true, the range excludes the upper bound
* value.
* @return {!goog.db.KeyRange} The key range.
*/
goog.db.KeyRange.bound = function(lower, upper, opt_lowerOpen, opt_upperOpen) {
return new goog.db.KeyRange(goog.db.KeyRange.IDB_KEY_RANGE_.bound(
lower, upper, opt_lowerOpen, opt_upperOpen));
};
/**
* Creates a key range with a lower bound only, finishes at the last record.
*
* @param {IDBKeyType} lower The value of the lower bound.
* @param {boolean=} opt_lowerOpen If true, the range excludes the lower bound
* value.
* @return {!goog.db.KeyRange} The key range.
*/
goog.db.KeyRange.lowerBound = function(lower, opt_lowerOpen) {
return new goog.db.KeyRange(goog.db.KeyRange.IDB_KEY_RANGE_.lowerBound(
lower, opt_lowerOpen));
};
/**
* Creates a key range with a upper bound only, starts at the first record.
*
* @param {IDBKeyType} upper The value of the upper bound.
* @param {boolean=} opt_upperOpen If true, the range excludes the upper bound
* value.
* @return {!goog.db.KeyRange} The key range.
*/
goog.db.KeyRange.upperBound = function(upper, opt_upperOpen) {
return new goog.db.KeyRange(goog.db.KeyRange.IDB_KEY_RANGE_.upperBound(
upper, opt_upperOpen));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper for an IndexedDB database.
*
*/
goog.provide('goog.db.IndexedDb');
goog.require('goog.async.Deferred');
goog.require('goog.db.Error');
goog.require('goog.db.Error.VersionChangeBlockedError');
goog.require('goog.db.ObjectStore');
goog.require('goog.db.Transaction');
goog.require('goog.db.Transaction.TransactionMode');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
/**
* Creates an IDBDatabase wrapper object. The database object has methods for
* setting the version to change the structure of the database and for creating
* transactions to get or modify the stored records. Should not be created
* directly, call {@link goog.db.openDatabase} to set up the connection.
*
* @param {!IDBDatabase} db Underlying IndexedDB database object.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.db.IndexedDb = function(db) {
goog.base(this);
/**
* Underlying IndexedDB database object.
*
* @type {!IDBDatabase}
* @private
*/
this.db_ = db;
/**
* Internal event handler that listens to IDBDatabase events.
* @type {!goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
this.eventHandler_.listen(
this.db_,
goog.db.IndexedDb.EventType.ABORT,
goog.bind(
this.dispatchEvent,
this,
goog.db.IndexedDb.EventType.ABORT));
this.eventHandler_.listen(
this.db_,
goog.db.IndexedDb.EventType.ERROR,
this.dispatchError_);
this.eventHandler_.listen(
this.db_,
goog.db.IndexedDb.EventType.VERSION_CHANGE,
this.dispatchVersionChange_);
};
goog.inherits(goog.db.IndexedDb, goog.events.EventTarget);
/**
* True iff the database connection is open.
*
* @type {boolean}
* @private
*/
goog.db.IndexedDb.prototype.open_ = true;
/**
* Dispatches a wrapped error event based on the given event.
*
* @param {Event} ev The error event given to the underlying IDBDatabase.
* @private
*/
goog.db.IndexedDb.prototype.dispatchError_ = function(ev) {
this.dispatchEvent({
type: goog.db.IndexedDb.EventType.ERROR,
errorCode: /** @type {IDBRequest} */ (ev.target).errorCode
});
};
/**
* Dispatches a wrapped version change event based on the given event.
*
* @param {Event} ev The version change event given to the underlying
* IDBDatabase.
* @private
*/
goog.db.IndexedDb.prototype.dispatchVersionChange_ = function(ev) {
this.dispatchEvent(new goog.db.IndexedDb.VersionChangeEvent(
ev.oldVersion, ev.newVersion));
};
/**
* Closes the database connection. Metadata queries can still be made after this
* method is called, but otherwise this wrapper should not be used further.
*/
goog.db.IndexedDb.prototype.close = function() {
if (this.open_) {
this.db_.close();
this.open_ = false;
}
};
/**
* @return {boolean} Whether a connection is open and the database can be used.
*/
goog.db.IndexedDb.prototype.isOpen = function() {
return this.open_;
};
/**
* @return {string} The name of this database.
*/
goog.db.IndexedDb.prototype.getName = function() {
return this.db_.name;
};
/**
* @return {string} The current database version.
*/
goog.db.IndexedDb.prototype.getVersion = function() {
return this.db_.version;
};
/**
* @return {DOMStringList} List of object stores in this database.
*/
goog.db.IndexedDb.prototype.getObjectStoreNames = function() {
return this.db_.objectStoreNames;
};
/**
* Creates an object store in this database. Can only be called inside a
* {@link goog.db.UpgradeNeededCallback} or the callback for the Deferred
* returned from #setVersion.
*
* @param {string} name Name for the new object store.
* @param {Object=} opt_params Options object. The available options are:
* keyPath, which is a string and determines what object attribute
* to use as the key when storing objects in this object store; and
* autoIncrement, which is a boolean, which defaults to false and determines
* whether the object store should automatically generate keys for stored
* objects. If keyPath is not provided and autoIncrement is false, then all
* insert operations must provide a key as a parameter.
* @return {goog.db.ObjectStore} The newly created object store.
* @throws {goog.db.Error} If there's a problem creating the object store.
*/
goog.db.IndexedDb.prototype.createObjectStore = function(name, opt_params) {
try {
return new goog.db.ObjectStore(this.db_.createObjectStore(
name, opt_params));
} catch (ex) {
throw goog.db.Error.fromException(ex, 'creating object store ' + name);
}
};
/**
* Deletes an object store. Can only be called inside a
* {@link goog.db.UpgradeNeededCallback} or the callback for the Deferred
* returned from #setVersion.
*
* @param {string} name Name of the object store to delete.
* @throws {goog.db.Error} If there's a problem deleting the object store.
*/
goog.db.IndexedDb.prototype.deleteObjectStore = function(name) {
try {
this.db_.deleteObjectStore(name);
} catch (ex) {
throw goog.db.Error.fromException(ex, 'deleting object store ' + name);
}
};
/**
* Updates the version of the database and returns a Deferred transaction.
* The database's structure can be changed inside this Deferred's callback, but
* nowhere else. This means adding or deleting object stores, and adding or
* deleting indexes. The version change will not succeed unless there are no
* other connections active for this database anywhere. A new database
* connection should be opened after the version change is finished to pick
* up changes.
*
* This is deprecated, and only supported on Chrome prior to version 25. New
* applications should use the version parameter to {@link goog.db.openDatabase}
* instead.
*
* @param {string} version The new version of the database.
* @return {!goog.async.Deferred} The deferred transaction for changing the
* version.
*/
goog.db.IndexedDb.prototype.setVersion = function(version) {
var self = this;
var d = new goog.async.Deferred();
var request = this.db_.setVersion(version);
request.onsuccess = function(ev) {
// the transaction is in the result field (the transaction field is null
// for version change requests)
d.callback(new goog.db.Transaction(ev.target.result, self));
};
request.onerror = function(ev) {
// If a version change is blocked, onerror and onblocked may both fire.
// Check d.hasFired() to avoid an AlreadyCalledError.
if (!d.hasFired()) {
d.errback(goog.db.Error.fromRequest(ev.target, 'setting version'));
}
};
request.onblocked = function(ev) {
// If a version change is blocked, onerror and onblocked may both fire.
// Check d.hasFired() to avoid an AlreadyCalledError.
if (!d.hasFired()) {
d.errback(new goog.db.Error.VersionChangeBlockedError());
}
};
return d;
};
/**
* Creates a new transaction.
*
* @param {!Array.<string>} storeNames A list of strings that contains the
* transaction's scope, the object stores that this transaction can operate
* on.
* @param {goog.db.Transaction.TransactionMode=} opt_mode The mode of the
* transaction. If not present, the default is READ_ONLY. For VERSION_CHANGE
* transactions call {@link goog.db.IndexedDB#setVersion} instead.
* @return {!goog.db.Transaction} The wrapper for the newly created transaction.
* @throws {goog.db.Error} If there's a problem creating the transaction.
*/
goog.db.IndexedDb.prototype.createTransaction = function(storeNames, opt_mode) {
try {
// IndexedDB on Chrome 22+ requires that opt_mode not be passed rather than
// be explicitly passed as undefined.
var transaction = opt_mode ?
this.db_.transaction(storeNames, opt_mode) :
this.db_.transaction(storeNames);
return new goog.db.Transaction(transaction, this);
} catch (ex) {
throw goog.db.Error.fromException(ex, 'creating transaction');
}
};
/** @override */
goog.db.IndexedDb.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.eventHandler_.dispose();
};
/**
* Event types fired by a database.
*
* @enum {string} The event types for the web socket.
*/
goog.db.IndexedDb.EventType = {
/**
* Fired when a transaction is aborted and the event bubbles to its database.
*/
ABORT: 'abort',
/**
* Fired when a transaction has an error.
*/
ERROR: 'error',
/**
* Fired when someone (possibly in another window) is attempting to modify the
* structure of the database. Since a change can only be made when there are
* no active database connections, this usually means that the database should
* be closed so that the other client can make its changes.
*/
VERSION_CHANGE: 'versionchange'
};
/**
* Event representing a (possibly attempted) change in the database structure.
*
* At time of writing, no Chrome versions support oldVersion or newVersion. See
* http://crbug.com/153122.
*
* @param {number} oldVersion The previous version of the database.
* @param {number} newVersion The version the database is being or has been
* updated to.
* @constructor
* @extends {goog.events.Event}
*/
goog.db.IndexedDb.VersionChangeEvent = function(oldVersion, newVersion) {
goog.base(this, goog.db.IndexedDb.EventType.VERSION_CHANGE);
/**
* The previous version of the database.
* @type {number}
*/
this.oldVersion = oldVersion;
/**
* The version the database is being or has been updated to.
* @type {number}
*/
this.newVersion = newVersion;
};
goog.inherits(goog.db.IndexedDb.VersionChangeEvent, goog.events.Event);
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrappers for the HTML5 IndexedDB. The wrappers export nearly
* the same interface as the standard API, but return goog.async.Deferred
* objects instead of request objects and use Closure events. The wrapper works
* and has been tested on Chrome version 22+. It may work on older Chrome
* versions, but they aren't explicitly supported.
*
* Example usage:
*
* <code>
* goog.db.openDatabase('mydb', 1, function(ev, db, tx) {
* db.createObjectStore('mystore');
* }).addCallback(function(db) {
* var putTx = db.createTransaction(
* [],
* goog.db.Transaction.TransactionMode.READ_WRITE);
* var store = putTx.objectStore('mystore');
* store.put('value', 'key');
* goog.listen(putTx, goog.db.Transaction.EventTypes.COMPLETE, function() {
* var getTx = db.createTransaction([]);
* var request = getTx.objectStore('mystore').get('key');
* request.addCallback(function(result) {
* ...
* });
* });
* </code>
*
*/
goog.provide('goog.db');
goog.require('goog.async.Deferred');
goog.require('goog.db.Error');
goog.require('goog.db.IndexedDb');
goog.require('goog.db.Transaction');
/**
* The IndexedDB factory object.
*
* @type {IDBFactory}
* @private
*/
goog.db.indexedDb_ = goog.global.indexedDB || goog.global.mozIndexedDB ||
goog.global.webkitIndexedDB || goog.global.moz_indexedDB;
/**
* A callback that's called if a blocked event is received. When a database is
* supposed to be deleted or upgraded (i.e. versionchange), and there are open
* connections to this database, a block event will be fired to prevent the
* operations from going through until all such open connections are closed.
* This callback can be used to notify users that they should close other tabs
* that have open connections, or to close the connections manually. Databases
* can also listen for the {@link goog.db.IndexedDb.EventType.VERSION_CHANGE}
* event to automatically close themselves when they're blocking such
* operations.
*
* This is passed a VersionChangeEvent that has the version of the database
* before it was deleted, and "null" as the new version.
*
* @typedef {function(!goog.db.IndexedDb.VersionChangeEvent)}
*/
goog.db.BlockedCallback;
/**
* A callback that's called when opening a database whose internal version is
* lower than the version passed to {@link goog.db.openDatabase}.
*
* This callback is passed three arguments: a VersionChangeEvent with both the
* old version and the new version of the database; the database that's being
* opened, for which you can create and delete object stores; and the version
* change transaction, with which you can abort the version change.
*
* Note that the transaction is not active, which means that it can't be used to
* make changes to the database. However, since there is a transaction running,
* you can't create another one via {@link goog.db.IndexedDb.createTransaction}.
* This means that it's not possible to manipulate the database other than
* creating or removing object stores in this callback.
*
* @typedef {function(!goog.db.IndexedDb.VersionChangeEvent,
* !goog.db.IndexedDb,
* !goog.db.Transaction)}
*/
goog.db.UpgradeNeededCallback;
/**
* Opens a database connection and wraps it.
*
* @param {string} name The name of the database to open.
* @param {number=} opt_version The expected version of the database. If this is
* larger than the actual version, opt_onUpgradeNeeded will be called
* (possibly after opt_onBlocked; see {@link goog.db.BlockedCallback}). If
* this is passed, opt_onUpgradeNeeded must be passed as well.
* @param {goog.db.UpgradeNeededCallback=} opt_onUpgradeNeeded Called if
* opt_version is greater than the old version of the database. If
* opt_version is passed, this must be passed as well.
* @param {goog.db.BlockedCallback=} opt_onBlocked Called if there are active
* connections to the database.
* @return {!goog.async.Deferred} The deferred database object.
*/
goog.db.openDatabase = function(name, opt_version, opt_onUpgradeNeeded,
opt_onBlocked) {
goog.asserts.assert(
goog.isDef(opt_version) == goog.isDef(opt_onUpgradeNeeded),
'opt_version must be passed to goog.db.openDatabase if and only if ' +
'opt_onUpgradeNeeded is also passed');
var d = new goog.async.Deferred();
var openRequest = opt_version ?
goog.db.indexedDb_.open(name, opt_version) :
goog.db.indexedDb_.open(name);
openRequest.onsuccess = function(ev) {
var db = new goog.db.IndexedDb(ev.target.result);
d.callback(db);
};
openRequest.onerror = function(ev) {
var msg = 'opening database ' + name;
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
openRequest.onupgradeneeded = function(ev) {
if (!opt_onUpgradeNeeded) return;
var db = new goog.db.IndexedDb(ev.target.result);
opt_onUpgradeNeeded(
new goog.db.IndexedDb.VersionChangeEvent(ev.oldVersion, ev.newVersion),
db,
new goog.db.Transaction(ev.target.transaction, db));
};
openRequest.onblocked = function(ev) {
if (opt_onBlocked) {
opt_onBlocked(new goog.db.IndexedDb.VersionChangeEvent(
ev.oldVersion, ev.newVersion));
}
};
return d;
};
/**
* Deletes a database once all open connections have been closed.
*
* @param {string} name The name of the database to delete.
* @param {goog.db.BlockedCallback=} opt_onBlocked Called if there are active
* connections to the database.
* @return {goog.async.Deferred} A deferred object that will fire once the
* database is deleted.
*/
goog.db.deleteDatabase = function(name, opt_onBlocked) {
var d = new goog.async.Deferred();
var deleteRequest = goog.db.indexedDb_.deleteDatabase(name);
deleteRequest.onsuccess = function(ev) {
d.callback();
};
deleteRequest.onerror = function(ev) {
var msg = 'deleting database ' + name;
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
deleteRequest.onblocked = function(ev) {
if (opt_onBlocked) {
opt_onBlocked(new goog.db.IndexedDb.VersionChangeEvent(
ev.oldVersion, ev.newVersion));
}
};
return d;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Error classes for the IndexedDB wrapper.
*
*/
goog.provide('goog.db.Error');
goog.provide('goog.db.Error.ErrorCode');
goog.provide('goog.db.Error.ErrorName');
goog.provide('goog.db.Error.VersionChangeBlockedError');
goog.require('goog.debug.Error');
/**
* A database error. Since the stack trace can be unhelpful in an asynchronous
* context, the error provides a message about where it was produced.
*
* @param {number|!DOMError} error The DOMError instance returned by the
* browser for Chrome22+, or an error code for previous versions.
* @param {string} context A description of where the error occured.
* @param {string=} opt_message Additional message.
* @constructor
* @extends {goog.debug.Error}
*/
goog.db.Error = function(error, context, opt_message) {
var errorCode = null;
var internalError = null;
if (goog.isNumber(error)) {
errorCode = error;
internalError = {name: goog.db.Error.getName(errorCode)};
} else {
internalError = error;
errorCode = goog.db.Error.getCode(error.name);
}
/**
* The code for this error.
*
* @type {number}
*/
this.code = errorCode;
/**
* The DOMException as returned by the browser.
*
* @type {!DOMError}
* @private
*/
this.error_ = /** @type {!DOMError} */ (internalError);
var msg = 'Error ' + context + ': ' + this.getName();
if (opt_message) {
msg += ', ' + opt_message;
}
goog.base(this, msg);
};
goog.inherits(goog.db.Error, goog.debug.Error);
/**
* @return {string} The name of the error.
*/
goog.db.Error.prototype.getName = function() {
return this.error_.name;
};
/**
* A specific kind of database error. If a Version Change is unable to proceed
* due to other open database connections, it will block and this error will be
* thrown.
*
* @constructor
* @extends {goog.debug.Error}
*/
goog.db.Error.VersionChangeBlockedError = function() {
goog.base(this, 'Version change blocked');
};
goog.inherits(goog.db.Error.VersionChangeBlockedError, goog.debug.Error);
/**
* Synthetic error codes for database errors, for use when IndexedDB
* support is not available. This numbering differs in practice
* from the browser implementations, but it is not meant to be reliable:
* this object merely ensures that goog.db.Error is loadable on platforms
* that do not support IndexedDB.
*
* @enum {number}
* @private
*/
goog.db.Error.DatabaseErrorCode_ = {
UNKNOWN_ERR: 1,
NON_TRANSIENT_ERR: 2,
NOT_FOUND_ERR: 3,
CONSTRAINT_ERR: 4,
DATA_ERR: 5,
NOT_ALLOWED_ERR: 6,
TRANSACTION_INACTIVE_ERR: 7,
ABORT_ERR: 8,
READ_ONLY_ERR: 9,
TRANSIENT_ERR: 11,
TIMEOUT_ERR: 10,
QUOTA_ERR: 11,
INVALID_ACCESS_ERR: 12,
INVALID_STATE_ERR: 13
};
/**
* Error codes for database errors.
* @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException
*
* @enum {number}
*/
goog.db.Error.ErrorCode = {
UNKNOWN_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).UNKNOWN_ERR,
NON_TRANSIENT_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).NON_TRANSIENT_ERR,
NOT_FOUND_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).NOT_FOUND_ERR,
CONSTRAINT_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).CONSTRAINT_ERR,
DATA_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).DATA_ERR,
NOT_ALLOWED_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).NOT_ALLOWED_ERR,
TRANSACTION_INACTIVE_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).TRANSACTION_INACTIVE_ERR,
ABORT_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).ABORT_ERR,
READ_ONLY_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).READ_ONLY_ERR,
TIMEOUT_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).TIMEOUT_ERR,
QUOTA_ERR: (goog.global.IDBDatabaseException ||
goog.global.webkitIDBDatabaseException ||
goog.db.Error.DatabaseErrorCode_).QUOTA_ERR,
INVALID_ACCESS_ERR: (goog.global.DOMException ||
goog.db.Error.DatabaseErrorCode_).INVALID_ACCESS_ERR,
INVALID_STATE_ERR: (goog.global.DOMException ||
goog.db.Error.DatabaseErrorCode_).INVALID_STATE_ERR
};
/**
* Translates an error code into a more useful message.
*
* @param {number} code Error code.
* @return {string} A debug message.
*/
goog.db.Error.getMessage = function(code) {
switch (code) {
case goog.db.Error.ErrorCode.UNKNOWN_ERR:
return 'Unknown error';
case goog.db.Error.ErrorCode.NON_TRANSIENT_ERR:
return 'Invalid operation';
case goog.db.Error.ErrorCode.NOT_FOUND_ERR:
return 'Required database object not found';
case goog.db.Error.ErrorCode.CONSTRAINT_ERR:
return 'Constraint unsatisfied';
case goog.db.Error.ErrorCode.DATA_ERR:
return 'Invalid data';
case goog.db.Error.ErrorCode.NOT_ALLOWED_ERR:
return 'Operation disallowed';
case goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR:
return 'Transaction not active';
case goog.db.Error.ErrorCode.ABORT_ERR:
return 'Request aborted';
case goog.db.Error.ErrorCode.READ_ONLY_ERR:
return 'Modifying operation not allowed in a read-only transaction';
case goog.db.Error.ErrorCode.TIMEOUT_ERR:
return 'Transaction timed out';
case goog.db.Error.ErrorCode.QUOTA_ERR:
return 'Database storage space quota exceeded';
case goog.db.Error.ErrorCode.INVALID_ACCESS_ERR:
return 'Invalid operation';
case goog.db.Error.ErrorCode.INVALID_STATE_ERR:
return 'Invalid state';
default:
return 'Unrecognized exception with code ' + code;
}
};
/**
* Names of all possible errors as returned from the browser.
* @see http://www.w3.org/TR/IndexedDB/#exceptions
* @enum {string}
*/
goog.db.Error.ErrorName = {
ABORT_ERR: 'AbortError',
CONSTRAINT_ERR: 'ConstraintError',
DATA_CLONE_ERR: 'DataCloneError',
DATA_ERR: 'DataError',
INVALID_ACCESS_ERR: 'InvalidAccessError',
INVALID_STATE_ERR: 'InvalidStateError',
NOT_FOUND_ERR: 'NotFoundError',
QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
READ_ONLY_ERR: 'ReadOnlyError',
SYNTAX_ERROR: 'SyntaxError',
TIMEOUT_ERR: 'TimeoutError',
TRANSACTION_INACTIVE_ERR: 'TransactionInactiveError',
UNKNOWN_ERR: 'UnknownError',
VERSION_ERR: 'VersionError'
};
/**
* Translates an error name to an error code. This is purely kept for backwards
* compatibility with Chrome21.
*
* @param {string} name The name of the erorr.
* @return {number} The error code corresponding to the error.
*/
goog.db.Error.getCode = function(name) {
switch (name) {
case goog.db.Error.ErrorName.UNKNOWN_ERR:
return goog.db.Error.ErrorCode.UNKNOWN_ERR;
case goog.db.Error.ErrorName.NOT_FOUND_ERR:
return goog.db.Error.ErrorCode.NOT_FOUND_ERR;
case goog.db.Error.ErrorName.CONSTRAINT_ERR:
return goog.db.Error.ErrorCode.CONSTRAINT_ERR;
case goog.db.Error.ErrorName.DATA_ERR:
return goog.db.Error.ErrorCode.DATA_ERR;
case goog.db.Error.ErrorName.TRANSACTION_INACTIVE_ERR:
return goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR;
case goog.db.Error.ErrorName.ABORT_ERR:
return goog.db.Error.ErrorCode.ABORT_ERR;
case goog.db.Error.ErrorName.READ_ONLY_ERR:
return goog.db.Error.ErrorCode.READ_ONLY_ERR;
case goog.db.Error.ErrorName.TIMEOUT_ERR:
return goog.db.Error.ErrorCode.TIMEOUT_ERR;
case goog.db.Error.ErrorName.QUOTA_EXCEEDED_ERR:
return goog.db.Error.ErrorCode.QUOTA_ERR;
case goog.db.Error.ErrorName.INVALID_ACCESS_ERR:
return goog.db.Error.ErrorCode.INVALID_ACCESS_ERR;
case goog.db.Error.ErrorName.INVALID_STATE_ERR:
return goog.db.Error.ErrorCode.INVALID_STATE_ERR;
default:
return goog.db.Error.ErrorCode.UNKNOWN_ERR;
}
};
/**
* Converts an error code used by the old spec, to an error name used by the
* latest spec.
* @see http://www.w3.org/TR/IndexedDB/#exceptions
*
* @param {!goog.db.Error.ErrorCode|number} code The error code to convert.
* @return {!goog.db.Error.ErrorName} The corresponding name of the error.
*/
goog.db.Error.getName = function(code) {
switch (code) {
case goog.db.Error.ErrorCode.UNKNOWN_ERR:
return goog.db.Error.ErrorName.UNKNOWN_ERR;
case goog.db.Error.ErrorCode.NOT_FOUND_ERR:
return goog.db.Error.ErrorName.NOT_FOUND_ERR;
case goog.db.Error.ErrorCode.CONSTRAINT_ERR:
return goog.db.Error.ErrorName.CONSTRAINT_ERR;
case goog.db.Error.ErrorCode.DATA_ERR:
return goog.db.Error.ErrorName.DATA_ERR;
case goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR:
return goog.db.Error.ErrorName.TRANSACTION_INACTIVE_ERR;
case goog.db.Error.ErrorCode.ABORT_ERR:
return goog.db.Error.ErrorName.ABORT_ERR;
case goog.db.Error.ErrorCode.READ_ONLY_ERR:
return goog.db.Error.ErrorName.READ_ONLY_ERR;
case goog.db.Error.ErrorCode.TIMEOUT_ERR:
return goog.db.Error.ErrorName.TIMEOUT_ERR;
case goog.db.Error.ErrorCode.QUOTA_ERR:
return goog.db.Error.ErrorName.QUOTA_EXCEEDED_ERR;
case goog.db.Error.ErrorCode.INVALID_ACCESS_ERR:
return goog.db.Error.ErrorName.INVALID_ACCESS_ERR;
case goog.db.Error.ErrorCode.INVALID_STATE_ERR:
return goog.db.Error.ErrorName.INVALID_STATE_ERR;
default:
return goog.db.Error.ErrorName.UNKNOWN_ERR;
}
};
/**
* Constructs an goog.db.Error instance from an IDBRequest. This abstraction is
* necessary to provide backwards compatibility with Chrome21.
*
* @param {!IDBRequest} request The request that failed.
* @param {string} message The error message to add to err if it's wrapped.
* @return {!goog.db.Error} The error that caused the failure.
*/
goog.db.Error.fromRequest = function(request, message) {
if ('error' in request) {
// Chrome 21 and before.
return new goog.db.Error(request.error, message);
} else if ('name' in request) {
// Chrome 22+.
var errorName = goog.db.Error.getName(request.errorCode);
return new goog.db.Error(
/**@type {!DOMError} */ ({name: errorName}), message);
} else {
return new goog.db.Error(/** @type {!DOMError} */ (
{name: goog.db.Error.ErrorName.UNKNOWN_ERR}), message);
}
};
/**
* Constructs an goog.db.Error instance from an DOMException. This abstraction
* is necessary to provide backwards compatibility with Chrome21.
*
* @param {!IDBDatabaseException} ex The exception that was thrown.
* @param {string} message The error message to add to err if it's wrapped.
* @return {!goog.db.Error} The error that caused the failure.
* @suppress {invalidCasts} The cast from IDBDatabaseException to DOMError
* is invalid and will not compile.
*/
goog.db.Error.fromException = function(ex, message) {
if ('name' in ex) {
// Chrome 21 and before.
return new goog.db.Error(/** @type {!DOMError} */ (ex), message);
} else if ('code' in ex) {
// Chrome 22+.
var errorName = goog.db.Error.getName(ex.code);
return new goog.db.Error(
/** @type {!DOMError} */ ({name: errorName}), message);
} else {
return new goog.db.Error(/** @type {!DOMError} */ (
{name: goog.db.Error.ErrorName.UNKNOWN_ERR}), message);
}
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper for an IndexedDB transaction.
*
*/
goog.provide('goog.db.Transaction');
goog.provide('goog.db.Transaction.TransactionMode');
goog.require('goog.async.Deferred');
goog.require('goog.db.Error');
goog.require('goog.db.ObjectStore');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
/**
* Creates a new transaction. Transactions contain methods for accessing object
* stores and are created from the database object. Should not be created
* directly, open a database and call createTransaction on it.
* @see goog.db.IndexedDb#createTransaction
*
* @param {!IDBTransaction} tx IndexedDB transaction to back this wrapper.
* @param {!goog.db.IndexedDb} db The database that this transaction modifies.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.db.Transaction = function(tx, db) {
goog.base(this);
/**
* Underlying IndexedDB transaction object.
*
* @type {!IDBTransaction}
* @private
*/
this.tx_ = tx;
/**
* The database that this transaction modifies.
*
* @type {!goog.db.IndexedDb}
* @private
*/
this.db_ = db;
/**
* Event handler for this transaction.
*
* @type {!goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
// TODO(user): remove these casts once the externs file is updated to
// correctly reflect that IDBTransaction extends EventTarget
this.eventHandler_.listen(
/** @type {EventTarget} */ (this.tx_),
'complete',
goog.bind(
this.dispatchEvent,
this,
goog.db.Transaction.EventTypes.COMPLETE));
this.eventHandler_.listen(
/** @type {EventTarget} */ (this.tx_),
'abort',
goog.bind(
this.dispatchEvent,
this,
goog.db.Transaction.EventTypes.ABORT));
this.eventHandler_.listen(
/** @type {EventTarget} */ (this.tx_),
'error',
this.dispatchError_);
};
goog.inherits(goog.db.Transaction, goog.events.EventTarget);
/**
* Dispatches an error event based on the given event, wrapping the error
* if necessary.
*
* @param {Event} ev The error event given to the underlying IDBTransaction.
* @private
*/
goog.db.Transaction.prototype.dispatchError_ = function(ev) {
if (ev.target instanceof goog.db.Error) {
this.dispatchEvent({
type: goog.db.Transaction.EventTypes.ERROR,
target: ev.target
});
} else {
this.dispatchEvent({
type: goog.db.Transaction.EventTypes.ERROR,
target: goog.db.Error.fromRequest(
/** @type {!IDBRequest} */ (ev.target), 'in transaction')
});
}
};
/**
* Event types the Transaction can dispatch. COMPLETE events are dispatched
* when the transaction is committed. If a transaction is aborted it dispatches
* both an ABORT event and an ERROR event with the ABORT_ERR code. Error events
* are dispatched on any error.
*
* @enum {string}
*/
goog.db.Transaction.EventTypes = {
COMPLETE: 'complete',
ABORT: 'abort',
ERROR: 'error'
};
/**
* @return {goog.db.Transaction.TransactionMode} The transaction's mode.
*/
goog.db.Transaction.prototype.getMode = function() {
return /** @type {goog.db.Transaction.TransactionMode} */ (this.tx_.mode);
};
/**
* @return {!goog.db.IndexedDb} The database that this transaction modifies.
*/
goog.db.Transaction.prototype.getDatabase = function() {
return this.db_;
};
/**
* Opens an object store to do operations on in this transaction. The requested
* object store must be one that is in this transaction's scope.
* @see goog.db.IndexedDb#createTransaction
*
* @param {string} name The name of the requested object store.
* @return {!goog.db.ObjectStore} The wrapped object store.
* @throws {goog.db.Error} In case of error getting the object store.
*/
goog.db.Transaction.prototype.objectStore = function(name) {
try {
return new goog.db.ObjectStore(this.tx_.objectStore(name));
} catch (ex) {
throw goog.db.Error.fromException(ex, 'getting object store ' + name);
}
};
/**
* @return {!goog.async.Deferred} A deferred that will fire once the
* transaction is complete. It fires the errback chain if an error occurs
* in the transaction, or if it is aborted.
*/
goog.db.Transaction.prototype.wait = function() {
var d = new goog.async.Deferred();
goog.events.listenOnce(
this, goog.db.Transaction.EventTypes.COMPLETE, goog.bind(d.callback, d));
goog.events.listenOnce(
this, goog.db.Transaction.EventTypes.ABORT, function() {
d.errback(new goog.db.Error(goog.db.Error.ErrorCode.ABORT_ERR,
'waiting for transaction to complete'));
});
goog.events.listenOnce(
this, goog.db.Transaction.EventTypes.ERROR, function(e) {
d.errback(e.target);
});
var db = this.getDatabase();
return d.addCallback(function() {
return db;
});
};
/**
* Aborts this transaction. No pending operations will be applied to the
* database. Dispatches an ABORT event.
*/
goog.db.Transaction.prototype.abort = function() {
this.tx_.abort();
};
/** @override */
goog.db.Transaction.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.eventHandler_.dispose();
};
/**
* The three possible transaction modes.
* @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBTransaction
*
* @enum {string}
*/
goog.db.Transaction.TransactionMode = {
READ_ONLY: 'readonly',
READ_WRITE: 'readwrite',
VERSION_CHANGE: 'versionchange'
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper for a IndexedDB cursor.
*
*/
goog.provide('goog.db.Cursor');
goog.require('goog.async.Deferred');
goog.require('goog.db.Error');
goog.require('goog.debug');
goog.require('goog.events.EventTarget');
/**
* Creates a new IDBCursor wrapper object. Should not be created directly,
* access cursor through object store.
* @see goog.db.ObjectStore#openCursor
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.db.Cursor = function() {
goog.base(this);
};
goog.inherits(goog.db.Cursor, goog.events.EventTarget);
/**
* Underlying IndexedDB cursor object.
*
* @type {IDBCursor}
* @private
*/
goog.db.Cursor.prototype.cursor_ = null;
/**
* Advances the cursor to the next position along its direction. When new data
* is available, the NEW_DATA event will be fired. If the cursor has reached the
* end of the range it will fire the COMPLETE event. If opt_key is specified it
* will advance to the key it matches in its direction.
*
* This wraps the native #continue method on the underlying object.
*
* @param {IDBKeyType=} opt_key The optional key to advance to.
*/
goog.db.Cursor.prototype.next = function(opt_key) {
if (opt_key) {
this.cursor_['continue'](opt_key);
} else {
this.cursor_['continue']();
}
};
/**
* Updates the value at the current position of the cursor in the object store.
* If the cursor points to a value that has just been deleted, a new value is
* created.
*
* @param {*} value The value to be stored.
* @return {!goog.async.Deferred} The resulting deferred request.
*/
goog.db.Cursor.prototype.update = function(value) {
var msg = 'updating via cursor with value ';
var d = new goog.async.Deferred();
var request;
try {
request = this.cursor_.update(value);
} catch (err) {
msg += goog.debug.deepExpose(value);
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback();
};
request.onerror = function(ev) {
msg += goog.debug.deepExpose(value);
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Deletes the value at the cursor's position, without changing the cursor's
* position. Once the value is deleted, the cursor's value is set to null.
*
* @return {!goog.async.Deferred} The resulting deferred request.
*/
goog.db.Cursor.prototype.remove = function() {
var msg = 'deleting via cursor';
var d = new goog.async.Deferred();
var request;
try {
request = this.cursor_['delete']();
} catch (err) {
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback();
};
request.onerror = function(ev) {
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* @return {*} The value for the value at the cursor's position. Undefined
* if no current value, or null if value has just been deleted.
*/
goog.db.Cursor.prototype.getValue = function() {
return this.cursor_['value'];
};
/**
* @return {IDBKeyType} The key for the value at the cursor's position. If
* the cursor is outside its range, this is undefined.
*/
goog.db.Cursor.prototype.getKey = function() {
return this.cursor_.key;
};
/**
* Possible cursor directions.
* @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBCursor
*
* @enum {string}
*/
goog.db.Cursor.Direction = {
NEXT: 'next',
NEXT_NO_DUPLICATE: 'nextunique',
PREV: 'prev',
PREV_NO_DUPLICATE: 'prevunique'
};
/**
* Event types that the cursor can dispatch. COMPLETE events are dispatched when
* a cursor is depleted of values, a NEW_DATA event if there is new data
* available, and ERROR if an error occurred.
*
* @enum {string}
*/
goog.db.Cursor.EventType = {
COMPLETE: 'c',
ERROR: 'e',
NEW_DATA: 'n'
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper for an IndexedDB index.
*
*/
goog.provide('goog.db.Index');
goog.require('goog.async.Deferred');
goog.require('goog.db.Error');
goog.require('goog.debug');
/**
* Creates an IDBIndex wrapper object. Indexes are associated with object
* stores and provide methods for looking up objects based on their non-key
* properties. Should not be created directly, access through the object store
* it belongs to.
* @see goog.db.ObjectStore#getIndex
*
* @param {!IDBIndex} index Underlying IDBIndex object.
* @constructor
*/
goog.db.Index = function(index) {
/**
* Underlying IndexedDB index object.
*
* @type {!IDBIndex}
* @private
*/
this.index_ = index;
};
/**
* @return {string} Name of the index.
*/
goog.db.Index.prototype.getName = function() {
return this.index_.name;
};
/**
* @return {string} Key path of the index.
*/
goog.db.Index.prototype.getKeyPath = function() {
return this.index_.keyPath;
};
/**
* @return {boolean} True if the index enforces that there is only one object
* for each unique value it indexes on.
*/
goog.db.Index.prototype.isUnique = function() {
return this.index_.unique;
};
/**
* Helper function for get and getKey.
*
* @param {string} fn Function name to call on the index to get the request.
* @param {string} msg Message to give to the error.
* @param {IDBKeyType} key The key to look up in the index.
* @return {!goog.async.Deferred} The resulting deferred object.
* @private
*/
goog.db.Index.prototype.get_ = function(fn, msg, key) {
var d = new goog.async.Deferred();
var request;
try {
request = this.index_[fn](key);
} catch (err) {
msg += ' with key ' + goog.debug.deepExpose(key);
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback(ev.target.result);
};
request.onerror = function(ev) {
msg += ' with key ' + goog.debug.deepExpose(key);
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Fetches a single object from the object store. Even if there are multiple
* objects that match the given key, this method will get only one of them.
*
* @param {IDBKeyType} key Key to look up in the index.
* @return {!goog.async.Deferred} The deferred object for the given record.
*/
goog.db.Index.prototype.get = function(key) {
return this.get_('get', 'getting from index ' + this.getName(), key);
};
/**
* Looks up a single object from the object store and gives back the key that
* it's listed under in the object store. Even if there are multiple records
* that match the given key, this method returns the first.
*
* @param {IDBKeyType} key Key to look up in the index.
* @return {!goog.async.Deferred} The deferred key for the record that matches
* the key.
*/
goog.db.Index.prototype.getKey = function(key) {
return this.get_('getKey', 'getting key from index ' + this.getName(), key);
};
/**
* Helper function for getAll and getAllKeys.
*
* @param {string} fn Function name to call on the index to get the request.
* @param {string} msg Message to give to the error.
* @param {IDBKeyType=} opt_key Key to look up in the index.
* @return {!goog.async.Deferred} The resulting deferred array of objects.
* @private
*/
goog.db.Index.prototype.getAll_ = function(fn, msg, opt_key) {
// This is the most common use of IDBKeyRange. If more specific uses of
// cursors are needed then a full wrapper should be created.
var IDBKeyRange = goog.global.IDBKeyRange || goog.global.webkitIDBKeyRange;
var d = new goog.async.Deferred();
var request;
try {
if (opt_key) {
request = this.index_[fn](IDBKeyRange.only(opt_key));
} else {
request = this.index_[fn]();
}
} catch (err) {
if (opt_key) {
msg += ' for key ' + goog.debug.deepExpose(opt_key);
}
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
var result = [];
request.onsuccess = function(ev) {
var cursor = ev.target.result;
if (cursor) {
result.push(cursor.value);
cursor['continue']();
} else {
d.callback(result);
}
};
request.onerror = function(ev) {
if (opt_key) {
msg += ' for key ' + goog.debug.deepExpose(opt_key);
}
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Gets all indexed objects. If the key is provided, gets all indexed objects
* that match the key instead.
*
* @param {IDBKeyType=} opt_key Key to look up in the index.
* @return {!goog.async.Deferred} A deferred array of objects that match the
* key.
*/
goog.db.Index.prototype.getAll = function(opt_key) {
return this.getAll_(
'openCursor',
'getting all from index ' + this.getName(),
opt_key);
};
/**
* Gets the keys to look up all the indexed objects. If the key is provided,
* gets all records for objects that match the key instead.
*
* @param {IDBKeyType=} opt_key Key to look up in the index.
* @return {!goog.async.Deferred} A deferred array of keys for objects that
* match the key.
*/
goog.db.Index.prototype.getAllKeys = function(opt_key) {
return this.getAll_(
'openKeyCursor',
'getting all keys from index ' + this.getName(),
opt_key);
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Wrapper for an IndexedDB object store.
*
*/
goog.provide('goog.db.ObjectStore');
goog.require('goog.async.Deferred');
goog.require('goog.db.Cursor');
goog.require('goog.db.Error');
goog.require('goog.db.Index');
goog.require('goog.debug');
goog.require('goog.events');
/**
* Creates an IDBObjectStore wrapper object. Object stores have methods for
* storing and retrieving records, and are accessed through a transaction
* object. They also have methods for creating indexes associated with the
* object store. They can only be created when setting the version of the
* database. Should not be created directly, access object stores through
* transactions.
* @see goog.db.IndexedDb#setVersion
* @see goog.db.Transaction#objectStore
*
* @param {!IDBObjectStore} store The backing IndexedDb object.
* @constructor
*/
goog.db.ObjectStore = function(store) {
/**
* Underlying IndexedDB object store object.
*
* @type {!IDBObjectStore}
* @private
*/
this.store_ = store;
};
/**
* @return {string} The name of the object store.
*/
goog.db.ObjectStore.prototype.getName = function() {
return this.store_.name;
};
/**
* Helper function for put and add.
*
* @param {string} fn Function name to call on the object store.
* @param {string} msg Message to give to the error.
* @param {*} value Value to insert into the object store.
* @param {IDBKeyType=} opt_key The key to use.
* @return {!goog.async.Deferred} The resulting deferred request.
* @private
*/
goog.db.ObjectStore.prototype.insert_ = function(fn, msg, value, opt_key) {
// TODO(user): refactor wrapping an IndexedDB request in a Deferred by
// creating a higher-level abstraction for it (mostly affects here and
// goog.db.Index)
var d = new goog.async.Deferred();
var request;
try {
// put or add with (value, undefined) throws an error, so we need to check
// for undefined ourselves
if (opt_key) {
request = this.store_[fn](value, opt_key);
} else {
request = this.store_[fn](value);
}
} catch (ex) {
msg += goog.debug.deepExpose(value);
if (opt_key) {
msg += ', with key ' + goog.debug.deepExpose(opt_key);
}
d.errback(goog.db.Error.fromException(ex, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback();
};
var self = this;
request.onerror = function(ev) {
msg += goog.debug.deepExpose(value);
if (opt_key) {
msg += ', with key ' + goog.debug.deepExpose(opt_key);
}
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Adds an object to the object store. Replaces existing objects with the
* same key.
*
* @param {*} value The value to put.
* @param {IDBKeyType=} opt_key The key to use. Cannot be used if the
* keyPath was specified for the object store. If the keyPath was not
* specified but autoIncrement was not enabled, it must be used.
* @return {!goog.async.Deferred} The deferred put request.
*/
goog.db.ObjectStore.prototype.put = function(value, opt_key) {
return this.insert_(
'put',
'putting into ' + this.getName() + ' with value',
value,
opt_key);
};
/**
* Adds an object to the object store. Requires that there is no object with
* the same key already present.
*
* @param {*} value The value to add.
* @param {IDBKeyType=} opt_key The key to use. Cannot be used if the
* keyPath was specified for the object store. If the keyPath was not
* specified but autoIncrement was not enabled, it must be used.
* @return {!goog.async.Deferred} The deferred add request.
*/
goog.db.ObjectStore.prototype.add = function(value, opt_key) {
return this.insert_(
'add',
'adding into ' + this.getName() + ' with value ',
value,
opt_key);
};
/**
* Removes an object from the store. No-op if there is no object present with
* the given key.
*
* @param {IDBKeyType} key The key to remove objects under.
* @return {!goog.async.Deferred} The deferred remove request.
*/
goog.db.ObjectStore.prototype.remove = function(key) {
var d = new goog.async.Deferred();
var request;
try {
request = this.store_['delete'](key);
} catch (err) {
var msg = 'removing from ' + this.getName() + ' with key ' +
goog.debug.deepExpose(key);
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback();
};
var self = this;
request.onerror = function(ev) {
var msg = 'removing from ' + self.getName() + ' with key ' +
goog.debug.deepExpose(key);
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Gets an object from the store. If no object is present with that key
* the result is {@code undefined}.
*
* @param {IDBKeyType} key The key to look up.
* @return {!goog.async.Deferred} The deferred get request.
*/
goog.db.ObjectStore.prototype.get = function(key) {
var d = new goog.async.Deferred();
var request;
try {
request = this.store_.get(key);
} catch (err) {
var msg = 'getting from ' + this.getName() + ' with key ' +
goog.debug.deepExpose(key);
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback(ev.target.result);
};
var self = this;
request.onerror = function(ev) {
var msg = 'getting from ' + self.getName() + ' with key ' +
goog.debug.deepExpose(key);
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Gets all objects from the store and returns them as an array.
*
* @param {!goog.db.KeyRange=} opt_range The key range. If undefined iterates
* over the whole object store.
* @param {!goog.db.Cursor.Direction=} opt_direction The direction. If undefined
* moves in a forward direction with duplicates.
* @return {!goog.async.Deferred} The deferred getAll request.
*/
goog.db.ObjectStore.prototype.getAll = function(opt_range, opt_direction) {
var d = new goog.async.Deferred();
var cursor;
try {
cursor = this.openCursor(opt_range, opt_direction);
} catch (err) {
d.errback(err);
return d;
}
var result = [];
var key = goog.events.listen(
cursor, goog.db.Cursor.EventType.NEW_DATA, function() {
result.push(cursor.getValue());
cursor.next();
});
goog.events.listenOnce(cursor, [
goog.db.Cursor.EventType.ERROR,
goog.db.Cursor.EventType.COMPLETE
], function(evt) {
cursor.dispose();
if (evt.type == goog.db.Cursor.EventType.COMPLETE) {
d.callback(result);
} else {
d.errback();
}
});
return d;
};
/**
* Opens a cursor over the specified key range. Returns a cursor object which is
* able to iterate over the given range.
*
* Example usage:
*
* <code>
* var cursor = objectStore.openCursor(goog.db.Range.bound('a', 'c'));
*
* var key = goog.events.listen(
* cursor, goog.db.Cursor.EventType.NEW_DATA, function() {
* // Do something with data.
* cursor.next();
* });
*
* goog.events.listenOnce(
* cursor, goog.db.Cursor.EventType.COMPLETE, function() {
* // Clean up listener, and perform a finishing operation on the data.
* goog.events.unlistenByKey(key);
* });
* </code>
*
* @param {!goog.db.KeyRange=} opt_range The key range. If undefined iterates
* over the whole object store.
* @param {!goog.db.Cursor.Direction=} opt_direction The direction. If undefined
* moves in a forward direction with duplicates.
* @return {!goog.db.Cursor} The cursor.
* @throws {goog.db.Error} If there was a problem opening the cursor.
* @suppress {accessControls}
*/
goog.db.ObjectStore.prototype.openCursor = function(opt_range, opt_direction) {
var msg = 'opening cursor ' + this.getName();
var cursor = new goog.db.Cursor();
var request;
try {
var range = opt_range ? opt_range.range_ : null;
if (opt_direction) {
request = this.store_.openCursor(range, opt_direction);
} else {
request = this.store_.openCursor(range);
}
} catch (ex) {
cursor.dispose();
throw goog.db.Error.fromException(ex, msg);
}
request.onsuccess = function(ev) {
cursor.cursor_ = ev.target.result || null;
if (cursor.cursor_) {
cursor.dispatchEvent(goog.db.Cursor.EventType.NEW_DATA);
} else {
cursor.dispatchEvent(goog.db.Cursor.EventType.COMPLETE);
}
};
request.onerror = function(ev) {
cursor.dispatchEvent(goog.db.Cursor.EventType.ERROR);
};
return cursor;
};
/**
* Deletes all objects from the store.
*
* @return {!goog.async.Deferred} The deferred clear request.
*/
goog.db.ObjectStore.prototype.clear = function() {
var msg = 'clearing store ' + this.getName();
var d = new goog.async.Deferred();
var request;
try {
request = this.store_.clear();
} catch (err) {
d.errback(goog.db.Error.fromException(err, msg));
return d;
}
request.onsuccess = function(ev) {
d.callback();
};
request.onerror = function(ev) {
d.errback(goog.db.Error.fromRequest(ev.target, msg));
};
return d;
};
/**
* Creates an index in this object store. Can only be called inside the callback
* for the Deferred returned from goog.db.IndexedDb#setVersion.
*
* @param {string} name Name of the index to create.
* @param {string} keyPath Attribute to index on.
* @param {!Object=} opt_parameters Optional parameters object. The only
* available option is unique, which defaults to false. If unique is true,
* the index will enforce that there is only ever one object in the object
* store for each unique value it indexes on.
* @return {goog.db.Index} The newly created, wrapped index.
* @throws {goog.db.Error} In case of an error creating the index.
*/
goog.db.ObjectStore.prototype.createIndex = function(
name, keyPath, opt_parameters) {
try {
return new goog.db.Index(this.store_.createIndex(
name, keyPath, opt_parameters));
} catch (ex) {
var msg = 'creating new index ' + name + ' with key path ' + keyPath;
throw goog.db.Error.fromException(ex, msg);
}
};
/**
* Gets an index.
*
* @param {string} name Name of the index to fetch.
* @return {goog.db.Index} The requested wrapped index.
* @throws {goog.db.Error} In case of an error getting the index.
*/
goog.db.ObjectStore.prototype.getIndex = function(name) {
try {
return new goog.db.Index(this.store_.index(name));
} catch (ex) {
var msg = 'getting index ' + name;
throw goog.db.Error.fromException(ex, msg);
}
};
/**
* Deletes an index from the object store. Can only be called inside the
* callback for the Deferred returned from goog.db.IndexedDb#setVersion.
*
* @param {string} name Name of the index to delete.
* @throws {goog.db.Error} In case of an error deleting the index.
*/
goog.db.ObjectStore.prototype.deleteIndex = function(name) {
try {
this.store_.deleteIndex(name);
} catch (ex) {
var msg = 'deleting index ' + name;
throw goog.db.Error.fromException(ex, msg);
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for manipulating arrays.
*
*/
goog.provide('goog.array');
goog.provide('goog.array.ArrayLike');
goog.require('goog.asserts');
/**
* @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
* rely on Array.prototype functions, if available.
*
* The Array.prototype functions can be defined by external libraries like
* Prototype and setting this flag to false forces closure to use its own
* goog.array implementation.
*
* If your javascript can be loaded by a third party site and you are wary about
* relying on the prototype functions, specify
* "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
*
* Setting goog.TRUSTED_SITE to false will automatically set
* NATIVE_ARRAY_PROTOTYPES to false.
*/
goog.NATIVE_ARRAY_PROTOTYPES = goog.TRUSTED_SITE;
/**
* @typedef {Array|NodeList|Arguments|{length: number}}
*/
goog.array.ArrayLike;
/**
* Returns the last element in an array without removing it.
* @param {goog.array.ArrayLike} array The array.
* @return {*} Last item in array.
*/
goog.array.peek = function(array) {
return array[array.length - 1];
};
/**
* Reference to the original {@code Array.prototype}.
* @private
*/
goog.array.ARRAY_PROTOTYPE_ = Array.prototype;
// NOTE(arv): Since most of the array functions are generic it allows you to
// pass an array-like object. Strings have a length and are considered array-
// like. However, the 'in' operator does not work on strings so we cannot just
// use the array path even if the browser supports indexing into strings. We
// therefore end up splitting the string.
/**
* Returns the index of the first element of an array with a specified
* value, or -1 if the element is not present in the array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
*
* @param {goog.array.ArrayLike} arr The array to be searched.
* @param {*} obj The object for which we are searching.
* @param {number=} opt_fromIndex The index at which to start the search. If
* omitted the search starts at index 0.
* @return {number} The index of the first matching array element.
*/
goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.indexOf ?
function(arr, obj, opt_fromIndex) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex == null ?
0 : (opt_fromIndex < 0 ?
Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
if (goog.isString(arr)) {
// Array.prototype.indexOf uses === so only strings should be found.
if (!goog.isString(obj) || obj.length != 1) {
return -1;
}
return arr.indexOf(obj, fromIndex);
}
for (var i = fromIndex; i < arr.length; i++) {
if (i in arr && arr[i] === obj)
return i;
}
return -1;
};
/**
* Returns the index of the last element of an array with a specified value, or
* -1 if the element is not present in the array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
*
* @param {goog.array.ArrayLike} arr The array to be searched.
* @param {*} obj The object for which we are searching.
* @param {?number=} opt_fromIndex The index at which to start the search. If
* omitted the search starts at the end of the array.
* @return {number} The index of the last matching array element.
*/
goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.lastIndexOf ?
function(arr, obj, opt_fromIndex) {
goog.asserts.assert(arr.length != null);
// Firefox treats undefined and null as 0 in the fromIndex argument which
// leads it to always return -1
var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
return goog.array.ARRAY_PROTOTYPE_.lastIndexOf.call(arr, obj, fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
if (fromIndex < 0) {
fromIndex = Math.max(0, arr.length + fromIndex);
}
if (goog.isString(arr)) {
// Array.prototype.lastIndexOf uses === so only strings should be found.
if (!goog.isString(obj) || obj.length != 1) {
return -1;
}
return arr.lastIndexOf(obj, fromIndex);
}
for (var i = fromIndex; i >= 0; i--) {
if (i in arr && arr[i] === obj)
return i;
}
return -1;
};
/**
* Calls a function for each element in an array. Skips holes in the array.
* See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
* which to iterate.
* @param {?function(this: S, T, number, ?): ?} f The function to call for every
* element. This function takes 3 arguments (the element, the index and the
* array). The return value is ignored.
* @param {S=} opt_obj The object to be used as the value of 'this' within f.
* @template T,S
*/
goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.forEach ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
f.call(opt_obj, arr2[i], i, arr);
}
}
};
/**
* Calls a function for each element in an array, starting from the last
* element rather than the first.
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this: S, T, number, ?): ?} f The function to call for every
* element. This function
* takes 3 arguments (the element, the index and the array). The return
* value is ignored.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @template T,S
*/
goog.array.forEachRight = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = l - 1; i >= 0; --i) {
if (i in arr2) {
f.call(opt_obj, arr2[i], i, arr);
}
}
};
/**
* Calls a function for each element in an array, and if the function returns
* true adds the element to a new array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?):boolean} f The function to call for
* every element. This function
* takes 3 arguments (the element, the index and the array) and must
* return a Boolean. If the return value is true the element is added to the
* result array. If it is false the element is not included.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {!Array} a new array in which only elements that passed the test are
* present.
* @template T,S
*/
goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.filter ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var res = [];
var resLength = 0;
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
var val = arr2[i]; // in case f mutates arr2
if (f.call(opt_obj, val, i, arr)) {
res[resLength++] = val;
}
}
}
return res;
};
/**
* Calls a function for each element in an array and inserts the result into a
* new array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-map}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?):?} f The function to call for every
* element. This function
* takes 3 arguments (the element, the index and the array) and should
* return something. The result will be inserted into a new array.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {!Array} a new array with the results from f.
* @template T,S
*/
goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.map ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var res = new Array(l);
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
res[i] = f.call(opt_obj, arr2[i], i, arr);
}
}
return res;
};
/**
* Passes every element of an array into a function and accumulates the result.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
*
* For example:
* var a = [1, 2, 3, 4];
* goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
* returns 10
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, R, T, number, ?) : R} f The function to call for
* every element. This function
* takes 4 arguments (the function's previous result or the initial value,
* the value of the current array element, the current array index, and the
* array itself)
* function(previousValue, currentValue, index, array).
* @param {?} val The initial value to pass into the function on the first call.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {R} Result of evaluating f repeatedly across the values of the array.
* @template T,S,R
*/
goog.array.reduce = function(arr, f, val, opt_obj) {
if (arr.reduce) {
if (opt_obj) {
return arr.reduce(goog.bind(f, opt_obj), val);
} else {
return arr.reduce(f, val);
}
}
var rval = val;
goog.array.forEach(arr, function(val, index) {
rval = f.call(opt_obj, rval, val, index, arr);
});
return rval;
};
/**
* Passes every element of an array into a function and accumulates the result,
* starting from the last element and working towards the first.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
*
* For example:
* var a = ['a', 'b', 'c'];
* goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
* returns 'cba'
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, R, T, number, ?) : R} f The function to call for
* every element. This function
* takes 4 arguments (the function's previous result or the initial value,
* the value of the current array element, the current array index, and the
* array itself)
* function(previousValue, currentValue, index, array).
* @param {?} val The initial value to pass into the function on the first call.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {R} Object returned as a result of evaluating f repeatedly across the
* values of the array.
* @template T,S,R
*/
goog.array.reduceRight = function(arr, f, val, opt_obj) {
if (arr.reduceRight) {
if (opt_obj) {
return arr.reduceRight(goog.bind(f, opt_obj), val);
} else {
return arr.reduceRight(f, val);
}
}
var rval = val;
goog.array.forEachRight(arr, function(val, index) {
rval = f.call(opt_obj, rval, val, index, arr);
});
return rval;
};
/**
* Calls f for each element of an array. If any call returns true, some()
* returns true (without checking the remaining elements). If all calls
* return false, some() returns false.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-some}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {boolean} true if any element passes the test.
* @template T,S
*/
goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.some ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return true;
}
}
return false;
};
/**
* Call f for each element of an array. If all calls return true, every()
* returns true. If any call returns false, every() returns false and
* does not continue to check the remaining elements.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-every}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {boolean} false if any element fails the test.
* @template T,S
*/
goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.every ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) {
return false;
}
}
return true;
};
/**
* Counts the array elements that fulfill the predicate, i.e. for which the
* callback function returns true. Skips holes in the array.
*
* @param {!(Array.<T>|goog.array.ArrayLike)} arr Array or array like object
* over which to iterate.
* @param {function(this: S, T, number, ?): boolean} f The function to call for
* every element. Takes 3 arguments (the element, the index and the array).
* @param {S=} opt_obj The object to be used as the value of 'this' within f.
* @return {number} The number of the matching elements.
* @template T,S
*/
goog.array.count = function(arr, f, opt_obj) {
var count = 0;
goog.array.forEach(arr, function(element, index, arr) {
if (f.call(opt_obj, element, index, arr)) {
++count;
}
}, opt_obj);
return count;
};
/**
* Search an array for the first element that satisfies a given condition and
* return that element.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {T} The first array element that passes the test, or null if no
* element is found.
* @template T,S
*/
goog.array.find = function(arr, f, opt_obj) {
var i = goog.array.findIndex(arr, f, opt_obj);
return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
};
/**
* Search an array for the first element that satisfies a given condition and
* return its index.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {number} The index of the first array element that passes the test,
* or -1 if no element is found.
* @template T,S
*/
goog.array.findIndex = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return i;
}
}
return -1;
};
/**
* Search an array (in reverse order) for the last element that satisfies a
* given condition and return that element.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {T} The last array element that passes the test, or null if no
* element is found.
* @template T,S
*/
goog.array.findRight = function(arr, f, opt_obj) {
var i = goog.array.findIndexRight(arr, f, opt_obj);
return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
};
/**
* Search an array (in reverse order) for the last element that satisfies a
* given condition and return its index.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {Object=} opt_obj An optional "this" context for the function.
* @return {number} The index of the last array element that passes the test,
* or -1 if no element is found.
* @template T,S
*/
goog.array.findIndexRight = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = l - 1; i >= 0; i--) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return i;
}
}
return -1;
};
/**
* Whether the array contains the given object.
* @param {goog.array.ArrayLike} arr The array to test for the presence of the
* element.
* @param {*} obj The object for which to test.
* @return {boolean} true if obj is present.
*/
goog.array.contains = function(arr, obj) {
return goog.array.indexOf(arr, obj) >= 0;
};
/**
* Whether the array is empty.
* @param {goog.array.ArrayLike} arr The array to test.
* @return {boolean} true if empty.
*/
goog.array.isEmpty = function(arr) {
return arr.length == 0;
};
/**
* Clears the array.
* @param {goog.array.ArrayLike} arr Array or array like object to clear.
*/
goog.array.clear = function(arr) {
// For non real arrays we don't have the magic length so we delete the
// indices.
if (!goog.isArray(arr)) {
for (var i = arr.length - 1; i >= 0; i--) {
delete arr[i];
}
}
arr.length = 0;
};
/**
* Pushes an item into an array, if it's not already in the array.
* @param {Array.<T>} arr Array into which to insert the item.
* @param {T} obj Value to add.
* @template T
*/
goog.array.insert = function(arr, obj) {
if (!goog.array.contains(arr, obj)) {
arr.push(obj);
}
};
/**
* Inserts an object at the given index of the array.
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {*} obj The object to insert.
* @param {number=} opt_i The index at which to insert the object. If omitted,
* treated as 0. A negative index is counted from the end of the array.
*/
goog.array.insertAt = function(arr, obj, opt_i) {
goog.array.splice(arr, opt_i, 0, obj);
};
/**
* Inserts at the given index of the array, all elements of another array.
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {goog.array.ArrayLike} elementsToAdd The array of elements to add.
* @param {number=} opt_i The index at which to insert the object. If omitted,
* treated as 0. A negative index is counted from the end of the array.
*/
goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
};
/**
* Inserts an object into an array before a specified object.
* @param {Array.<T>} arr The array to modify.
* @param {T} obj The object to insert.
* @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
* is omitted or not found, obj is inserted at the end of the array.
* @template T
*/
goog.array.insertBefore = function(arr, obj, opt_obj2) {
var i;
if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
arr.push(obj);
} else {
goog.array.insertAt(arr, obj, i);
}
};
/**
* Removes the first occurrence of a particular value from an array.
* @param {goog.array.ArrayLike} arr Array from which to remove value.
* @param {*} obj Object to remove.
* @return {boolean} True if an element was removed.
*/
goog.array.remove = function(arr, obj) {
var i = goog.array.indexOf(arr, obj);
var rv;
if ((rv = i >= 0)) {
goog.array.removeAt(arr, i);
}
return rv;
};
/**
* Removes from an array the element at index i
* @param {goog.array.ArrayLike} arr Array or array like object from which to
* remove value.
* @param {number} i The index to remove.
* @return {boolean} True if an element was removed.
*/
goog.array.removeAt = function(arr, i) {
goog.asserts.assert(arr.length != null);
// use generic form of splice
// splice returns the removed items and if successful the length of that
// will be 1
return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;
};
/**
* Removes the first value that satisfies the given condition.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {boolean} True if an element was removed.
* @template T,S
*/
goog.array.removeIf = function(arr, f, opt_obj) {
var i = goog.array.findIndex(arr, f, opt_obj);
if (i >= 0) {
goog.array.removeAt(arr, i);
return true;
}
return false;
};
/**
* Returns a new array that is the result of joining the arguments. If arrays
* are passed then their items are added, however, if non-arrays are passed they
* will be added to the return array as is.
*
* Note that ArrayLike objects will be added as is, rather than having their
* items added.
*
* goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
* goog.array.concat(0, [1, 2]) -> [0, 1, 2]
* goog.array.concat([1, 2], null) -> [1, 2, null]
*
* There is bug in all current versions of IE (6, 7 and 8) where arrays created
* in an iframe become corrupted soon (not immediately) after the iframe is
* destroyed. This is common if loading data via goog.net.IframeIo, for example.
* This corruption only affects the concat method which will start throwing
* Catastrophic Errors (#-2147418113).
*
* See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
*
* Internally goog.array should use this, so that all methods will continue to
* work on these broken array objects.
*
* @param {...*} var_args Items to concatenate. Arrays will have each item
* added, while primitives and objects will be added as is.
* @return {!Array} The new resultant array.
*/
goog.array.concat = function(var_args) {
return goog.array.ARRAY_PROTOTYPE_.concat.apply(
goog.array.ARRAY_PROTOTYPE_, arguments);
};
/**
* Converts an object to an array.
* @param {goog.array.ArrayLike} object The object to convert to an array.
* @return {!Array} The object converted into an array. If object has a
* length property, every property indexed with a non-negative number
* less than length will be included in the result. If object does not
* have a length property, an empty array will be returned.
*/
goog.array.toArray = function(object) {
var length = object.length;
// If length is not a number the following it false. This case is kept for
// backwards compatibility since there are callers that pass objects that are
// not array like.
if (length > 0) {
var rv = new Array(length);
for (var i = 0; i < length; i++) {
rv[i] = object[i];
}
return rv;
}
return [];
};
/**
* Does a shallow copy of an array.
* @param {goog.array.ArrayLike} arr Array or array-like object to clone.
* @return {!Array} Clone of the input array.
*/
goog.array.clone = goog.array.toArray;
/**
* Extends an array with another array, element, or "array like" object.
* This function operates 'in-place', it does not create a new Array.
*
* Example:
* var a = [];
* goog.array.extend(a, [0, 1]);
* a; // [0, 1]
* goog.array.extend(a, 2);
* a; // [0, 1, 2]
*
* @param {Array} arr1 The array to modify.
* @param {...*} var_args The elements or arrays of elements to add to arr1.
*/
goog.array.extend = function(arr1, var_args) {
for (var i = 1; i < arguments.length; i++) {
var arr2 = arguments[i];
// If we have an Array or an Arguments object we can just call push
// directly.
var isArrayLike;
if (goog.isArray(arr2) ||
// Detect Arguments. ES5 says that the [[Class]] of an Arguments object
// is "Arguments" but only V8 and JSC/Safari gets this right. We instead
// detect Arguments by checking for array like and presence of "callee".
(isArrayLike = goog.isArrayLike(arr2)) &&
// The getter for callee throws an exception in strict mode
// according to section 10.6 in ES5 so check for presence instead.
Object.prototype.hasOwnProperty.call(arr2, 'callee')) {
arr1.push.apply(arr1, arr2);
} else if (isArrayLike) {
// Otherwise loop over arr2 to prevent copying the object.
var len1 = arr1.length;
var len2 = arr2.length;
for (var j = 0; j < len2; j++) {
arr1[len1 + j] = arr2[j];
}
} else {
arr1.push(arr2);
}
}
};
/**
* Adds or removes elements from an array. This is a generic version of Array
* splice. This means that it might work on other objects similar to arrays,
* such as the arguments object.
*
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {number|undefined} index The index at which to start changing the
* array. If not defined, treated as 0.
* @param {number} howMany How many elements to remove (0 means no removal. A
* value below 0 is treated as zero and so is any other non number. Numbers
* are floored).
* @param {...*} var_args Optional, additional elements to insert into the
* array.
* @return {!Array} the removed elements.
*/
goog.array.splice = function(arr, index, howMany, var_args) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.splice.apply(
arr, goog.array.slice(arguments, 1));
};
/**
* Returns a new array from a segment of an array. This is a generic version of
* Array slice. This means that it might work on other objects similar to
* arrays, such as the arguments object.
*
* @param {Array.<T>|goog.array.ArrayLike} arr The array from
* which to copy a segment.
* @param {number} start The index of the first element to copy.
* @param {number=} opt_end The index after the last element to copy.
* @return {!Array.<T>} A new array containing the specified segment of the
* original array.
* @template T
*/
goog.array.slice = function(arr, start, opt_end) {
goog.asserts.assert(arr.length != null);
// passing 1 arg to slice is not the same as passing 2 where the second is
// null or undefined (in that case the second argument is treated as 0).
// we could use slice on the arguments object and then use apply instead of
// testing the length
if (arguments.length <= 2) {
return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
} else {
return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
}
};
/**
* Removes all duplicates from an array (retaining only the first
* occurrence of each array element). This function modifies the
* array in place and doesn't change the order of the non-duplicate items.
*
* For objects, duplicates are identified as having the same unique ID as
* defined by {@link goog.getUid}.
*
* Runtime: N,
* Worstcase space: 2N (no dupes)
*
* @param {goog.array.ArrayLike} arr The array from which to remove duplicates.
* @param {Array=} opt_rv An optional array in which to return the results,
* instead of performing the removal inplace. If specified, the original
* array will remain unchanged.
*/
goog.array.removeDuplicates = function(arr, opt_rv) {
var returnArray = opt_rv || arr;
var seen = {}, cursorInsert = 0, cursorRead = 0;
while (cursorRead < arr.length) {
var current = arr[cursorRead++];
// Prefix each type with a single character representing the type to
// prevent conflicting keys (e.g. true and 'true').
var key = goog.isObject(current) ?
'o' + goog.getUid(current) :
(typeof current).charAt(0) + current;
if (!Object.prototype.hasOwnProperty.call(seen, key)) {
seen[key] = true;
returnArray[cursorInsert++] = current;
}
}
returnArray.length = cursorInsert;
};
/**
* Searches the specified array for the specified target using the binary
* search algorithm. If no opt_compareFn is specified, elements are compared
* using <code>goog.array.defaultCompare</code>, which compares the elements
* using the built in < and > operators. This will produce the expected
* behavior for homogeneous arrays of String(s) and Number(s). The array
* specified <b>must</b> be sorted in ascending order (as defined by the
* comparison function). If the array is not sorted, results are undefined.
* If the array contains multiple instances of the specified target value, any
* of these instances may be found.
*
* Runtime: O(log n)
*
* @param {goog.array.ArrayLike} arr The array to be searched.
* @param {*} target The sought value.
* @param {Function=} opt_compareFn Optional comparison function by which the
* array is ordered. Should take 2 arguments to compare, and return a
* negative number, zero, or a positive number depending on whether the
* first argument is less than, equal to, or greater than the second.
* @return {number} Lowest index of the target value if found, otherwise
* (-(insertion point) - 1). The insertion point is where the value should
* be inserted into arr to preserve the sorted property. Return value >= 0
* iff target is found.
*/
goog.array.binarySearch = function(arr, target, opt_compareFn) {
return goog.array.binarySearch_(arr,
opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
target);
};
/**
* Selects an index in the specified array using the binary search algorithm.
* The evaluator receives an element and determines whether the desired index
* is before, at, or after it. The evaluator must be consistent (formally,
* goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
* must be monotonically non-increasing).
*
* Runtime: O(log n)
*
* @param {goog.array.ArrayLike} arr The array to be searched.
* @param {Function} evaluator Evaluator function that receives 3 arguments
* (the element, the index and the array). Should return a negative number,
* zero, or a positive number depending on whether the desired index is
* before, at, or after the element passed to it.
* @param {Object=} opt_obj The object to be used as the value of 'this'
* within evaluator.
* @return {number} Index of the leftmost element matched by the evaluator, if
* such exists; otherwise (-(insertion point) - 1). The insertion point is
* the index of the first element for which the evaluator returns negative,
* or arr.length if no such element exists. The return value is non-negative
* iff a match is found.
*/
goog.array.binarySelect = function(arr, evaluator, opt_obj) {
return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,
undefined /* opt_target */, opt_obj);
};
/**
* Implementation of a binary search algorithm which knows how to use both
* comparison functions and evaluators. If an evaluator is provided, will call
* the evaluator with the given optional data object, conforming to the
* interface defined in binarySelect. Otherwise, if a comparison function is
* provided, will call the comparison function against the given data object.
*
* This implementation purposefully does not use goog.bind or goog.partial for
* performance reasons.
*
* Runtime: O(log n)
*
* @param {goog.array.ArrayLike} arr The array to be searched.
* @param {Function} compareFn Either an evaluator or a comparison function,
* as defined by binarySearch and binarySelect above.
* @param {boolean} isEvaluator Whether the function is an evaluator or a
* comparison function.
* @param {*=} opt_target If the function is a comparison function, then this is
* the target to binary search for.
* @param {Object=} opt_selfObj If the function is an evaluator, this is an
* optional this object for the evaluator.
* @return {number} Lowest index of the target value if found, otherwise
* (-(insertion point) - 1). The insertion point is where the value should
* be inserted into arr to preserve the sorted property. Return value >= 0
* iff target is found.
* @private
*/
goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
opt_selfObj) {
var left = 0; // inclusive
var right = arr.length; // exclusive
var found;
while (left < right) {
var middle = (left + right) >> 1;
var compareResult;
if (isEvaluator) {
compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
} else {
compareResult = compareFn(opt_target, arr[middle]);
}
if (compareResult > 0) {
left = middle + 1;
} else {
right = middle;
// We are looking for the lowest index so we can't return immediately.
found = !compareResult;
}
}
// left is the index if found, or the insertion point otherwise.
// ~left is a shorthand for -left - 1.
return found ? left : ~left;
};
/**
* Sorts the specified array into ascending order. If no opt_compareFn is
* specified, elements are compared using
* <code>goog.array.defaultCompare</code>, which compares the elements using
* the built in < and > operators. This will produce the expected behavior
* for homogeneous arrays of String(s) and Number(s), unlike the native sort,
* but will give unpredictable results for heterogenous lists of strings and
* numbers with different numbers of digits.
*
* This sort is not guaranteed to be stable.
*
* Runtime: Same as <code>Array.prototype.sort</code>
*
* @param {Array.<T>} arr The array to be sorted.
* @param {?function(T,T):number=} opt_compareFn Optional comparison
* function by which the
* array is to be ordered. Should take 2 arguments to compare, and return a
* negative number, zero, or a positive number depending on whether the
* first argument is less than, equal to, or greater than the second.
* @template T
*/
goog.array.sort = function(arr, opt_compareFn) {
// TODO(arv): Update type annotation since null is not accepted.
goog.asserts.assert(arr.length != null);
goog.array.ARRAY_PROTOTYPE_.sort.call(
arr, opt_compareFn || goog.array.defaultCompare);
};
/**
* Sorts the specified array into ascending order in a stable way. If no
* opt_compareFn is specified, elements are compared using
* <code>goog.array.defaultCompare</code>, which compares the elements using
* the built in < and > operators. This will produce the expected behavior
* for homogeneous arrays of String(s) and Number(s).
*
* Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
* O(n) overhead of copying the array twice.
*
* @param {Array.<T>} arr The array to be sorted.
* @param {?function(T, T): number=} opt_compareFn Optional comparison function
* by which the array is to be ordered. Should take 2 arguments to compare,
* and return a negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @template T
*/
goog.array.stableSort = function(arr, opt_compareFn) {
for (var i = 0; i < arr.length; i++) {
arr[i] = {index: i, value: arr[i]};
}
var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
function stableCompareFn(obj1, obj2) {
return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
};
goog.array.sort(arr, stableCompareFn);
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].value;
}
};
/**
* Sorts an array of objects by the specified object key and compare
* function. If no compare function is provided, the key values are
* compared in ascending order using <code>goog.array.defaultCompare</code>.
* This won't work for keys that get renamed by the compiler. So use
* {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
* @param {Array.<Object>} arr An array of objects to sort.
* @param {string} key The object key to sort by.
* @param {Function=} opt_compareFn The function to use to compare key
* values.
*/
goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
var compare = opt_compareFn || goog.array.defaultCompare;
goog.array.sort(arr, function(a, b) {
return compare(a[key], b[key]);
});
};
/**
* Tells if the array is sorted.
* @param {!Array.<T>} arr The array.
* @param {?function(T,T):number=} opt_compareFn Function to compare the
* array elements.
* Should take 2 arguments to compare, and return a negative number, zero,
* or a positive number depending on whether the first argument is less
* than, equal to, or greater than the second.
* @param {boolean=} opt_strict If true no equal elements are allowed.
* @return {boolean} Whether the array is sorted.
* @template T
*/
goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
var compare = opt_compareFn || goog.array.defaultCompare;
for (var i = 1; i < arr.length; i++) {
var compareResult = compare(arr[i - 1], arr[i]);
if (compareResult > 0 || compareResult == 0 && opt_strict) {
return false;
}
}
return true;
};
/**
* Compares two arrays for equality. Two arrays are considered equal if they
* have the same length and their corresponding elements are equal according to
* the comparison function.
*
* @param {goog.array.ArrayLike} arr1 The first array to compare.
* @param {goog.array.ArrayLike} arr2 The second array to compare.
* @param {Function=} opt_equalsFn Optional comparison function.
* Should take 2 arguments to compare, and return true if the arguments
* are equal. Defaults to {@link goog.array.defaultCompareEquality} which
* compares the elements using the built-in '===' operator.
* @return {boolean} Whether the two arrays are equal.
*/
goog.array.equals = function(arr1, arr2, opt_equalsFn) {
if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
arr1.length != arr2.length) {
return false;
}
var l = arr1.length;
var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
for (var i = 0; i < l; i++) {
if (!equalsFn(arr1[i], arr2[i])) {
return false;
}
}
return true;
};
/**
* @deprecated Use {@link goog.array.equals}.
* @param {goog.array.ArrayLike} arr1 See {@link goog.array.equals}.
* @param {goog.array.ArrayLike} arr2 See {@link goog.array.equals}.
* @param {Function=} opt_equalsFn See {@link goog.array.equals}.
* @return {boolean} See {@link goog.array.equals}.
*/
goog.array.compare = function(arr1, arr2, opt_equalsFn) {
return goog.array.equals(arr1, arr2, opt_equalsFn);
};
/**
* 3-way array compare function.
* @param {!goog.array.ArrayLike} arr1 The first array to compare.
* @param {!goog.array.ArrayLike} arr2 The second array to compare.
* @param {?function(?, ?): number=} opt_compareFn Optional comparison function
* by which the array is to be ordered. Should take 2 arguments to compare,
* and return a negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @return {number} Negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
*/
goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
var compare = opt_compareFn || goog.array.defaultCompare;
var l = Math.min(arr1.length, arr2.length);
for (var i = 0; i < l; i++) {
var result = compare(arr1[i], arr2[i]);
if (result != 0) {
return result;
}
}
return goog.array.defaultCompare(arr1.length, arr2.length);
};
/**
* Compares its two arguments for order, using the built in < and >
* operators.
* @param {*} a The first object to be compared.
* @param {*} b The second object to be compared.
* @return {number} A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second.
*/
goog.array.defaultCompare = function(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
};
/**
* Compares its two arguments for equality, using the built in === operator.
* @param {*} a The first object to compare.
* @param {*} b The second object to compare.
* @return {boolean} True if the two arguments are equal, false otherwise.
*/
goog.array.defaultCompareEquality = function(a, b) {
return a === b;
};
/**
* Inserts a value into a sorted array. The array is not modified if the
* value is already present.
* @param {Array.<T>} array The array to modify.
* @param {T} value The object to insert.
* @param {?function(T,T):number=} opt_compareFn Optional comparison function by
* which the
* array is ordered. Should take 2 arguments to compare, and return a
* negative number, zero, or a positive number depending on whether the
* first argument is less than, equal to, or greater than the second.
* @return {boolean} True if an element was inserted.
* @template T
*/
goog.array.binaryInsert = function(array, value, opt_compareFn) {
var index = goog.array.binarySearch(array, value, opt_compareFn);
if (index < 0) {
goog.array.insertAt(array, value, -(index + 1));
return true;
}
return false;
};
/**
* Removes a value from a sorted array.
* @param {Array} array The array to modify.
* @param {*} value The object to remove.
* @param {Function=} opt_compareFn Optional comparison function by which the
* array is ordered. Should take 2 arguments to compare, and return a
* negative number, zero, or a positive number depending on whether the
* first argument is less than, equal to, or greater than the second.
* @return {boolean} True if an element was removed.
*/
goog.array.binaryRemove = function(array, value, opt_compareFn) {
var index = goog.array.binarySearch(array, value, opt_compareFn);
return (index >= 0) ? goog.array.removeAt(array, index) : false;
};
/**
* Splits an array into disjoint buckets according to a splitting function.
* @param {Array.<T>} array The array.
* @param {function(T,number,Array.<T>):?} sorter Function to call for every
* element. This
* takes 3 arguments (the element, the index and the array) and must
* return a valid object key (a string, number, etc), or undefined, if
* that object should not be placed in a bucket.
* @return {!Object} An object, with keys being all of the unique return values
* of sorter, and values being arrays containing the items for
* which the splitter returned that key.
* @template T
*/
goog.array.bucket = function(array, sorter) {
var buckets = {};
for (var i = 0; i < array.length; i++) {
var value = array[i];
var key = sorter(value, i, array);
if (goog.isDef(key)) {
// Push the value to the right bucket, creating it if necessary.
var bucket = buckets[key] || (buckets[key] = []);
bucket.push(value);
}
}
return buckets;
};
/**
* Creates a new object built from the provided array and the key-generation
* function.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
* which to iterate whose elements will be the values in the new object.
* @param {?function(this:S, T, number, ?) : string} keyFunc The function to
* call for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a string that will be used as the
* key for the element in the new object. If the function returns the same
* key for more than one element, the value for that key is
* implementation-defined.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within keyFunc.
* @return {!Object.<T>} The new object.
* @template T,S
*/
goog.array.toObject = function(arr, keyFunc, opt_obj) {
var ret = {};
goog.array.forEach(arr, function(element, index) {
ret[keyFunc.call(opt_obj, element, index, arr)] = element;
});
return ret;
};
/**
* Creates a range of numbers in an arithmetic progression.
*
* Range takes 1, 2, or 3 arguments:
* <pre>
* range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
* range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
* range(-2, -5, -1) produces [-2, -3, -4]
* range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
* </pre>
*
* @param {number} startOrEnd The starting value of the range if an end argument
* is provided. Otherwise, the start value is 0, and this is the end value.
* @param {number=} opt_end The optional end value of the range.
* @param {number=} opt_step The step size between range values. Defaults to 1
* if opt_step is undefined or 0.
* @return {!Array.<number>} An array of numbers for the requested range. May be
* an empty array if adding the step would not converge toward the end
* value.
*/
goog.array.range = function(startOrEnd, opt_end, opt_step) {
var array = [];
var start = 0;
var end = startOrEnd;
var step = opt_step || 1;
if (opt_end !== undefined) {
start = startOrEnd;
end = opt_end;
}
if (step * (end - start) < 0) {
// Sign mismatch: start + step will never reach the end value.
return [];
}
if (step > 0) {
for (var i = start; i < end; i += step) {
array.push(i);
}
} else {
for (var i = start; i > end; i += step) {
array.push(i);
}
}
return array;
};
/**
* Returns an array consisting of the given value repeated N times.
*
* @param {*} value The value to repeat.
* @param {number} n The repeat count.
* @return {!Array} An array with the repeated value.
*/
goog.array.repeat = function(value, n) {
var array = [];
for (var i = 0; i < n; i++) {
array[i] = value;
}
return array;
};
/**
* Returns an array consisting of every argument with all arrays
* expanded in-place recursively.
*
* @param {...*} var_args The values to flatten.
* @return {!Array} An array containing the flattened values.
*/
goog.array.flatten = function(var_args) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (goog.isArray(element)) {
result.push.apply(result, goog.array.flatten.apply(null, element));
} else {
result.push(element);
}
}
return result;
};
/**
* Rotates an array in-place. After calling this method, the element at
* index i will be the element previously at index (i - n) %
* array.length, for all values of i between 0 and array.length - 1,
* inclusive.
*
* For example, suppose list comprises [t, a, n, k, s]. After invoking
* rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
*
* @param {!Array.<T>} array The array to rotate.
* @param {number} n The amount to rotate.
* @return {!Array.<T>} The array.
* @template T
*/
goog.array.rotate = function(array, n) {
goog.asserts.assert(array.length != null);
if (array.length) {
n %= array.length;
if (n > 0) {
goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n));
} else if (n < 0) {
goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n));
}
}
return array;
};
/**
* Creates a new array for which the element at position i is an array of the
* ith element of the provided arrays. The returned array will only be as long
* as the shortest array provided; additional values are ignored. For example,
* the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
*
* This is similar to the zip() function in Python. See {@link
* http://docs.python.org/library/functions.html#zip}
*
* @param {...!goog.array.ArrayLike} var_args Arrays to be combined.
* @return {!Array.<!Array>} A new array of arrays created from provided arrays.
*/
goog.array.zip = function(var_args) {
if (!arguments.length) {
return [];
}
var result = [];
for (var i = 0; true; i++) {
var value = [];
for (var j = 0; j < arguments.length; j++) {
var arr = arguments[j];
// If i is larger than the array length, this is the shortest array.
if (i >= arr.length) {
return result;
}
value.push(arr[i]);
}
result.push(value);
}
};
/**
* Shuffles the values in the specified array using the Fisher-Yates in-place
* shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
* and so resets the state of that random number generator. Similarly, may reset
* the state of the any other specified random number generator.
*
* Runtime: O(n)
*
* @param {!Array} arr The array to be shuffled.
* @param {function():number=} opt_randFn Optional random function to use for
* shuffling.
* Takes no arguments, and returns a random number on the interval [0, 1).
* Defaults to Math.random() using JavaScript's built-in Math library.
*/
goog.array.shuffle = function(arr, opt_randFn) {
var randFn = opt_randFn || Math.random;
for (var i = arr.length - 1; i > 0; i--) {
// Choose a random array index in [0, i] (inclusive with i).
var j = Math.floor(randFn() * (i + 1));
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utility methods to deal with CSS3 transitions
* programmatically.
*/
goog.provide('goog.style.transition');
goog.provide('goog.style.transition.Css3Property');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom.vendor');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* A typedef to represent a CSS3 transition property. Duration and delay
* are both in seconds. Timing is CSS3 timing function string, such as
* 'easein', 'linear'.
*
* Alternatively, specifying string in the form of '[property] [duration]
* [timing] [delay]' as specified in CSS3 transition is fine too.
*
* @typedef { {
* property: string,
* duration: number,
* timing: string,
* delay: number
* } | string }
*/
goog.style.transition.Css3Property;
/**
* Sets the element CSS3 transition to properties.
* @param {Element} element The element to set transition on.
* @param {goog.style.transition.Css3Property|
* Array.<goog.style.transition.Css3Property>} properties A single CSS3
* transition property or array of properties.
*/
goog.style.transition.set = function(element, properties) {
if (!goog.isArray(properties)) {
properties = [properties];
}
goog.asserts.assert(
properties.length > 0, 'At least one Css3Property should be specified.');
var values = goog.array.map(
properties, function(p) {
if (goog.isString(p)) {
return p;
} else {
goog.asserts.assertObject(p,
'Expected css3 property to be an object.');
var propString = p.property + ' ' + p.duration + 's ' + p.timing +
' ' + p.delay + 's';
goog.asserts.assert(p.property && goog.isNumber(p.duration) &&
p.timing && goog.isNumber(p.delay),
'Unexpected css3 property value: %s', propString);
return propString;
}
});
goog.style.transition.setPropertyValue_(element, values.join(','));
};
/**
* Removes any programmatically-added CSS3 transition in the given element.
* @param {Element} element The element to remove transition from.
*/
goog.style.transition.removeAll = function(element) {
goog.style.transition.setPropertyValue_(element, '');
};
/**
* @return {boolean} Whether CSS3 transition is supported.
*/
goog.style.transition.isSupported = function() {
if (!goog.isDef(goog.style.transition.css3TransitionSupported_)) {
// Since IE would allow any attribute, we need to explicitly check the
// browser version here instead.
if (goog.userAgent.IE) {
goog.style.transition.css3TransitionSupported_ =
goog.userAgent.isVersion('10.0');
} else {
// We create a test element with style=-vendor-transition
// We then detect whether those style properties are recognized and
// available from js.
var el = document.createElement('div');
var transition = 'transition:opacity 1s linear;';
var vendorPrefix = goog.dom.vendor.getVendorPrefix();
var vendorTransition =
vendorPrefix ? vendorPrefix + '-' + transition : '';
el.innerHTML = '<div style="' + vendorTransition + transition + '">';
var testElement = /** @type {Element} */ (el.firstChild);
goog.asserts.assert(testElement.nodeType == Node.ELEMENT_NODE);
goog.style.transition.css3TransitionSupported_ =
goog.style.getStyle(testElement, 'transition') != '';
}
}
return goog.style.transition.css3TransitionSupported_;
};
/**
* Whether CSS3 transition is supported.
* @type {boolean}
* @private
*/
goog.style.transition.css3TransitionSupported_;
/**
* Sets CSS3 transition property value to the given value.
* @param {Element} element The element to set transition on.
* @param {string} transitionValue The CSS3 transition property value.
* @private
*/
goog.style.transition.setPropertyValue_ = function(element, transitionValue) {
goog.style.setStyle(element, 'transition', transitionValue);
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for element styles.
*
* @see ../demos/inline_block_quirks.html
* @see ../demos/inline_block_standards.html
* @see ../demos/style_viewport.html
*/
goog.provide('goog.style');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.vendor');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Rect');
goog.require('goog.math.Size');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* Sets a style value on an element.
*
* This function is not indended to patch issues in the browser's style
* handling, but to allow easy programmatic access to setting dash-separated
* style properties. An example is setting a batch of properties from a data
* object without overwriting old styles. When possible, use native APIs:
* elem.style.propertyKey = 'value' or (if obliterating old styles is fine)
* elem.style.cssText = 'property1: value1; property2: value2'.
*
* @param {Element} element The element to change.
* @param {string|Object} style If a string, a style name. If an object, a hash
* of style names to style values.
* @param {string|number|boolean=} opt_value If style was a string, then this
* should be the value.
*/
goog.style.setStyle = function(element, style, opt_value) {
if (goog.isString(style)) {
goog.style.setStyle_(element, opt_value, style);
} else {
goog.object.forEach(style, goog.partial(goog.style.setStyle_, element));
}
};
/**
* Sets a style value on an element, with parameters swapped to work with
* {@code goog.object.forEach()}. Prepends a vendor-specific prefix when
* necessary.
* @param {Element} element The element to change.
* @param {string|number|boolean|undefined} value Style value.
* @param {string} style Style name.
* @private
*/
goog.style.setStyle_ = function(element, value, style) {
var propertyName = goog.style.getVendorJsStyleName_(element, style);
if (propertyName) {
element.style[propertyName] = value;
}
};
/**
* Returns the style property name in camel-case. If it does not exist and a
* vendor-specific version of the property does exist, then return the vendor-
* specific property name instead.
* @param {Element} element The element to change.
* @param {string} style Style name.
* @return {string} Vendor-specific style.
* @private
*/
goog.style.getVendorJsStyleName_ = function(element, style) {
var camelStyle = goog.string.toCamelCase(style);
if (element.style[camelStyle] === undefined) {
var prefixedStyle = goog.dom.vendor.getVendorJsPrefix() +
goog.string.toTitleCase(style);
if (element.style[prefixedStyle] !== undefined) {
return prefixedStyle;
}
}
return camelStyle;
};
/**
* Returns the style property name in CSS notation. If it does not exist and a
* vendor-specific version of the property does exist, then return the vendor-
* specific property name instead.
* @param {Element} element The element to change.
* @param {string} style Style name.
* @return {string} Vendor-specific style.
* @private
*/
goog.style.getVendorStyleName_ = function(element, style) {
var camelStyle = goog.string.toCamelCase(style);
if (element.style[camelStyle] === undefined) {
var prefixedStyle = goog.dom.vendor.getVendorJsPrefix() +
goog.string.toTitleCase(style);
if (element.style[prefixedStyle] !== undefined) {
return goog.dom.vendor.getVendorPrefix() + '-' + style;
}
}
return style;
};
/**
* Retrieves an explicitly-set style value of a node. This returns '' if there
* isn't a style attribute on the element or if this style property has not been
* explicitly set in script.
*
* @param {Element} element Element to get style of.
* @param {string} property Property to get, css-style (if you have a camel-case
* property, use element.style[style]).
* @return {string} Style value.
*/
goog.style.getStyle = function(element, property) {
// element.style is '' for well-known properties which are unset.
// For for browser specific styles as 'filter' is undefined
// so we need to return '' explicitly to make it consistent across
// browsers.
var styleValue = element.style[goog.string.toCamelCase(property)];
// Using typeof here because of a bug in Safari 5.1, where this value
// was undefined, but === undefined returned false.
if (typeof(styleValue) !== 'undefined') {
return styleValue;
}
return element.style[goog.style.getVendorJsStyleName_(element, property)] ||
'';
};
/**
* Retrieves a computed style value of a node. It returns empty string if the
* value cannot be computed (which will be the case in Internet Explorer) or
* "none" if the property requested is an SVG one and it has not been
* explicitly set (firefox and webkit).
*
* @param {Element} element Element to get style of.
* @param {string} property Property to get (camel-case).
* @return {string} Style value.
*/
goog.style.getComputedStyle = function(element, property) {
var doc = goog.dom.getOwnerDocument(element);
if (doc.defaultView && doc.defaultView.getComputedStyle) {
var styles = doc.defaultView.getComputedStyle(element, null);
if (styles) {
// element.style[..] is undefined for browser specific styles
// as 'filter'.
return styles[property] || styles.getPropertyValue(property) || '';
}
}
return '';
};
/**
* Gets the cascaded style value of a node, or null if the value cannot be
* computed (only Internet Explorer can do this).
*
* @param {Element} element Element to get style of.
* @param {string} style Property to get (camel-case).
* @return {string} Style value.
*/
goog.style.getCascadedStyle = function(element, style) {
// TODO(nicksantos): This should be documented to return null. #fixTypes
return element.currentStyle ? element.currentStyle[style] : null;
};
/**
* Cross-browser pseudo get computed style. It returns the computed style where
* available. If not available it tries the cascaded style value (IE
* currentStyle) and in worst case the inline style value. It shouldn't be
* called directly, see http://wiki/Main/ComputedStyleVsCascadedStyle for
* discussion.
*
* @param {Element} element Element to get style of.
* @param {string} style Property to get (must be camelCase, not css-style.).
* @return {string} Style value.
* @private
*/
goog.style.getStyle_ = function(element, style) {
return goog.style.getComputedStyle(element, style) ||
goog.style.getCascadedStyle(element, style) ||
(element.style && element.style[style]);
};
/**
* Retrieves the computed value of the position CSS attribute.
* @param {Element} element The element to get the position of.
* @return {string} Position value.
*/
goog.style.getComputedPosition = function(element) {
return goog.style.getStyle_(element, 'position');
};
/**
* Retrieves the computed background color string for a given element. The
* string returned is suitable for assigning to another element's
* background-color, but is not guaranteed to be in any particular string
* format. Accessing the color in a numeric form may not be possible in all
* browsers or with all input.
*
* If the background color for the element is defined as a hexadecimal value,
* the resulting string can be parsed by goog.color.parse in all supported
* browsers.
*
* Whether named colors like "red" or "lightblue" get translated into a
* format which can be parsed is browser dependent. Calling this function on
* transparent elements will return "transparent" in most browsers or
* "rgba(0, 0, 0, 0)" in WebKit.
* @param {Element} element The element to get the background color of.
* @return {string} The computed string value of the background color.
*/
goog.style.getBackgroundColor = function(element) {
return goog.style.getStyle_(element, 'backgroundColor');
};
/**
* Retrieves the computed value of the overflow-x CSS attribute.
* @param {Element} element The element to get the overflow-x of.
* @return {string} The computed string value of the overflow-x attribute.
*/
goog.style.getComputedOverflowX = function(element) {
return goog.style.getStyle_(element, 'overflowX');
};
/**
* Retrieves the computed value of the overflow-y CSS attribute.
* @param {Element} element The element to get the overflow-y of.
* @return {string} The computed string value of the overflow-y attribute.
*/
goog.style.getComputedOverflowY = function(element) {
return goog.style.getStyle_(element, 'overflowY');
};
/**
* Retrieves the computed value of the z-index CSS attribute.
* @param {Element} element The element to get the z-index of.
* @return {string|number} The computed value of the z-index attribute.
*/
goog.style.getComputedZIndex = function(element) {
return goog.style.getStyle_(element, 'zIndex');
};
/**
* Retrieves the computed value of the text-align CSS attribute.
* @param {Element} element The element to get the text-align of.
* @return {string} The computed string value of the text-align attribute.
*/
goog.style.getComputedTextAlign = function(element) {
return goog.style.getStyle_(element, 'textAlign');
};
/**
* Retrieves the computed value of the cursor CSS attribute.
* @param {Element} element The element to get the cursor of.
* @return {string} The computed string value of the cursor attribute.
*/
goog.style.getComputedCursor = function(element) {
return goog.style.getStyle_(element, 'cursor');
};
/**
* Sets the top/left values of an element. If no unit is specified in the
* argument then it will add px. The second argument is required if the first
* argument is a string or number and is ignored if the first argument
* is a coordinate.
* @param {Element} el Element to move.
* @param {string|number|goog.math.Coordinate} arg1 Left position or coordinate.
* @param {string|number=} opt_arg2 Top position.
*/
goog.style.setPosition = function(el, arg1, opt_arg2) {
var x, y;
var buggyGeckoSubPixelPos = goog.userAgent.GECKO &&
(goog.userAgent.MAC || goog.userAgent.X11) &&
goog.userAgent.isVersion('1.9');
if (arg1 instanceof goog.math.Coordinate) {
x = arg1.x;
y = arg1.y;
} else {
x = arg1;
y = opt_arg2;
}
// Round to the nearest pixel for buggy sub-pixel support.
el.style.left = goog.style.getPixelStyleValue_(
/** @type {number|string} */ (x), buggyGeckoSubPixelPos);
el.style.top = goog.style.getPixelStyleValue_(
/** @type {number|string} */ (y), buggyGeckoSubPixelPos);
};
/**
* Gets the offsetLeft and offsetTop properties of an element and returns them
* in a Coordinate object
* @param {Element} element Element.
* @return {!goog.math.Coordinate} The position.
*/
goog.style.getPosition = function(element) {
return new goog.math.Coordinate(element.offsetLeft, element.offsetTop);
};
/**
* Returns the viewport element for a particular document
* @param {Node=} opt_node DOM node (Document is OK) to get the viewport element
* of.
* @return {Element} document.documentElement or document.body.
*/
goog.style.getClientViewportElement = function(opt_node) {
var doc;
if (opt_node) {
doc = goog.dom.getOwnerDocument(opt_node);
} else {
doc = goog.dom.getDocument();
}
// In old IE versions the document.body represented the viewport
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9) &&
!goog.dom.getDomHelper(doc).isCss1CompatMode()) {
return doc.body;
}
return doc.documentElement;
};
/**
* Calculates the viewport coordinates relative to the page/document
* containing the node. The viewport may be the browser viewport for
* non-iframe document, or the iframe container for iframe'd document.
* @param {!Document} doc The document to use as the reference point.
* @return {!goog.math.Coordinate} The page offset of the viewport.
*/
goog.style.getViewportPageOffset = function(doc) {
var body = doc.body;
var documentElement = doc.documentElement;
var scrollLeft = body.scrollLeft || documentElement.scrollLeft;
var scrollTop = body.scrollTop || documentElement.scrollTop;
return new goog.math.Coordinate(scrollLeft, scrollTop);
};
/**
* Gets the client rectangle of the DOM element.
*
* getBoundingClientRect is part of a new CSS object model draft (with a
* long-time presence in IE), replacing the error-prone parent offset
* computation and the now-deprecated Gecko getBoxObjectFor.
*
* This utility patches common browser bugs in getBoundingClientRect. It
* will fail if getBoundingClientRect is unsupported.
*
* If the element is not in the DOM, the result is undefined, and an error may
* be thrown depending on user agent.
*
* @param {!Element} el The element whose bounding rectangle is being queried.
* @return {Object} A native bounding rectangle with numerical left, top,
* right, and bottom. Reported by Firefox to be of object type ClientRect.
* @private
*/
goog.style.getBoundingClientRect_ = function(el) {
var rect = el.getBoundingClientRect();
// Patch the result in IE only, so that this function can be inlined if
// compiled for non-IE.
if (goog.userAgent.IE) {
// In IE, most of the time, 2 extra pixels are added to the top and left
// due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
// IE6 standards mode, this border can be overridden by setting the
// document element's border to zero -- thus, we cannot rely on the
// offset always being 2 pixels.
// In quirks mode, the offset can be determined by querying the body's
// clientLeft/clientTop, but in standards mode, it is found by querying
// the document element's clientLeft/clientTop. Since we already called
// getBoundingClientRect we have already forced a reflow, so it is not
// too expensive just to query them all.
// See: http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx
var doc = el.ownerDocument;
rect.left -= doc.documentElement.clientLeft + doc.body.clientLeft;
rect.top -= doc.documentElement.clientTop + doc.body.clientTop;
}
return /** @type {Object} */ (rect);
};
/**
* Returns the first parent that could affect the position of a given element.
* @param {Element} element The element to get the offset parent for.
* @return {Element} The first offset parent or null if one cannot be found.
*/
goog.style.getOffsetParent = function(element) {
// element.offsetParent does the right thing in IE7 and below. In other
// browsers it only includes elements with position absolute, relative or
// fixed, not elements with overflow set to auto or scroll.
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(8)) {
return element.offsetParent;
}
var doc = goog.dom.getOwnerDocument(element);
var positionStyle = goog.style.getStyle_(element, 'position');
var skipStatic = positionStyle == 'fixed' || positionStyle == 'absolute';
for (var parent = element.parentNode; parent && parent != doc;
parent = parent.parentNode) {
positionStyle =
goog.style.getStyle_(/** @type {!Element} */ (parent), 'position');
skipStatic = skipStatic && positionStyle == 'static' &&
parent != doc.documentElement && parent != doc.body;
if (!skipStatic && (parent.scrollWidth > parent.clientWidth ||
parent.scrollHeight > parent.clientHeight ||
positionStyle == 'fixed' ||
positionStyle == 'absolute' ||
positionStyle == 'relative')) {
return /** @type {!Element} */ (parent);
}
}
return null;
};
/**
* Calculates and returns the visible rectangle for a given element. Returns a
* box describing the visible portion of the nearest scrollable offset ancestor.
* Coordinates are given relative to the document.
*
* @param {Element} element Element to get the visible rect for.
* @return {goog.math.Box} Bounding elementBox describing the visible rect or
* null if scrollable ancestor isn't inside the visible viewport.
*/
goog.style.getVisibleRectForElement = function(element) {
var visibleRect = new goog.math.Box(0, Infinity, Infinity, 0);
var dom = goog.dom.getDomHelper(element);
var body = dom.getDocument().body;
var documentElement = dom.getDocument().documentElement;
var scrollEl = dom.getDocumentScrollElement();
// Determine the size of the visible rect by climbing the dom accounting for
// all scrollable containers.
for (var el = element; el = goog.style.getOffsetParent(el); ) {
// clientWidth is zero for inline block elements in IE.
// on WEBKIT, body element can have clientHeight = 0 and scrollHeight > 0
if ((!goog.userAgent.IE || el.clientWidth != 0) &&
(!goog.userAgent.WEBKIT || el.clientHeight != 0 || el != body) &&
// body may have overflow set on it, yet we still get the entire
// viewport. In some browsers, el.offsetParent may be
// document.documentElement, so check for that too.
(el != body && el != documentElement &&
goog.style.getStyle_(el, 'overflow') != 'visible')) {
var pos = goog.style.getPageOffset(el);
var client = goog.style.getClientLeftTop(el);
pos.x += client.x;
pos.y += client.y;
visibleRect.top = Math.max(visibleRect.top, pos.y);
visibleRect.right = Math.min(visibleRect.right,
pos.x + el.clientWidth);
visibleRect.bottom = Math.min(visibleRect.bottom,
pos.y + el.clientHeight);
visibleRect.left = Math.max(visibleRect.left, pos.x);
}
}
// Clip by window's viewport.
var scrollX = scrollEl.scrollLeft, scrollY = scrollEl.scrollTop;
visibleRect.left = Math.max(visibleRect.left, scrollX);
visibleRect.top = Math.max(visibleRect.top, scrollY);
var winSize = dom.getViewportSize();
visibleRect.right = Math.min(visibleRect.right, scrollX + winSize.width);
visibleRect.bottom = Math.min(visibleRect.bottom, scrollY + winSize.height);
return visibleRect.top >= 0 && visibleRect.left >= 0 &&
visibleRect.bottom > visibleRect.top &&
visibleRect.right > visibleRect.left ?
visibleRect : null;
};
/**
* Calculate the scroll position of {@code container} with the minimum amount so
* that the content and the borders of the given {@code element} become visible.
* If the element is bigger than the container, its top left corner will be
* aligned as close to the container's top left corner as possible.
*
* @param {Element} element The element to make visible.
* @param {Element} container The container to scroll.
* @param {boolean=} opt_center Whether to center the element in the container.
* Defaults to false.
* @return {!goog.math.Coordinate} The new scroll position of the container,
* in form of goog.math.Coordinate(scrollLeft, scrollTop).
*/
goog.style.getContainerOffsetToScrollInto =
function(element, container, opt_center) {
// Absolute position of the element's border's top left corner.
var elementPos = goog.style.getPageOffset(element);
// Absolute position of the container's border's top left corner.
var containerPos = goog.style.getPageOffset(container);
var containerBorder = goog.style.getBorderBox(container);
// Relative pos. of the element's border box to the container's content box.
var relX = elementPos.x - containerPos.x - containerBorder.left;
var relY = elementPos.y - containerPos.y - containerBorder.top;
// How much the element can move in the container, i.e. the difference between
// the element's bottom-right-most and top-left-most position where it's
// fully visible.
var spaceX = container.clientWidth - element.offsetWidth;
var spaceY = container.clientHeight - element.offsetHeight;
var scrollLeft = container.scrollLeft;
var scrollTop = container.scrollTop;
if (opt_center) {
// All browsers round non-integer scroll positions down.
scrollLeft += relX - spaceX / 2;
scrollTop += relY - spaceY / 2;
} else {
// This formula was designed to give the correct scroll values in the
// following cases:
// - element is higher than container (spaceY < 0) => scroll down by relY
// - element is not higher that container (spaceY >= 0):
// - it is above container (relY < 0) => scroll up by abs(relY)
// - it is below container (relY > spaceY) => scroll down by relY - spaceY
// - it is in the container => don't scroll
scrollLeft += Math.min(relX, Math.max(relX - spaceX, 0));
scrollTop += Math.min(relY, Math.max(relY - spaceY, 0));
}
return new goog.math.Coordinate(scrollLeft, scrollTop);
};
/**
* Changes the scroll position of {@code container} with the minimum amount so
* that the content and the borders of the given {@code element} become visible.
* If the element is bigger than the container, its top left corner will be
* aligned as close to the container's top left corner as possible.
*
* @param {Element} element The element to make visible.
* @param {Element} container The container to scroll.
* @param {boolean=} opt_center Whether to center the element in the container.
* Defaults to false.
*/
goog.style.scrollIntoContainerView = function(element, container, opt_center) {
var offset =
goog.style.getContainerOffsetToScrollInto(element, container, opt_center);
container.scrollLeft = offset.x;
container.scrollTop = offset.y;
};
/**
* Returns clientLeft (width of the left border and, if the directionality is
* right to left, the vertical scrollbar) and clientTop as a coordinate object.
*
* @param {Element} el Element to get clientLeft for.
* @return {!goog.math.Coordinate} Client left and top.
*/
goog.style.getClientLeftTop = function(el) {
// NOTE(eae): Gecko prior to 1.9 doesn't support clientTop/Left, see
// https://bugzilla.mozilla.org/show_bug.cgi?id=111207
if (goog.userAgent.GECKO && !goog.userAgent.isVersion('1.9')) {
var left = parseFloat(goog.style.getComputedStyle(el, 'borderLeftWidth'));
if (goog.style.isRightToLeft(el)) {
var scrollbarWidth = el.offsetWidth - el.clientWidth - left -
parseFloat(goog.style.getComputedStyle(el, 'borderRightWidth'));
left += scrollbarWidth;
}
return new goog.math.Coordinate(left,
parseFloat(goog.style.getComputedStyle(el, 'borderTopWidth')));
}
return new goog.math.Coordinate(el.clientLeft, el.clientTop);
};
/**
* Returns a Coordinate object relative to the top-left of the HTML document.
* Implemented as a single function to save having to do two recursive loops in
* opera and safari just to get both coordinates. If you just want one value do
* use goog.style.getPageOffsetLeft() and goog.style.getPageOffsetTop(), but
* note if you call both those methods the tree will be analysed twice.
*
* @param {Element} el Element to get the page offset for.
* @return {!goog.math.Coordinate} The page offset.
*/
goog.style.getPageOffset = function(el) {
var box, doc = goog.dom.getOwnerDocument(el);
var positionStyle = goog.style.getStyle_(el, 'position');
// TODO(gboyer): Update the jsdoc in a way that doesn't break the universe.
goog.asserts.assertObject(el, 'Parameter is required');
// NOTE(eae): Gecko pre 1.9 normally use getBoxObjectFor to calculate the
// position. When invoked for an element with position absolute and a negative
// position though it can be off by one. Therefor the recursive implementation
// is used in those (relatively rare) cases.
var BUGGY_GECKO_BOX_OBJECT = goog.userAgent.GECKO && doc.getBoxObjectFor &&
!el.getBoundingClientRect && positionStyle == 'absolute' &&
(box = doc.getBoxObjectFor(el)) && (box.screenX < 0 || box.screenY < 0);
// NOTE(arv): If element is hidden (display none or disconnected or any the
// ancestors are hidden) we get (0,0) by default but we still do the
// accumulation of scroll position.
// TODO(arv): Should we check if the node is disconnected and in that case
// return (0,0)?
var pos = new goog.math.Coordinate(0, 0);
var viewportElement = goog.style.getClientViewportElement(doc);
if (el == viewportElement) {
// viewport is always at 0,0 as that defined the coordinate system for this
// function - this avoids special case checks in the code below
return pos;
}
// IE, Gecko 1.9+, and most modern WebKit.
if (el.getBoundingClientRect) {
box = goog.style.getBoundingClientRect_(el);
// Must add the scroll coordinates in to get the absolute page offset
// of element since getBoundingClientRect returns relative coordinates to
// the viewport.
var scrollCoord = goog.dom.getDomHelper(doc).getDocumentScroll();
pos.x = box.left + scrollCoord.x;
pos.y = box.top + scrollCoord.y;
// Gecko prior to 1.9.
} else if (doc.getBoxObjectFor && !BUGGY_GECKO_BOX_OBJECT) {
// Gecko ignores the scroll values for ancestors, up to 1.9. See:
// https://bugzilla.mozilla.org/show_bug.cgi?id=328881 and
// https://bugzilla.mozilla.org/show_bug.cgi?id=330619
box = doc.getBoxObjectFor(el);
// TODO(user): Fix the off-by-one error when window is scrolled down
// or right more than 1 pixel. The viewport offset does not move in lock
// step with the window scroll; it moves in increments of 2px and at
// somewhat random intervals.
var vpBox = doc.getBoxObjectFor(viewportElement);
pos.x = box.screenX - vpBox.screenX;
pos.y = box.screenY - vpBox.screenY;
// Safari, Opera and Camino up to 1.0.4.
} else {
var parent = el;
do {
pos.x += parent.offsetLeft;
pos.y += parent.offsetTop;
// For safari/chrome, we need to add parent's clientLeft/Top as well.
if (parent != el) {
pos.x += parent.clientLeft || 0;
pos.y += parent.clientTop || 0;
}
// In Safari when hit a position fixed element the rest of the offsets
// are not correct.
if (goog.userAgent.WEBKIT &&
goog.style.getComputedPosition(parent) == 'fixed') {
pos.x += doc.body.scrollLeft;
pos.y += doc.body.scrollTop;
break;
}
parent = parent.offsetParent;
} while (parent && parent != el);
// Opera & (safari absolute) incorrectly account for body offsetTop.
if (goog.userAgent.OPERA || (goog.userAgent.WEBKIT &&
positionStyle == 'absolute')) {
pos.y -= doc.body.offsetTop;
}
for (parent = el; (parent = goog.style.getOffsetParent(parent)) &&
parent != doc.body && parent != viewportElement; ) {
pos.x -= parent.scrollLeft;
// Workaround for a bug in Opera 9.2 (and earlier) where table rows may
// report an invalid scroll top value. The bug was fixed in Opera 9.5
// however as that version supports getBoundingClientRect it won't
// trigger this code path. https://bugs.opera.com/show_bug.cgi?id=249965
if (!goog.userAgent.OPERA || parent.tagName != 'TR') {
pos.y -= parent.scrollTop;
}
}
}
return pos;
};
/**
* Returns the left coordinate of an element relative to the HTML document
* @param {Element} el Elements.
* @return {number} The left coordinate.
*/
goog.style.getPageOffsetLeft = function(el) {
return goog.style.getPageOffset(el).x;
};
/**
* Returns the top coordinate of an element relative to the HTML document
* @param {Element} el Elements.
* @return {number} The top coordinate.
*/
goog.style.getPageOffsetTop = function(el) {
return goog.style.getPageOffset(el).y;
};
/**
* Returns a Coordinate object relative to the top-left of an HTML document
* in an ancestor frame of this element. Used for measuring the position of
* an element inside a frame relative to a containing frame.
*
* @param {Element} el Element to get the page offset for.
* @param {Window} relativeWin The window to measure relative to. If relativeWin
* is not in the ancestor frame chain of the element, we measure relative to
* the top-most window.
* @return {!goog.math.Coordinate} The page offset.
*/
goog.style.getFramedPageOffset = function(el, relativeWin) {
var position = new goog.math.Coordinate(0, 0);
// Iterate up the ancestor frame chain, keeping track of the current window
// and the current element in that window.
var currentWin = goog.dom.getWindow(goog.dom.getOwnerDocument(el));
var currentEl = el;
do {
// if we're at the top window, we want to get the page offset.
// if we're at an inner frame, we only want to get the window position
// so that we can determine the actual page offset in the context of
// the outer window.
var offset = currentWin == relativeWin ?
goog.style.getPageOffset(currentEl) :
goog.style.getClientPosition(currentEl);
position.x += offset.x;
position.y += offset.y;
} while (currentWin && currentWin != relativeWin &&
(currentEl = currentWin.frameElement) &&
(currentWin = currentWin.parent));
return position;
};
/**
* Translates the specified rect relative to origBase page, for newBase page.
* If origBase and newBase are the same, this function does nothing.
*
* @param {goog.math.Rect} rect The source rectangle relative to origBase page,
* and it will have the translated result.
* @param {goog.dom.DomHelper} origBase The DomHelper for the input rectangle.
* @param {goog.dom.DomHelper} newBase The DomHelper for the resultant
* coordinate. This must be a DOM for an ancestor frame of origBase
* or the same as origBase.
*/
goog.style.translateRectForAnotherFrame = function(rect, origBase, newBase) {
if (origBase.getDocument() != newBase.getDocument()) {
var body = origBase.getDocument().body;
var pos = goog.style.getFramedPageOffset(body, newBase.getWindow());
// Adjust Body's margin.
pos = goog.math.Coordinate.difference(pos, goog.style.getPageOffset(body));
if (goog.userAgent.IE && !origBase.isCss1CompatMode()) {
pos = goog.math.Coordinate.difference(pos, origBase.getDocumentScroll());
}
rect.left += pos.x;
rect.top += pos.y;
}
};
/**
* Returns the position of an element relative to another element in the
* document. A relative to B
* @param {Element|Event|goog.events.Event} a Element or mouse event whose
* position we're calculating.
* @param {Element|Event|goog.events.Event} b Element or mouse event position
* is relative to.
* @return {!goog.math.Coordinate} The relative position.
*/
goog.style.getRelativePosition = function(a, b) {
var ap = goog.style.getClientPosition(a);
var bp = goog.style.getClientPosition(b);
return new goog.math.Coordinate(ap.x - bp.x, ap.y - bp.y);
};
/**
* Returns the position of the event or the element's border box relative to
* the client viewport.
* @param {Element|Event|goog.events.Event} el Element or a mouse / touch event.
* @return {!goog.math.Coordinate} The position.
*/
goog.style.getClientPosition = function(el) {
var pos = new goog.math.Coordinate;
if (el.nodeType == goog.dom.NodeType.ELEMENT) {
el = /** @type {!Element} */ (el);
if (el.getBoundingClientRect) {
// IE, Gecko 1.9+, and most modern WebKit
var box = goog.style.getBoundingClientRect_(el);
pos.x = box.left;
pos.y = box.top;
} else {
var scrollCoord = goog.dom.getDomHelper(el).getDocumentScroll();
var pageCoord = goog.style.getPageOffset(el);
pos.x = pageCoord.x - scrollCoord.x;
pos.y = pageCoord.y - scrollCoord.y;
}
if (goog.userAgent.GECKO && !goog.userAgent.isVersion(12)) {
pos = goog.math.Coordinate.sum(pos, goog.style.getCssTranslation(el));
}
} else {
var isAbstractedEvent = goog.isFunction(el.getBrowserEvent);
var targetEvent = el;
if (el.targetTouches) {
targetEvent = el.targetTouches[0];
} else if (isAbstractedEvent && el.getBrowserEvent().targetTouches) {
targetEvent = el.getBrowserEvent().targetTouches[0];
}
pos.x = targetEvent.clientX;
pos.y = targetEvent.clientY;
}
return pos;
};
/**
* Moves an element to the given coordinates relative to the client viewport.
* @param {Element} el Absolutely positioned element to set page offset for.
* It must be in the document.
* @param {number|goog.math.Coordinate} x Left position of the element's margin
* box or a coordinate object.
* @param {number=} opt_y Top position of the element's margin box.
*/
goog.style.setPageOffset = function(el, x, opt_y) {
// Get current pageoffset
var cur = goog.style.getPageOffset(el);
if (x instanceof goog.math.Coordinate) {
opt_y = x.y;
x = x.x;
}
// NOTE(arv): We cannot allow strings for x and y. We could but that would
// require us to manually transform between different units
// Work out deltas
var dx = x - cur.x;
var dy = opt_y - cur.y;
// Set position to current left/top + delta
goog.style.setPosition(el, el.offsetLeft + dx, el.offsetTop + dy);
};
/**
* Sets the width/height values of an element. If an argument is numeric,
* or a goog.math.Size is passed, it is assumed to be pixels and will add
* 'px' after converting it to an integer in string form. (This just sets the
* CSS width and height properties so it might set content-box or border-box
* size depending on the box model the browser is using.)
*
* @param {Element} element Element to set the size of.
* @param {string|number|goog.math.Size} w Width of the element, or a
* size object.
* @param {string|number=} opt_h Height of the element. Required if w is not a
* size object.
*/
goog.style.setSize = function(element, w, opt_h) {
var h;
if (w instanceof goog.math.Size) {
h = w.height;
w = w.width;
} else {
if (opt_h == undefined) {
throw Error('missing height argument');
}
h = opt_h;
}
goog.style.setWidth(element, /** @type {string|number} */ (w));
goog.style.setHeight(element, /** @type {string|number} */ (h));
};
/**
* Helper function to create a string to be set into a pixel-value style
* property of an element. Can round to the nearest integer value.
*
* @param {string|number} value The style value to be used. If a number,
* 'px' will be appended, otherwise the value will be applied directly.
* @param {boolean} round Whether to round the nearest integer (if property
* is a number).
* @return {string} The string value for the property.
* @private
*/
goog.style.getPixelStyleValue_ = function(value, round) {
if (typeof value == 'number') {
value = (round ? Math.round(value) : value) + 'px';
}
return value;
};
/**
* Set the height of an element. Sets the element's style property.
* @param {Element} element Element to set the height of.
* @param {string|number} height The height value to set. If a number, 'px'
* will be appended, otherwise the value will be applied directly.
*/
goog.style.setHeight = function(element, height) {
element.style.height = goog.style.getPixelStyleValue_(height, true);
};
/**
* Set the width of an element. Sets the element's style property.
* @param {Element} element Element to set the width of.
* @param {string|number} width The width value to set. If a number, 'px'
* will be appended, otherwise the value will be applied directly.
*/
goog.style.setWidth = function(element, width) {
element.style.width = goog.style.getPixelStyleValue_(width, true);
};
/**
* Gets the height and width of an element, even if its display is none.
* Specifically, this returns the height and width of the border box,
* irrespective of the box model in effect.
* @param {Element} element Element to get size of.
* @return {!goog.math.Size} Object with width/height properties.
*/
goog.style.getSize = function(element) {
if (goog.style.getStyle_(element, 'display') != 'none') {
return goog.style.getSizeWithDisplay_(element);
}
var style = element.style;
var originalDisplay = style.display;
var originalVisibility = style.visibility;
var originalPosition = style.position;
style.visibility = 'hidden';
style.position = 'absolute';
style.display = 'inline';
var size = goog.style.getSizeWithDisplay_(element);
style.display = originalDisplay;
style.position = originalPosition;
style.visibility = originalVisibility;
return size;
};
/**
* Gets the height and with of an element when the display is not none.
* @param {Element} element Element to get size of.
* @return {!goog.math.Size} Object with width/height properties.
* @private
*/
goog.style.getSizeWithDisplay_ = function(element) {
var offsetWidth = element.offsetWidth;
var offsetHeight = element.offsetHeight;
var webkitOffsetsZero =
goog.userAgent.WEBKIT && !offsetWidth && !offsetHeight;
if ((!goog.isDef(offsetWidth) || webkitOffsetsZero) &&
element.getBoundingClientRect) {
// Fall back to calling getBoundingClientRect when offsetWidth or
// offsetHeight are not defined, or when they are zero in WebKit browsers.
// This makes sure that we return for the correct size for SVG elements, but
// will still return 0 on Webkit prior to 534.8, see
// http://trac.webkit.org/changeset/67252.
var clientRect = goog.style.getBoundingClientRect_(element);
return new goog.math.Size(clientRect.right - clientRect.left,
clientRect.bottom - clientRect.top);
}
return new goog.math.Size(offsetWidth, offsetHeight);
};
/**
* Returns a bounding rectangle for a given element in page space.
* @param {Element} element Element to get bounds of. Must not be display none.
* @return {!goog.math.Rect} Bounding rectangle for the element.
*/
goog.style.getBounds = function(element) {
var o = goog.style.getPageOffset(element);
var s = goog.style.getSize(element);
return new goog.math.Rect(o.x, o.y, s.width, s.height);
};
/**
* Converts a CSS selector in the form style-property to styleProperty.
* @param {*} selector CSS Selector.
* @return {string} Camel case selector.
* @deprecated Use goog.string.toCamelCase instead.
*/
goog.style.toCamelCase = function(selector) {
return goog.string.toCamelCase(String(selector));
};
/**
* Converts a CSS selector in the form styleProperty to style-property.
* @param {string} selector Camel case selector.
* @return {string} Selector cased.
* @deprecated Use goog.string.toSelectorCase instead.
*/
goog.style.toSelectorCase = function(selector) {
return goog.string.toSelectorCase(selector);
};
/**
* Gets the opacity of a node (x-browser). This gets the inline style opacity
* of the node, and does not take into account the cascaded or the computed
* style for this node.
* @param {Element} el Element whose opacity has to be found.
* @return {number|string} Opacity between 0 and 1 or an empty string {@code ''}
* if the opacity is not set.
*/
goog.style.getOpacity = function(el) {
var style = el.style;
var result = '';
if ('opacity' in style) {
result = style.opacity;
} else if ('MozOpacity' in style) {
result = style.MozOpacity;
} else if ('filter' in style) {
var match = style.filter.match(/alpha\(opacity=([\d.]+)\)/);
if (match) {
result = String(match[1] / 100);
}
}
return result == '' ? result : Number(result);
};
/**
* Sets the opacity of a node (x-browser).
* @param {Element} el Elements whose opacity has to be set.
* @param {number|string} alpha Opacity between 0 and 1 or an empty string
* {@code ''} to clear the opacity.
*/
goog.style.setOpacity = function(el, alpha) {
var style = el.style;
if ('opacity' in style) {
style.opacity = alpha;
} else if ('MozOpacity' in style) {
style.MozOpacity = alpha;
} else if ('filter' in style) {
// TODO(arv): Overwriting the filter might have undesired side effects.
if (alpha === '') {
style.filter = '';
} else {
style.filter = 'alpha(opacity=' + alpha * 100 + ')';
}
}
};
/**
* Sets the background of an element to a transparent image in a browser-
* independent manner.
*
* This function does not support repeating backgrounds or alternate background
* positions to match the behavior of Internet Explorer. It also does not
* support sizingMethods other than crop since they cannot be replicated in
* browsers other than Internet Explorer.
*
* @param {Element} el The element to set background on.
* @param {string} src The image source URL.
*/
goog.style.setTransparentBackgroundImage = function(el, src) {
var style = el.style;
// It is safe to use the style.filter in IE only. In Safari 'filter' is in
// style object but access to style.filter causes it to throw an exception.
// Note: IE8 supports images with an alpha channel.
if (goog.userAgent.IE && !goog.userAgent.isVersion('8')) {
// See TODO in setOpacity.
style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(' +
'src="' + src + '", sizingMethod="crop")';
} else {
// Set style properties individually instead of using background shorthand
// to prevent overwriting a pre-existing background color.
style.backgroundImage = 'url(' + src + ')';
style.backgroundPosition = 'top left';
style.backgroundRepeat = 'no-repeat';
}
};
/**
* Clears the background image of an element in a browser independent manner.
* @param {Element} el The element to clear background image for.
*/
goog.style.clearTransparentBackgroundImage = function(el) {
var style = el.style;
if ('filter' in style) {
// See TODO in setOpacity.
style.filter = '';
} else {
// Set style properties individually instead of using background shorthand
// to prevent overwriting a pre-existing background color.
style.backgroundImage = 'none';
}
};
/**
* NOTE: This is deprecated, new code should call setElementShown() instead.
*
* Shows or hides an element from the page. Hiding the element is done by
* setting the display property to "none", removing the element from the
* rendering hierarchy so it takes up no space. To show the element, the default
* inherited display property is restored (defined either in stylesheets or by
* the browser's default style rules.)
*
* Caveat 1: if the inherited display property for the element is set to "none"
* by the stylesheets, that is the property that will be restored by a call to
* showElement(), effectively toggling the display between "none" and "none".
*
* Caveat 2: if the element display style is set inline (by setting either
* element.style.display or a style attribute in the HTML), a call to
* showElement will clear that setting and defer to the inherited style in the
* stylesheet.
* @param {Element} el Element to show or hide.
* @param {*} display True to render the element in its default style,
* false to disable rendering the element.
*/
goog.style.showElement = function(el, display) {
goog.style.setElementShown(el, display);
};
/**
* Shows or hides an element from the page. Hiding the element is done by
* setting the display property to "none", removing the element from the
* rendering hierarchy so it takes up no space. To show the element, the default
* inherited display property is restored (defined either in stylesheets or by
* the browser's default style rules).
*
* Caveat 1: if the inherited display property for the element is set to "none"
* by the stylesheets, that is the property that will be restored by a call to
* setElementShown(), effectively toggling the display between "none" and
* "none".
*
* Caveat 2: if the element display style is set inline (by setting either
* element.style.display or a style attribute in the HTML), a call to
* setElementShown will clear that setting and defer to the inherited style in
* the stylesheet.
* @param {Element} el Element to show or hide.
* @param {*} isShown True to render the element in its default style,
* false to disable rendering the element.
*/
goog.style.setElementShown = function(el, isShown) {
el.style.display = isShown ? '' : 'none';
};
/**
* Test whether the given element has been shown or hidden via a call to
* {@link #setElementShown}.
*
* Note this is strictly a companion method for a call
* to {@link #setElementShown} and the same caveats apply; in particular, this
* method does not guarantee that the return value will be consistent with
* whether or not the element is actually visible.
*
* @param {Element} el The element to test.
* @return {boolean} Whether the element has been shown.
* @see #setElementShown
*/
goog.style.isElementShown = function(el) {
return el.style.display != 'none';
};
/**
* Installs the styles string into the window that contains opt_element. If
* opt_element is null, the main window is used.
* @param {string} stylesString The style string to install.
* @param {Node=} opt_node Node whose parent document should have the
* styles installed.
* @return {Element|StyleSheet} The style element created.
*/
goog.style.installStyles = function(stylesString, opt_node) {
var dh = goog.dom.getDomHelper(opt_node);
var styleSheet = null;
if (goog.userAgent.IE) {
styleSheet = dh.getDocument().createStyleSheet();
goog.style.setStyles(styleSheet, stylesString);
} else {
var head = dh.getElementsByTagNameAndClass('head')[0];
// In opera documents are not guaranteed to have a head element, thus we
// have to make sure one exists before using it.
if (!head) {
var body = dh.getElementsByTagNameAndClass('body')[0];
head = dh.createDom('head');
body.parentNode.insertBefore(head, body);
}
styleSheet = dh.createDom('style');
// NOTE(user): Setting styles after the style element has been appended
// to the head results in a nasty Webkit bug in certain scenarios. Please
// refer to https://bugs.webkit.org/show_bug.cgi?id=26307 for additional
// details.
goog.style.setStyles(styleSheet, stylesString);
dh.appendChild(head, styleSheet);
}
return styleSheet;
};
/**
* Removes the styles added by {@link #installStyles}.
* @param {Element|StyleSheet} styleSheet The value returned by
* {@link #installStyles}.
*/
goog.style.uninstallStyles = function(styleSheet) {
var node = styleSheet.ownerNode || styleSheet.owningElement ||
/** @type {Element} */ (styleSheet);
goog.dom.removeNode(node);
};
/**
* Sets the content of a style element. The style element can be any valid
* style element. This element will have its content completely replaced by
* the new stylesString.
* @param {Element|StyleSheet} element A stylesheet element as returned by
* installStyles.
* @param {string} stylesString The new content of the stylesheet.
*/
goog.style.setStyles = function(element, stylesString) {
if (goog.userAgent.IE) {
// Adding the selectors individually caused the browser to hang if the
// selector was invalid or there were CSS comments. Setting the cssText of
// the style node works fine and ignores CSS that IE doesn't understand
element.cssText = stylesString;
} else {
element.innerHTML = stylesString;
}
};
/**
* Sets 'white-space: pre-wrap' for a node (x-browser).
*
* There are as many ways of specifying pre-wrap as there are browsers.
*
* CSS3/IE8: white-space: pre-wrap;
* Mozilla: white-space: -moz-pre-wrap;
* Opera: white-space: -o-pre-wrap;
* IE6/7: white-space: pre; word-wrap: break-word;
*
* @param {Element} el Element to enable pre-wrap for.
*/
goog.style.setPreWrap = function(el) {
var style = el.style;
if (goog.userAgent.IE && !goog.userAgent.isVersion('8')) {
style.whiteSpace = 'pre';
style.wordWrap = 'break-word';
} else if (goog.userAgent.GECKO) {
style.whiteSpace = '-moz-pre-wrap';
} else {
style.whiteSpace = 'pre-wrap';
}
};
/**
* Sets 'display: inline-block' for an element (cross-browser).
* @param {Element} el Element to which the inline-block display style is to be
* applied.
* @see ../demos/inline_block_quirks.html
* @see ../demos/inline_block_standards.html
*/
goog.style.setInlineBlock = function(el) {
var style = el.style;
// Without position:relative, weirdness ensues. Just accept it and move on.
style.position = 'relative';
if (goog.userAgent.IE && !goog.userAgent.isVersion('8')) {
// IE8 supports inline-block so fall through to the else
// Zoom:1 forces hasLayout, display:inline gives inline behavior.
style.zoom = '1';
style.display = 'inline';
} else if (goog.userAgent.GECKO) {
// Pre-Firefox 3, Gecko doesn't support inline-block, but -moz-inline-box
// is close enough.
style.display = goog.userAgent.isVersion('1.9a') ? 'inline-block' :
'-moz-inline-box';
} else {
// Opera, Webkit, and Safari seem to do OK with the standard inline-block
// style.
style.display = 'inline-block';
}
};
/**
* Returns true if the element is using right to left (rtl) direction.
* @param {Element} el The element to test.
* @return {boolean} True for right to left, false for left to right.
*/
goog.style.isRightToLeft = function(el) {
return 'rtl' == goog.style.getStyle_(el, 'direction');
};
/**
* The CSS style property corresponding to an element being
* unselectable on the current browser platform (null if none).
* Opera and IE instead use a DOM attribute 'unselectable'.
* @type {?string}
* @private
*/
goog.style.unselectableStyle_ =
goog.userAgent.GECKO ? 'MozUserSelect' :
goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
null;
/**
* Returns true if the element is set to be unselectable, false otherwise.
* Note that on some platforms (e.g. Mozilla), even if an element isn't set
* to be unselectable, it will behave as such if any of its ancestors is
* unselectable.
* @param {Element} el Element to check.
* @return {boolean} Whether the element is set to be unselectable.
*/
goog.style.isUnselectable = function(el) {
if (goog.style.unselectableStyle_) {
return el.style[goog.style.unselectableStyle_].toLowerCase() == 'none';
} else if (goog.userAgent.IE || goog.userAgent.OPERA) {
return el.getAttribute('unselectable') == 'on';
}
return false;
};
/**
* Makes the element and its descendants selectable or unselectable. Note
* that on some platforms (e.g. Mozilla), even if an element isn't set to
* be unselectable, it will behave as such if any of its ancestors is
* unselectable.
* @param {Element} el The element to alter.
* @param {boolean} unselectable Whether the element and its descendants
* should be made unselectable.
* @param {boolean=} opt_noRecurse Whether to only alter the element's own
* selectable state, and leave its descendants alone; defaults to false.
*/
goog.style.setUnselectable = function(el, unselectable, opt_noRecurse) {
// TODO(attila): Do we need all of TR_DomUtil.makeUnselectable() in Closure?
var descendants = !opt_noRecurse ? el.getElementsByTagName('*') : null;
var name = goog.style.unselectableStyle_;
if (name) {
// Add/remove the appropriate CSS style to/from the element and its
// descendants.
var value = unselectable ? 'none' : '';
el.style[name] = value;
if (descendants) {
for (var i = 0, descendant; descendant = descendants[i]; i++) {
descendant.style[name] = value;
}
}
} else if (goog.userAgent.IE || goog.userAgent.OPERA) {
// Toggle the 'unselectable' attribute on the element and its descendants.
var value = unselectable ? 'on' : '';
el.setAttribute('unselectable', value);
if (descendants) {
for (var i = 0, descendant; descendant = descendants[i]; i++) {
descendant.setAttribute('unselectable', value);
}
}
}
};
/**
* Gets the border box size for an element.
* @param {Element} element The element to get the size for.
* @return {!goog.math.Size} The border box size.
*/
goog.style.getBorderBoxSize = function(element) {
return new goog.math.Size(element.offsetWidth, element.offsetHeight);
};
/**
* Sets the border box size of an element. This is potentially expensive in IE
* if the document is CSS1Compat mode
* @param {Element} element The element to set the size on.
* @param {goog.math.Size} size The new size.
*/
goog.style.setBorderBoxSize = function(element, size) {
var doc = goog.dom.getOwnerDocument(element);
var isCss1CompatMode = goog.dom.getDomHelper(doc).isCss1CompatMode();
if (goog.userAgent.IE &&
(!isCss1CompatMode || !goog.userAgent.isVersion('8'))) {
var style = element.style;
if (isCss1CompatMode) {
var paddingBox = goog.style.getPaddingBox(element);
var borderBox = goog.style.getBorderBox(element);
style.pixelWidth = size.width - borderBox.left - paddingBox.left -
paddingBox.right - borderBox.right;
style.pixelHeight = size.height - borderBox.top - paddingBox.top -
paddingBox.bottom - borderBox.bottom;
} else {
style.pixelWidth = size.width;
style.pixelHeight = size.height;
}
} else {
goog.style.setBoxSizingSize_(element, size, 'border-box');
}
};
/**
* Gets the content box size for an element. This is potentially expensive in
* all browsers.
* @param {Element} element The element to get the size for.
* @return {!goog.math.Size} The content box size.
*/
goog.style.getContentBoxSize = function(element) {
var doc = goog.dom.getOwnerDocument(element);
var ieCurrentStyle = goog.userAgent.IE && element.currentStyle;
if (ieCurrentStyle &&
goog.dom.getDomHelper(doc).isCss1CompatMode() &&
ieCurrentStyle.width != 'auto' && ieCurrentStyle.height != 'auto' &&
!ieCurrentStyle.boxSizing) {
// If IE in CSS1Compat mode than just use the width and height.
// If we have a boxSizing then fall back on measuring the borders etc.
var width = goog.style.getIePixelValue_(element, ieCurrentStyle.width,
'width', 'pixelWidth');
var height = goog.style.getIePixelValue_(element, ieCurrentStyle.height,
'height', 'pixelHeight');
return new goog.math.Size(width, height);
} else {
var borderBoxSize = goog.style.getBorderBoxSize(element);
var paddingBox = goog.style.getPaddingBox(element);
var borderBox = goog.style.getBorderBox(element);
return new goog.math.Size(borderBoxSize.width -
borderBox.left - paddingBox.left -
paddingBox.right - borderBox.right,
borderBoxSize.height -
borderBox.top - paddingBox.top -
paddingBox.bottom - borderBox.bottom);
}
};
/**
* Sets the content box size of an element. This is potentially expensive in IE
* if the document is BackCompat mode.
* @param {Element} element The element to set the size on.
* @param {goog.math.Size} size The new size.
*/
goog.style.setContentBoxSize = function(element, size) {
var doc = goog.dom.getOwnerDocument(element);
var isCss1CompatMode = goog.dom.getDomHelper(doc).isCss1CompatMode();
if (goog.userAgent.IE &&
(!isCss1CompatMode || !goog.userAgent.isVersion('8'))) {
var style = element.style;
if (isCss1CompatMode) {
style.pixelWidth = size.width;
style.pixelHeight = size.height;
} else {
var paddingBox = goog.style.getPaddingBox(element);
var borderBox = goog.style.getBorderBox(element);
style.pixelWidth = size.width + borderBox.left + paddingBox.left +
paddingBox.right + borderBox.right;
style.pixelHeight = size.height + borderBox.top + paddingBox.top +
paddingBox.bottom + borderBox.bottom;
}
} else {
goog.style.setBoxSizingSize_(element, size, 'content-box');
}
};
/**
* Helper function that sets the box sizing as well as the width and height
* @param {Element} element The element to set the size on.
* @param {goog.math.Size} size The new size to set.
* @param {string} boxSizing The box-sizing value.
* @private
*/
goog.style.setBoxSizingSize_ = function(element, size, boxSizing) {
var style = element.style;
if (goog.userAgent.GECKO) {
style.MozBoxSizing = boxSizing;
} else if (goog.userAgent.WEBKIT) {
style.WebkitBoxSizing = boxSizing;
} else {
// Includes IE8 and Opera 9.50+
style.boxSizing = boxSizing;
}
// Setting this to a negative value will throw an exception on IE
// (and doesn't do anything different than setting it to 0).
style.width = Math.max(size.width, 0) + 'px';
style.height = Math.max(size.height, 0) + 'px';
};
/**
* IE specific function that converts a non pixel unit to pixels.
* @param {Element} element The element to convert the value for.
* @param {string} value The current value as a string. The value must not be
* ''.
* @param {string} name The CSS property name to use for the converstion. This
* should be 'left', 'top', 'width' or 'height'.
* @param {string} pixelName The CSS pixel property name to use to get the
* value in pixels.
* @return {number} The value in pixels.
* @private
*/
goog.style.getIePixelValue_ = function(element, value, name, pixelName) {
// Try if we already have a pixel value. IE does not do half pixels so we
// only check if it matches a number followed by 'px'.
if (/^\d+px?$/.test(value)) {
return parseInt(value, 10);
} else {
var oldStyleValue = element.style[name];
var oldRuntimeValue = element.runtimeStyle[name];
// set runtime style to prevent changes
element.runtimeStyle[name] = element.currentStyle[name];
element.style[name] = value;
var pixelValue = element.style[pixelName];
// restore
element.style[name] = oldStyleValue;
element.runtimeStyle[name] = oldRuntimeValue;
return pixelValue;
}
};
/**
* Helper function for getting the pixel padding or margin for IE.
* @param {Element} element The element to get the padding for.
* @param {string} propName The property name.
* @return {number} The pixel padding.
* @private
*/
goog.style.getIePixelDistance_ = function(element, propName) {
var value = goog.style.getCascadedStyle(element, propName);
return value ?
goog.style.getIePixelValue_(element, value, 'left', 'pixelLeft') : 0;
};
/**
* Gets the computed paddings or margins (on all sides) in pixels.
* @param {Element} element The element to get the padding for.
* @param {string} stylePrefix Pass 'padding' to retrieve the padding box,
* or 'margin' to retrieve the margin box.
* @return {!goog.math.Box} The computed paddings or margins.
* @private
*/
goog.style.getBox_ = function(element, stylePrefix) {
if (goog.userAgent.IE) {
var left = goog.style.getIePixelDistance_(element, stylePrefix + 'Left');
var right = goog.style.getIePixelDistance_(element, stylePrefix + 'Right');
var top = goog.style.getIePixelDistance_(element, stylePrefix + 'Top');
var bottom = goog.style.getIePixelDistance_(
element, stylePrefix + 'Bottom');
return new goog.math.Box(top, right, bottom, left);
} else {
// On non-IE browsers, getComputedStyle is always non-null.
var left = /** @type {string} */ (
goog.style.getComputedStyle(element, stylePrefix + 'Left'));
var right = /** @type {string} */ (
goog.style.getComputedStyle(element, stylePrefix + 'Right'));
var top = /** @type {string} */ (
goog.style.getComputedStyle(element, stylePrefix + 'Top'));
var bottom = /** @type {string} */ (
goog.style.getComputedStyle(element, stylePrefix + 'Bottom'));
// NOTE(arv): Gecko can return floating point numbers for the computed
// style values.
return new goog.math.Box(parseFloat(top),
parseFloat(right),
parseFloat(bottom),
parseFloat(left));
}
};
/**
* Gets the computed paddings (on all sides) in pixels.
* @param {Element} element The element to get the padding for.
* @return {!goog.math.Box} The computed paddings.
*/
goog.style.getPaddingBox = function(element) {
return goog.style.getBox_(element, 'padding');
};
/**
* Gets the computed margins (on all sides) in pixels.
* @param {Element} element The element to get the margins for.
* @return {!goog.math.Box} The computed margins.
*/
goog.style.getMarginBox = function(element) {
return goog.style.getBox_(element, 'margin');
};
/**
* A map used to map the border width keywords to a pixel width.
* @type {Object}
* @private
*/
goog.style.ieBorderWidthKeywords_ = {
'thin': 2,
'medium': 4,
'thick': 6
};
/**
* Helper function for IE to get the pixel border.
* @param {Element} element The element to get the pixel border for.
* @param {string} prop The part of the property name.
* @return {number} The value in pixels.
* @private
*/
goog.style.getIePixelBorder_ = function(element, prop) {
if (goog.style.getCascadedStyle(element, prop + 'Style') == 'none') {
return 0;
}
var width = goog.style.getCascadedStyle(element, prop + 'Width');
if (width in goog.style.ieBorderWidthKeywords_) {
return goog.style.ieBorderWidthKeywords_[width];
}
return goog.style.getIePixelValue_(element, width, 'left', 'pixelLeft');
};
/**
* Gets the computed border widths (on all sides) in pixels
* @param {Element} element The element to get the border widths for.
* @return {!goog.math.Box} The computed border widths.
*/
goog.style.getBorderBox = function(element) {
if (goog.userAgent.IE) {
var left = goog.style.getIePixelBorder_(element, 'borderLeft');
var right = goog.style.getIePixelBorder_(element, 'borderRight');
var top = goog.style.getIePixelBorder_(element, 'borderTop');
var bottom = goog.style.getIePixelBorder_(element, 'borderBottom');
return new goog.math.Box(top, right, bottom, left);
} else {
// On non-IE browsers, getComputedStyle is always non-null.
var left = /** @type {string} */ (
goog.style.getComputedStyle(element, 'borderLeftWidth'));
var right = /** @type {string} */ (
goog.style.getComputedStyle(element, 'borderRightWidth'));
var top = /** @type {string} */ (
goog.style.getComputedStyle(element, 'borderTopWidth'));
var bottom = /** @type {string} */ (
goog.style.getComputedStyle(element, 'borderBottomWidth'));
return new goog.math.Box(parseFloat(top),
parseFloat(right),
parseFloat(bottom),
parseFloat(left));
}
};
/**
* Returns the font face applied to a given node. Opera and IE should return
* the font actually displayed. Firefox returns the author's most-preferred
* font (whether the browser is capable of displaying it or not.)
* @param {Element} el The element whose font family is returned.
* @return {string} The font family applied to el.
*/
goog.style.getFontFamily = function(el) {
var doc = goog.dom.getOwnerDocument(el);
var font = '';
if (doc.body.createTextRange) {
var range = doc.body.createTextRange();
range.moveToElementText(el);
/** @preserveTry */
try {
font = range.queryCommandValue('FontName');
} catch (e) {
// This is a workaround for a awkward exception.
// On some IE, there is an exception coming from it.
// The error description from this exception is:
// This window has already been registered as a drop target
// This is bogus description, likely due to a bug in ie.
font = '';
}
}
if (!font) {
// Note if for some reason IE can't derive FontName with a TextRange, we
// fallback to using currentStyle
font = goog.style.getStyle_(el, 'fontFamily');
}
// Firefox returns the applied font-family string (author's list of
// preferred fonts.) We want to return the most-preferred font, in lieu of
// the *actually* applied font.
var fontsArray = font.split(',');
if (fontsArray.length > 1) font = fontsArray[0];
// Sanitize for x-browser consistency:
// Strip quotes because browsers aren't consistent with how they're
// applied; Opera always encloses, Firefox sometimes, and IE never.
return goog.string.stripQuotes(font, '"\'');
};
/**
* Regular expression used for getLengthUnits.
* @type {RegExp}
* @private
*/
goog.style.lengthUnitRegex_ = /[^\d]+$/;
/**
* Returns the units used for a CSS length measurement.
* @param {string} value A CSS length quantity.
* @return {?string} The units of measurement.
*/
goog.style.getLengthUnits = function(value) {
var units = value.match(goog.style.lengthUnitRegex_);
return units && units[0] || null;
};
/**
* Map of absolute CSS length units
* @type {Object}
* @private
*/
goog.style.ABSOLUTE_CSS_LENGTH_UNITS_ = {
'cm' : 1,
'in' : 1,
'mm' : 1,
'pc' : 1,
'pt' : 1
};
/**
* Map of relative CSS length units that can be accurately converted to px
* font-size values using getIePixelValue_. Only units that are defined in
* relation to a font size are convertible (%, small, etc. are not).
* @type {Object}
* @private
*/
goog.style.CONVERTIBLE_RELATIVE_CSS_UNITS_ = {
'em' : 1,
'ex' : 1
};
/**
* Returns the font size, in pixels, of text in an element.
* @param {Element} el The element whose font size is returned.
* @return {number} The font size (in pixels).
*/
goog.style.getFontSize = function(el) {
var fontSize = goog.style.getStyle_(el, 'fontSize');
var sizeUnits = goog.style.getLengthUnits(fontSize);
if (fontSize && 'px' == sizeUnits) {
// NOTE(user): This could be parseFloat instead, but IE doesn't return
// decimal fractions in getStyle_ and Firefox reports the fractions, but
// ignores them when rendering. Interestingly enough, when we force the
// issue and size something to e.g., 50% of 25px, the browsers round in
// opposite directions with Firefox reporting 12px and IE 13px. I punt.
return parseInt(fontSize, 10);
}
// In IE, we can convert absolute length units to a px value using
// goog.style.getIePixelValue_. Units defined in relation to a font size
// (em, ex) are applied relative to the element's parentNode and can also
// be converted.
if (goog.userAgent.IE) {
if (sizeUnits in goog.style.ABSOLUTE_CSS_LENGTH_UNITS_) {
return goog.style.getIePixelValue_(el,
fontSize,
'left',
'pixelLeft');
} else if (el.parentNode &&
el.parentNode.nodeType == goog.dom.NodeType.ELEMENT &&
sizeUnits in goog.style.CONVERTIBLE_RELATIVE_CSS_UNITS_) {
// Check the parent size - if it is the same it means the relative size
// value is inherited and we therefore don't want to count it twice. If
// it is different, this element either has explicit style or has a CSS
// rule applying to it.
var parentElement = /** @type {Element} */ (el.parentNode);
var parentSize = goog.style.getStyle_(parentElement, 'fontSize');
return goog.style.getIePixelValue_(parentElement,
fontSize == parentSize ?
'1em' : fontSize,
'left',
'pixelLeft');
}
}
// Sometimes we can't cleanly find the font size (some units relative to a
// node's parent's font size are difficult: %, smaller et al), so we create
// an invisible, absolutely-positioned span sized to be the height of an 'M'
// rendered in its parent's (i.e., our target element's) font size. This is
// the definition of CSS's font size attribute.
var sizeElement = goog.dom.createDom(
'span',
{'style': 'visibility:hidden;position:absolute;' +
'line-height:0;padding:0;margin:0;border:0;height:1em;'});
goog.dom.appendChild(el, sizeElement);
fontSize = sizeElement.offsetHeight;
goog.dom.removeNode(sizeElement);
return fontSize;
};
/**
* Parses a style attribute value. Converts CSS property names to camel case.
* @param {string} value The style attribute value.
* @return {!Object} Map of CSS properties to string values.
*/
goog.style.parseStyleAttribute = function(value) {
var result = {};
goog.array.forEach(value.split(/\s*;\s*/), function(pair) {
var keyValue = pair.split(/\s*:\s*/);
if (keyValue.length == 2) {
result[goog.string.toCamelCase(keyValue[0].toLowerCase())] = keyValue[1];
}
});
return result;
};
/**
* Reverse of parseStyleAttribute; that is, takes a style object and returns the
* corresponding attribute value. Converts camel case property names to proper
* CSS selector names.
* @param {Object} obj Map of CSS properties to values.
* @return {string} The style attribute value.
*/
goog.style.toStyleAttribute = function(obj) {
var buffer = [];
goog.object.forEach(obj, function(value, key) {
buffer.push(goog.string.toSelectorCase(key), ':', value, ';');
});
return buffer.join('');
};
/**
* Sets CSS float property on an element.
* @param {Element} el The element to set float property on.
* @param {string} value The value of float CSS property to set on this element.
*/
goog.style.setFloat = function(el, value) {
el.style[goog.userAgent.IE ? 'styleFloat' : 'cssFloat'] = value;
};
/**
* Gets value of explicitly-set float CSS property on an element.
* @param {Element} el The element to get float property of.
* @return {string} The value of explicitly-set float CSS property on this
* element.
*/
goog.style.getFloat = function(el) {
return el.style[goog.userAgent.IE ? 'styleFloat' : 'cssFloat'] || '';
};
/**
* Returns the scroll bar width (represents the width of both horizontal
* and vertical scroll).
*
* @param {string=} opt_className An optional class name (or names) to apply
* to the invisible div created to measure the scrollbar. This is necessary
* if some scrollbars are styled differently than others.
* @return {number} The scroll bar width in px.
*/
goog.style.getScrollbarWidth = function(opt_className) {
// Add two hidden divs. The child div is larger than the parent and
// forces scrollbars to appear on it.
// Using overflow:scroll does not work consistently with scrollbars that
// are styled with ::-webkit-scrollbar.
var outerDiv = goog.dom.createElement('div');
if (opt_className) {
outerDiv.className = opt_className;
}
outerDiv.style.cssText = 'overflow:auto;' +
'position:absolute;top:0;width:100px;height:100px';
var innerDiv = goog.dom.createElement('div');
goog.style.setSize(innerDiv, '200px', '200px');
outerDiv.appendChild(innerDiv);
goog.dom.appendChild(goog.dom.getDocument().body, outerDiv);
var width = outerDiv.offsetWidth - outerDiv.clientWidth;
goog.dom.removeNode(outerDiv);
return width;
};
/**
* Regular expression to extract x and y translation components from a CSS
* transform Matrix representation.
*
* @type {!RegExp}
* @const
* @private
*/
goog.style.MATRIX_TRANSLATION_REGEX_ =
new RegExp('matrix\\([0-9\\.\\-]+, [0-9\\.\\-]+, ' +
'[0-9\\.\\-]+, [0-9\\.\\-]+, ' +
'([0-9\\.\\-]+)p?x?, ([0-9\\.\\-]+)p?x?\\)');
/**
* Returns the x,y translation component of any CSS transforms applied to the
* element, in pixels.
*
* @param {!Element} element The element to get the translation of.
* @return {!goog.math.Coordinate} The CSS translation of the element in px.
*/
goog.style.getCssTranslation = function(element) {
var property;
if (goog.userAgent.IE) {
property = '-ms-transform';
} else if (goog.userAgent.WEBKIT) {
property = '-webkit-transform';
} else if (goog.userAgent.OPERA) {
property = '-o-transform';
} else if (goog.userAgent.GECKO) {
property = '-moz-transform';
}
var transform;
if (property) {
transform = goog.style.getStyle_(element, property);
}
if (!transform) {
transform = goog.style.getStyle_(element, 'transform');
}
if (!transform) {
return new goog.math.Coordinate(0, 0);
}
var matches = transform.match(goog.style.MATRIX_TRANSLATION_REGEX_);
if (!matches) {
return new goog.math.Coordinate(0, 0);
}
return new goog.math.Coordinate(parseFloat(matches[1]),
parseFloat(matches[2]));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Shared unit tests for scrollbar measurement.
*
* @author flan@google.com (Ian Flanigan)
*/
goog.provide('goog.styleScrollbarTester');
goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.testing.asserts');
goog.setTestOnly('goog.styleScrollbarTester');
/**
* Tests the scrollbar width calculation. Assumes that there is an element with
* id 'test-scrollbarwidth' in the page.
*/
function testScrollbarWidth() {
var width = goog.style.getScrollbarWidth();
assertTrue(width > 0);
var outer = goog.dom.getElement('test-scrollbarwidth');
var inner = goog.dom.getElementsByTagNameAndClass('div', null, outer)[0];
assertTrue('should have a scroll bar',
hasVerticalScroll(outer));
assertTrue('should have a scroll bar',
hasHorizontalScroll(outer));
// Get the inner div absolute width
goog.style.setStyle(outer, 'width', '100%');
assertTrue('should have a scroll bar',
hasVerticalScroll(outer));
assertFalse('should not have a scroll bar',
hasHorizontalScroll(outer));
var innerAbsoluteWidth = inner.offsetWidth;
// Leave the vertical scroll and remove the horizontal by using the scroll
// bar width calculation.
goog.style.setStyle(outer, 'width',
(innerAbsoluteWidth + width) + 'px');
assertTrue('should have a scroll bar',
hasVerticalScroll(outer));
assertFalse('should not have a scroll bar',
hasHorizontalScroll(outer));
// verify by adding 1 more pixel (brings back the vertical scroll bar).
goog.style.setStyle(outer, 'width',
(innerAbsoluteWidth + width - 1) + 'px');
assertTrue('should have a scroll bar',
hasVerticalScroll(outer));
assertTrue('should have a scroll bar',
hasHorizontalScroll(outer));
}
function hasVerticalScroll(el) {
return el.clientWidth != 0 && el.offsetWidth - el.clientWidth > 0;
}
function hasHorizontalScroll(el) {
return el.clientHeight != 0 && el.offsetHeight - el.clientHeight > 0;
}
| JavaScript |
// Copyright 2005 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Functions to create special cursor styles, like "draggable"
* (open hand) or "dragging" (closed hand).
*
*/
goog.provide('goog.style.cursor');
goog.require('goog.userAgent');
/**
* The file name for the open-hand (draggable) cursor.
* @type {string}
*/
goog.style.cursor.OPENHAND_FILE = 'openhand.cur';
/**
* The file name for the close-hand (dragging) cursor.
* @type {string}
*/
goog.style.cursor.CLOSEDHAND_FILE = 'closedhand.cur';
/**
* Create the style for the draggable cursor based on browser and OS.
* The value can be extended to be '!important' if needed.
*
* @param {string} absoluteDotCurFilePath The absolute base path of
* 'openhand.cur' file to be used if the browser supports it.
* @param {boolean=} opt_obsolete Just for compiler backward compatibility.
* @return {string} The "draggable" mouse cursor style value.
*/
goog.style.cursor.getDraggableCursorStyle = function(
absoluteDotCurFilePath, opt_obsolete) {
return goog.style.cursor.getCursorStyle_(
'-moz-grab',
absoluteDotCurFilePath + goog.style.cursor.OPENHAND_FILE,
'default');
};
/**
* Create the style for the dragging cursor based on browser and OS.
* The value can be extended to be '!important' if needed.
*
* @param {string} absoluteDotCurFilePath The absolute base path of
* 'closedhand.cur' file to be used if the browser supports it.
* @param {boolean=} opt_obsolete Just for compiler backward compatibility.
* @return {string} The "dragging" mouse cursor style value.
*/
goog.style.cursor.getDraggingCursorStyle = function(
absoluteDotCurFilePath, opt_obsolete) {
return goog.style.cursor.getCursorStyle_(
'-moz-grabbing',
absoluteDotCurFilePath + goog.style.cursor.CLOSEDHAND_FILE,
'move');
};
/**
* Create the style for the cursor based on browser and OS.
*
* @param {string} geckoNonWinBuiltInStyleValue The Gecko on non-Windows OS,
* built in cursor style.
* @param {string} absoluteDotCurFilePath The .cur file absolute file to be
* used if the browser supports it.
* @param {string} defaultStyle The default fallback cursor style.
* @return {string} The computed mouse cursor style value.
* @private
*/
goog.style.cursor.getCursorStyle_ = function(geckoNonWinBuiltInStyleValue,
absoluteDotCurFilePath, defaultStyle) {
// Use built in cursors for Gecko on non Windows OS.
// We prefer our custom cursor, but Firefox Mac and Firefox Linux
// cannot do custom cursors. They do have a built-in hand, so use it:
if (goog.userAgent.GECKO && !goog.userAgent.WINDOWS) {
return geckoNonWinBuiltInStyleValue;
}
// Use the custom cursor file.
var cursorStyleValue = 'url("' + absoluteDotCurFilePath + '")';
// Change hot-spot for Safari.
if (goog.userAgent.WEBKIT) {
// Safari seems to ignore the hotspot specified in the .cur file (it uses
// 0,0 instead). This causes the cursor to jump as it transitions between
// openhand and pointer which is especially annoying when trying to hover
// over the route for draggable routes. We specify the hotspot here as 7,5
// in the css - unfortunately ie6 can't understand this and falls back to
// the builtin cursors so we just do this for safari (but ie DOES correctly
// use the hotspot specified in the file so this is ok). The appropriate
// coordinates were determined by looking at a hex dump and the format
// description from wikipedia.
cursorStyleValue += ' 7 5';
}
// Add default cursor fallback.
cursorStyleValue += ', ' + defaultStyle;
return cursorStyleValue;
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Shared unit tests for styles.
*/
/** @suppress {extraProvide} */
goog.provide('goog.style_test');
goog.require('goog.array');
goog.require('goog.color');
goog.require('goog.dom');
goog.require('goog.events.BrowserEvent');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Rect');
goog.require('goog.math.Size');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.testing.ExpectedFailures');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.require('goog.userAgent.product.isVersion');
goog.setTestOnly('goog.style_test');
// IE before version 6 will always be border box in compat mode.
var isBorderBox = goog.dom.isCss1CompatMode() ?
(goog.userAgent.IE && !goog.userAgent.isVersion('6')) :
true;
var EPSILON = 2;
var expectedFailures = new goog.testing.ExpectedFailures();
var $ = goog.dom.getElement;
var propertyReplacer = new goog.testing.PropertyReplacer();
var UserAgents = {
GECKO: 'GECKO',
IE: 'IE',
OPERA: 'OPERA',
WEBKIT: 'WEBKIT'
};
function setUpPage() {
var viewportSize = goog.dom.getViewportSize();
// When the window is too short or not wide enough, some tests, especially
// those for off-screen elements, fail. Oddly, the most reliable
// indicator is a width of zero (which is of course erroneous), since
// height sometimes includes a scroll bar. We can make no assumptions on
// window size on the Selenium farm.
if (goog.userAgent.IE && viewportSize.width < 300) {
// Move to origin, since IE won't resize outside the screen.
window.moveTo(0, 0);
window.resizeTo(640, 480);
}
}
function setUp() {
window.scrollTo(0, 0);
}
function tearDown() {
expectedFailures.handleTearDown();
var testVisibleDiv2 = goog.dom.getElement('test-visible2');
testVisibleDiv2.setAttribute('style', '');
testVisibleDiv2.innerHTML = '';
var testViewport = goog.dom.getElement('test-viewport');
testViewport.setAttribute('style', '');
testViewport.innerHTML = '';
propertyReplacer.reset();
reinitializeUserAgent();
}
function testSetStyle() {
var el = $('span1');
goog.style.setStyle(el, 'textDecoration', 'underline');
assertEquals('Should be underline', 'underline', el.style.textDecoration);
}
function testSetStyleMap() {
var el = $('span6');
var styles = {
'background-color': 'blue',
'font-size': '100px',
textAlign: 'center'
};
goog.style.setStyle(el, styles);
var answers = {
backgroundColor: 'blue',
fontSize: '100px',
textAlign: 'center'
};
goog.object.forEach(answers, function(value, style) {
assertEquals('Should be ' + value, value, el.style[style]);
});
}
function testSetStyleWithNonCamelizedString() {
var el = $('span5');
goog.style.setStyle(el, 'text-decoration', 'underline');
assertEquals('Should be underline', 'underline', el.style.textDecoration);
}
function testGetStyle() {
var el = goog.dom.getElement('styleTest3');
goog.style.setStyle(el, 'width', '80px');
goog.style.setStyle(el, 'textDecoration', 'underline');
assertEquals('80px', goog.style.getStyle(el, 'width'));
assertEquals('underline', goog.style.getStyle(el, 'textDecoration'));
assertEquals('underline', goog.style.getStyle(el, 'text-decoration'));
// Non set properties are always empty strings.
assertEquals('', goog.style.getStyle(el, 'border'));
}
function testGetStyleMsFilter() {
// Element with -ms-filter style set.
var e = goog.dom.getElement('msFilter');
if (goog.userAgent.IE && goog.userAgent.isDocumentMode(8)) {
// Only IE8 supports -ms-filter and returns it as value for the "filter"
// property. When in compatibility mode, -ms-filter is not supported
// and IE8 behaves as IE7 so the other case will apply.
assertEquals('alpha(opacity=0)', goog.style.getStyle(e, 'filter'));
} else {
// Any other browser does not support ms-filter so it returns empty string.
assertEquals('', goog.style.getStyle(e, 'filter'));
}
}
function testGetStyleFilter() {
// Element with filter style set.
var e = goog.dom.getElement('filter');
if (goog.userAgent.IE) {
// Filter supported.
assertEquals('alpha(opacity=0)', goog.style.getStyle(e, 'filter'));
} else {
assertEquals('', goog.style.getStyle(e, 'filter'));
}
}
function testGetComputedStyleMsFilter() {
// Element with -ms-filter style set.
var e = goog.dom.getElement('msFilter');
if (goog.userAgent.IE) {
// IE always returns empty string for computed styles.
assertEquals('', goog.style.getComputedStyle(e, 'filter'));
} else {
// Non IE returns 'none' for filter as it is an SVG property
assertEquals('none', goog.style.getComputedStyle(e, 'filter'));
}
}
function testGetComputedStyleFilter() {
// Element with filter style set.
var e = goog.dom.getElement('filter');
if (goog.userAgent.IE) {
// IE always returns empty string for computed styles.
assertEquals('', goog.style.getComputedStyle(e, 'filter'));
} else {
// Non IE returns 'none' for filter as it is an SVG property
assertEquals('none', goog.style.getComputedStyle(e, 'filter'));
}
}
function testGetComputedPosition() {
assertEquals('position not set', 'static',
goog.style.getComputedPosition($('position-unset')));
assertEquals('position:relative in style attribute', 'relative',
goog.style.getComputedPosition($('style-position-relative')));
if (goog.userAgent.IE && !goog.dom.isCss1CompatMode()) {
assertEquals('position:fixed in style attribute', 'static',
goog.style.getComputedPosition($('style-position-fixed')));
} else {
assertEquals('position:fixed in style attribute', 'fixed',
goog.style.getComputedPosition($('style-position-fixed')));
}
assertEquals('position:absolute in css', 'absolute',
goog.style.getComputedPosition($('css-position-absolute')));
}
function testGetComputedOverflowXAndY() {
assertEquals('overflow-x:scroll in style attribute', 'scroll',
goog.style.getComputedOverflowX($('style-overflow-scroll')));
assertEquals('overflow-y:scroll in style attribute', 'scroll',
goog.style.getComputedOverflowY($('style-overflow-scroll')));
assertEquals('overflow-x:hidden in css', 'hidden',
goog.style.getComputedOverflowX($('css-overflow-hidden')));
assertEquals('overflow-y:hidden in css', 'hidden',
goog.style.getComputedOverflowY($('css-overflow-hidden')));
}
function testGetComputedZIndex() {
assertEquals('z-index:200 in style attribute', '200',
'' + goog.style.getComputedZIndex($('style-z-index-200')));
assertEquals('z-index:200 in css', '200',
'' + goog.style.getComputedZIndex($('css-z-index-200')));
}
function testGetComputedTextAlign() {
assertEquals('text-align:right in style attribute', 'right',
goog.style.getComputedTextAlign($('style-text-align-right')));
assertEquals(
'text-align:right inherited from parent', 'right',
goog.style.getComputedTextAlign($('style-text-align-right-inner')));
assertEquals('text-align:center in css', 'center',
goog.style.getComputedTextAlign($('css-text-align-center')));
}
function testGetComputedCursor() {
assertEquals('cursor:move in style attribute', 'move',
goog.style.getComputedCursor($('style-cursor-move')));
assertEquals('cursor:move inherited from parent', 'move',
goog.style.getComputedCursor($('style-cursor-move-inner')));
assertEquals('cursor:poiner in css', 'pointer',
goog.style.getComputedCursor($('css-cursor-pointer')));
}
function testGetBackgroundColor() {
var dest = $('bgcolorDest');
for (var i = 0; $('bgcolorTest' + i); i++) {
var src = $('bgcolorTest' + i);
var bgColor = goog.style.getBackgroundColor(src);
dest.style.backgroundColor = bgColor;
assertEquals('Background colors should be equal',
goog.style.getBackgroundColor(src),
goog.style.getBackgroundColor(dest));
try {
// goog.color.parse throws a generic exception if handed input it
// doesn't understand.
var c = goog.color.parse(bgColor);
assertEquals('rgb(255,0,0)', goog.color.hexToRgbStyle(c.hex));
} catch (e) {
// Internet Explorer is unable to parse colors correctly after test 4.
// Other browsers may vary, but all should be able to handle straight
// hex input.
assertFalse('Should be able to parse color "' + bgColor + '"', i < 5);
}
}
}
function testSetPosition() {
var el = $('testEl');
goog.style.setPosition(el, 100, 100);
assertEquals('100px', el.style.left);
assertEquals('100px', el.style.top);
goog.style.setPosition(el, '50px', '25px');
assertEquals('50px', el.style.left);
assertEquals('25px', el.style.top);
goog.style.setPosition(el, '10ex', '25px');
assertEquals('10ex', el.style.left);
assertEquals('25px', el.style.top);
goog.style.setPosition(el, '10%', '25%');
assertEquals('10%', el.style.left);
assertEquals('25%', el.style.top);
// ignores stupid units
goog.style.setPosition(el, 0, 0);
// TODO(user): IE errors if you set these values. Should we make setStyle
// catch these? Or leave it up to the app. Fixing the tests for now.
//goog.style.setPosition(el, '10rainbows', '25rainbows');
assertEquals('0px', el.style.left);
assertEquals('0px', el.style.top);
goog.style.setPosition(el, new goog.math.Coordinate(20, 40));
assertEquals('20px', el.style.left);
assertEquals('40px', el.style.top);
}
function testGetClientPositionAbsPositionElement() {
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '100px';
div.style.top = '200px';
document.body.appendChild(div);
var pos = goog.style.getClientPosition(div);
assertEquals(100, pos.x);
assertEquals(200, pos.y);
}
function testGetClientPositionNestedElements() {
var innerDiv = goog.dom.createDom('DIV');
innerDiv.style.position = 'relative';
innerDiv.style.left = '-10px';
innerDiv.style.top = '-10px';
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '150px';
div.style.top = '250px';
div.appendChild(innerDiv);
document.body.appendChild(div);
var pos = goog.style.getClientPosition(innerDiv);
assertEquals(140, pos.x);
assertEquals(240, pos.y);
}
function testGetClientPositionOfOffscreenElement() {
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '2000px';
div.style.top = '2000px';
div.style.width = '10px';
div.style.height = '10px';
document.body.appendChild(div);
try {
window.scroll(0, 0);
var pos = goog.style.getClientPosition(div);
assertEquals(2000, pos.x);
assertEquals(2000, pos.y);
// The following tests do not work in Gecko 1.8 and below, due to an
// obscure off-by-one bug in goog.style.getPageOffset. Same for IE.
if (!goog.userAgent.IE &&
!(goog.userAgent.GECKO && !goog.userAgent.isVersion('1.9'))) {
window.scroll(1, 1);
var pos = goog.style.getClientPosition(div);
assertEquals(1999, pos.x);
assertEquals(1999, pos.y);
window.scroll(2, 2);
pos = goog.style.getClientPosition(div);
assertEquals(1998, pos.x);
assertEquals(1998, pos.y);
window.scroll(100, 100);
pos = goog.style.getClientPosition(div);
assertEquals(1900, pos.x);
assertEquals(1900, pos.y);
}
}
finally {
window.scroll(0, 0);
document.body.removeChild(div);
}
}
function testGetClientPositionEvent() {
var mockEvent = {};
mockEvent.clientX = 100;
mockEvent.clientY = 200;
var pos = goog.style.getClientPosition(mockEvent);
assertEquals(100, pos.x);
assertEquals(200, pos.y);
}
function testGetClientPositionTouchEvent() {
var mockTouchEvent = {};
mockTouchEvent.targetTouches = [{}];
mockTouchEvent.targetTouches[0].clientX = 100;
mockTouchEvent.targetTouches[0].clientY = 200;
mockTouchEvent.touches = [{}];
mockTouchEvent.touches[0].clientX = 100;
mockTouchEvent.touches[0].clientY = 200;
var pos = goog.style.getClientPosition(mockTouchEvent);
assertEquals(100, pos.x);
assertEquals(200, pos.y);
}
function testGetClientPositionAbstractedTouchEvent() {
var e = new goog.events.BrowserEvent();
e.event_ = {};
e.event_.touches = [{}];
e.event_.touches[0].clientX = 100;
e.event_.touches[0].clientY = 200;
e.event_.targetTouches = [{}];
e.event_.targetTouches[0].clientX = 100;
e.event_.targetTouches[0].clientY = 200;
var pos = goog.style.getClientPosition(e);
assertEquals(100, pos.x);
assertEquals(200, pos.y);
}
function testGetPageOffsetAbsPositionedElement() {
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '100px';
div.style.top = '200px';
document.body.appendChild(div);
var pos = goog.style.getPageOffset(div);
assertEquals(100, pos.x);
assertEquals(200, pos.y);
}
function testGetPageOffsetNestedElements() {
var innerDiv = goog.dom.createDom('DIV');
innerDiv.style.position = 'relative';
innerDiv.style.left = '-10px';
innerDiv.style.top = '-10px';
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '150px';
div.style.top = '250px';
div.appendChild(innerDiv);
document.body.appendChild(div);
var pos = goog.style.getPageOffset(innerDiv);
assertEquals(140, pos.x);
assertEquals(240, pos.y);
}
function testGetPageOffsetWithBodyPadding() {
document.body.style.margin = '40px';
document.body.style.padding = '60px';
document.body.style.borderWidth = '70px';
try {
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '100px';
div.style.top = '200px';
// Margin will affect position, but padding and borders should not.
div.style.margin = '1px';
div.style.padding = '2px';
div.style.borderWidth = '3px';
document.body.appendChild(div);
var pos = goog.style.getPageOffset(div);
assertEquals(101, pos.x);
assertEquals(201, pos.y);
}
finally {
document.body.removeChild(div);
document.body.style.margin = '';
document.body.style.padding = '';
document.body.style.borderWidth = '';
}
}
function testGetPageOffsetWithDocumentElementPadding() {
document.documentElement.style.margin = '40px';
document.documentElement.style.padding = '60px';
document.documentElement.style.borderWidth = '70px';
try {
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '100px';
div.style.top = '200px';
// Margin will affect position, but padding and borders should not.
div.style.margin = '1px';
div.style.padding = '2px';
div.style.borderWidth = '3px';
document.body.appendChild(div);
var pos = goog.style.getPageOffset(div);
// FF3 (but not beyond) gets confused by document margins.
if (goog.userAgent.GECKO && goog.userAgent.isVersion('1.9') &&
!goog.userAgent.isVersion('1.9.1')) {
assertEquals(141, pos.x);
assertEquals(241, pos.y);
} else {
assertEquals(101, pos.x);
assertEquals(201, pos.y);
}
}
finally {
document.body.removeChild(div);
document.documentElement.style.margin = '';
document.documentElement.style.padding = '';
document.documentElement.style.borderWidth = '';
}
}
function testGetPageOffsetElementOffscreen() {
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '10000px';
div.style.top = '20000px';
document.body.appendChild(div);
window.scroll(0, 0);
try {
var pos = goog.style.getPageOffset(div);
assertEquals(10000, pos.x);
assertEquals(20000, pos.y);
// The following tests do not work in Gecko 1.8 and below, due to an
// obscure off-by-one bug in goog.style.getPageOffset. Same for IE.
if (!(goog.userAgent.IE) &&
!(goog.userAgent.GECKO && !goog.userAgent.isVersion('1.9'))) {
window.scroll(1, 1);
pos = goog.style.getPageOffset(div);
assertEquals(10000, pos.x);
assertEquals(20000, pos.y);
window.scroll(1000, 2000);
pos = goog.style.getPageOffset(div);
assertEquals(10000, pos.x);
assertRoughlyEquals(20000, pos.y, 1);
window.scroll(10000, 20000);
pos = goog.style.getPageOffset(div);
assertEquals(10000, pos.x);
assertRoughlyEquals(20000, pos.y, 1);
}
}
// Undo changes.
finally {
document.body.removeChild(div);
window.scroll(0, 0);
}
}
function testGetPageOffsetFixedPositionElements() {
// Skip these tests in certain browsers.
// position:fixed is not supported in IE before version 7
if (!goog.userAgent.IE || !goog.userAgent.isVersion('6')) {
// Test with a position fixed element
var div = goog.dom.createDom('DIV');
div.style.position = 'fixed';
div.style.top = '10px';
div.style.left = '10px';
document.body.appendChild(div);
var pos = goog.style.getPageOffset(div);
assertEquals(10, pos.x);
assertEquals(10, pos.y);
// Test with a position fixed element as parent
var innerDiv = goog.dom.createDom('DIV');
div = goog.dom.createDom('DIV');
div.style.position = 'fixed';
div.style.top = '10px';
div.style.left = '10px';
div.style.padding = '5px';
div.appendChild(innerDiv);
document.body.appendChild(div);
pos = goog.style.getPageOffset(innerDiv);
assertEquals(15, pos.x);
assertEquals(15, pos.y);
}
}
function testGetPositionTolerantToNoDocumentElementBorder() {
// In IE, removing the border on the document element undoes the normal
// 2-pixel offset. Ensure that we're correctly compensating for both cases.
try {
document.documentElement.style.borderWidth = '0';
var div = goog.dom.createDom('DIV');
div.style.position = 'absolute';
div.style.left = '100px';
div.style.top = '200px';
document.body.appendChild(div);
// Test all major positioning methods.
// Temporarily disabled for IE8 - IE8 returns dimensions multiplied by 100
expectedFailures.expectFailureFor(isIE8() && !goog.dom.isCss1CompatMode());
try {
// Test all major positioning methods.
var pos = goog.style.getClientPosition(div);
assertEquals(100, pos.x);
assertEquals(200, pos.y);
var offset = goog.style.getPageOffset(div);
assertEquals(100, offset.x);
assertEquals(200, offset.y);
} catch (e) {
expectedFailures.handleException(e);
}
} finally {
document.documentElement.style.borderWidth = '';
}
}
function testSetSize() {
var el = $('testEl');
goog.style.setSize(el, 100, 100);
assertEquals('100px', el.style.width);
assertEquals('100px', el.style.height);
goog.style.setSize(el, '50px', '25px');
assertEquals('should be "50px"', '50px', el.style.width);
assertEquals('should be "25px"', '25px', el.style.height);
goog.style.setSize(el, '10ex', '25px');
assertEquals('10ex', el.style.width);
assertEquals('25px', el.style.height);
goog.style.setSize(el, '10%', '25%');
assertEquals('10%', el.style.width);
assertEquals('25%', el.style.height);
// ignores stupid units
goog.style.setSize(el, 0, 0);
// TODO(user): IE errors if you set these values. Should we make setStyle
// catch these? Or leave it up to the app. Fixing the tests for now.
//goog.style.setSize(el, '10rainbows', '25rainbows');
assertEquals('0px', el.style.width);
assertEquals('0px', el.style.height);
goog.style.setSize(el, new goog.math.Size(20, 40));
assertEquals('20px', el.style.width);
assertEquals('40px', el.style.height);
}
function testSetWidthAndHeight() {
var el = $('testEl');
// Replicate all of the setSize tests above.
goog.style.setWidth(el, 100);
goog.style.setHeight(el, 100);
assertEquals('100px', el.style.width);
assertEquals('100px', el.style.height);
goog.style.setWidth(el, '50px');
goog.style.setHeight(el, '25px');
assertEquals('should be "50px"', '50px', el.style.width);
assertEquals('should be "25px"', '25px', el.style.height);
goog.style.setWidth(el, '10ex');
goog.style.setHeight(el, '25px');
assertEquals('10ex', el.style.width);
assertEquals('25px', el.style.height);
goog.style.setWidth(el, '10%');
goog.style.setHeight(el, '25%');
assertEquals('10%', el.style.width);
assertEquals('25%', el.style.height);
goog.style.setWidth(el, 0);
goog.style.setHeight(el, 0);
assertEquals('0px', el.style.width);
assertEquals('0px', el.style.height);
goog.style.setWidth(el, 20);
goog.style.setHeight(el, 40);
assertEquals('20px', el.style.width);
assertEquals('40px', el.style.height);
// Additional tests testing each separately.
goog.style.setWidth(el, '');
goog.style.setHeight(el, '');
assertEquals('', el.style.width);
assertEquals('', el.style.height);
goog.style.setHeight(el, 20);
assertEquals('', el.style.width);
assertEquals('20px', el.style.height);
goog.style.setWidth(el, 40);
assertEquals('40px', el.style.width);
assertEquals('20px', el.style.height);
}
function testGetSize() {
var el = $('testEl');
goog.style.setSize(el, 100, 100);
var dims = goog.style.getSize(el);
assertEquals(100, dims.width);
assertEquals(100, dims.height);
goog.style.setStyle(el, 'display', 'none');
dims = goog.style.getSize(el);
assertEquals(100, dims.width);
assertEquals(100, dims.height);
el = $('testEl5');
goog.style.setSize(el, 100, 100);
dims = goog.style.getSize(el);
assertEquals(100, dims.width);
assertEquals(100, dims.height);
el = $('span0');
dims = goog.style.getSize(el);
assertNotEquals(0, dims.width);
assertNotEquals(0, dims.height);
el = $('table1');
dims = goog.style.getSize(el);
assertNotEquals(0, dims.width);
assertNotEquals(0, dims.height);
el = $('td1');
dims = goog.style.getSize(el);
assertNotEquals(0, dims.width);
assertNotEquals(0, dims.height);
el = $('li1');
dims = goog.style.getSize(el);
assertNotEquals(0, dims.width);
assertNotEquals(0, dims.height);
el = goog.dom.getElementsByTagNameAndClass('html')[0];
dims = goog.style.getSize(el);
assertNotEquals(0, dims.width);
assertNotEquals(0, dims.height);
el = goog.dom.getElementsByTagNameAndClass('body')[0];
dims = goog.style.getSize(el);
assertNotEquals(0, dims.width);
assertNotEquals(0, dims.height);
}
function testGetSizeSvgElements() {
var svgEl = document.createElementNS &&
document.createElementNS('http://www.w3.org/2000/svg', 'svg');
if (!svgEl || svgEl.getAttribute('transform') == '' ||
(goog.userAgent.WEBKIT && !goog.userAgent.isVersion(534.8))) {
// SVG not supported, or getBoundingClientRect not supported on SVG
// elements.
return;
}
document.body.appendChild(svgEl);
el = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
el.setAttribute('x', 10);
el.setAttribute('y', 10);
el.setAttribute('width', 32);
el.setAttribute('height', 21);
el.setAttribute('fill', '#000');
svgEl.appendChild(el);
dims = goog.style.getSize(el);
assertEquals(32, dims.width);
assertRoughlyEquals(21, dims.height, 0.01);
dims = goog.style.getSize(svgEl);
if (goog.userAgent.WEBKIT) {
// The size of the <svg> will be the viewport size on WebKit browsers.
assertTrue(dims.width >= 32);
assertTrue(dims.height >= 21);
} else {
assertEquals(32, dims.width);
assertRoughlyEquals(21, dims.height, 0.01);
}
el.style.visibility = 'none';
dims = goog.style.getSize(el);
assertEquals(32, dims.width);
assertRoughlyEquals(21, dims.height, 0.01);
dims = goog.style.getSize(svgEl);
if (goog.userAgent.WEBKIT) {
// The size of the <svg> will be the viewport size on WebKit browsers.
assertTrue(dims.width >= 32);
assertTrue(dims.height >= 21);
} else {
assertEquals(32, dims.width);
assertRoughlyEquals(21, dims.height, 0.01);
}
}
function testGetSizeInlineBlock() {
var el = $('height-test-inner');
var dims = goog.style.getSize(el);
assertNotEquals(0, dims.height);
}
function testGetBounds() {
var el = $('testEl');
var dims = goog.style.getSize(el);
var pos = goog.style.getPageOffset(el);
var rect = goog.style.getBounds(el);
// Relies on getSize and getPageOffset being correct.
assertEquals(dims.width, rect.width);
assertEquals(dims.height, rect.height);
assertEquals(pos.x, rect.left);
assertEquals(pos.y, rect.top);
}
function testInstallStyles() {
var el = $('installTest0');
var originalBackground = goog.style.getBackgroundColor(el);
// Uses background-color because it's easy to get the computed value
var result = goog.style.installStyles(
'#installTest0 { background-color: rgb(255, 192, 203); }');
// For some odd reason, the change in computed style does not register on
// Chrome 19 unless the style property is touched. The behavior goes
// away again in Chrome 20.
// TODO(nnaze): Remove special caseing once we switch the testing image
// to Chrome 20 or higher.
if (isChrome19()) {
el.style.display = '';
}
assertColorRgbEquals('rgb(255,192,203)', goog.style.getBackgroundColor(el));
goog.style.uninstallStyles(result);
assertEquals(originalBackground, goog.style.getBackgroundColor(el));
}
function testSetStyles() {
var el = $('installTest1');
// Change to pink
var ss = goog.style.installStyles(
'#installTest1 { background-color: rgb(255, 192, 203); }');
// For some odd reason, the change in computed style does not register on
// Chrome 19 unless the style property is touched. The behavior goes
// away again in Chrome 20.
// TODO(nnaze): Remove special caseing once we switch the testing image
// to Chrome 20 or higher.
if (isChrome19()) {
el.style.display = '';
}
assertColorRgbEquals('rgb(255,192,203)', goog.style.getBackgroundColor(el));
// Now change to orange
goog.style.setStyles(ss,
'#installTest1 { background-color: rgb(255, 255, 0); }');
assertColorRgbEquals('rgb(255,255,0)', goog.style.getBackgroundColor(el));
}
function assertColorRgbEquals(expected, actual) {
assertEquals(expected,
goog.color.hexToRgbStyle(goog.color.parse(actual).hex));
}
function isChrome19() {
return goog.userAgent.product.CHROME &&
goog.string.startsWith(goog.userAgent.product.VERSION, '19.');
}
function testIsRightToLeft() {
assertFalse(goog.style.isRightToLeft($('rtl1')));
assertTrue(goog.style.isRightToLeft($('rtl2')));
assertFalse(goog.style.isRightToLeft($('rtl3')));
assertFalse(goog.style.isRightToLeft($('rtl4')));
assertTrue(goog.style.isRightToLeft($('rtl5')));
assertFalse(goog.style.isRightToLeft($('rtl6')));
assertTrue(goog.style.isRightToLeft($('rtl7')));
assertFalse(goog.style.isRightToLeft($('rtl8')));
assertTrue(goog.style.isRightToLeft($('rtl9')));
assertFalse(goog.style.isRightToLeft($('rtl10')));
}
function testPosWithAbsoluteAndScroll() {
var el = $('pos-scroll-abs');
var el1 = $('pos-scroll-abs-1');
var el2 = $('pos-scroll-abs-2');
el1.scrollTop = 200;
var pos = goog.style.getPageOffset(el2);
assertEquals(200, pos.x);
// Don't bother with IE in quirks mode
if (!goog.userAgent.IE || document.compatMode == 'CSS1Compat') {
assertEquals(300, pos.y);
}
}
function testPosWithAbsoluteAndWindowScroll() {
window.scrollBy(0, 200);
var el = $('abs-upper-left');
var pos = goog.style.getPageOffset(el);
assertEquals('Top should be about 0', 0, pos.y);
}
function testGetBorderBoxSize() {
// Strict mode
var getBorderBoxSize = goog.style.getBorderBoxSize;
var el = $('size-a');
var rect = getBorderBoxSize(el);
assertEquals('width:100px', 100, rect.width);
assertEquals('height:100px', 100, rect.height);
// with border: 10px
el = $('size-b');
rect = getBorderBoxSize(el);
assertEquals('width:100px;border:10px', isBorderBox ? 100 : 120, rect.width);
assertEquals('height:100px;border:10px', isBorderBox ? 100 : 120,
rect.height);
// with border: 10px; padding: 10px
el = $('size-c');
rect = getBorderBoxSize(el);
assertEquals('width:100px;border:10px;padding:10px',
isBorderBox ? 100 : 140, rect.width);
assertEquals('height:100px;border:10px;padding:10px',
isBorderBox ? 100 : 140, rect.height);
// size, padding and borders are all in non pixel units
// all we test here is that we get a number out
el = $('size-d');
rect = getBorderBoxSize(el);
assertEquals('number', typeof rect.width);
assertEquals('number', typeof rect.height);
assertFalse(isNaN(rect.width));
assertFalse(isNaN(rect.height));
}
function testGetContentBoxSize() {
// Strict mode
var getContentBoxSize = goog.style.getContentBoxSize;
var el = $('size-a');
var rect = getContentBoxSize(el);
assertEquals('width:100px', 100, rect.width);
assertEquals('height:100px', 100, rect.height);
// with border: 10px
el = $('size-b');
rect = getContentBoxSize(el);
assertEquals('width:100px;border:10px',
isBorderBox ? 80 : 100, rect.width);
assertEquals('height:100px;border:10px',
isBorderBox ? 80 : 100, rect.height);
// with border: 10px; padding: 10px
el = $('size-c');
rect = getContentBoxSize(el);
assertEquals('width:100px;border:10px;padding:10px',
isBorderBox ? 60 : 100, rect.width);
assertEquals('height:100px;border:10px;padding:10px',
isBorderBox ? 60 : 100, rect.height);
// size, padding and borders are all in non pixel units
// all we test here is that we get a number out
el = $('size-d');
rect = getContentBoxSize(el);
assertEquals('number', typeof rect.width);
assertEquals('number', typeof rect.height);
assertFalse(isNaN(rect.width));
assertFalse(isNaN(rect.height));
// test whether getContentBoxSize works when width and height
// aren't explicitly set, but the default of 'auto'.
// 'size-f' has no margin, border, or padding, so offsetWidth/Height
// should match the content box size
el = $('size-f');
rect = getContentBoxSize(el);
assertEquals(el.offsetWidth, rect.width);
assertEquals(el.offsetHeight, rect.height);
}
function testSetBorderBoxSize() {
// Strict mode
var el = $('size-e');
var Size = goog.math.Size;
var setBorderBoxSize = goog.style.setBorderBoxSize;
// Clean up
// style element has 100x100, no border and no padding
el.style.padding = '';
el.style.margin = '';
el.style.borderWidth = '';
el.style.width = '';
el.style.height = '';
setBorderBoxSize(el, new Size(100, 100));
assertEquals(100, el.offsetWidth);
assertEquals(100, el.offsetHeight);
el.style.borderWidth = '10px';
setBorderBoxSize(el, new Size(100, 100));
assertEquals('width:100px;border:10px', 100, el.offsetWidth);
assertEquals('height:100px;border:10px', 100, el.offsetHeight);
el.style.padding = '10px';
setBorderBoxSize(el, new Size(100, 100));
assertEquals(100, el.offsetWidth);
assertEquals(100, el.offsetHeight);
el.style.borderWidth = '0';
setBorderBoxSize(el, new Size(100, 100));
assertEquals(100, el.offsetWidth);
assertEquals(100, el.offsetHeight);
if (goog.userAgent.GECKO) {
assertEquals('border-box', el.style.MozBoxSizing);
} else if (goog.userAgent.WEBKIT) {
assertEquals('border-box', el.style.WebkitBoxSizing);
} else if (goog.userAgent.OPERA ||
goog.userAgent.IE && goog.userAgent.isDocumentMode(8)) {
assertEquals('border-box', el.style.boxSizing);
}
// Try a negative width/height.
setBorderBoxSize(el, new Size(-10, -10));
// Setting the border box smaller than the borders will just give you
// a content box of size 0.
// NOTE(nicksantos): I'm not really sure why IE7 is special here.
var isIeLt8Quirks = goog.userAgent.IE &&
!goog.userAgent.isDocumentMode(8) &&
!goog.dom.isCss1CompatMode();
assertEquals(20, el.offsetWidth);
assertEquals(isIeLt8Quirks ? 39 : 20, el.offsetHeight);
}
function testSetContentBoxSize() {
// Strict mode
var el = $('size-e');
var Size = goog.math.Size;
var setContentBoxSize = goog.style.setContentBoxSize;
// Clean up
// style element has 100x100, no border and no padding
el.style.padding = '';
el.style.margin = '';
el.style.borderWidth = '';
el.style.width = '';
el.style.height = '';
setContentBoxSize(el, new Size(100, 100));
assertEquals(100, el.offsetWidth);
assertEquals(100, el.offsetHeight);
el.style.borderWidth = '10px';
setContentBoxSize(el, new Size(100, 100));
assertEquals('width:100px;border-width:10px', 120, el.offsetWidth);
assertEquals('height:100px;border-width:10px', 120, el.offsetHeight);
el.style.padding = '10px';
setContentBoxSize(el, new Size(100, 100));
assertEquals('width:100px;border-width:10px;padding:10px',
140, el.offsetWidth);
assertEquals('height:100px;border-width:10px;padding:10px',
140, el.offsetHeight);
el.style.borderWidth = '0';
setContentBoxSize(el, new Size(100, 100));
assertEquals('width:100px;padding:10px', 120, el.offsetWidth);
assertEquals('height:100px;padding:10px', 120, el.offsetHeight);
if (goog.userAgent.GECKO) {
assertEquals('content-box', el.style.MozBoxSizing);
} else if (goog.userAgent.WEBKIT) {
assertEquals('content-box', el.style.WebkitBoxSizing);
} else if (goog.userAgent.OPERA ||
goog.userAgent.IE && goog.userAgent.isDocumentMode(8)) {
assertEquals('content-box', el.style.boxSizing);
}
// Try a negative width/height.
setContentBoxSize(el, new Size(-10, -10));
// NOTE(nicksantos): I'm not really sure why IE7 is special here.
var isIeLt8Quirks = goog.userAgent.IE &&
!goog.userAgent.isDocumentMode('8') &&
!goog.dom.isCss1CompatMode();
assertEquals(20, el.offsetWidth);
assertEquals(isIeLt8Quirks ? 39 : 20, el.offsetHeight);
}
function testGetPaddingBox() {
// Strict mode
var el = $('size-e');
var Size = goog.math.Size;
var getPaddingBox = goog.style.getPaddingBox;
// Clean up
// style element has 100x100, no border and no padding
el.style.padding = '';
el.style.margin = '';
el.style.borderWidth = '';
el.style.width = '';
el.style.height = '';
el.style.padding = '10px';
var rect = getPaddingBox(el);
assertEquals(10, rect.left);
assertEquals(10, rect.right);
assertEquals(10, rect.top);
assertEquals(10, rect.bottom);
el.style.padding = '0';
rect = getPaddingBox(el);
assertEquals(0, rect.left);
assertEquals(0, rect.right);
assertEquals(0, rect.top);
assertEquals(0, rect.bottom);
el.style.padding = '1px 2px 3px 4px';
rect = getPaddingBox(el);
assertEquals(1, rect.top);
assertEquals(2, rect.right);
assertEquals(3, rect.bottom);
assertEquals(4, rect.left);
el.style.padding = '1mm 2em 3ex 4%';
rect = getPaddingBox(el);
assertFalse(isNaN(rect.top));
assertFalse(isNaN(rect.right));
assertFalse(isNaN(rect.bottom));
assertFalse(isNaN(rect.left));
assertTrue(rect.top >= 0);
assertTrue(rect.right >= 0);
assertTrue(rect.bottom >= 0);
assertTrue(rect.left >= 0);
}
function testGetPaddingBoxUnattached() {
var el = document.createElement('div');
var box = goog.style.getPaddingBox(el);
if (goog.userAgent.WEBKIT) {
assertTrue(isNaN(box.top));
assertTrue(isNaN(box.right));
assertTrue(isNaN(box.bottom));
assertTrue(isNaN(box.left));
} else {
assertObjectEquals(new goog.math.Box(0, 0, 0, 0), box);
}
}
function testGetMarginBox() {
// Strict mode
var el = $('size-e');
var Size = goog.math.Size;
var getMarginBox = goog.style.getMarginBox;
// Clean up
// style element has 100x100, no border and no padding
el.style.padding = '';
el.style.margin = '';
el.style.borderWidth = '';
el.style.width = '';
el.style.height = '';
el.style.margin = '10px';
var rect = getMarginBox(el);
assertEquals(10, rect.left);
// In webkit the right margin is the calculated distance from right edge and
// not the computed right margin so it is not reliable.
// See https://bugs.webkit.org/show_bug.cgi?id=19828
if (!goog.userAgent.WEBKIT) {
assertEquals(10, rect.right);
}
assertEquals(10, rect.top);
assertEquals(10, rect.bottom);
el.style.margin = '0';
rect = getMarginBox(el);
assertEquals(0, rect.left);
// In webkit the right margin is the calculated distance from right edge and
// not the computed right margin so it is not reliable.
// See https://bugs.webkit.org/show_bug.cgi?id=19828
if (!goog.userAgent.WEBKIT) {
assertEquals(0, rect.right);
}
assertEquals(0, rect.top);
assertEquals(0, rect.bottom);
el.style.margin = '1px 2px 3px 4px';
rect = getMarginBox(el);
assertEquals(1, rect.top);
// In webkit the right margin is the calculated distance from right edge and
// not the computed right margin so it is not reliable.
// See https://bugs.webkit.org/show_bug.cgi?id=19828
if (!goog.userAgent.WEBKIT) {
assertEquals(2, rect.right);
}
assertEquals(3, rect.bottom);
assertEquals(4, rect.left);
el.style.margin = '1mm 2em 3ex 4%';
rect = getMarginBox(el);
assertFalse(isNaN(rect.top));
assertFalse(isNaN(rect.right));
assertFalse(isNaN(rect.bottom));
assertFalse(isNaN(rect.left));
assertTrue(rect.top >= 0);
// In webkit the right margin is the calculated distance from right edge and
// not the computed right margin so it is not reliable.
// See https://bugs.webkit.org/show_bug.cgi?id=19828
if (!goog.userAgent.WEBKIT) {
assertTrue(rect.right >= 0);
}
assertTrue(rect.bottom >= 0);
assertTrue(rect.left >= 0);
}
function testGetBorderBox() {
// Strict mode
var el = $('size-e');
var Size = goog.math.Size;
var getBorderBox = goog.style.getBorderBox;
// Clean up
// style element has 100x100, no border and no padding
el.style.padding = '';
el.style.margin = '';
el.style.borderWidth = '';
el.style.width = '';
el.style.height = '';
el.style.borderWidth = '10px';
var rect = getBorderBox(el);
assertEquals(10, rect.left);
assertEquals(10, rect.right);
assertEquals(10, rect.top);
assertEquals(10, rect.bottom);
el.style.borderWidth = '0';
rect = getBorderBox(el);
assertEquals(0, rect.left);
assertEquals(0, rect.right);
assertEquals(0, rect.top);
assertEquals(0, rect.bottom);
el.style.borderWidth = '1px 2px 3px 4px';
rect = getBorderBox(el);
assertEquals(1, rect.top);
assertEquals(2, rect.right);
assertEquals(3, rect.bottom);
assertEquals(4, rect.left);
// % does not work for border widths in IE
el.style.borderWidth = '1mm 2em 3ex 4pt';
rect = getBorderBox(el);
assertFalse(isNaN(rect.top));
assertFalse(isNaN(rect.right));
assertFalse(isNaN(rect.bottom));
assertFalse(isNaN(rect.left));
assertTrue(rect.top >= 0);
assertTrue(rect.right >= 0);
assertTrue(rect.bottom >= 0);
assertTrue(rect.left >= 0);
el.style.borderWidth = 'thin medium thick 1px';
rect = getBorderBox(el);
assertFalse(isNaN(rect.top));
assertFalse(isNaN(rect.right));
assertFalse(isNaN(rect.bottom));
assertFalse(isNaN(rect.left));
assertTrue(rect.top >= 0);
assertTrue(rect.right >= 0);
assertTrue(rect.bottom >= 0);
assertTrue(rect.left >= 0);
}
function testGetFontFamily() {
// I tried to use common fonts for these tests. It's possible the test fails
// because the testing platform doesn't have one of these fonts installed:
// Comic Sans MS or Century Schoolbook L
// Times
// Helvetica
var tmpFont = goog.style.getFontFamily($('font-tag'));
assertTrue('FontFamily should be detectable when set via <font face>',
'Times' == tmpFont || 'Times New Roman' == tmpFont);
tmpFont = goog.style.getFontFamily($('small-text'));
assertTrue('Multiword fonts should be reported with quotes stripped.',
'Comic Sans MS' == tmpFont ||
'Century Schoolbook L' == tmpFont);
// Firefox fails this test & retuns a generic 'monospace' instead of the
// actually displayed font (e.g., "Times New").
//tmpFont = goog.style.getFontFamily($('pre-font'));
//assertEquals('<pre> tags should use a fixed-width font',
// 'Times New',
// tmpFont);
tmpFont = goog.style.getFontFamily($('inherit-font'));
assertEquals('Explicitly inherited fonts should be detectable',
'Helvetica',
tmpFont);
tmpFont = goog.style.getFontFamily($('times-font-family'));
assertEquals('Font-family set via style attribute should be detected',
'Times',
tmpFont);
tmpFont = goog.style.getFontFamily($('bold-font'));
assertEquals('Implicitly inherited font should be detected',
'Helvetica',
tmpFont);
tmpFont = goog.style.getFontFamily($('css-html-tag-redefinition'));
assertEquals('HTML tag CSS rewrites should be detected',
'Times',
tmpFont);
tmpFont = goog.style.getFontFamily($('no-text-font-styles'));
assertEquals('Font family should exist even with no text',
'Helvetica',
tmpFont);
tmpFont = goog.style.getFontFamily($('icon-font'));
assertNotEquals('icon is a special font-family value',
'icon',
tmpFont.toLowerCase());
tmpFont = goog.style.getFontFamily($('font-style-badfont'));
// Firefox fails this test and reports the specified "badFont", which is
// obviously not displayed.
//assertEquals('Invalid fonts should not be returned',
// 'Helvetica',
// tmpFont);
tmpFont = goog.style.getFontFamily($('img-font-test'));
assertTrue('Even img tags should inherit the document body\'s font',
tmpFont != '');
tmpFont = goog.style.getFontFamily($('nested-font'));
assertEquals('An element with nested content should be unaffected.',
'Arial',
tmpFont);
}
function testGetFontSize() {
assertEquals('Font size should be determined even without any text',
30,
goog.style.getFontSize($('no-text-font-styles')));
assertEquals('A 5em font should be 5x larger than its parent.',
150,
goog.style.getFontSize($('css-html-tag-redefinition')));
assertTrue('Setting font size=-1 should result in a positive font size.',
goog.style.getFontSize($('font-tag')) > 0);
assertEquals('Inheriting a 50% font-size should have no additional effect',
goog.style.getFontSize($('font-style-badfont')),
goog.style.getFontSize($('inherit-50pct-font')));
assertTrue('In pretty much any display, 3in should be > 8px',
goog.style.getFontSize($('times-font-family')) >
goog.style.getFontSize($('no-text-font-styles')));
assertTrue('With no applied styles, font-size should still be defined.',
goog.style.getFontSize($('no-font-style')) > 0);
assertEquals('50% of 30px is 15',
15,
goog.style.getFontSize($('font-style-badfont')));
assertTrue('x-small text should be smaller than small text',
goog.style.getFontSize($('x-small-text')) <
goog.style.getFontSize($('small-text')));
// IE fails this test, the decimal portion of px lengths isn't reported
// by getCascadedStyle. Firefox passes, but only because it ignores the
// decimals altogether.
//assertEquals('12.5px should be the same as 0.5em nested in a 25px node.',
// goog.style.getFontSize($('font-size-12-point-5-px')),
// goog.style.getFontSize($('font-size-50-pct-of-25-px')));
assertEquals('Font size should not doubly count em values',
2, goog.style.getFontSize($('em-font-size')));
}
function testGetLengthUnits() {
assertEquals('px', goog.style.getLengthUnits('15px'));
assertEquals('%', goog.style.getLengthUnits('99%'));
assertNull(goog.style.getLengthUnits(''));
}
function testParseStyleAttribute() {
var css = 'left: 0px; text-align: center';
var expected = {'left': '0px', 'textAlign': 'center'};
assertObjectEquals(expected, goog.style.parseStyleAttribute(css));
}
function testToStyleAttribute() {
var object = {'left': '0px', 'textAlign': 'center'};
var expected = 'left:0px;text-align:center;';
assertEquals(expected, goog.style.toStyleAttribute(object));
}
function testStyleAttributePassthrough() {
var object = {'left': '0px', 'textAlign': 'center'};
assertObjectEquals(object,
goog.style.parseStyleAttribute(goog.style.toStyleAttribute(object)));
}
function testGetFloat() {
assertEquals('', goog.style.getFloat($('no-float')));
assertEquals('none', goog.style.getFloat($('float-none')));
assertEquals('left', goog.style.getFloat($('float-left')));
}
function testSetFloat() {
var el = $('float-test');
goog.style.setFloat(el, 'left');
assertEquals('left', goog.style.getFloat(el));
goog.style.setFloat(el, 'right');
assertEquals('right', goog.style.getFloat(el));
goog.style.setFloat(el, 'none');
assertEquals('none', goog.style.getFloat(el));
goog.style.setFloat(el, '');
assertEquals('', goog.style.getFloat(el));
}
function testIsElementShown() {
var el = $('testEl');
goog.style.setElementShown(el, false);
assertFalse(goog.style.isElementShown(el));
goog.style.setElementShown(el, true);
assertTrue(goog.style.isElementShown(el));
}
function testGetOpacity() {
var el1 = {
style: {
opacity: '0.3'
}
};
var el2 = {
style: {
MozOpacity: '0.1'
}
};
var el3 = {
style: {
filter: 'some:other,filter;alpha(opacity=25.5);alpha(more=100);'
}
};
assertEquals(0.3, goog.style.getOpacity(el1));
assertEquals(0.1, goog.style.getOpacity(el2));
assertEquals(0.255, goog.style.getOpacity(el3));
el1.style.opacity = '0';
el2.style.MozOpacity = '0';
el3.style.filter = 'some:other,filter;alpha(opacity=0);alpha(more=100);';
assertEquals(0, goog.style.getOpacity(el1));
assertEquals(0, goog.style.getOpacity(el2));
assertEquals(0, goog.style.getOpacity(el3));
el1.style.opacity = '';
el2.style.MozOpacity = '';
el3.style.filter = '';
assertEquals('', goog.style.getOpacity(el1));
assertEquals('', goog.style.getOpacity(el2));
assertEquals('', goog.style.getOpacity(el3));
var el4 = {
style: {}
};
assertEquals('', goog.style.getOpacity(el4));
assertEquals('', goog.style.getOpacity($('test-opacity')));
}
function testSetOpacity() {
var el1 = {
style: {
opacity: '0.3'
}
};
goog.style.setOpacity(el1, 0.8);
var el2 = {
style: {
MozOpacity: '0.1'
}
};
goog.style.setOpacity(el2, 0.5);
var el3 = {
style: {
filter: 'alpha(opacity=25)'
}
};
goog.style.setOpacity(el3, 0.1);
assertEquals(0.8, Number(el1.style.opacity));
assertEquals(0.5, Number(el2.style.MozOpacity));
assertEquals('alpha(opacity=10)', el3.style.filter);
goog.style.setOpacity(el1, 0);
goog.style.setOpacity(el2, 0);
goog.style.setOpacity(el3, 0);
assertEquals(0, Number(el1.style.opacity));
assertEquals(0, Number(el2.style.MozOpacity));
assertEquals('alpha(opacity=0)', el3.style.filter);
goog.style.setOpacity(el1, '');
goog.style.setOpacity(el2, '');
goog.style.setOpacity(el3, '');
assertEquals('', el1.style.opacity);
assertEquals('', el2.style.MozOpacity);
assertEquals('', el3.style.filter);
}
function testFramedPageOffset() {
// Set up a complicated iframe ancestor chain.
var iframe = goog.dom.getElement('test-frame-offset');
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
var iframeWindow = goog.dom.getWindow(iframeDoc);
var iframePos = 'style="display:block;position:absolute;' +
'top:50px;left:50px;width:50px;height:50px;"';
iframeDoc.write('<iframe id="test-frame-offset-2" ' +
iframePos + '></iframe>' +
'<div id="test-element-2" ' +
' style="position:absolute;left:300px;top:300px">hi mom!</div>');
iframeDoc.close();
var iframe2 = iframeDoc.getElementById('test-frame-offset-2');
var testElement2 = iframeDoc.getElementById('test-element-2');
var iframeDoc2 = goog.dom.getFrameContentDocument(iframe2);
var iframeWindow2 = goog.dom.getWindow(iframeDoc2);
iframeDoc2.write(
'<div id="test-element-3" ' +
' style="position:absolute;left:500px;top:500px">hi mom!</div>');
iframeDoc2.close();
var testElement3 = iframeDoc2.getElementById('test-element-3');
assertCoordinateApprox(300, 300, 0,
goog.style.getPageOffset(testElement2));
assertCoordinateApprox(500, 500, 0,
goog.style.getPageOffset(testElement3));
assertCoordinateApprox(350, 350, 0,
goog.style.getFramedPageOffset(testElement2, window));
assertCoordinateApprox(300, 300, 0,
goog.style.getFramedPageOffset(testElement2, iframeWindow));
assertCoordinateApprox(600, 600, 0,
goog.style.getFramedPageOffset(testElement3, window));
assertCoordinateApprox(550, 550, 0,
goog.style.getFramedPageOffset(testElement3, iframeWindow));
assertCoordinateApprox(500, 500, 0,
goog.style.getFramedPageOffset(testElement3, iframeWindow2));
// Scroll the iframes a bit.
window.scrollBy(0, 5);
iframeWindow.scrollBy(0, 11);
iframeWindow2.scrollBy(0, 18);
// On Firefox 2, scrolling inner iframes causes off by one errors
// in the page position, because we're using screen coords to compute them.
assertCoordinateApprox(300, 300, 2,
goog.style.getPageOffset(testElement2));
assertCoordinateApprox(500, 500, 2,
goog.style.getPageOffset(testElement3));
assertCoordinateApprox(350, 350 - 11, 2,
goog.style.getFramedPageOffset(testElement2, window));
assertCoordinateApprox(300, 300, 2,
goog.style.getFramedPageOffset(testElement2, iframeWindow));
assertCoordinateApprox(600, 600 - 18 - 11, 2,
goog.style.getFramedPageOffset(testElement3, window));
assertCoordinateApprox(550, 550 - 18, 2,
goog.style.getFramedPageOffset(testElement3, iframeWindow));
assertCoordinateApprox(500, 500, 2,
goog.style.getFramedPageOffset(testElement3, iframeWindow2));
}
/**
* Asserts that the coordinate is approximately equal to the given
* x and y coordinates, give or take delta.
*/
function assertCoordinateApprox(x, y, delta, coord) {
assertTrue('Expected x: ' + x + ', actual x: ' + coord.x,
coord.x >= x - delta && coord.x <= x + delta);
assertTrue('Expected y: ' + y + ', actual y: ' + coord.y,
coord.y >= y - delta && coord.y <= y + delta);
}
function testTranslateRectForAnotherFrame() {
var rect = new goog.math.Rect(1, 2, 3, 4);
var thisDom = goog.dom.getDomHelper();
goog.style.translateRectForAnotherFrame(rect, thisDom, thisDom);
assertEquals(1, rect.left);
assertEquals(2, rect.top);
assertEquals(3, rect.width);
assertEquals(4, rect.height);
var iframe = $('test-translate-frame-standard');
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
var iframeDom = goog.dom.getDomHelper(iframeDoc);
// Cannot rely on iframe starting at origin.
iframeDom.getWindow().scrollTo(0, 0);
// iframe is at (100, 150) and its body is not scrolled.
rect = new goog.math.Rect(1, 2, 3, 4);
goog.style.translateRectForAnotherFrame(rect, iframeDom, thisDom);
assertEquals(1 + 100, rect.left);
assertEquals(2 + 150, rect.top);
assertEquals(3, rect.width);
assertEquals(4, rect.height);
iframeDom.getWindow().scrollTo(11, 13);
rect = new goog.math.Rect(1, 2, 3, 4);
goog.style.translateRectForAnotherFrame(rect, iframeDom, thisDom);
assertEquals(1 + 100 - 11, rect.left);
assertEquals(2 + 150 - 13, rect.top);
assertEquals(3, rect.width);
assertEquals(4, rect.height);
iframe = $('test-translate-frame-quirk');
iframeDoc = goog.dom.getFrameContentDocument(iframe);
iframeDom = goog.dom.getDomHelper(iframeDoc);
// Cannot rely on iframe starting at origin.
iframeDom.getWindow().scrollTo(0, 0);
// iframe is at (100, 350) and its body is not scrolled.
rect = new goog.math.Rect(1, 2, 3, 4);
goog.style.translateRectForAnotherFrame(rect, iframeDom, thisDom);
assertEquals(1 + 100, rect.left);
assertEquals(2 + 350, rect.top);
assertEquals(3, rect.width);
assertEquals(4, rect.height);
iframeDom.getWindow().scrollTo(11, 13);
rect = new goog.math.Rect(1, 2, 3, 4);
goog.style.translateRectForAnotherFrame(rect, iframeDom, thisDom);
assertEquals(1 + 100 - 11, rect.left);
assertEquals(2 + 350 - 13, rect.top);
assertEquals(3, rect.width);
assertEquals(4, rect.height);
}
function testGetVisibleRectForElement() {
var container = goog.dom.getElement('test-visible');
var el = goog.dom.getElement('test-visible-el');
var dom = goog.dom.getDomHelper(el);
var winScroll = dom.getDocumentScroll();
var winSize = dom.getViewportSize();
// Skip this test if the window size is small. Firefox3/Linux in Selenium
// sometimes fails without this check.
if (winSize.width < 20 || winSize.height < 20) {
return;
}
// Move the container element to the window's viewport.
var h = winSize.height < 100 ? winSize.height / 2 : 100;
goog.style.setSize(container, winSize.width / 2, h);
goog.style.setPosition(container, 8, winScroll.y + winSize.height - h);
var visible = goog.style.getVisibleRectForElement(el);
var bounds = goog.style.getBounds(container);
// VisibleRect == Bounds rect of the offsetParent
assertNotNull(visible);
assertEquals(bounds.left, visible.left);
assertEquals(bounds.top, visible.top);
assertEquals(bounds.left + bounds.width, visible.right);
assertEquals(bounds.top + bounds.height, visible.bottom);
// Move a part of the container element to outside of the viewpoert.
goog.style.setPosition(container, 8, winScroll.y + winSize.height - h / 2);
visible = goog.style.getVisibleRectForElement(el);
bounds = goog.style.getBounds(container);
// Confirm VisibleRect == Intersection of the bounds rect of the
// offsetParent and the viewport.
assertNotNull(visible);
assertEquals(bounds.left, visible.left);
assertEquals(bounds.top, visible.top);
assertEquals(bounds.left + bounds.width, visible.right);
assertEquals(winScroll.y + winSize.height, visible.bottom);
// Move the container element to outside of the viewpoert.
goog.style.setPosition(container, 8, winScroll.y + winSize.height);
visible = goog.style.getVisibleRectForElement(el);
assertNull(visible);
// Test the case with body element of height 0
var iframe = goog.dom.getElement('test-visible-frame');
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
el = iframeDoc.getElementById('test-visible');
visible = goog.style.getVisibleRectForElement(el);
var iframeViewportSize = goog.dom.getDomHelper(el).getViewportSize();
// NOTE(user): For iframe, the clipping viewport is always the iframe
// viewport, and not the actual browser viewport.
assertNotNull(visible);
assertEquals(0, visible.top);
assertEquals(iframeViewportSize.height, visible.bottom);
assertEquals(0, visible.left);
assertEquals(iframeViewportSize.width, visible.right);
}
function testGetVisibleRectForElementWithBodyScrolled() {
var container = goog.dom.getElement('test-visible2');
var dom = goog.dom.getDomHelper(container);
var el = dom.createDom('div', undefined, 'Test');
el.style.position = 'absolute';
dom.append(container, el);
container.style.position = 'absolute';
goog.style.setPosition(container, 20, 500);
goog.style.setSize(container, 100, 150);
// Scroll body container such that container is exactly at top.
window.scrollTo(0, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(20, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(120, visibleRect.right, EPSILON);
// Top 100px is clipped by window viewport.
window.scrollTo(0, 600);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(600, visibleRect.top, EPSILON);
assertRoughlyEquals(20, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(120, visibleRect.right, EPSILON);
var winSize = dom.getViewportSize();
// Left 50px is clipped by window viewport.
// Right part is clipped by window viewport.
goog.style.setSize(container, 10000, 150);
window.scrollTo(70, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(70, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(70 + winSize.width, visibleRect.right, EPSILON);
// Bottom part is clipped by window viewport.
goog.style.setSize(container, 100, 2000);
window.scrollTo(0, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(20, visibleRect.left, EPSILON);
assertRoughlyEquals(120, visibleRect.right, EPSILON);
assertRoughlyEquals(500 + winSize.height, visibleRect.bottom, EPSILON);
goog.style.setPosition(container, 10000, 10000);
assertNull(goog.style.getVisibleRectForElement(el));
}
function testGetVisibleRectForElementWithNestedAreaAndNonOffsetAncestor() {
// IE7 quirks mode somehow consider container2 below as offset parent
// of the element, which is incorrect.
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(8) &&
!goog.dom.isCss1CompatMode()) {
return;
}
var container = goog.dom.getElement('test-visible2');
var dom = goog.dom.getDomHelper(container);
var container2 = dom.createDom('div');
var el = dom.createDom('div', undefined, 'Test');
el.style.position = 'absolute';
dom.append(container, container2);
dom.append(container2, el);
container.style.position = 'absolute';
goog.style.setPosition(container, 20, 500);
goog.style.setSize(container, 100, 150);
// container2 is a scrollable container but is not an offsetParent of
// the element. It is ignored in the computation.
container2.style.overflow = 'hidden';
container2.style.marginTop = '50px';
container2.style.marginLeft = '100px';
goog.style.setSize(container2, 150, 100);
// Scroll body container such that container is exactly at top.
window.scrollTo(0, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(20, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(120, visibleRect.right, EPSILON);
// Top 100px is clipped by window viewport.
window.scrollTo(0, 600);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(600, visibleRect.top, EPSILON);
assertRoughlyEquals(20, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(120, visibleRect.right, EPSILON);
var winSize = dom.getViewportSize();
// Left 50px is clipped by window viewport.
// Right part is clipped by window viewport.
goog.style.setSize(container, 10000, 150);
window.scrollTo(70, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(70, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(70 + winSize.width, visibleRect.right, EPSILON);
// Bottom part is clipped by window viewport.
goog.style.setSize(container, 100, 2000);
window.scrollTo(0, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(20, visibleRect.left, EPSILON);
assertRoughlyEquals(120, visibleRect.right, EPSILON);
assertRoughlyEquals(500 + winSize.height, visibleRect.bottom, EPSILON);
goog.style.setPosition(container, 10000, 10000);
assertNull(goog.style.getVisibleRectForElement(el));
}
function testGetVisibleRectForElementInsideNestedScrollableArea() {
var container = goog.dom.getElement('test-visible2');
var dom = goog.dom.getDomHelper(container);
var container2 = dom.createDom('div');
var el = dom.createDom('div', undefined, 'Test');
el.style.position = 'absolute';
dom.append(container, container2);
dom.append(container2, el);
container.style.position = 'absolute';
goog.style.setPosition(container, 100 /* left */, 500 /* top */);
goog.style.setSize(container, 300 /* width */, 300 /* height */);
container2.style.overflow = 'hidden';
container2.style.position = 'relative';
goog.style.setPosition(container2, 100, 50);
goog.style.setSize(container2, 150, 100);
// Scroll body container such that container is exactly at top.
window.scrollTo(0, 500);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(550, visibleRect.top, EPSILON);
assertRoughlyEquals(200, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(350, visibleRect.right, EPSILON);
// Left 50px is clipped by container.
goog.style.setPosition(container2, -50, 50);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(550, visibleRect.top, EPSILON);
assertRoughlyEquals(100, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(200, visibleRect.right, EPSILON);
// Right part is clipped by container.
goog.style.setPosition(container2, 100, 50);
goog.style.setWidth(container2, 1000, 100);
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(550, visibleRect.top, EPSILON);
assertRoughlyEquals(200, visibleRect.left, EPSILON);
assertRoughlyEquals(650, visibleRect.bottom, EPSILON);
assertRoughlyEquals(400, visibleRect.right, EPSILON);
// Top 50px is clipped by container.
goog.style.setStyle(container2, 'width', '150px');
goog.style.setStyle(container2, 'top', '-50px');
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(500, visibleRect.top, EPSILON);
assertRoughlyEquals(200, visibleRect.left, EPSILON);
assertRoughlyEquals(550, visibleRect.bottom, EPSILON);
assertRoughlyEquals(350, visibleRect.right, EPSILON);
// Bottom part is clipped by container.
goog.style.setStyle(container2, 'top', '50px');
goog.style.setStyle(container2, 'height', '1000px');
var visibleRect = goog.style.getVisibleRectForElement(el);
assertNotNull(visibleRect);
assertRoughlyEquals(550, visibleRect.top, EPSILON);
assertRoughlyEquals(200, visibleRect.left, EPSILON);
assertRoughlyEquals(800, visibleRect.bottom, EPSILON);
assertRoughlyEquals(350, visibleRect.right, EPSILON);
// Outside viewport.
goog.style.setStyle(container2, 'top', '10000px');
goog.style.setStyle(container2, 'left', '10000px');
assertNull(goog.style.getVisibleRectForElement(el));
}
function testGeckoMacOrX11RoundPosition() {
if ((goog.userAgent.MAC || goog.userAgent.X11) && goog.userAgent.GECKO &&
goog.userAgent.isVersion('1.9')) {
var pos = new goog.math.Coordinate(1.5, 1.4);
var el = document.createElement('div');
goog.style.setPosition(el, pos);
assertEquals('The left position should have been rounded',
'2px', el.style.left);
assertEquals('The top position should have been rounded',
'1px', el.style.top);
}
}
function testScrollIntoContainerViewQuirks() {
if (goog.dom.isCss1CompatMode()) return;
var container = goog.dom.getElement('scrollable-container');
// Scroll the minimum amount to make the elements visible.
goog.style.scrollIntoContainerView(goog.dom.getElement('item7'), container);
assertEquals('scroll to item7', 79, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item8'), container);
assertEquals('scroll to item8', 100, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item7'), container);
assertEquals('item7 still visible', 100, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item1'), container);
assertEquals('scroll to item1', 17, container.scrollTop);
// Center the element in the first argument.
goog.style.scrollIntoContainerView(goog.dom.getElement('item1'), container,
true);
assertEquals('center item1', 0, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item4'), container,
true);
assertEquals('center item4', 48, container.scrollTop);
// The element is higher than the container.
goog.dom.getElement('item3').style.height = '140px';
goog.style.scrollIntoContainerView(goog.dom.getElement('item3'), container);
assertEquals('show item3 with increased height', 59, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item3'), container,
true);
assertEquals('center item3 with increased height', 87, container.scrollTop);
goog.dom.getElement('item3').style.height = '';
// Scroll to non-integer position.
goog.dom.getElement('item4').style.height = '21px';
goog.style.scrollIntoContainerView(goog.dom.getElement('item4'), container,
true);
assertEquals('scroll position is rounded down', 48, container.scrollTop);
goog.dom.getElement('item4').style.height = '';
}
function testScrollIntoContainerViewStandard() {
if (!goog.dom.isCss1CompatMode()) return;
var container = goog.dom.getElement('scrollable-container');
// Scroll the minimum amount to make the elements visible.
goog.style.scrollIntoContainerView(goog.dom.getElement('item7'), container);
assertEquals('scroll to item7', 115, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item8'), container);
assertEquals('scroll to item8', 148, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item7'), container);
assertEquals('item7 still visible', 148, container.scrollTop);
goog.style.scrollIntoContainerView(goog.dom.getElement('item1'), container);
assertEquals('scroll to item1', 17, container.scrollTop);
// Center the element in the first argument.
goog.style.scrollIntoContainerView(
goog.dom.getElement('item1'), container, true);
assertEquals('center item1', 0, container.scrollTop);
goog.style.scrollIntoContainerView(
goog.dom.getElement('item4'), container, true);
assertEquals('center item4', 66, container.scrollTop);
// The element is higher than the container.
goog.dom.getElement('item3').style.height = '140px';
goog.style.scrollIntoContainerView(goog.dom.getElement('item3'), container);
assertEquals('show item3 with increased height', 83, container.scrollTop);
goog.style.scrollIntoContainerView(
goog.dom.getElement('item3'), container, true);
assertEquals('center item3 with increased height', 93, container.scrollTop);
goog.dom.getElement('item3').style.height = '';
// Scroll to non-integer position.
goog.dom.getElement('item4').style.height = '21px';
goog.style.scrollIntoContainerView(
goog.dom.getElement('item4'), container, true);
assertEquals('scroll position is rounded down', 66, container.scrollTop);
goog.dom.getElement('item4').style.height = '';
}
function testOffsetParent() {
var parent = goog.dom.getElement('offset-parent');
var child = goog.dom.getElement('offset-child');
assertEquals(parent, goog.style.getOffsetParent(child));
}
function testOverflowOffsetParent() {
var parent = goog.dom.getElement('offset-parent-overflow');
var child = goog.dom.getElement('offset-child-overflow');
assertEquals(parent, goog.style.getOffsetParent(child));
}
function testGetViewportPageOffset() {
var testViewport = goog.dom.getElement('test-viewport');
testViewport.style.height = '5000px';
testViewport.style.width = '5000px';
var offset = goog.style.getViewportPageOffset(document);
assertEquals(0, offset.x);
assertEquals(0, offset.y);
window.scrollTo(0, 100);
offset = goog.style.getViewportPageOffset(document);
assertEquals(0, offset.x);
assertEquals(100, offset.y);
window.scrollTo(100, 0);
offset = goog.style.getViewportPageOffset(document);
assertEquals(100, offset.x);
assertEquals(0, offset.y);
}
function testGetsTranslation() {
var element = document.getElementById('translation');
expectedFailures.expectFailureFor(
goog.userAgent.IE && !goog.userAgent.product.isVersion(9),
'CSS transforms were only introduced in IE9');
// First check the element is actually translated, and we haven't missed
// one of the vendor-specific transform properties
var position = goog.style.getClientPosition(element);
var translation = goog.style.getCssTranslation(element);
var expectedTranslation = new goog.math.Coordinate(20, 30);
expectedFailures.run(function() {
assertObjectEquals(new goog.math.Coordinate(30, 40), position);
assertObjectEquals(expectedTranslation, translation);
});
}
/**
* Return whether a given user agent has been detected.
* @param {number} agent Value in UserAgents.
* @return {boolean} Whether the user agent has been detected.
*/
function getUserAgentDetected_(agent) {
switch (agent) {
case UserAgents.GECKO:
return goog.userAgent.detectedGecko_;
case UserAgents.IE:
return goog.userAgent.detectedIe_;
case UserAgents.OPERA:
return goog.userAgent.detectedOpera_;
case UserAgents.WEBKIT:
return goog.userAgent.detectedWebkit_;
}
return null;
}
/**
* Rerun the initialization code to set all of the goog.userAgent constants.
*/
function reinitializeUserAgent() {
goog.userAgent.init_();
// Unfortunately we can't isolate the useragent setting in a function
// we can call, because things rely on it compiling to nothing when
// one of the ASSUME flags is set, and the compiler isn't smart enough
// to do that when the setting is done inside a function that's inlined.
goog.userAgent.OPERA = goog.userAgent.detectedOpera_;
goog.userAgent.IE = goog.userAgent.detectedIe_;
goog.userAgent.GECKO = goog.userAgent.detectedGecko_;
goog.userAgent.WEBKIT = goog.userAgent.detectedWebkit_;
goog.userAgent.MOBILE = goog.userAgent.detectedMobile_;
goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
goog.userAgent.initPlatform_();
goog.userAgent.VERSION = goog.userAgent.determineVersion_();
}
/**
* Test browser detection for a user agent configuration.
* @param {Array.<number>} expectedAgents Array of expected userAgents.
* @param {string} uaString User agent string.
* @param {string=} opt_product Navigator product string.
* @param {string=} opt_vendor Navigator vendor string.
*/
function assertUserAgent(expectedAgents, uaString, opt_product, opt_vendor) {
var mockGlobal = {
'navigator': {
'userAgent': uaString,
'product': opt_product,
'vendor': opt_vendor
}
};
propertyReplacer.set(goog, 'global', mockGlobal);
reinitializeUserAgent();
for (var ua in UserAgents) {
var isExpected = goog.array.contains(expectedAgents, UserAgents[ua]);
assertEquals(isExpected, getUserAgentDetected_(UserAgents[ua]));
}
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for Webkit.
*/
function testGetVendorStyleNameWebkit() {
var mockElement = {
'style': {
'WebkitTransform': ''
}
};
assertUserAgent([UserAgents.WEBKIT], 'WebKit');
assertEquals('-webkit-transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for Webkit.
*/
function testGetVendorStyleNameWebkitNoPrefix() {
var mockElement = {
'style': {
'WebkitTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.WEBKIT], 'WebKit');
assertEquals(
'transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for Gecko.
*/
function testGetVendorStyleNameGecko() {
var mockElement = {
'style': {
'MozTransform': ''
}
};
assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko');
assertEquals('-moz-transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for Gecko.
*/
function testGetVendorStyleNameGeckoNoPrefix() {
var mockElement = {
'style': {
'MozTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko');
assertEquals(
'transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for IE.
*/
function testGetVendorStyleNameIE() {
var mockElement = {
'style': {
'msTransform': ''
}
};
assertUserAgent([UserAgents.IE], 'MSIE');
assertEquals('-ms-transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for IE.
*/
function testGetVendorStyleNameIENoPrefix() {
var mockElement = {
'style': {
'msTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.IE], 'MSIE');
assertEquals(
'transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for Opera.
*/
function testGetVendorStyleNameOpera() {
var mockElement = {
'style': {
'OTransform': ''
}
};
assertUserAgent([UserAgents.OPERA], 'Opera');
assertEquals('-o-transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for Opera.
*/
function testGetVendorStyleNameOperaNoPrefix() {
var mockElement = {
'style': {
'OTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.OPERA], 'Opera');
assertEquals(
'transform',
goog.style.getVendorStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for Webkit.
*/
function testGetVendorJsStyleNameWebkit() {
var mockElement = {
'style': {
'WebkitTransform': ''
}
};
assertUserAgent([UserAgents.WEBKIT], 'WebKit');
assertEquals('WebkitTransform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for Webkit.
*/
function testGetVendorJsStyleNameWebkitNoPrefix() {
var mockElement = {
'style': {
'WebkitTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.WEBKIT], 'WebKit');
assertEquals(
'transform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for Gecko.
*/
function testGetVendorJsStyleNameGecko() {
var mockElement = {
'style': {
'MozTransform': ''
}
};
assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko');
assertEquals('MozTransform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for Gecko.
*/
function testGetVendorJsStyleNameGeckoNoPrefix() {
var mockElement = {
'style': {
'MozTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko');
assertEquals(
'transform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for IE.
*/
function testGetVendorJsStyleNameIE() {
var mockElement = {
'style': {
'msTransform': ''
}
};
assertUserAgent([UserAgents.IE], 'MSIE');
assertEquals('msTransform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for IE.
*/
function testGetVendorJsStyleNameIENoPrefix() {
var mockElement = {
'style': {
'msTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.IE], 'MSIE');
assertEquals(
'transform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* with a vendor prefix for Opera.
*/
function testGetVendorJsStyleNameOpera() {
var mockElement = {
'style': {
'OTransform': ''
}
};
assertUserAgent([UserAgents.OPERA], 'Opera');
assertEquals('OTransform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the proper vendor style name for a CSS property
* when it exists without a vendor prefix for Opera.
*/
function testGetVendorJsStyleNameOperaNoPrefix() {
var mockElement = {
'style': {
'OTransform': '',
'transform': ''
}
};
assertUserAgent([UserAgents.OPERA], 'Opera');
assertEquals(
'transform',
goog.style.getVendorJsStyleName_(mockElement, 'transform'));
}
/**
* Test for the setting a style name for a CSS property
* with a vendor prefix for Webkit.
*/
function testSetVendorStyleWebkit() {
var mockElement = {
'style': {
'WebkitTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.WEBKIT], 'WebKit');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, mockElement.style.WebkitTransform);
}
/**
* Test for the setting a style name for a CSS property
* with a vendor prefix for Mozilla.
*/
function testSetVendorStyleGecko() {
var mockElement = {
'style': {
'MozTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, mockElement.style.MozTransform);
}
/**
* Test for the setting a style name for a CSS property
* with a vendor prefix for IE.
*/
function testSetVendorStyleIE() {
var mockElement = {
'style': {
'msTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.IE], 'MSIE');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, mockElement.style.msTransform);
}
/**
* Test for the setting a style name for a CSS property
* with a vendor prefix for Opera.
*/
function testSetVendorStyleOpera() {
var mockElement = {
'style': {
'OTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.OPERA], 'Opera');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, mockElement.style.OTransform);
}
/**
* Test for the getting a style name for a CSS property
* with a vendor prefix for Webkit.
*/
function testGetVendorStyleWebkit() {
var mockElement = {
'style': {
'WebkitTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.WEBKIT], 'WebKit');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, goog.style.getStyle(mockElement, 'transform'));
}
/**
* Test for the getting a style name for a CSS property
* with a vendor prefix for Mozilla.
*/
function testGetVendorStyleGecko() {
var mockElement = {
'style': {
'MozTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, goog.style.getStyle(mockElement, 'transform'));
}
/**
* Test for the getting a style name for a CSS property
* with a vendor prefix for IE.
*/
function testGetVendorStyleIE() {
var mockElement = {
'style': {
'msTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.IE], 'MSIE');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, goog.style.getStyle(mockElement, 'transform'));
}
/**
* Test for the getting a style name for a CSS property
* with a vendor prefix for Opera.
*/
function testGetVendorStyleOpera() {
var mockElement = {
'style': {
'OTransform': ''
}
};
var styleValue = 'translate3d(0,0,0)';
assertUserAgent([UserAgents.OPERA], 'Opera');
goog.style.setStyle(mockElement, 'transform', styleValue);
assertEquals(styleValue, goog.style.getStyle(mockElement, 'transform'));
}
function isIE8() {
return goog.userAgent.IE && goog.userAgent.isDocumentMode(8) &&
!goog.userAgent.isDocumentMode(9);
}
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Bidi utility functions.
*
*/
goog.provide('goog.style.bidi');
goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* Returns the normalized scrollLeft position for a scrolled element.
* @param {Element} element The scrolled element.
* @return {number} The number of pixels the element is scrolled. 0 indicates
* that the element is not scrolled at all (which, in general, is the
* left-most position in ltr and the right-most position in rtl).
*/
goog.style.bidi.getScrollLeft = function(element) {
var isRtl = goog.style.isRightToLeft(element);
if (isRtl && goog.userAgent.GECKO) {
// ScrollLeft starts at 0 and then goes negative as the element is scrolled
// towards the left.
return -element.scrollLeft;
} else if (isRtl && !(goog.userAgent.IE && goog.userAgent.isVersion('8'))) {
// ScrollLeft starts at the maximum positive value and decreases towards
// 0 as the element is scrolled towards the left. However, for overflow
// visible, there is no scrollLeft and the value always stays correctly at 0
var overflowX = goog.style.getComputedOverflowX(element);
if (overflowX == 'visible') {
return element.scrollLeft;
} else {
return element.scrollWidth - element.clientWidth - element.scrollLeft;
}
}
// ScrollLeft behavior is identical in rtl and ltr, it starts at 0 and
// increases as the element is scrolled away from the start.
return element.scrollLeft;
};
/**
* Returns the "offsetStart" of an element, analagous to offsetLeft but
* normalized for right-to-left environments and various browser
* inconsistencies. This value returned can always be passed to setScrollOffset
* to scroll to an element's left edge in a left-to-right offsetParent or
* right edge in a right-to-left offsetParent.
*
* For example, here offsetStart is 10px in an LTR environment and 5px in RTL:
*
* <pre>
* | xxxxxxxxxx |
* ^^^^^^^^^^ ^^^^ ^^^^^
* 10px elem 5px
* </pre>
*
* If an element is positioned before the start of its offsetParent, the
* startOffset may be negative. This can be used with setScrollOffset to
* reliably scroll to an element:
*
* <pre>
* var scrollOffset = goog.style.bidi.getOffsetStart(element);
* goog.style.bidi.setScrollOffset(element.offsetParent, scrollOffset);
* </pre>
*
* @see setScrollOffset
*
* @param {Element} element The element for which we need to determine the
* offsetStart position.
* @return {number} The offsetStart for that element.
*/
goog.style.bidi.getOffsetStart = function(element) {
var offsetLeftForReal = element.offsetLeft;
// The element might not have an offsetParent.
// For example, the node might not be attached to the DOM tree,
// and position:fixed children do not have an offset parent.
// Just try to do the best we can with what we have.
var bestParent = element.offsetParent;
if (!bestParent && goog.style.getComputedPosition(element) == 'fixed') {
bestParent = goog.dom.getOwnerDocument(element).documentElement;
}
// Just give up in this case.
if (!bestParent) {
return offsetLeftForReal;
}
if (goog.userAgent.GECKO) {
// When calculating an element's offsetLeft, Firefox erroneously subtracts
// the border width from the actual distance. So we need to add it back.
var borderWidths = goog.style.getBorderBox(bestParent);
offsetLeftForReal += borderWidths.left;
} else if (goog.userAgent.isDocumentMode(8)) {
// When calculating an element's offsetLeft, IE8-Standards Mode erroneously
// adds the border width to the actual distance. So we need to subtract it.
var borderWidths = goog.style.getBorderBox(bestParent);
offsetLeftForReal -= borderWidths.left;
}
if (goog.style.isRightToLeft(bestParent)) {
// Right edge of the element relative to the left edge of its parent.
var elementRightOffset = offsetLeftForReal + element.offsetWidth;
// Distance from the parent's right edge to the element's right edge.
return bestParent.clientWidth - elementRightOffset;
}
return offsetLeftForReal;
};
/**
* Sets the element's scrollLeft attribute so it is correctly scrolled by
* offsetStart pixels. This takes into account whether the element is RTL and
* the nuances of different browsers. To scroll to the "beginning" of an
* element use getOffsetStart to obtain the element's offsetStart value and then
* pass the value to setScrollOffset.
* @see getOffsetStart
* @param {Element} element The element to set scrollLeft on.
* @param {number} offsetStart The number of pixels to scroll the element.
* If this value is < 0, 0 is used.
*/
goog.style.bidi.setScrollOffset = function(element, offsetStart) {
offsetStart = Math.max(offsetStart, 0);
// In LTR and in "mirrored" browser RTL (such as IE), we set scrollLeft to
// the number of pixels to scroll.
// Otherwise, in RTL, we need to account for different browser behavior.
if (!goog.style.isRightToLeft(element)) {
element.scrollLeft = offsetStart;
} else if (goog.userAgent.GECKO) {
// Negative scroll-left positions in RTL.
element.scrollLeft = -offsetStart;
} else if (!(goog.userAgent.IE && goog.userAgent.isVersion('8'))) {
// Take the current scrollLeft value and move to the right by the
// offsetStart to get to the left edge of the element, and then by
// the clientWidth of the element to get to the right edge.
element.scrollLeft =
element.scrollWidth - offsetStart - element.clientWidth;
} else {
element.scrollLeft = offsetStart;
}
};
/**
* Sets the element's left style attribute in LTR or right style attribute in
* RTL. Also clears the left attribute in RTL and the right attribute in LTR.
* @param {Element} elem The element to position.
* @param {number} left The left position in LTR; will be set as right in RTL.
* @param {?number} top The top position. If null only the left/right is set.
* @param {boolean} isRtl Whether we are in RTL mode.
*/
goog.style.bidi.setPosition = function(elem, left, top, isRtl) {
if (!goog.isNull(top)) {
elem.style.top = top + 'px';
}
if (isRtl) {
elem.style.right = left + 'px';
elem.style.left = '';
} else {
elem.style.left = left + 'px';
elem.style.right = '';
}
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for creating functions. Loosely inspired by the
* java classes: http://go/functions.java and http://go/predicate.java.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.functions');
/**
* Creates a function that always returns the same value.
* @param {T} retValue The value to return.
* @return {function():T} The new function.
* @template T
*/
goog.functions.constant = function(retValue) {
return function() {
return retValue;
};
};
/**
* Always returns false.
* @type {function(...): boolean}
*/
goog.functions.FALSE = goog.functions.constant(false);
/**
* Always returns true.
* @type {function(...): boolean}
*/
goog.functions.TRUE = goog.functions.constant(true);
/**
* Always returns NULL.
* @type {function(...): null}
*/
goog.functions.NULL = goog.functions.constant(null);
/**
* A simple function that returns the first argument of whatever is passed
* into it.
* @param {T=} opt_returnValue The single value that will be returned.
* @param {...*} var_args Optional trailing arguments. These are ignored.
* @return {T} The first argument passed in, or undefined if nothing was passed.
* @template T
*/
goog.functions.identity = function(opt_returnValue, var_args) {
return opt_returnValue;
};
/**
* Creates a function that always throws an error with the given message.
* @param {string} message The error message.
* @return {!Function} The error-throwing function.
*/
goog.functions.error = function(message) {
return function() {
throw Error(message);
};
};
/**
* Given a function, create a function that keeps opt_numArgs arguments and
* silently discards all additional arguments.
* @param {Function} f The original function.
* @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.
* @return {!Function} A version of f that only keeps the first opt_numArgs
* arguments.
*/
goog.functions.lock = function(f, opt_numArgs) {
opt_numArgs = opt_numArgs || 0;
return function() {
return f.apply(this, Array.prototype.slice.call(arguments, 0, opt_numArgs));
};
};
/**
* Given a function, create a new function that swallows its return value
* and replaces it with a new one.
* @param {Function} f A function.
* @param {T} retValue A new return value.
* @return {function(...[?]):T} A new function.
* @template T
*/
goog.functions.withReturnValue = function(f, retValue) {
return goog.functions.sequence(f, goog.functions.constant(retValue));
};
/**
* Creates the composition of the functions passed in.
* For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).
* @param {function(...[?]):T} fn The final function.
* @param {...Function} var_args A list of functions.
* @return {function(...[?]):T} The composition of all inputs.
* @template T
*/
goog.functions.compose = function(fn, var_args) {
var functions = arguments;
var length = functions.length;
return function() {
var result;
if (length) {
result = functions[length - 1].apply(this, arguments);
}
for (var i = length - 2; i >= 0; i--) {
result = functions[i].call(this, result);
}
return result;
};
};
/**
* Creates a function that calls the functions passed in in sequence, and
* returns the value of the last function. For example,
* (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).
* @param {...Function} var_args A list of functions.
* @return {!Function} A function that calls all inputs in sequence.
*/
goog.functions.sequence = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
var result;
for (var i = 0; i < length; i++) {
result = functions[i].apply(this, arguments);
}
return result;
};
};
/**
* Creates a function that returns true if each of its components evaluates
* to true. The components are evaluated in order, and the evaluation will be
* short-circuited as soon as a function returns false.
* For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).
* @param {...Function} var_args A list of functions.
* @return {function(...[?]):boolean} A function that ANDs its component
* functions.
*/
goog.functions.and = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
for (var i = 0; i < length; i++) {
if (!functions[i].apply(this, arguments)) {
return false;
}
}
return true;
};
};
/**
* Creates a function that returns true if any of its components evaluates
* to true. The components are evaluated in order, and the evaluation will be
* short-circuited as soon as a function returns true.
* For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).
* @param {...Function} var_args A list of functions.
* @return {function(...[?]):boolean} A function that ORs its component
* functions.
*/
goog.functions.or = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
for (var i = 0; i < length; i++) {
if (functions[i].apply(this, arguments)) {
return true;
}
}
return false;
};
};
/**
* Creates a function that returns the Boolean opposite of a provided function.
* For example, (goog.functions.not(f))(x) is equivalent to !f(x).
* @param {!Function} f The original function.
* @return {function(...[?]):boolean} A function that delegates to f and returns
* opposite.
*/
goog.functions.not = function(f) {
return function() {
return !f.apply(this, arguments);
};
};
/**
* Generic factory function to construct an object given the constructor
* and the arguments. Intended to be bound to create object factories.
*
* Callers should cast the result to the appropriate type for proper type
* checking by the compiler.
* @param {!Function} constructor The constructor for the Object.
* @param {...*} var_args The arguments to be passed to the constructor.
* @return {!Object} A new instance of the class given in {@code constructor}.
*/
goog.functions.create = function(constructor, var_args) {
/** @constructor */
var temp = function() {};
temp.prototype = constructor.prototype;
// obj will have constructor's prototype in its chain and
// 'obj instanceof constructor' will be true.
var obj = new temp();
// obj is initialized by constructor.
// arguments is only array-like so lacks shift(), but can be used with
// the Array prototype function.
constructor.apply(obj, Array.prototype.slice.call(arguments, 1));
return obj;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview VmlGraphics sub class that uses VML to draw the graphics.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.VmlGraphics');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.graphics.AbstractGraphics');
goog.require('goog.graphics.Font');
goog.require('goog.graphics.LinearGradient');
goog.require('goog.graphics.SolidFill');
goog.require('goog.graphics.Stroke');
goog.require('goog.graphics.VmlEllipseElement');
goog.require('goog.graphics.VmlGroupElement');
goog.require('goog.graphics.VmlImageElement');
goog.require('goog.graphics.VmlPathElement');
goog.require('goog.graphics.VmlRectElement');
goog.require('goog.graphics.VmlTextElement');
goog.require('goog.math.Size');
goog.require('goog.string');
goog.require('goog.style');
/**
* A Graphics implementation for drawing using VML.
* @param {string|number} width The (non-zero) width in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {string|number} height The (non-zero) height in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {?number=} opt_coordWidth The coordinate width - if
* omitted or null, defaults to same as width.
* @param {?number=} opt_coordHeight The coordinate height - if
* omitted or null, defaults to same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @constructor
* @extends {goog.graphics.AbstractGraphics}
*/
goog.graphics.VmlGraphics = function(width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper) {
goog.graphics.AbstractGraphics.call(this, width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper);
this.handler_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.graphics.VmlGraphics, goog.graphics.AbstractGraphics);
/**
* The prefix to use for VML elements
* @private
* @type {string}
*/
goog.graphics.VmlGraphics.VML_PREFIX_ = 'g_vml_';
/**
* The VML namespace URN
* @private
* @type {string}
*/
goog.graphics.VmlGraphics.VML_NS_ = 'urn:schemas-microsoft-com:vml';
/**
* The VML behavior URL.
* @private
* @type {string}
*/
goog.graphics.VmlGraphics.VML_IMPORT_ = '#default#VML';
/**
* Whether the document is using IE8 standards mode, and therefore needs hacks.
* @private
* @type {boolean}
*/
goog.graphics.VmlGraphics.IE8_MODE_ = document.documentMode &&
document.documentMode >= 8;
/**
* The coordinate multiplier to allow sub-pixel rendering
* @type {number}
*/
goog.graphics.VmlGraphics.COORD_MULTIPLIER = 100;
/**
* Converts the given size to a css size. If it is a percentage, leaves it
* alone. Otherwise assumes px.
*
* @param {number|string} size The size to use.
* @return {string} The position adjusted for COORD_MULTIPLIER.
*/
goog.graphics.VmlGraphics.toCssSize = function(size) {
return goog.isString(size) && goog.string.endsWith(size, '%') ?
size : parseFloat(size.toString()) + 'px';
};
/**
* Multiplies positioning coordinates by COORD_MULTIPLIER to allow sub-pixel
* coordinates. Also adds a half pixel offset to match SVG.
*
* This function is internal for the VML supporting classes, and
* should not be used externally.
*
* @param {number|string} number A position in pixels.
* @return {number} The position adjusted for COORD_MULTIPLIER.
*/
goog.graphics.VmlGraphics.toPosCoord = function(number) {
return Math.round((parseFloat(number.toString()) - 0.5) *
goog.graphics.VmlGraphics.COORD_MULTIPLIER);
};
/**
* Add a "px" suffix to a number of pixels, and multiplies all coordinates by
* COORD_MULTIPLIER to allow sub-pixel coordinates.
*
* This function is internal for the VML supporting classes, and
* should not be used externally.
*
* @param {number|string} number A position in pixels.
* @return {string} The position with suffix 'px'.
*/
goog.graphics.VmlGraphics.toPosPx = function(number) {
return goog.graphics.VmlGraphics.toPosCoord(number) + 'px';
};
/**
* Multiplies the width or height coordinate by COORD_MULTIPLIER to allow
* sub-pixel coordinates.
*
* This function is internal for the VML supporting classes, and
* should not be used externally.
*
* @param {string|number} number A size in units.
* @return {number} The size multiplied by the correct factor.
*/
goog.graphics.VmlGraphics.toSizeCoord = function(number) {
return Math.round(parseFloat(number.toString()) *
goog.graphics.VmlGraphics.COORD_MULTIPLIER);
};
/**
* Add a "px" suffix to a number of pixels, and multiplies all coordinates by
* COORD_MULTIPLIER to allow sub-pixel coordinates.
*
* This function is internal for the VML supporting classes, and
* should not be used externally.
*
* @param {number|string} number A size in pixels.
* @return {string} The size with suffix 'px'.
*/
goog.graphics.VmlGraphics.toSizePx = function(number) {
return goog.graphics.VmlGraphics.toSizeCoord(number) + 'px';
};
/**
* Sets an attribute on the given VML element, in the way best suited to the
* current version of IE. Should only be used in the goog.graphics package.
* @param {Element} element The element to set an attribute
* on.
* @param {string} name The name of the attribute to set.
* @param {string} value The value to set it to.
*/
goog.graphics.VmlGraphics.setAttribute = function(element, name, value) {
if (goog.graphics.VmlGraphics.IE8_MODE_) {
element[name] = value;
} else {
element.setAttribute(name, value);
}
};
/**
* Event handler.
* @type {goog.events.EventHandler}
* @private
*/
goog.graphics.VmlGraphics.prototype.handler_;
/**
* Creates a VML element. Used internally and by different VML classes.
* @param {string} tagName The type of element to create.
* @return {Element} The created element.
*/
goog.graphics.VmlGraphics.prototype.createVmlElement = function(tagName) {
var element =
this.dom_.createElement(goog.graphics.VmlGraphics.VML_PREFIX_ + ':' +
tagName);
element.id = goog.string.createUniqueString();
return element;
};
/**
* Returns the VML element with the given id that is a child of this graphics
* object.
* Should be considered package private, and not used externally.
* @param {string} id The element id to find.
* @return {Element} The element with the given id, or null if none is found.
*/
goog.graphics.VmlGraphics.prototype.getVmlElement = function(id) {
return this.dom_.getElement(id);
};
/**
* Resets the graphics so they will display properly on IE8. Noop in older
* versions.
* @private
*/
goog.graphics.VmlGraphics.prototype.updateGraphics_ = function() {
if (goog.graphics.VmlGraphics.IE8_MODE_ && this.isInDocument()) {
this.getElement().innerHTML = this.getElement().innerHTML;
}
};
/**
* Appends an element.
*
* @param {goog.graphics.Element} element The element wrapper.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
* @private
*/
goog.graphics.VmlGraphics.prototype.append_ = function(element, opt_group) {
var parent = opt_group || this.canvasElement;
parent.getElement().appendChild(element.getElement());
this.updateGraphics_();
};
/**
* Sets the fill for the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element wrapper.
* @param {goog.graphics.Fill?} fill The fill object.
* @override
*/
goog.graphics.VmlGraphics.prototype.setElementFill = function(element, fill) {
var vmlElement = element.getElement();
this.removeFill(vmlElement);
if (fill instanceof goog.graphics.SolidFill) {
// NOTE(arv): VML does not understand 'transparent' so hard code support
// for it.
if (fill.getColor() == 'transparent') {
vmlElement.filled = false;
} else if (fill.getOpacity() != 1) {
vmlElement.filled = true;
// Set opacity (number 0-1 is translated to percent)
var fillNode = this.createVmlElement('fill');
fillNode.opacity = Math.round(fill.getOpacity() * 100) + '%';
fillNode.color = fill.getColor();
vmlElement.appendChild(fillNode);
} else {
vmlElement.filled = true;
vmlElement.fillcolor = fill.getColor();
}
} else if (fill instanceof goog.graphics.LinearGradient) {
vmlElement.filled = true;
// Add a 'fill' element
var gradient = this.createVmlElement('fill');
gradient.color = fill.getColor1();
gradient.color2 = fill.getColor2();
if (goog.isNumber(fill.getOpacity1())) {
gradient.opacity = fill.getOpacity1();
}
if (goog.isNumber(fill.getOpacity2())) {
gradient.opacity2 = fill.getOpacity2();
}
var angle = goog.math.angle(fill.getX1(), fill.getY1(),
fill.getX2(), fill.getY2());
// Our angles start from 0 to the right, and grow clockwise.
// MSIE starts from 0 to top, and grows anti-clockwise.
angle = Math.round(goog.math.standardAngle(270 - angle));
gradient.angle = angle;
gradient.type = 'gradient';
vmlElement.appendChild(gradient);
} else {
vmlElement.filled = false;
}
this.updateGraphics_();
};
/**
* Sets the stroke for the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element wrapper.
* @param {goog.graphics.Stroke?} stroke The stroke object.
* @override
*/
goog.graphics.VmlGraphics.prototype.setElementStroke = function(element,
stroke) {
var vmlElement = element.getElement();
if (stroke) {
vmlElement.stroked = true;
var width = stroke.getWidth();
if (goog.isString(width) && width.indexOf('px') == -1) {
width = parseFloat(width);
} else {
width = width * this.getPixelScaleX();
}
var strokeElement = vmlElement.getElementsByTagName('stroke')[0];
if (width < 1) {
strokeElement = strokeElement || this.createVmlElement('stroke');
strokeElement.opacity = width;
strokeElement.weight = '1px';
strokeElement.color = stroke.getColor();
vmlElement.appendChild(strokeElement);
} else {
if (strokeElement) {
vmlElement.removeChild(strokeElement);
}
vmlElement.strokecolor = stroke.getColor();
vmlElement.strokeweight = width + 'px';
}
} else {
vmlElement.stroked = false;
}
this.updateGraphics_();
};
/**
* Set the transformation of an element.
* @param {goog.graphics.Element} element The element wrapper.
* @param {number} x The x coordinate of the translation transform.
* @param {number} y The y coordinate of the translation transform.
* @param {number} angle The angle of the rotation transform.
* @param {number} centerX The horizontal center of the rotation transform.
* @param {number} centerY The vertical center of the rotation transform.
* @override
*/
goog.graphics.VmlGraphics.prototype.setElementTransform = function(element, x,
y, angle, centerX, centerY) {
var el = element.getElement();
el.style.left = goog.graphics.VmlGraphics.toPosPx(x);
el.style.top = goog.graphics.VmlGraphics.toPosPx(y);
if (angle || el.rotation) {
el.rotation = angle;
el.coordsize = goog.graphics.VmlGraphics.toSizeCoord(centerX * 2) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(centerY * 2);
}
};
/**
* Removes the fill information from a dom element.
* @param {Element} element DOM element.
*/
goog.graphics.VmlGraphics.prototype.removeFill = function(element) {
element.fillcolor = '';
var v = element.childNodes.length;
for (var i = 0; i < element.childNodes.length; i++) {
var child = element.childNodes[i];
if (child.tagName == 'fill') {
element.removeChild(child);
}
}
};
/**
* Set top, left, width and height for an element.
* This function is internal for the VML supporting classes, and
* should not be used externally.
*
* @param {Element} element DOM element.
* @param {number} left Left ccordinate in pixels.
* @param {number} top Top ccordinate in pixels.
* @param {number} width Width in pixels.
* @param {number} height Height in pixels.
*/
goog.graphics.VmlGraphics.setPositionAndSize = function(
element, left, top, width, height) {
var style = element.style;
style.position = 'absolute';
style.left = goog.graphics.VmlGraphics.toPosPx(left);
style.top = goog.graphics.VmlGraphics.toPosPx(top);
style.width = goog.graphics.VmlGraphics.toSizePx(width);
style.height = goog.graphics.VmlGraphics.toSizePx(height);
if (element.tagName == 'shape') {
element.coordsize = goog.graphics.VmlGraphics.toSizeCoord(width) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(height);
}
};
/**
* Creates an element spanning the surface.
*
* @param {string} type The type of element to create.
* @return {Element} The created, positioned, and sized element.
* @private
*/
goog.graphics.VmlGraphics.prototype.createFullSizeElement_ = function(type) {
var element = this.createVmlElement(type);
var size = this.getCoordSize();
goog.graphics.VmlGraphics.setPositionAndSize(element, 0, 0, size.width,
size.height);
return element;
};
/**
* IE magic - if this "no-op" line is not here, the if statement below will
* fail intermittently. The eval is used to prevent the JsCompiler from
* stripping this piece of code, which it quite reasonably thinks is doing
* nothing. Put it in try-catch block to prevent "Unspecified Error" when
* this statement is executed in a defer JS in IE.
* More info here:
* http://www.mail-archive.com/users@openlayers.org/msg01838.html
*/
try {
eval('document.namespaces');
} catch (ex) {}
/**
* Creates the DOM representation of the graphics area.
* @override
*/
goog.graphics.VmlGraphics.prototype.createDom = function() {
var doc = this.dom_.getDocument();
// Add the namespace.
if (!doc.namespaces[goog.graphics.VmlGraphics.VML_PREFIX_]) {
if (goog.graphics.VmlGraphics.IE8_MODE_) {
doc.namespaces.add(goog.graphics.VmlGraphics.VML_PREFIX_,
goog.graphics.VmlGraphics.VML_NS_,
goog.graphics.VmlGraphics.VML_IMPORT_);
} else {
doc.namespaces.add(goog.graphics.VmlGraphics.VML_PREFIX_,
goog.graphics.VmlGraphics.VML_NS_);
}
// We assume that we only need to add the CSS if the namespace was not
// present
var ss = doc.createStyleSheet();
ss.cssText = goog.graphics.VmlGraphics.VML_PREFIX_ + '\\:*' +
'{behavior:url(#default#VML)}';
}
// Outer a DIV with overflow hidden for clipping.
// All inner elements are absolutly positioned on-top of this div.
var pixelWidth = this.width;
var pixelHeight = this.height;
var divElement = this.dom_.createDom('div', {
'style': 'overflow:hidden;position:relative;width:' +
goog.graphics.VmlGraphics.toCssSize(pixelWidth) + ';height:' +
goog.graphics.VmlGraphics.toCssSize(pixelHeight)
});
this.setElementInternal(divElement);
var group = this.createVmlElement('group');
var style = group.style;
style.position = 'absolute';
style.left = style.top = 0;
style.width = this.width;
style.height = this.height;
if (this.coordWidth) {
group.coordsize =
goog.graphics.VmlGraphics.toSizeCoord(this.coordWidth) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(
/** @type {number} */ (this.coordHeight));
} else {
group.coordsize = goog.graphics.VmlGraphics.toSizeCoord(pixelWidth) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(pixelHeight);
}
if (goog.isDef(this.coordLeft)) {
group.coordorigin = goog.graphics.VmlGraphics.toSizeCoord(this.coordLeft) +
' ' + goog.graphics.VmlGraphics.toSizeCoord(this.coordTop);
} else {
group.coordorigin = '0 0';
}
divElement.appendChild(group);
this.canvasElement = new goog.graphics.VmlGroupElement(group, this);
goog.events.listen(divElement, goog.events.EventType.RESIZE, goog.bind(
this.handleContainerResize_, this));
};
/**
* Changes the canvas element size to match the container element size.
* @private
*/
goog.graphics.VmlGraphics.prototype.handleContainerResize_ = function() {
var size = goog.style.getSize(this.getElement());
var style = this.canvasElement.getElement().style;
if (size.width) {
style.width = size.width + 'px';
style.height = size.height + 'px';
} else {
var current = this.getElement();
while (current && current.currentStyle &&
current.currentStyle.display != 'none') {
current = current.parentNode;
}
if (current && current.currentStyle) {
this.handler_.listen(current, 'propertychange',
this.handleContainerResize_);
}
}
this.dispatchEvent(goog.events.EventType.RESIZE);
};
/**
* Handle property changes on hidden ancestors.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.graphics.VmlGraphics.prototype.handlePropertyChange_ = function(e) {
var prop = e.getBrowserEvent().propertyName;
if (prop == 'display' || prop == 'className') {
this.handler_.unlisten(/** @type {Element} */(e.target),
'propertychange', this.handlePropertyChange_);
this.handleContainerResize_();
}
};
/**
* Changes the coordinate system position.
* @param {number} left The coordinate system left bound.
* @param {number} top The coordinate system top bound.
* @override
*/
goog.graphics.VmlGraphics.prototype.setCoordOrigin = function(left, top) {
this.coordLeft = left;
this.coordTop = top;
this.canvasElement.getElement().coordorigin =
goog.graphics.VmlGraphics.toSizeCoord(this.coordLeft) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(this.coordTop);
};
/**
* Changes the coordinate size.
* @param {number} coordWidth The coordinate width.
* @param {number} coordHeight The coordinate height.
* @override
*/
goog.graphics.VmlGraphics.prototype.setCoordSize = function(coordWidth,
coordHeight) {
goog.graphics.VmlGraphics.superClass_.setCoordSize.apply(this, arguments);
this.canvasElement.getElement().coordsize =
goog.graphics.VmlGraphics.toSizeCoord(coordWidth) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(coordHeight);
};
/**
* Change the size of the canvas.
* @param {number} pixelWidth The width in pixels.
* @param {number} pixelHeight The height in pixels.
* @override
*/
goog.graphics.VmlGraphics.prototype.setSize = function(pixelWidth,
pixelHeight) {
goog.style.setSize(this.getElement(), pixelWidth, pixelHeight);
};
/**
* @return {goog.math.Size} Returns the number of pixels spanned by the surface.
* @override
*/
goog.graphics.VmlGraphics.prototype.getPixelSize = function() {
var el = this.getElement();
// The following relies on the fact that the size can never be 0.
return new goog.math.Size(el.style.pixelWidth || el.offsetWidth || 1,
el.style.pixelHeight || el.offsetHeight || 1);
};
/**
* Remove all drawing elements from the graphics.
* @override
*/
goog.graphics.VmlGraphics.prototype.clear = function() {
this.canvasElement.clear();
};
/**
* Draw an ellipse.
*
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.EllipseElement} The newly created element.
* @override
*/
goog.graphics.VmlGraphics.prototype.drawEllipse = function(cx, cy, rx, ry,
stroke, fill, opt_group) {
var element = this.createVmlElement('oval');
goog.graphics.VmlGraphics.setPositionAndSize(element, cx - rx, cy - ry,
rx * 2, ry * 2);
var wrapper = new goog.graphics.VmlEllipseElement(element, this,
cx, cy, rx, ry, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw a rectangle.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.RectElement} The newly created element.
* @override
*/
goog.graphics.VmlGraphics.prototype.drawRect = function(x, y, width, height,
stroke, fill, opt_group) {
var element = this.createVmlElement('rect');
goog.graphics.VmlGraphics.setPositionAndSize(element, x, y, width, height);
var wrapper = new goog.graphics.VmlRectElement(element, this, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw an image.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of image.
* @param {number} height Height of image.
* @param {string} src Source of the image.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.ImageElement} The newly created element.
*/
goog.graphics.VmlGraphics.prototype.drawImage = function(x, y, width, height,
src, opt_group) {
var element = this.createVmlElement('image');
goog.graphics.VmlGraphics.setPositionAndSize(element, x, y, width, height);
goog.graphics.VmlGraphics.setAttribute(element, 'src', src);
var wrapper = new goog.graphics.VmlImageElement(element, this);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw a text string vertically centered on a given line.
*
* @param {string} text The text to draw.
* @param {number} x1 X coordinate of start of line.
* @param {number} y1 Y coordinate of start of line.
* @param {number} x2 X coordinate of end of line.
* @param {number} y2 Y coordinate of end of line.
* @param {?string} align Horizontal alignment: left (default), center, right.
* @param {goog.graphics.Font} font Font describing the font properties.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.TextElement} The newly created element.
* @override
*/
goog.graphics.VmlGraphics.prototype.drawTextOnLine = function(
text, x1, y1, x2, y2, align, font, stroke, fill, opt_group) {
var shape = this.createFullSizeElement_('shape');
var pathElement = this.createVmlElement('path');
var path = 'M' + goog.graphics.VmlGraphics.toPosCoord(x1) + ',' +
goog.graphics.VmlGraphics.toPosCoord(y1) + 'L' +
goog.graphics.VmlGraphics.toPosCoord(x2) + ',' +
goog.graphics.VmlGraphics.toPosCoord(y2) + 'E';
goog.graphics.VmlGraphics.setAttribute(pathElement, 'v', path);
goog.graphics.VmlGraphics.setAttribute(pathElement, 'textpathok', 'true');
var textPathElement = this.createVmlElement('textpath');
textPathElement.setAttribute('on', 'true');
var style = textPathElement.style;
style.fontSize = font.size * this.getPixelScaleX();
style.fontFamily = font.family;
if (align != null) {
style['v-text-align'] = align;
}
if (font.bold) {
style.fontWeight = 'bold';
}
if (font.italic) {
style.fontStyle = 'italic';
}
goog.graphics.VmlGraphics.setAttribute(textPathElement, 'string', text);
shape.appendChild(pathElement);
shape.appendChild(textPathElement);
var wrapper = new goog.graphics.VmlTextElement(shape, this, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw a path.
*
* @param {!goog.graphics.Path} path The path object to draw.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.PathElement} The newly created element.
* @override
*/
goog.graphics.VmlGraphics.prototype.drawPath = function(path, stroke, fill,
opt_group) {
var element = this.createFullSizeElement_('shape');
goog.graphics.VmlGraphics.setAttribute(element, 'path',
goog.graphics.VmlGraphics.getVmlPath(path));
var wrapper = new goog.graphics.VmlPathElement(element, this, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Returns a string representation of a logical path suitable for use in
* a VML element.
*
* @param {goog.graphics.Path} path The logical path.
* @return {string} The VML path representation.
*/
goog.graphics.VmlGraphics.getVmlPath = function(path) {
var list = [];
path.forEachSegment(function(segment, args) {
switch (segment) {
case goog.graphics.Path.Segment.MOVETO:
list.push('m');
Array.prototype.push.apply(list, goog.array.map(args,
goog.graphics.VmlGraphics.toSizeCoord));
break;
case goog.graphics.Path.Segment.LINETO:
list.push('l');
Array.prototype.push.apply(list, goog.array.map(args,
goog.graphics.VmlGraphics.toSizeCoord));
break;
case goog.graphics.Path.Segment.CURVETO:
list.push('c');
Array.prototype.push.apply(list, goog.array.map(args,
goog.graphics.VmlGraphics.toSizeCoord));
break;
case goog.graphics.Path.Segment.CLOSE:
list.push('x');
break;
case goog.graphics.Path.Segment.ARCTO:
var toAngle = args[2] + args[3];
var cx = goog.graphics.VmlGraphics.toSizeCoord(
args[4] - goog.math.angleDx(toAngle, args[0]));
var cy = goog.graphics.VmlGraphics.toSizeCoord(
args[5] - goog.math.angleDy(toAngle, args[1]));
var rx = goog.graphics.VmlGraphics.toSizeCoord(args[0]);
var ry = goog.graphics.VmlGraphics.toSizeCoord(args[1]);
// VML angles are in fd units (see http://www.w3.org/TR/NOTE-VML) and
// are positive counter-clockwise.
var fromAngle = Math.round(args[2] * -65536);
var extent = Math.round(args[3] * -65536);
list.push('ae', cx, cy, rx, ry, fromAngle, extent);
break;
}
});
return list.join(' ');
};
/**
* Create an empty group of drawing elements.
*
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.GroupElement} The newly created group.
* @override
*/
goog.graphics.VmlGraphics.prototype.createGroup = function(opt_group) {
var element = this.createFullSizeElement_('group');
var parent = opt_group || this.canvasElement;
parent.getElement().appendChild(element);
return new goog.graphics.VmlGroupElement(element, this);
};
/**
* Measure and return the width (in pixels) of a given text string.
* Text measurement is needed to make sure a text can fit in the allocated
* area. The way text length is measured is by writing it into a div that is
* after the visible area, measure the div width, and immediatly erase the
* written value.
*
* @param {string} text The text string to measure.
* @param {goog.graphics.Font} font The font object describing the font style.
*
* @return {number} The width in pixels of the text strings.
* @override
*/
goog.graphics.VmlGraphics.prototype.getTextWidth = function(text, font) {
// TODO(arv): Implement
return 0;
};
/** @override */
goog.graphics.VmlGraphics.prototype.enterDocument = function() {
goog.graphics.VmlGraphics.superClass_.enterDocument.call(this);
this.handleContainerResize_();
this.updateGraphics_();
};
/**
* Disposes of the component by removing event handlers, detacing DOM nodes from
* the document body, and removing references to them.
* @override
* @protected
*/
goog.graphics.VmlGraphics.prototype.disposeInternal = function() {
this.canvasElement = null;
goog.graphics.VmlGraphics.superClass_.disposeInternal.call(this);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Graphics utility functions and factory methods.
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.graphics.AbstractGraphics');
goog.require('goog.graphics.Path');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.ui.Component');
/**
* Base class for the different graphics. You should never construct objects
* of this class. Instead us goog.graphics.createGraphics
* @param {number|string} width The width in pixels or percent.
* @param {number|string} height The height in pixels or percent.
* @param {?number=} opt_coordWidth Optional coordinate system width - if
* omitted or null, defaults to same as width.
* @param {?number=} opt_coordHeight Optional coordinate system height - if
* omitted or null, defaults to same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @constructor
* @extends {goog.ui.Component}
*/
goog.graphics.AbstractGraphics = function(width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* Width of graphics in pixels or percentage points.
* @type {number|string}
* @protected
*/
this.width = width;
/**
* Height of graphics in pixels or precentage points.
* @type {number|string}
* @protected
*/
this.height = height;
/**
* Width of coordinate system in units.
* @type {?number}
* @protected
*/
this.coordWidth = opt_coordWidth || null;
/**
* Height of coordinate system in units.
* @type {?number}
* @protected
*/
this.coordHeight = opt_coordHeight || null;
};
goog.inherits(goog.graphics.AbstractGraphics, goog.ui.Component);
/**
* The root level group element.
* @type {goog.graphics.GroupElement?}
* @protected
*/
goog.graphics.AbstractGraphics.prototype.canvasElement = null;
/**
* Left coordinate of the view box
* @type {number}
* @protected
*/
goog.graphics.AbstractGraphics.prototype.coordLeft = 0;
/**
* Top coordinate of the view box
* @type {number}
* @protected
*/
goog.graphics.AbstractGraphics.prototype.coordTop = 0;
/**
* @return {goog.graphics.GroupElement} The root level canvas element.
*/
goog.graphics.AbstractGraphics.prototype.getCanvasElement = function() {
return this.canvasElement;
};
/**
* Changes the coordinate size.
* @param {number} coordWidth The coordinate width.
* @param {number} coordHeight The coordinate height.
*/
goog.graphics.AbstractGraphics.prototype.setCoordSize = function(coordWidth,
coordHeight) {
this.coordWidth = coordWidth;
this.coordHeight = coordHeight;
};
/**
* @return {goog.math.Size} The coordinate size.
*/
goog.graphics.AbstractGraphics.prototype.getCoordSize = function() {
if (this.coordWidth) {
return new goog.math.Size(this.coordWidth,
/** @type {number} */ (this.coordHeight));
} else {
return this.getPixelSize();
}
};
/**
* Changes the coordinate system position.
* @param {number} left The coordinate system left bound.
* @param {number} top The coordinate system top bound.
*/
goog.graphics.AbstractGraphics.prototype.setCoordOrigin = goog.abstractMethod;
/**
* @return {goog.math.Coordinate} The coordinate system position.
*/
goog.graphics.AbstractGraphics.prototype.getCoordOrigin = function() {
return new goog.math.Coordinate(this.coordLeft, this.coordTop);
};
/**
* Change the size of the canvas.
* @param {number} pixelWidth The width in pixels.
* @param {number} pixelHeight The height in pixels.
*/
goog.graphics.AbstractGraphics.prototype.setSize = goog.abstractMethod;
/**
* @return {goog.math.Size} The size of canvas.
* @deprecated Use getPixelSize.
*/
goog.graphics.AbstractGraphics.prototype.getSize = function() {
return this.getPixelSize();
};
/**
* @return {goog.math.Size?} Returns the number of pixels spanned by the
* surface, or null if the size could not be computed due to the size being
* specified in percentage points and the component not being in the
* document.
*/
goog.graphics.AbstractGraphics.prototype.getPixelSize = function() {
if (this.isInDocument()) {
return goog.style.getSize(this.getElement());
}
if (goog.isNumber(this.width) && goog.isNumber(this.height)) {
return new goog.math.Size(this.width, this.height);
}
return null;
};
/**
* @return {number} Returns the number of pixels per unit in the x direction.
*/
goog.graphics.AbstractGraphics.prototype.getPixelScaleX = function() {
var pixelSize = this.getPixelSize();
return pixelSize ? pixelSize.width / this.getCoordSize().width : 0;
};
/**
* @return {number} Returns the number of pixels per unit in the y direction.
*/
goog.graphics.AbstractGraphics.prototype.getPixelScaleY = function() {
var pixelSize = this.getPixelSize();
return pixelSize ? pixelSize.height / this.getCoordSize().height : 0;
};
/**
* Remove all drawing elements from the graphics.
*/
goog.graphics.AbstractGraphics.prototype.clear = goog.abstractMethod;
/**
* Remove a single drawing element from the surface. The default implementation
* assumes a DOM based drawing surface.
* @param {goog.graphics.Element} element The element to remove.
*/
goog.graphics.AbstractGraphics.prototype.removeElement = function(element) {
goog.dom.removeNode(element.getElement());
};
/**
* Sets the fill for the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element wrapper.
* @param {goog.graphics.Fill?} fill The fill object.
*/
goog.graphics.AbstractGraphics.prototype.setElementFill = goog.abstractMethod;
/**
* Sets the stroke for the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element wrapper.
* @param {goog.graphics.Stroke?} stroke The stroke object.
*/
goog.graphics.AbstractGraphics.prototype.setElementStroke = goog.abstractMethod;
/**
* Set the transformation of an element.
* @param {goog.graphics.Element} element The element wrapper.
* @param {number} x The x coordinate of the translation transform.
* @param {number} y The y coordinate of the translation transform.
* @param {number} angle The angle of the rotation transform.
* @param {number} centerX The horizontal center of the rotation transform.
* @param {number} centerY The vertical center of the rotation transform.
*/
goog.graphics.AbstractGraphics.prototype.setElementTransform =
goog.abstractMethod;
/**
* Draw a circle
*
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} r Radius length.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.EllipseElement} The newly created element.
*/
goog.graphics.AbstractGraphics.prototype.drawCircle = function(
cx, cy, r, stroke, fill, opt_group) {
return this.drawEllipse(cx, cy, r, r, stroke, fill, opt_group);
};
/**
* Draw an ellipse
*
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.EllipseElement} The newly created element.
*/
goog.graphics.AbstractGraphics.prototype.drawEllipse = goog.abstractMethod;
/**
* Draw a rectangle
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.RectElement} The newly created element.
*/
goog.graphics.AbstractGraphics.prototype.drawRect = goog.abstractMethod;
/**
* Draw a text string within a rectangle (drawing is horizontal)
*
* @param {string} text The text to draw.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @param {string} align Horizontal alignment: left (default), center, right.
* @param {string} vAlign Vertical alignment: top (default), center, bottom.
* @param {goog.graphics.Font} font Font describing the font properties.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.TextElement} The newly created element.
*/
goog.graphics.AbstractGraphics.prototype.drawText = function(
text, x, y, width, height, align, vAlign, font, stroke, fill, opt_group) {
var baseline = font.size / 2; // Baseline is middle of line
var textY;
if (vAlign == 'bottom') {
textY = y + height - baseline;
} else if (vAlign == 'center') {
textY = y + height / 2;
} else {
textY = y + baseline;
}
return this.drawTextOnLine(text, x, textY, x + width, textY, align,
font, stroke, fill, opt_group);
};
/**
* Draw a text string vertically centered on a given line.
*
* @param {string} text The text to draw.
* @param {number} x1 X coordinate of start of line.
* @param {number} y1 Y coordinate of start of line.
* @param {number} x2 X coordinate of end of line.
* @param {number} y2 Y coordinate of end of line.
* @param {string} align Horizontal alingnment: left (default), center, right.
* @param {goog.graphics.Font} font Font describing the font properties.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.TextElement} The newly created element.
*/
goog.graphics.AbstractGraphics.prototype.drawTextOnLine = goog.abstractMethod;
/**
* Draw a path.
*
* @param {!goog.graphics.Path} path The path object to draw.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.PathElement} The newly created element.
*/
goog.graphics.AbstractGraphics.prototype.drawPath = goog.abstractMethod;
/**
* Create an empty group of drawing elements.
*
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element to
* append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.GroupElement} The newly created group.
*/
goog.graphics.AbstractGraphics.prototype.createGroup = goog.abstractMethod;
/**
* Create an empty path.
*
* @return {goog.graphics.Path} The path.
* @deprecated Use {@code new goog.graphics.Path()}.
*/
goog.graphics.AbstractGraphics.prototype.createPath = function() {
return new goog.graphics.Path();
};
/**
* Measure and return the width (in pixels) of a given text string.
* Text measurement is needed to make sure a text can fit in the allocated
* area. The way text length is measured is by writing it into a div that is
* after the visible area, measure the div width, and immediatly erase the
* written value.
*
* @param {string} text The text string to measure.
* @param {goog.graphics.Font} font The font object describing the font style.
*
* @return {number} The width in pixels of the text strings.
*/
goog.graphics.AbstractGraphics.prototype.getTextWidth = goog.abstractMethod;
/**
* @return {boolean} Whether the underlying element can be cloned resulting in
* an accurate reproduction of the graphics contents.
*/
goog.graphics.AbstractGraphics.prototype.isDomClonable = function() {
return false;
};
/**
* Start preventing redraws - useful for chaining large numbers of changes
* together. Not guaranteed to do anything - i.e. only use this for
* optimization of a single code path.
*/
goog.graphics.AbstractGraphics.prototype.suspend = function() {
};
/**
* Stop preventing redraws. If any redraws had been prevented, a redraw will
* be done now.
*/
goog.graphics.AbstractGraphics.prototype.resume = function() {
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for rectangles.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.RectElement');
goog.require('goog.graphics.StrokeAndFillElement');
/**
* Interface for a graphics rectangle element.
* You should not construct objects from this constructor. The graphics
* will return an implementation of this interface for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.StrokeAndFillElement}
*/
goog.graphics.RectElement = function(element, graphics, stroke, fill) {
goog.graphics.StrokeAndFillElement.call(this, element, graphics, stroke,
fill);
};
goog.inherits(goog.graphics.RectElement, goog.graphics.StrokeAndFillElement);
/**
* Update the position of the rectangle.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
*/
goog.graphics.RectElement.prototype.setPosition = goog.abstractMethod;
/**
* Update the size of the rectangle.
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
*/
goog.graphics.RectElement.prototype.setSize = goog.abstractMethod;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Thin wrappers around the DOM element returned from
* the different draw methods of the graphics. This is the VML implementation.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.VmlEllipseElement');
goog.provide('goog.graphics.VmlGroupElement');
goog.provide('goog.graphics.VmlImageElement');
goog.provide('goog.graphics.VmlPathElement');
goog.provide('goog.graphics.VmlRectElement');
goog.provide('goog.graphics.VmlTextElement');
goog.require('goog.dom');
goog.require('goog.graphics.EllipseElement');
goog.require('goog.graphics.GroupElement');
goog.require('goog.graphics.ImageElement');
goog.require('goog.graphics.PathElement');
goog.require('goog.graphics.RectElement');
goog.require('goog.graphics.TextElement');
/**
* Returns the VML element corresponding to this object. This method is added
* to several classes below. Note that the return value of this method may
* change frequently in IE8, so it should not be cached externally.
* @return {Element} The VML element corresponding to this object.
* @this {goog.graphics.VmlGroupElement|goog.graphics.VmlEllipseElement|
* goog.graphics.VmlRectElement|goog.graphics.VmlPathElement|
* goog.graphics.VmlTextElement|goog.graphics.VmlImageElement}
* @private
*/
goog.graphics.vmlGetElement_ = function() {
this.element_ = this.getGraphics().getVmlElement(this.id_) || this.element_;
return this.element_;
};
/**
* Thin wrapper for VML group elements.
* This is an implementation of the goog.graphics.GroupElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.VmlGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.GroupElement}
*/
goog.graphics.VmlGroupElement = function(element, graphics) {
this.id_ = element.id;
goog.graphics.GroupElement.call(this, element, graphics);
};
goog.inherits(goog.graphics.VmlGroupElement, goog.graphics.GroupElement);
/** @override */
goog.graphics.VmlGroupElement.prototype.getElement =
goog.graphics.vmlGetElement_;
/**
* Remove all drawing elements from the group.
* @override
*/
goog.graphics.VmlGroupElement.prototype.clear = function() {
goog.dom.removeChildren(this.getElement());
};
/**
* @return {boolean} True if this group is the root canvas element.
* @private
*/
goog.graphics.VmlGroupElement.prototype.isRootElement_ = function() {
return this.getGraphics().getCanvasElement() == this;
};
/**
* Set the size of the group element.
* @param {number|string} width The width of the group element.
* @param {number|string} height The height of the group element.
* @override
*/
goog.graphics.VmlGroupElement.prototype.setSize = function(width, height) {
var element = this.getElement();
var style = element.style;
style.width = goog.graphics.VmlGraphics.toSizePx(width);
style.height = goog.graphics.VmlGraphics.toSizePx(height);
element.coordsize = goog.graphics.VmlGraphics.toSizeCoord(width) + ' ' +
goog.graphics.VmlGraphics.toSizeCoord(height);
// Don't overwrite the root element's origin.
if (!this.isRootElement_()) {
element.coordorigin = '0 0';
}
};
/**
* Thin wrapper for VML ellipse elements.
* This is an implementation of the goog.graphics.EllipseElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.VmlGraphics} graphics The graphics creating
* this element.
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.EllipseElement}
*/
goog.graphics.VmlEllipseElement = function(element, graphics,
cx, cy, rx, ry, stroke, fill) {
this.id_ = element.id;
goog.graphics.EllipseElement.call(this, element, graphics, stroke, fill);
// Store center and radius for future calls to setRadius or setCenter.
/**
* X coordinate of the ellipse center.
* @type {number}
*/
this.cx = cx;
/**
* Y coordinate of the ellipse center.
* @type {number}
*/
this.cy = cy;
/**
* Radius length for the x-axis.
* @type {number}
*/
this.rx = rx;
/**
* Radius length for the y-axis.
* @type {number}
*/
this.ry = ry;
};
goog.inherits(goog.graphics.VmlEllipseElement, goog.graphics.EllipseElement);
/** @override */
goog.graphics.VmlEllipseElement.prototype.getElement =
goog.graphics.vmlGetElement_;
/**
* Update the center point of the ellipse.
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @override
*/
goog.graphics.VmlEllipseElement.prototype.setCenter = function(cx, cy) {
this.cx = cx;
this.cy = cy;
goog.graphics.VmlGraphics.setPositionAndSize(this.getElement(),
cx - this.rx, cy - this.ry, this.rx * 2, this.ry * 2);
};
/**
* Update the radius of the ellipse.
* @param {number} rx Center X coordinate.
* @param {number} ry Center Y coordinate.
* @override
*/
goog.graphics.VmlEllipseElement.prototype.setRadius = function(rx, ry) {
this.rx = rx;
this.ry = ry;
goog.graphics.VmlGraphics.setPositionAndSize(this.getElement(),
this.cx - rx, this.cy - ry, rx * 2, ry * 2);
};
/**
* Thin wrapper for VML rectangle elements.
* This is an implementation of the goog.graphics.RectElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.VmlGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.RectElement}
*/
goog.graphics.VmlRectElement = function(element, graphics, stroke, fill) {
this.id_ = element.id;
goog.graphics.RectElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.VmlRectElement, goog.graphics.RectElement);
/** @override */
goog.graphics.VmlRectElement.prototype.getElement =
goog.graphics.vmlGetElement_;
/**
* Update the position of the rectangle.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @override
*/
goog.graphics.VmlRectElement.prototype.setPosition = function(x, y) {
var style = this.getElement().style;
style.left = goog.graphics.VmlGraphics.toPosPx(x);
style.top = goog.graphics.VmlGraphics.toPosPx(y);
};
/**
* Update the size of the rectangle.
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @override
*/
goog.graphics.VmlRectElement.prototype.setSize = function(width, height) {
var style = this.getElement().style;
style.width = goog.graphics.VmlGraphics.toSizePx(width);
style.height = goog.graphics.VmlGraphics.toSizePx(height);
};
/**
* Thin wrapper for VML path elements.
* This is an implementation of the goog.graphics.PathElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.VmlGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.PathElement}
*/
goog.graphics.VmlPathElement = function(element, graphics, stroke, fill) {
this.id_ = element.id;
goog.graphics.PathElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.VmlPathElement, goog.graphics.PathElement);
/** @override */
goog.graphics.VmlPathElement.prototype.getElement =
goog.graphics.vmlGetElement_;
/**
* Update the underlying path.
* @param {!goog.graphics.Path} path The path object to draw.
* @override
*/
goog.graphics.VmlPathElement.prototype.setPath = function(path) {
goog.graphics.VmlGraphics.setAttribute(
this.getElement(), 'path', goog.graphics.VmlGraphics.getVmlPath(path));
};
/**
* Thin wrapper for VML text elements.
* This is an implementation of the goog.graphics.TextElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.VmlGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.TextElement}
*/
goog.graphics.VmlTextElement = function(element, graphics, stroke, fill) {
this.id_ = element.id;
goog.graphics.TextElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.VmlTextElement, goog.graphics.TextElement);
/** @override */
goog.graphics.VmlTextElement.prototype.getElement =
goog.graphics.vmlGetElement_;
/**
* Update the displayed text of the element.
* @param {string} text The text to draw.
* @override
*/
goog.graphics.VmlTextElement.prototype.setText = function(text) {
goog.graphics.VmlGraphics.setAttribute(this.getElement().childNodes[1],
'string', text);
};
/**
* Thin wrapper for VML image elements.
* This is an implementation of the goog.graphics.ImageElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.VmlGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.ImageElement}
*/
goog.graphics.VmlImageElement = function(element, graphics) {
this.id_ = element.id;
goog.graphics.ImageElement.call(this, element, graphics);
};
goog.inherits(goog.graphics.VmlImageElement, goog.graphics.ImageElement);
/** @override */
goog.graphics.VmlImageElement.prototype.getElement =
goog.graphics.vmlGetElement_;
/**
* Update the position of the image.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @override
*/
goog.graphics.VmlImageElement.prototype.setPosition = function(x, y) {
var style = this.getElement().style;
style.left = goog.graphics.VmlGraphics.toPosPx(x);
style.top = goog.graphics.VmlGraphics.toPosPx(y);
};
/**
* Update the size of the image.
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @override
*/
goog.graphics.VmlImageElement.prototype.setSize = function(width, height) {
var style = this.getElement().style;
style.width = goog.graphics.VmlGraphics.toPosPx(width);
style.height = goog.graphics.VmlGraphics.toPosPx(height);
};
/**
* Update the source of the image.
* @param {string} src Source of the image.
* @override
*/
goog.graphics.VmlImageElement.prototype.setSource = function(src) {
goog.graphics.VmlGraphics.setAttribute(this.getElement(), 'src', src);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a stroke object for goog.graphics.
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.graphics.Stroke');
/**
* Creates an immutable stroke object.
*
* @param {number|string} width The width of the stroke.
* @param {string} color The color of the stroke.
* @constructor
*/
goog.graphics.Stroke = function(width, color) {
/**
* The width of the stroke.
* @type {number|string}
* @private
*/
this.width_ = width;
/**
* The color with which to fill.
* @type {string}
* @private
*/
this.color_ = color;
};
/**
* @return {number|string} The width of this stroke.
*/
goog.graphics.Stroke.prototype.getWidth = function() {
return this.width_;
};
/**
* @return {string} The color of this stroke.
*/
goog.graphics.Stroke.prototype.getColor = function() {
return this.color_;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a fill goog.graphics.
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.graphics.Fill');
/**
* Creates a fill object
* @constructor
*/
goog.graphics.Fill = function() {};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for ellipses.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.EllipseElement');
goog.require('goog.graphics.StrokeAndFillElement');
/**
* Interface for a graphics ellipse element.
* You should not construct objects from this constructor. The graphics
* will return an implementation of this interface for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.StrokeAndFillElement}
*/
goog.graphics.EllipseElement = function(element, graphics, stroke, fill) {
goog.graphics.StrokeAndFillElement.call(this, element, graphics, stroke,
fill);
};
goog.inherits(goog.graphics.EllipseElement, goog.graphics.StrokeAndFillElement);
/**
* Update the center point of the ellipse.
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
*/
goog.graphics.EllipseElement.prototype.setCenter = goog.abstractMethod;
/**
* Update the radius of the ellipse.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
*/
goog.graphics.EllipseElement.prototype.setRadius = goog.abstractMethod;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Graphics utility functions and factory methods.
* @author arv@google.com (Erik Arvidsson)
* @see ../demos/graphics/advancedcoordinates.html
* @see ../demos/graphics/advancedcoordinates2.html
* @see ../demos/graphics/basicelements.html
* @see ../demos/graphics/events.html
* @see ../demos/graphics/modifyelements.html
* @see ../demos/graphics/tiger.html
*/
goog.provide('goog.graphics');
goog.require('goog.graphics.CanvasGraphics');
goog.require('goog.graphics.SvgGraphics');
goog.require('goog.graphics.VmlGraphics');
goog.require('goog.userAgent');
/**
* Returns an instance of goog.graphics.AbstractGraphics that knows how to draw
* for the current platform (A factory for the proper Graphics implementation)
* @param {string|number} width The width in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {string|number} height The height in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {?number=} opt_coordWidth The optional coordinate width - if
* omitted or null, defaults to same as width.
* @param {?number=} opt_coordHeight The optional coordinate height - if
* omitted or null, defaults to same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @return {goog.graphics.AbstractGraphics} The created instance.
*/
goog.graphics.createGraphics = function(width, height, opt_coordWidth,
opt_coordHeight, opt_domHelper) {
var graphics;
if (goog.userAgent.IE && !goog.userAgent.isVersion('9')) {
graphics = new goog.graphics.VmlGraphics(width, height,
opt_coordWidth, opt_coordHeight, opt_domHelper);
} else if (goog.userAgent.WEBKIT && (!goog.userAgent.isVersion('420') ||
goog.userAgent.MOBILE)) {
graphics = new goog.graphics.CanvasGraphics(width, height,
opt_coordWidth, opt_coordHeight, opt_domHelper);
} else {
graphics = new goog.graphics.SvgGraphics(width, height,
opt_coordWidth, opt_coordHeight, opt_domHelper);
}
// Create the dom now, because all drawing methods require that the
// main dom element (the canvas) has been already created.
graphics.createDom();
return graphics;
};
/**
* Returns an instance of goog.graphics.AbstractGraphics that knows how to draw
* for the current platform (A factory for the proper Graphics implementation)
* @param {string|number} width The width in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {string|number} height The height in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {?number=} opt_coordWidth The optional coordinate width, defaults to
* same as width.
* @param {?number=} opt_coordHeight The optional coordinate height, defaults to
* same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @return {goog.graphics.AbstractGraphics} The created instance.
*/
goog.graphics.createSimpleGraphics = function(width, height,
opt_coordWidth, opt_coordHeight, opt_domHelper) {
if (goog.userAgent.MAC && goog.userAgent.GECKO &&
!goog.userAgent.isVersion('1.9a')) {
// Canvas is 6x faster than SVG on Mac FF 2.0
var graphics = new goog.graphics.CanvasGraphics(
width, height, opt_coordWidth, opt_coordHeight,
opt_domHelper);
graphics.createDom();
return graphics;
}
// Otherwise, defer to normal graphics object creation.
return goog.graphics.createGraphics(width, height, opt_coordWidth,
opt_coordHeight, opt_domHelper);
};
/**
* Static function to check if the current browser has Graphics support.
* @return {boolean} True if the current browser has Graphics support.
*/
goog.graphics.isBrowserSupported = function() {
if (goog.userAgent.IE) {
return goog.userAgent.isVersion('5.5');
}
if (goog.userAgent.GECKO) {
return goog.userAgent.isVersion('1.8');
}
if (goog.userAgent.OPERA) {
return goog.userAgent.isVersion('9.0');
}
if (goog.userAgent.WEBKIT) {
return goog.userAgent.isVersion('412');
}
return false;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for text elements.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.TextElement');
goog.require('goog.graphics.StrokeAndFillElement');
/**
* Interface for a graphics text element.
* You should not construct objects from this constructor. The graphics
* will return an implementation of this interface for you.
*
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.StrokeAndFillElement}
*/
goog.graphics.TextElement = function(element, graphics, stroke, fill) {
goog.graphics.StrokeAndFillElement.call(this, element, graphics, stroke,
fill);
};
goog.inherits(goog.graphics.TextElement, goog.graphics.StrokeAndFillElement);
/**
* Update the displayed text of the element.
* @param {string} text The text to draw.
*/
goog.graphics.TextElement.prototype.setText = goog.abstractMethod;
| JavaScript |
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Factories for common path types.
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.graphics.paths');
goog.require('goog.graphics.Path');
goog.require('goog.math.Coordinate');
/**
* Defines a regular n-gon by specifing the center, a vertex, and the total
* number of vertices.
* @param {goog.math.Coordinate} center The center point.
* @param {goog.math.Coordinate} vertex The vertex, which implicitly defines
* a radius as well.
* @param {number} n The number of vertices.
* @return {!goog.graphics.Path} The path.
*/
goog.graphics.paths.createRegularNGon = function(center, vertex, n) {
var path = new goog.graphics.Path();
path.moveTo(vertex.x, vertex.y);
var startAngle = Math.atan2(vertex.y - center.y, vertex.x - center.x);
var radius = goog.math.Coordinate.distance(center, vertex);
for (var i = 1; i < n; i++) {
var angle = startAngle + 2 * Math.PI * (i / n);
path.lineTo(center.x + radius * Math.cos(angle),
center.y + radius * Math.sin(angle));
}
path.close();
return path;
};
/**
* Defines an arrow.
* @param {goog.math.Coordinate} a Point A.
* @param {goog.math.Coordinate} b Point B.
* @param {?number} aHead The size of the arrow head at point A.
* 0 omits the head.
* @param {?number} bHead The size of the arrow head at point B.
* 0 omits the head.
* @return {!goog.graphics.Path} The path.
*/
goog.graphics.paths.createArrow = function(a, b, aHead, bHead) {
var path = new goog.graphics.Path();
path.moveTo(a.x, a.y);
path.lineTo(b.x, b.y);
var angle = Math.atan2(b.y - a.y, b.x - a.x);
if (aHead) {
path.appendPath(
goog.graphics.paths.createRegularNGon(
new goog.math.Coordinate(
a.x + aHead * Math.cos(angle),
a.y + aHead * Math.sin(angle)),
a, 3));
}
if (bHead) {
path.appendPath(
goog.graphics.paths.createRegularNGon(
new goog.math.Coordinate(
b.x + bHead * Math.cos(angle + Math.PI),
b.y + bHead * Math.sin(angle + Math.PI)),
b, 3));
}
return path;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides an object representation of an AffineTransform and
* methods for working with it.
*/
goog.provide('goog.graphics.AffineTransform');
goog.require('goog.math');
/**
* Creates a 2D affine transform. An affine transform performs a linear
* mapping from 2D coordinates to other 2D coordinates that preserves the
* "straightness" and "parallelness" of lines.
*
* Such a coordinate transformation can be represented by a 3 row by 3 column
* matrix with an implied last row of [ 0 0 1 ]. This matrix transforms source
* coordinates (x,y) into destination coordinates (x',y') by considering them
* to be a column vector and multiplying the coordinate vector by the matrix
* according to the following process:
* <pre>
* [ x'] [ m00 m01 m02 ] [ x ] [ m00x + m01y + m02 ]
* [ y'] = [ m10 m11 m12 ] [ y ] = [ m10x + m11y + m12 ]
* [ 1 ] [ 0 0 1 ] [ 1 ] [ 1 ]
* </pre>
*
* This class is optimized for speed and minimizes calculations based on its
* knowledge of the underlying matrix (as opposed to say simply performing
* matrix multiplication).
*
* @param {number=} opt_m00 The m00 coordinate of the transform.
* @param {number=} opt_m10 The m10 coordinate of the transform.
* @param {number=} opt_m01 The m01 coordinate of the transform.
* @param {number=} opt_m11 The m11 coordinate of the transform.
* @param {number=} opt_m02 The m02 coordinate of the transform.
* @param {number=} opt_m12 The m12 coordinate of the transform.
* @constructor
*/
goog.graphics.AffineTransform = function(opt_m00, opt_m10, opt_m01,
opt_m11, opt_m02, opt_m12) {
if (arguments.length == 6) {
this.setTransform(/** @type {number} */ (opt_m00),
/** @type {number} */ (opt_m10),
/** @type {number} */ (opt_m01),
/** @type {number} */ (opt_m11),
/** @type {number} */ (opt_m02),
/** @type {number} */ (opt_m12));
} else if (arguments.length != 0) {
throw Error('Insufficient matrix parameters');
} else {
this.m00_ = this.m11_ = 1;
this.m10_ = this.m01_ = this.m02_ = this.m12_ = 0;
}
};
/**
* @return {boolean} Whether this transform is the identity transform.
*/
goog.graphics.AffineTransform.prototype.isIdentity = function() {
return this.m00_ == 1 && this.m10_ == 0 && this.m01_ == 0 &&
this.m11_ == 1 && this.m02_ == 0 && this.m12_ == 0;
};
/**
* @return {!goog.graphics.AffineTransform} A copy of this transform.
*/
goog.graphics.AffineTransform.prototype.clone = function() {
return new goog.graphics.AffineTransform(this.m00_, this.m10_, this.m01_,
this.m11_, this.m02_, this.m12_);
};
/**
* Sets this transform to the matrix specified by the 6 values.
*
* @param {number} m00 The m00 coordinate of the transform.
* @param {number} m10 The m10 coordinate of the transform.
* @param {number} m01 The m01 coordinate of the transform.
* @param {number} m11 The m11 coordinate of the transform.
* @param {number} m02 The m02 coordinate of the transform.
* @param {number} m12 The m12 coordinate of the transform.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.setTransform = function(m00, m10, m01,
m11, m02, m12) {
if (!goog.isNumber(m00) || !goog.isNumber(m10) || !goog.isNumber(m01) ||
!goog.isNumber(m11) || !goog.isNumber(m02) || !goog.isNumber(m12)) {
throw Error('Invalid transform parameters');
}
this.m00_ = m00;
this.m10_ = m10;
this.m01_ = m01;
this.m11_ = m11;
this.m02_ = m02;
this.m12_ = m12;
return this;
};
/**
* Sets this transform to be identical to the given transform.
*
* @param {!goog.graphics.AffineTransform} tx The transform to copy.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.copyFrom = function(tx) {
this.m00_ = tx.m00_;
this.m10_ = tx.m10_;
this.m01_ = tx.m01_;
this.m11_ = tx.m11_;
this.m02_ = tx.m02_;
this.m12_ = tx.m12_;
return this;
};
/**
* Concatenates this transform with a scaling transformation.
*
* @param {number} sx The x-axis scaling factor.
* @param {number} sy The y-axis scaling factor.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.scale = function(sx, sy) {
this.m00_ *= sx;
this.m10_ *= sx;
this.m01_ *= sy;
this.m11_ *= sy;
return this;
};
/**
* Pre-concatenates this transform with a scaling transformation,
* i.e. calculates the following matrix product:
*
* <pre>
* [sx 0 0] [m00 m01 m02]
* [ 0 sy 0] [m10 m11 m12]
* [ 0 0 1] [ 0 0 1]
* </pre>
*
* @param {number} sx The x-axis scaling factor.
* @param {number} sy The y-axis scaling factor.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.preScale = function(sx, sy) {
this.m00_ *= sx;
this.m01_ *= sx;
this.m02_ *= sx;
this.m10_ *= sy;
this.m11_ *= sy;
this.m12_ *= sy;
return this;
};
/**
* Concatenates this transform with a translate transformation.
*
* @param {number} dx The distance to translate in the x direction.
* @param {number} dy The distance to translate in the y direction.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.translate = function(dx, dy) {
this.m02_ += dx * this.m00_ + dy * this.m01_;
this.m12_ += dx * this.m10_ + dy * this.m11_;
return this;
};
/**
* Pre-concatenates this transform with a translate transformation,
* i.e. calculates the following matrix product:
*
* <pre>
* [1 0 dx] [m00 m01 m02]
* [0 1 dy] [m10 m11 m12]
* [0 0 1] [ 0 0 1]
* </pre>
*
* @param {number} dx The distance to translate in the x direction.
* @param {number} dy The distance to translate in the y direction.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.preTranslate = function(dx, dy) {
this.m02_ += dx;
this.m12_ += dy;
return this;
};
/**
* Concatenates this transform with a rotation transformation around an anchor
* point.
*
* @param {number} theta The angle of rotation measured in radians.
* @param {number} x The x coordinate of the anchor point.
* @param {number} y The y coordinate of the anchor point.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.rotate = function(theta, x, y) {
return this.concatenate(
goog.graphics.AffineTransform.getRotateInstance(theta, x, y));
};
/**
* Pre-concatenates this transform with a rotation transformation around an
* anchor point.
*
* @param {number} theta The angle of rotation measured in radians.
* @param {number} x The x coordinate of the anchor point.
* @param {number} y The y coordinate of the anchor point.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.preRotate = function(theta, x, y) {
return this.preConcatenate(
goog.graphics.AffineTransform.getRotateInstance(theta, x, y));
};
/**
* Concatenates this transform with a shear transformation.
*
* @param {number} shx The x shear factor.
* @param {number} shy The y shear factor.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.shear = function(shx, shy) {
var m00 = this.m00_;
var m10 = this.m10_;
this.m00_ += shy * this.m01_;
this.m10_ += shy * this.m11_;
this.m01_ += shx * m00;
this.m11_ += shx * m10;
return this;
};
/**
* Pre-concatenates this transform with a shear transformation.
* i.e. calculates the following matrix product:
*
* <pre>
* [ 1 shx 0] [m00 m01 m02]
* [shy 1 0] [m10 m11 m12]
* [ 0 0 1] [ 0 0 1]
* </pre>
*
* @param {number} shx The x shear factor.
* @param {number} shy The y shear factor.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.preShear = function(shx, shy) {
var m00 = this.m00_;
var m01 = this.m01_;
var m02 = this.m02_;
this.m00_ += shx * this.m10_;
this.m01_ += shx * this.m11_;
this.m02_ += shx * this.m12_;
this.m10_ += shy * m00;
this.m11_ += shy * m01;
this.m12_ += shy * m02;
return this;
};
/**
* @return {string} A string representation of this transform. The format of
* of the string is compatible with SVG matrix notation, i.e.
* "matrix(a,b,c,d,e,f)".
* @override
*/
goog.graphics.AffineTransform.prototype.toString = function() {
return 'matrix(' +
[this.m00_, this.m10_, this.m01_, this.m11_, this.m02_, this.m12_].join(
',') +
')';
};
/**
* @return {number} The scaling factor in the x-direction (m00).
*/
goog.graphics.AffineTransform.prototype.getScaleX = function() {
return this.m00_;
};
/**
* @return {number} The scaling factor in the y-direction (m11).
*/
goog.graphics.AffineTransform.prototype.getScaleY = function() {
return this.m11_;
};
/**
* @return {number} The translation in the x-direction (m02).
*/
goog.graphics.AffineTransform.prototype.getTranslateX = function() {
return this.m02_;
};
/**
* @return {number} The translation in the y-direction (m12).
*/
goog.graphics.AffineTransform.prototype.getTranslateY = function() {
return this.m12_;
};
/**
* @return {number} The shear factor in the x-direction (m01).
*/
goog.graphics.AffineTransform.prototype.getShearX = function() {
return this.m01_;
};
/**
* @return {number} The shear factor in the y-direction (m10).
*/
goog.graphics.AffineTransform.prototype.getShearY = function() {
return this.m10_;
};
/**
* Concatenates an affine transform to this transform.
*
* @param {!goog.graphics.AffineTransform} tx The transform to concatenate.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.concatenate = function(tx) {
var m0 = this.m00_;
var m1 = this.m01_;
this.m00_ = tx.m00_ * m0 + tx.m10_ * m1;
this.m01_ = tx.m01_ * m0 + tx.m11_ * m1;
this.m02_ += tx.m02_ * m0 + tx.m12_ * m1;
m0 = this.m10_;
m1 = this.m11_;
this.m10_ = tx.m00_ * m0 + tx.m10_ * m1;
this.m11_ = tx.m01_ * m0 + tx.m11_ * m1;
this.m12_ += tx.m02_ * m0 + tx.m12_ * m1;
return this;
};
/**
* Pre-concatenates an affine transform to this transform.
*
* @param {!goog.graphics.AffineTransform} tx The transform to preconcatenate.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.preConcatenate = function(tx) {
var m0 = this.m00_;
var m1 = this.m10_;
this.m00_ = tx.m00_ * m0 + tx.m01_ * m1;
this.m10_ = tx.m10_ * m0 + tx.m11_ * m1;
m0 = this.m01_;
m1 = this.m11_;
this.m01_ = tx.m00_ * m0 + tx.m01_ * m1;
this.m11_ = tx.m10_ * m0 + tx.m11_ * m1;
m0 = this.m02_;
m1 = this.m12_;
this.m02_ = tx.m00_ * m0 + tx.m01_ * m1 + tx.m02_;
this.m12_ = tx.m10_ * m0 + tx.m11_ * m1 + tx.m12_;
return this;
};
/**
* Transforms an array of coordinates by this transform and stores the result
* into a destination array.
*
* @param {!Array.<number>} src The array containing the source points
* as x, y value pairs.
* @param {number} srcOff The offset to the first point to be transformed.
* @param {!Array.<number>} dst The array into which to store the transformed
* point pairs.
* @param {number} dstOff The offset of the location of the first transformed
* point in the destination array.
* @param {number} numPts The number of points to tranform.
*/
goog.graphics.AffineTransform.prototype.transform = function(src, srcOff, dst,
dstOff, numPts) {
var i = srcOff;
var j = dstOff;
var srcEnd = srcOff + 2 * numPts;
while (i < srcEnd) {
var x = src[i++];
var y = src[i++];
dst[j++] = x * this.m00_ + y * this.m01_ + this.m02_;
dst[j++] = x * this.m10_ + y * this.m11_ + this.m12_;
}
};
/**
* @return {number} The determinant of this transform.
*/
goog.graphics.AffineTransform.prototype.getDeterminant = function() {
return this.m00_ * this.m11_ - this.m01_ * this.m10_;
};
/**
* Returns whether the transform is invertible. A transform is not invertible
* if the determinant is 0 or any value is non-finite or NaN.
*
* @return {boolean} Whether the transform is invertible.
*/
goog.graphics.AffineTransform.prototype.isInvertible = function() {
var det = this.getDeterminant();
return goog.math.isFiniteNumber(det) &&
goog.math.isFiniteNumber(this.m02_) &&
goog.math.isFiniteNumber(this.m12_) &&
det != 0;
};
/**
* @return {!goog.graphics.AffineTransform} An AffineTransform object
* representing the inverse transformation.
*/
goog.graphics.AffineTransform.prototype.createInverse = function() {
var det = this.getDeterminant();
return new goog.graphics.AffineTransform(
this.m11_ / det,
-this.m10_ / det,
-this.m01_ / det,
this.m00_ / det,
(this.m01_ * this.m12_ - this.m11_ * this.m02_) / det,
(this.m10_ * this.m02_ - this.m00_ * this.m12_) / det);
};
/**
* Creates a transform representing a scaling transformation.
*
* @param {number} sx The x-axis scaling factor.
* @param {number} sy The y-axis scaling factor.
* @return {!goog.graphics.AffineTransform} A transform representing a scaling
* transformation.
*/
goog.graphics.AffineTransform.getScaleInstance = function(sx, sy) {
return new goog.graphics.AffineTransform().setToScale(sx, sy);
};
/**
* Creates a transform representing a translation transformation.
*
* @param {number} dx The distance to translate in the x direction.
* @param {number} dy The distance to translate in the y direction.
* @return {!goog.graphics.AffineTransform} A transform representing a
* translation transformation.
*/
goog.graphics.AffineTransform.getTranslateInstance = function(dx, dy) {
return new goog.graphics.AffineTransform().setToTranslation(dx, dy);
};
/**
* Creates a transform representing a shearing transformation.
*
* @param {number} shx The x-axis shear factor.
* @param {number} shy The y-axis shear factor.
* @return {!goog.graphics.AffineTransform} A transform representing a shearing
* transformation.
*/
goog.graphics.AffineTransform.getShearInstance = function(shx, shy) {
return new goog.graphics.AffineTransform().setToShear(shx, shy);
};
/**
* Creates a transform representing a rotation transformation.
*
* @param {number} theta The angle of rotation measured in radians.
* @param {number} x The x coordinate of the anchor point.
* @param {number} y The y coordinate of the anchor point.
* @return {!goog.graphics.AffineTransform} A transform representing a rotation
* transformation.
*/
goog.graphics.AffineTransform.getRotateInstance = function(theta, x, y) {
return new goog.graphics.AffineTransform().setToRotation(theta, x, y);
};
/**
* Sets this transform to a scaling transformation.
*
* @param {number} sx The x-axis scaling factor.
* @param {number} sy The y-axis scaling factor.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.setToScale = function(sx, sy) {
return this.setTransform(sx, 0, 0, sy, 0, 0);
};
/**
* Sets this transform to a translation transformation.
*
* @param {number} dx The distance to translate in the x direction.
* @param {number} dy The distance to translate in the y direction.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.setToTranslation = function(dx, dy) {
return this.setTransform(1, 0, 0, 1, dx, dy);
};
/**
* Sets this transform to a shearing transformation.
*
* @param {number} shx The x-axis shear factor.
* @param {number} shy The y-axis shear factor.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.setToShear = function(shx, shy) {
return this.setTransform(1, shy, shx, 1, 0, 0);
};
/**
* Sets this transform to a rotation transformation.
*
* @param {number} theta The angle of rotation measured in radians.
* @param {number} x The x coordinate of the anchor point.
* @param {number} y The y coordinate of the anchor point.
* @return {!goog.graphics.AffineTransform} This affine transform.
*/
goog.graphics.AffineTransform.prototype.setToRotation = function(theta, x, y) {
var cos = Math.cos(theta);
var sin = Math.sin(theta);
return this.setTransform(cos, sin, -sin, cos,
x - x * cos + y * sin, y - x * sin - y * cos);
};
/**
* Compares two affine transforms for equality.
*
* @param {goog.graphics.AffineTransform} tx The other affine transform.
* @return {boolean} whether the two transforms are equal.
*/
goog.graphics.AffineTransform.prototype.equals = function(tx) {
if (this == tx) {
return true;
}
if (!tx) {
return false;
}
return this.m00_ == tx.m00_ &&
this.m01_ == tx.m01_ &&
this.m02_ == tx.m02_ &&
this.m10_ == tx.m10_ &&
this.m11_ == tx.m11_ &&
this.m12_ == tx.m12_;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Graphics utility functions for advanced coordinates.
*
* This file assists the use of advanced coordinates in goog.graphics. Coords
* can be specified as simple numbers which will correspond to units in the
* graphics element's coordinate space. Alternately, coords can be expressed
* in pixels, meaning no matter what tranformations or coordinate system changes
* are present, the number of pixel changes will remain constant. Coords can
* also be expressed as percentages of their parent's size.
*
* This file also allows for elements to have margins, expressable in any of
* the ways described above.
*
* Additional pieces of advanced coordinate functionality can (soon) be found in
* element.js and groupelement.js.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.coordinates');
goog.require('goog.string');
/**
* Cache of boolean values. For a given string (key), is it special? (value)
* @type {Object}
* @private
*/
goog.graphics.ext.coordinates.specialCoordinateCache_ = {};
/**
* Determines if the given coordinate is a percent based coordinate or an
* expression with a percent based component.
* @param {string} coord The coordinate to test.
* @return {boolean} Whether the coordinate contains the string '%'.
* @private
*/
goog.graphics.ext.coordinates.isPercent_ = function(coord) {
return goog.string.contains(coord, '%');
};
/**
* Determines if the given coordinate is a pixel based coordinate or an
* expression with a pixel based component.
* @param {string} coord The coordinate to test.
* @return {boolean} Whether the coordinate contains the string 'px'.
* @private
*/
goog.graphics.ext.coordinates.isPixels_ = function(coord) {
return goog.string.contains(coord, 'px');
};
/**
* Determines if the given coordinate is special - i.e. not just a number.
* @param {string|number|null} coord The coordinate to test.
* @return {boolean} Whether the coordinate is special.
*/
goog.graphics.ext.coordinates.isSpecial = function(coord) {
var cache = goog.graphics.ext.coordinates.specialCoordinateCache_;
if (!(coord in cache)) {
cache[coord] = goog.isString(coord) && (
goog.graphics.ext.coordinates.isPercent_(coord) ||
goog.graphics.ext.coordinates.isPixels_(coord));
}
return cache[coord];
};
/**
* Returns the value of the given expression in the given context.
*
* Should be treated as package scope.
*
* @param {string|number} coord The coordinate to convert.
* @param {number} size The size of the parent element.
* @param {number} scale The ratio of pixels to units.
* @return {number} The number of coordinate space units that corresponds to
* this coordinate.
*/
goog.graphics.ext.coordinates.computeValue = function(coord, size, scale) {
var number = parseFloat(String(coord));
if (goog.isString(coord)) {
if (goog.graphics.ext.coordinates.isPercent_(coord)) {
return number * size / 100;
} else if (goog.graphics.ext.coordinates.isPixels_(coord)) {
return number / scale;
}
}
return number;
};
/**
* Converts the given coordinate to a number value in units.
*
* Should be treated as package scope.
*
* @param {string|number} coord The coordinate to retrieve the value for.
* @param {boolean|undefined} forMaximum Whether we are computing the largest
* value this coordinate would be in a parent of no size. The container
* size in this case should be set to the size of the current element.
* @param {number} containerSize The unit value of the size of the container of
* this element. Should be set to the minimum width of this element if
* forMaximum is true.
* @param {number} scale The ratio of pixels to units.
* @param {Object=} opt_cache Optional (but highly recommend) object to store
* cached computations in. The calling class should manage clearing out
* the cache when the scale or containerSize changes.
* @return {number} The correct number of coordinate space units.
*/
goog.graphics.ext.coordinates.getValue = function(coord, forMaximum,
containerSize, scale, opt_cache) {
if (!goog.isNumber(coord)) {
var cacheString = opt_cache && ((forMaximum ? 'X' : '') + coord);
if (opt_cache && cacheString in opt_cache) {
coord = opt_cache[cacheString];
} else {
if (goog.graphics.ext.coordinates.isSpecial(
/** @type {string} */ (coord))) {
coord = goog.graphics.ext.coordinates.computeValue(coord,
containerSize, scale);
} else {
// Simple coordinates just need to be converted from a string to a
// number.
coord = parseFloat(/** @type {string} */ (coord));
}
// Cache the result.
if (opt_cache) {
opt_cache[cacheString] = coord;
}
}
}
return coord;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thick wrapper around shapes with custom paths.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Shape');
goog.require('goog.graphics.ext.Path');
goog.require('goog.graphics.ext.StrokeAndFillElement');
goog.require('goog.math.Rect');
/**
* Wrapper for a graphics shape element.
* @param {goog.graphics.ext.Group} group Parent for this element.
* @param {!goog.graphics.ext.Path} path The path to draw.
* @param {boolean=} opt_autoSize Optional flag to specify the path should
* automatically resize to fit the element. Defaults to false.
* @constructor
* @extends {goog.graphics.ext.StrokeAndFillElement}
*/
goog.graphics.ext.Shape = function(group, path, opt_autoSize) {
this.autoSize_ = !!opt_autoSize;
var graphics = group.getGraphicsImplementation();
var wrapper = graphics.drawPath(path, null, null,
group.getWrapper());
goog.graphics.ext.StrokeAndFillElement.call(this, group, wrapper);
this.setPath(path);
};
goog.inherits(goog.graphics.ext.Shape, goog.graphics.ext.StrokeAndFillElement);
/**
* Whether or not to automatically resize the shape's path when the element
* itself is resized.
* @type {boolean}
* @private
*/
goog.graphics.ext.Shape.prototype.autoSize_ = false;
/**
* The original path, specified by the caller.
* @type {goog.graphics.Path}
* @private
*/
goog.graphics.ext.Shape.prototype.path_;
/**
* The bounding box of the original path.
* @type {goog.math.Rect?}
* @private
*/
goog.graphics.ext.Shape.prototype.boundingBox_ = null;
/**
* The scaled path.
* @type {goog.graphics.Path}
* @private
*/
goog.graphics.ext.Shape.prototype.scaledPath_;
/**
* Get the path drawn by this shape.
* @return {goog.graphics.Path?} The path drawn by this shape.
*/
goog.graphics.ext.Shape.prototype.getPath = function() {
return this.path_;
};
/**
* Set the path to draw.
* @param {goog.graphics.ext.Path} path The path to draw.
*/
goog.graphics.ext.Shape.prototype.setPath = function(path) {
this.path_ = path;
if (this.autoSize_) {
this.boundingBox_ = path.getBoundingBox();
}
this.scaleAndSetPath_();
};
/**
* Scale the internal path to fit.
* @private
*/
goog.graphics.ext.Shape.prototype.scaleAndSetPath_ = function() {
this.scaledPath_ = this.boundingBox_ ? this.path_.clone().modifyBounds(
-this.boundingBox_.left, -this.boundingBox_.top,
this.getWidth() / (this.boundingBox_.width || 1),
this.getHeight() / (this.boundingBox_.height || 1)) : this.path_;
var wrapper = this.getWrapper();
if (wrapper) {
wrapper.setPath(this.scaledPath_);
}
};
/**
* Redraw the ellipse. Called when the coordinate system is changed.
* @protected
* @override
*/
goog.graphics.ext.Shape.prototype.redraw = function() {
goog.graphics.ext.Shape.superClass_.redraw.call(this);
if (this.autoSize_) {
this.scaleAndSetPath_();
}
};
/**
* @return {boolean} Whether the shape is parent dependent.
* @protected
* @override
*/
goog.graphics.ext.Shape.prototype.checkParentDependent = function() {
return this.autoSize_ ||
goog.graphics.ext.Shape.superClass_.checkParentDependent.call(this);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thicker wrapper around graphics groups.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Group');
goog.require('goog.graphics.ext.Element');
/**
* Wrapper for a graphics group.
* @param {goog.graphics.ext.Group} group Parent for this element. Can
* be null if this is a Graphics instance.
* @param {goog.graphics.GroupElement=} opt_wrapper The thin wrapper
* to wrap. If omitted, a new group will be created. Must be included
* when group is null.
* @constructor
* @extends {goog.graphics.ext.Element}
*/
goog.graphics.ext.Group = function(group, opt_wrapper) {
opt_wrapper = opt_wrapper || group.getGraphicsImplementation().createGroup(
group.getWrapper());
goog.graphics.ext.Element.call(this, group, opt_wrapper);
/**
* Array of child elements this group contains.
* @type {Array.<goog.graphics.ext.Element>}
* @private
*/
this.children_ = [];
};
goog.inherits(goog.graphics.ext.Group, goog.graphics.ext.Element);
/**
* Add an element to the group. This should be treated as package local, as
* it is called by the draw* methods.
* @param {!goog.graphics.ext.Element} element The element to add.
* @param {boolean=} opt_chain Whether this addition is part of a longer set
* of element additions.
*/
goog.graphics.ext.Group.prototype.addChild = function(element, opt_chain) {
if (!goog.array.contains(this.children_, element)) {
this.children_.push(element);
}
var transformed = this.growToFit_(element);
if (element.isParentDependent()) {
element.parentTransform();
}
if (!opt_chain && element.isPendingTransform()) {
element.reset();
}
if (transformed) {
this.reset();
}
};
/**
* Remove an element from the group.
* @param {goog.graphics.ext.Element} element The element to remove.
*/
goog.graphics.ext.Group.prototype.removeChild = function(element) {
goog.array.remove(this.children_, element);
// TODO(robbyw): shape.fireEvent('delete')
this.getGraphicsImplementation().removeElement(element.getWrapper());
};
/**
* Calls the given function on each of this component's children in order. If
* {@code opt_obj} is provided, it will be used as the 'this' object in the
* function when called. The function should take two arguments: the child
* component and its 0-based index. The return value is ignored.
* @param {Function} f The function to call for every child component; should
* take 2 arguments (the child and its index).
* @param {Object=} opt_obj Used as the 'this' object in f when called.
*/
goog.graphics.ext.Group.prototype.forEachChild = function(f, opt_obj) {
if (this.children_) {
goog.array.forEach(this.children_, f, opt_obj);
}
};
/**
* @return {goog.graphics.GroupElement} The underlying thin wrapper.
* @protected
*/
goog.graphics.ext.Group.prototype.getWrapper;
/**
* Reset the element.
* @override
*/
goog.graphics.ext.Group.prototype.reset = function() {
goog.graphics.ext.Group.superClass_.reset.call(this);
this.updateChildren();
};
/**
* Called from the parent class, this method resets any pre-computed positions
* and sizes.
* @protected
* @override
*/
goog.graphics.ext.Group.prototype.redraw = function() {
this.getWrapper().setSize(this.getWidth(), this.getHeight());
this.transformChildren();
};
/**
* Transform the children that need to be transformed.
* @protected
*/
goog.graphics.ext.Group.prototype.transformChildren = function() {
this.forEachChild(function(child) {
if (child.isParentDependent()) {
child.parentTransform();
}
});
};
/**
* As part of the reset process, update child elements.
*/
goog.graphics.ext.Group.prototype.updateChildren = function() {
this.forEachChild(function(child) {
if (child.isParentDependent() || child.isPendingTransform()) {
child.reset();
} else if (child.updateChildren) {
child.updateChildren();
}
});
};
/**
* When adding an element, grow this group's bounds to fit it.
* @param {!goog.graphics.ext.Element} element The added element.
* @return {boolean} Whether the size of this group changed.
* @private
*/
goog.graphics.ext.Group.prototype.growToFit_ = function(element) {
var transformed = false;
var x = element.getMaxX();
if (x > this.getWidth()) {
this.setMinWidth(x);
transformed = true;
}
var y = element.getMaxY();
if (y > this.getHeight()) {
this.setMinHeight(y);
transformed = true;
}
return transformed;
};
/**
* @return {number} The width of the element's coordinate space.
*/
goog.graphics.ext.Group.prototype.getCoordinateWidth = function() {
return this.getWidth();
};
/**
* @return {number} The height of the element's coordinate space.
*/
goog.graphics.ext.Group.prototype.getCoordinateHeight = function() {
return this.getHeight();
};
/**
* Remove all drawing elements from the group.
*/
goog.graphics.ext.Group.prototype.clear = function() {
while (this.children_.length) {
this.removeChild(this.children_[0]);
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Graphics surface type.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Graphics');
goog.require('goog.events.EventType');
goog.require('goog.graphics.ext.Group');
/**
* Wrapper for a graphics surface.
* @param {string|number} width The width in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {string|number} height The height in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {?number=} opt_coordWidth The coordinate width - if
* omitted or null, defaults to same as width.
* @param {?number=} opt_coordHeight The coordinate height. - if
* omitted or null, defaults to same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @param {boolean=} opt_isSimple Flag used to indicate the graphics object will
* be drawn to in a single pass, and the fastest implementation for this
* scenario should be favored. NOTE: Setting to true may result in
* degradation of text support.
* @constructor
* @extends {goog.graphics.ext.Group}
*/
goog.graphics.ext.Graphics = function(width, height, opt_coordWidth,
opt_coordHeight, opt_domHelper, opt_isSimple) {
var surface = opt_isSimple ?
goog.graphics.createSimpleGraphics(width, height,
opt_coordWidth, opt_coordHeight, opt_domHelper) :
goog.graphics.createGraphics(width, height,
opt_coordWidth, opt_coordHeight, opt_domHelper);
this.implementation_ = surface;
goog.graphics.ext.Group.call(this, null, surface.getCanvasElement());
goog.events.listen(surface, goog.events.EventType.RESIZE,
this.updateChildren, false, this);
};
goog.inherits(goog.graphics.ext.Graphics, goog.graphics.ext.Group);
/**
* The root level graphics implementation.
* @type {goog.graphics.AbstractGraphics}
* @private
*/
goog.graphics.ext.Graphics.prototype.implementation_;
/**
* @return {goog.graphics.AbstractGraphics} The graphics implementation layer.
*/
goog.graphics.ext.Graphics.prototype.getImplementation = function() {
return this.implementation_;
};
/**
* Changes the coordinate size.
* @param {number} coordWidth The coordinate width.
* @param {number} coordHeight The coordinate height.
*/
goog.graphics.ext.Graphics.prototype.setCoordSize = function(coordWidth,
coordHeight) {
this.implementation_.setCoordSize(coordWidth, coordHeight);
goog.graphics.ext.Graphics.superClass_.setSize.call(this, coordWidth,
coordHeight);
};
/**
* @return {goog.math.Size} The coordinate size.
*/
goog.graphics.ext.Graphics.prototype.getCoordSize = function() {
return this.implementation_.getCoordSize();
};
/**
* Changes the coordinate system position.
* @param {number} left The coordinate system left bound.
* @param {number} top The coordinate system top bound.
*/
goog.graphics.ext.Graphics.prototype.setCoordOrigin = function(left, top) {
this.implementation_.setCoordOrigin(left, top);
};
/**
* @return {goog.math.Coordinate} The coordinate system position.
*/
goog.graphics.ext.Graphics.prototype.getCoordOrigin = function() {
return this.implementation_.getCoordOrigin();
};
/**
* Change the size of the canvas.
* @param {number} pixelWidth The width in pixels.
* @param {number} pixelHeight The height in pixels.
*/
goog.graphics.ext.Graphics.prototype.setPixelSize = function(pixelWidth,
pixelHeight) {
this.implementation_.setSize(pixelWidth, pixelHeight);
var coordSize = this.getCoordSize();
goog.graphics.ext.Graphics.superClass_.setSize.call(this, coordSize.width,
coordSize.height);
};
/**
* @return {goog.math.Size?} Returns the number of pixels spanned by the
* surface, or null if the size could not be computed due to the size being
* specified in percentage points and the component not being in the
* document.
*/
goog.graphics.ext.Graphics.prototype.getPixelSize = function() {
return this.implementation_.getPixelSize();
};
/**
* @return {number} The coordinate width of the canvas.
* @override
*/
goog.graphics.ext.Graphics.prototype.getWidth = function() {
return this.implementation_.getCoordSize().width;
};
/**
* @return {number} The coordinate width of the canvas.
* @override
*/
goog.graphics.ext.Graphics.prototype.getHeight = function() {
return this.implementation_.getCoordSize().height;
};
/**
* @return {number} Returns the number of pixels per unit in the x direction.
* @override
*/
goog.graphics.ext.Graphics.prototype.getPixelScaleX = function() {
return this.implementation_.getPixelScaleX();
};
/**
* @return {number} Returns the number of pixels per unit in the y direction.
* @override
*/
goog.graphics.ext.Graphics.prototype.getPixelScaleY = function() {
return this.implementation_.getPixelScaleY();
};
/**
* @return {Element} The root element of the graphics surface.
*/
goog.graphics.ext.Graphics.prototype.getElement = function() {
return this.implementation_.getElement();
};
/**
* Renders the underlying graphics.
*
* @param {Element} parentElement Parent element to render the component into.
*/
goog.graphics.ext.Graphics.prototype.render = function(parentElement) {
this.implementation_.render(parentElement);
};
/**
* Never transform a surface.
* @override
*/
goog.graphics.ext.Graphics.prototype.transform = goog.nullFunction;
/**
* Called from the parent class, this method resets any pre-computed positions
* and sizes.
* @protected
* @override
*/
goog.graphics.ext.Graphics.prototype.redraw = function() {
this.transformChildren();
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thick wrapper around rectangles.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Rectangle');
goog.require('goog.graphics.ext.StrokeAndFillElement');
/**
* Wrapper for a graphics rectangle element.
* @param {goog.graphics.ext.Group} group Parent for this element.
* @constructor
* @extends {goog.graphics.ext.StrokeAndFillElement}
*/
goog.graphics.ext.Rectangle = function(group) {
// Initialize with some stock values.
var wrapper = group.getGraphicsImplementation().drawRect(0, 0, 1, 1, null,
null, group.getWrapper());
goog.graphics.ext.StrokeAndFillElement.call(this, group, wrapper);
};
goog.inherits(goog.graphics.ext.Rectangle,
goog.graphics.ext.StrokeAndFillElement);
/**
* Redraw the rectangle. Called when the coordinate system is changed.
* @protected
* @override
*/
goog.graphics.ext.Rectangle.prototype.redraw = function() {
goog.graphics.ext.Rectangle.superClass_.redraw.call(this);
// Our position is already handled by transform_.
this.getWrapper().setSize(this.getWidth(), this.getHeight());
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Extended graphics namespace.
*/
goog.provide('goog.graphics.ext');
goog.require('goog.graphics.ext.Ellipse');
goog.require('goog.graphics.ext.Graphics');
goog.require('goog.graphics.ext.Group');
goog.require('goog.graphics.ext.Image');
goog.require('goog.graphics.ext.Rectangle');
goog.require('goog.graphics.ext.Shape');
goog.require('goog.graphics.ext.coordinates');
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thick wrapper around paths.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Path');
goog.require('goog.graphics.AffineTransform');
goog.require('goog.graphics.Path');
goog.require('goog.math');
goog.require('goog.math.Rect');
/**
* Creates a path object
* @constructor
* @extends {goog.graphics.Path}
*/
goog.graphics.ext.Path = function() {
goog.graphics.Path.call(this);
};
goog.inherits(goog.graphics.ext.Path, goog.graphics.Path);
/**
* Optional cached or user specified bounding box. A user may wish to
* precompute a bounding box to save time and include more accurate
* computations.
* @type {goog.math.Rect?}
* @private
*/
goog.graphics.ext.Path.prototype.bounds_ = null;
/**
* Clones the path.
* @return {!goog.graphics.ext.Path} A clone of this path.
* @override
*/
goog.graphics.ext.Path.prototype.clone = function() {
var output = /** @type {goog.graphics.ext.Path} */
(goog.graphics.ext.Path.superClass_.clone.call(this));
output.bounds_ = this.bounds_ && this.bounds_.clone();
return output;
};
/**
* Transforms the path. Only simple paths are transformable. Attempting
* to transform a non-simple path will throw an error.
* @param {!goog.graphics.AffineTransform} tx The transformation to perform.
* @return {!goog.graphics.ext.Path} The path itself.
* @override
*/
goog.graphics.ext.Path.prototype.transform = function(tx) {
goog.graphics.ext.Path.superClass_.transform.call(this, tx);
// Make sure the precomputed bounds are cleared when the path is transformed.
this.bounds_ = null;
return this;
};
/**
* Modify the bounding box of the path. This may cause the path to be
* simplified (i.e. arcs converted to curves) as a side-effect.
* @param {number} deltaX How far to translate the x coordinates.
* @param {number} deltaY How far to translate the y coordinates.
* @param {number} xFactor After translation, all x coordinates are multiplied
* by this number.
* @param {number} yFactor After translation, all y coordinates are multiplied
* by this number.
* @return {goog.graphics.ext.Path} The path itself.
*/
goog.graphics.ext.Path.prototype.modifyBounds = function(deltaX, deltaY,
xFactor, yFactor) {
if (!this.isSimple()) {
var simple = goog.graphics.Path.createSimplifiedPath(this);
this.clear();
this.appendPath(simple);
}
return this.transform(goog.graphics.AffineTransform.getScaleInstance(
xFactor, yFactor).translate(deltaX, deltaY));
};
/**
* Set the precomputed bounds.
* @param {goog.math.Rect?} bounds The bounds to use, or set to null to clear
* and recompute on the next call to getBoundingBox.
*/
goog.graphics.ext.Path.prototype.useBoundingBox = function(bounds) {
this.bounds_ = bounds && bounds.clone();
};
/**
* @return {goog.math.Rect?} The bounding box of the path, or null if the
* path is empty.
*/
goog.graphics.ext.Path.prototype.getBoundingBox = function() {
if (!this.bounds_ && !this.isEmpty()) {
var minY;
var minX = minY = Number.POSITIVE_INFINITY;
var maxY;
var maxX = maxY = Number.NEGATIVE_INFINITY;
var simplePath = this.isSimple() ? this :
goog.graphics.Path.createSimplifiedPath(this);
simplePath.forEachSegment(function(type, points) {
for (var i = 0, len = points.length; i < len; i += 2) {
minX = Math.min(minX, points[i]);
maxX = Math.max(maxX, points[i]);
minY = Math.min(minY, points[i + 1]);
maxY = Math.max(maxY, points[i + 1]);
}
});
this.bounds_ = new goog.math.Rect(minX, minY, maxX - minX, maxY - minY);
}
return this.bounds_;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thick wrapper around elements with stroke and fill.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.StrokeAndFillElement');
goog.require('goog.graphics.ext.Element');
/**
* Interface for a graphics element that has a stroke and fill.
* This is the base interface for ellipse, rectangle and other
* shape interfaces.
* You should not construct objects from this constructor. Use a subclass.
* @param {goog.graphics.ext.Group} group Parent for this element.
* @param {goog.graphics.StrokeAndFillElement} wrapper The thin wrapper to wrap.
* @constructor
* @extends {goog.graphics.ext.Element}
*/
goog.graphics.ext.StrokeAndFillElement = function(group, wrapper) {
goog.graphics.ext.Element.call(this, group, wrapper);
};
goog.inherits(goog.graphics.ext.StrokeAndFillElement,
goog.graphics.ext.Element);
/**
* Sets the fill for this element.
* @param {goog.graphics.Fill?} fill The fill object.
*/
goog.graphics.ext.StrokeAndFillElement.prototype.setFill = function(fill) {
this.getWrapper().setFill(fill);
};
/**
* Sets the stroke for this element.
* @param {goog.graphics.Stroke?} stroke The stroke object.
*/
goog.graphics.ext.StrokeAndFillElement.prototype.setStroke = function(stroke) {
this.getWrapper().setStroke(stroke);
};
/**
* Redraw the rectangle. Called when the coordinate system is changed.
* @protected
* @override
*/
goog.graphics.ext.StrokeAndFillElement.prototype.redraw = function() {
this.getWrapper().reapplyStroke();
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thick wrapper around images.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Image');
goog.require('goog.graphics.ext.Element');
/**
* Wrapper for a graphics image element.
* @param {goog.graphics.ext.Group} group Parent for this element.
* @param {string} src The path to the image to display.
* @constructor
* @extends {goog.graphics.ext.Element}
*/
goog.graphics.ext.Image = function(group, src) {
// Initialize with some stock values.
var wrapper = group.getGraphicsImplementation().drawImage(0, 0, 1, 1, src,
group.getWrapper());
goog.graphics.ext.Element.call(this, group, wrapper);
};
goog.inherits(goog.graphics.ext.Image, goog.graphics.ext.Element);
/**
* Redraw the image. Called when the coordinate system is changed.
* @protected
* @override
*/
goog.graphics.ext.Image.prototype.redraw = function() {
goog.graphics.ext.Image.superClass_.redraw.call(this);
// Our position is already handled bu transform_.
this.getWrapper().setSize(this.getWidth(), this.getHeight());
};
/**
* Update the source of the image.
* @param {string} src Source of the image.
*/
goog.graphics.ext.Image.prototype.setSource = function(src) {
this.getWrapper().setSource(src);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thick wrapper around ellipses.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Ellipse');
goog.require('goog.graphics.ext.StrokeAndFillElement');
/**
* Wrapper for a graphics ellipse element.
* @param {goog.graphics.ext.Group} group Parent for this element.
* @constructor
* @extends {goog.graphics.ext.StrokeAndFillElement}
*/
goog.graphics.ext.Ellipse = function(group) {
// Initialize with some stock values.
var wrapper = group.getGraphicsImplementation().drawEllipse(1, 1, 2, 2, null,
null, group.getWrapper());
goog.graphics.ext.StrokeAndFillElement.call(this, group, wrapper);
};
goog.inherits(goog.graphics.ext.Ellipse,
goog.graphics.ext.StrokeAndFillElement);
/**
* Redraw the ellipse. Called when the coordinate system is changed.
* @protected
* @override
*/
goog.graphics.ext.Ellipse.prototype.redraw = function() {
goog.graphics.ext.Ellipse.superClass_.redraw.call(this);
// Our position is already transformed in transform_, but because this is an
// ellipse we need to position the center.
var xRadius = this.getWidth() / 2;
var yRadius = this.getHeight() / 2;
var wrapper = this.getWrapper();
wrapper.setCenter(xRadius, yRadius);
wrapper.setRadius(xRadius, yRadius);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thicker wrapper around the DOM element returned from
* the different draw methods of the graphics implementation, and
* all interfaces that the various element types support.
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.graphics.ext.Element');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.functions');
goog.require('goog.graphics');
goog.require('goog.graphics.ext.coordinates');
/**
* Base class for a wrapper around the goog.graphics wrapper that enables
* more advanced functionality.
* @param {goog.graphics.ext.Group?} group Parent for this element.
* @param {goog.graphics.Element} wrapper The thin wrapper to wrap.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.graphics.ext.Element = function(group, wrapper) {
goog.events.EventTarget.call(this);
this.wrapper_ = wrapper;
this.graphics_ = group ? group.getGraphics() : this;
this.xPosition_ = new goog.graphics.ext.Element.Position_(this, true);
this.yPosition_ = new goog.graphics.ext.Element.Position_(this, false);
// Handle parent / child relationships.
if (group) {
this.parent_ = group;
this.parent_.addChild(this);
}
};
goog.inherits(goog.graphics.ext.Element, goog.events.EventTarget);
/**
* The graphics object that contains this element.
* @type {goog.graphics.ext.Graphics|goog.graphics.ext.Element}
* @private
*/
goog.graphics.ext.Element.prototype.graphics_;
/**
* The goog.graphics wrapper this class wraps.
* @type {goog.graphics.Element}
* @private
*/
goog.graphics.ext.Element.prototype.wrapper_;
/**
* The group or surface containing this element.
* @type {goog.graphics.ext.Group|undefined}
* @private
*/
goog.graphics.ext.Element.prototype.parent_;
/**
* Whether or not computation of this element's position or size depends on its
* parent's size.
* @type {boolean}
* @private
*/
goog.graphics.ext.Element.prototype.parentDependent_ = false;
/**
* Whether the element has pending transformations.
* @type {boolean}
* @private
*/
goog.graphics.ext.Element.prototype.needsTransform_ = false;
/**
* The current angle of rotation, expressed in degrees.
* @type {number}
* @private
*/
goog.graphics.ext.Element.prototype.rotation_ = 0;
/**
* Object representing the x position and size of the element.
* @type {goog.graphics.ext.Element.Position_}
* @private
*/
goog.graphics.ext.Element.prototype.xPosition_;
/**
* Object representing the y position and size of the element.
* @type {goog.graphics.ext.Element.Position_}
* @private
*/
goog.graphics.ext.Element.prototype.yPosition_;
/**
* @return {goog.graphics.Element} The underlying thin wrapper.
* @protected
*/
goog.graphics.ext.Element.prototype.getWrapper = function() {
return this.wrapper_;
};
/**
* @return {goog.graphics.ext.Element|goog.graphics.ext.Graphics} The graphics
* surface the element is a part of.
*/
goog.graphics.ext.Element.prototype.getGraphics = function() {
return this.graphics_;
};
/**
* Returns the graphics implementation.
* @return {goog.graphics.AbstractGraphics} The underlying graphics
* implementation drawing this element's wrapper.
* @protected
*/
goog.graphics.ext.Element.prototype.getGraphicsImplementation = function() {
return this.graphics_.getImplementation();
};
/**
* @return {goog.graphics.ext.Group|undefined} The parent of this element.
*/
goog.graphics.ext.Element.prototype.getParent = function() {
return this.parent_;
};
// GENERAL POSITIONING
/**
* Internal convenience method for setting position - either as a left/top,
* center/middle, or right/bottom value. Only one should be specified.
* @param {goog.graphics.ext.Element.Position_} position The position object to
* set the value on.
* @param {number|string} value The value of the coordinate.
* @param {goog.graphics.ext.Element.PositionType_} type The type of the
* coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
* @private
*/
goog.graphics.ext.Element.prototype.setPosition_ = function(position, value,
type, opt_chain) {
position.setPosition(value, type);
this.computeIsParentDependent_(position);
this.needsTransform_ = true;
if (!opt_chain) {
this.transform();
}
};
/**
* Sets the width/height of the element.
* @param {goog.graphics.ext.Element.Position_} position The position object to
* set the value on.
* @param {string|number} size The new width/height value.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
* @private
*/
goog.graphics.ext.Element.prototype.setSize_ = function(position, size,
opt_chain) {
if (position.setSize(size)) {
this.needsTransform_ = true;
this.computeIsParentDependent_(position);
if (!opt_chain) {
this.reset();
}
} else if (!opt_chain && this.isPendingTransform()) {
this.reset();
}
};
/**
* Sets the minimum width/height of the element.
* @param {goog.graphics.ext.Element.Position_} position The position object to
* set the value on.
* @param {string|number} minSize The minimum width/height of the element.
* @private
*/
goog.graphics.ext.Element.prototype.setMinSize_ = function(position, minSize) {
position.setMinSize(minSize);
this.needsTransform_ = true;
this.computeIsParentDependent_(position);
};
// HORIZONTAL POSITIONING
/**
* @return {number} The distance from the left edge of this element to the left
* edge of its parent, specified in units of the parent's coordinate system.
*/
goog.graphics.ext.Element.prototype.getLeft = function() {
return this.xPosition_.getStart();
};
/**
* Sets the left coordinate of the element. Overwrites any previous value of
* left, center, or right for this element.
* @param {string|number} left The left coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setLeft = function(left, opt_chain) {
this.setPosition_(this.xPosition_,
left,
goog.graphics.ext.Element.PositionType_.START,
opt_chain);
};
/**
* @return {number} The right coordinate of the element, in units of the
* parent's coordinate system.
*/
goog.graphics.ext.Element.prototype.getRight = function() {
return this.xPosition_.getEnd();
};
/**
* Sets the right coordinate of the element. Overwrites any previous value of
* left, center, or right for this element.
* @param {string|number} right The right coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setRight = function(right, opt_chain) {
this.setPosition_(this.xPosition_,
right,
goog.graphics.ext.Element.PositionType_.END,
opt_chain);
};
/**
* @return {number} The center coordinate of the element, in units of the
* parent's coordinate system.
*/
goog.graphics.ext.Element.prototype.getCenter = function() {
return this.xPosition_.getMiddle();
};
/**
* Sets the center coordinate of the element. Overwrites any previous value of
* left, center, or right for this element.
* @param {string|number} center The center coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setCenter = function(center, opt_chain) {
this.setPosition_(this.xPosition_,
center,
goog.graphics.ext.Element.PositionType_.MIDDLE,
opt_chain);
};
// VERTICAL POSITIONING
/**
* @return {number} The distance from the top edge of this element to the top
* edge of its parent, specified in units of the parent's coordinate system.
*/
goog.graphics.ext.Element.prototype.getTop = function() {
return this.yPosition_.getStart();
};
/**
* Sets the top coordinate of the element. Overwrites any previous value of
* top, middle, or bottom for this element.
* @param {string|number} top The top coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setTop = function(top, opt_chain) {
this.setPosition_(this.yPosition_,
top,
goog.graphics.ext.Element.PositionType_.START,
opt_chain);
};
/**
* @return {number} The bottom coordinate of the element, in units of the
* parent's coordinate system.
*/
goog.graphics.ext.Element.prototype.getBottom = function() {
return this.yPosition_.getEnd();
};
/**
* Sets the bottom coordinate of the element. Overwrites any previous value of
* top, middle, or bottom for this element.
* @param {string|number} bottom The bottom coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setBottom = function(bottom, opt_chain) {
this.setPosition_(this.yPosition_,
bottom,
goog.graphics.ext.Element.PositionType_.END,
opt_chain);
};
/**
* @return {number} The middle coordinate of the element, in units of the
* parent's coordinate system.
*/
goog.graphics.ext.Element.prototype.getMiddle = function() {
return this.yPosition_.getMiddle();
};
/**
* Sets the middle coordinate of the element. Overwrites any previous value of
* top, middle, or bottom for this element
* @param {string|number} middle The middle coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setMiddle = function(middle, opt_chain) {
this.setPosition_(this.yPosition_,
middle,
goog.graphics.ext.Element.PositionType_.MIDDLE,
opt_chain);
};
// DIMENSIONS
/**
* @return {number} The width of the element, in units of the parent's
* coordinate system.
*/
goog.graphics.ext.Element.prototype.getWidth = function() {
return this.xPosition_.getSize();
};
/**
* Sets the width of the element.
* @param {string|number} width The new width value.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setWidth = function(width, opt_chain) {
this.setSize_(this.xPosition_, width, opt_chain);
};
/**
* @return {number} The minimum width of the element, in units of the parent's
* coordinate system.
*/
goog.graphics.ext.Element.prototype.getMinWidth = function() {
return this.xPosition_.getMinSize();
};
/**
* Sets the minimum width of the element.
* @param {string|number} minWidth The minimum width of the element.
*/
goog.graphics.ext.Element.prototype.setMinWidth = function(minWidth) {
this.setMinSize_(this.xPosition_, minWidth);
};
/**
* @return {number} The height of the element, in units of the parent's
* coordinate system.
*/
goog.graphics.ext.Element.prototype.getHeight = function() {
return this.yPosition_.getSize();
};
/**
* Sets the height of the element.
* @param {string|number} height The new height value.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setHeight = function(height, opt_chain) {
this.setSize_(this.yPosition_, height, opt_chain);
};
/**
* @return {number} The minimum height of the element, in units of the parent's
* coordinate system.
*/
goog.graphics.ext.Element.prototype.getMinHeight = function() {
return this.yPosition_.getMinSize();
};
/**
* Sets the minimum height of the element.
* @param {string|number} minHeight The minimum height of the element.
*/
goog.graphics.ext.Element.prototype.setMinHeight = function(minHeight) {
this.setMinSize_(this.yPosition_, minHeight);
};
// BOUNDS SHORTCUTS
/**
* Shortcut for setting the left and top position.
* @param {string|number} left The left coordinate.
* @param {string|number} top The top coordinate.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setPosition = function(left, top,
opt_chain) {
this.setLeft(left, true);
this.setTop(top, opt_chain);
};
/**
* Shortcut for setting the width and height.
* @param {string|number} width The new width value.
* @param {string|number} height The new height value.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setSize = function(width, height,
opt_chain) {
this.setWidth(width, true);
this.setHeight(height, opt_chain);
};
/**
* Shortcut for setting the left, top, width, and height.
* @param {string|number} left The left coordinate.
* @param {string|number} top The top coordinate.
* @param {string|number} width The new width value.
* @param {string|number} height The new height value.
* @param {boolean=} opt_chain Optional flag to specify this function is part
* of a chain of calls and therefore transformations should be set as
* pending but not yet performed.
*/
goog.graphics.ext.Element.prototype.setBounds = function(left, top, width,
height, opt_chain) {
this.setLeft(left, true);
this.setTop(top, true);
this.setWidth(width, true);
this.setHeight(height, opt_chain);
};
// MAXIMUM BOUNDS
/**
* @return {number} An estimate of the maximum x extent this element would have
* in a parent of no width.
*/
goog.graphics.ext.Element.prototype.getMaxX = function() {
return this.xPosition_.getMaxPosition();
};
/**
* @return {number} An estimate of the maximum y extent this element would have
* in a parent of no height.
*/
goog.graphics.ext.Element.prototype.getMaxY = function() {
return this.yPosition_.getMaxPosition();
};
// RESET
/**
* Reset the element. This is called when the element changes size, or when
* the coordinate system changes in a way that would affect pixel based
* rendering
*/
goog.graphics.ext.Element.prototype.reset = function() {
this.xPosition_.resetCache();
this.yPosition_.resetCache();
this.redraw();
this.needsTransform_ = true;
this.transform();
};
/**
* Overridable function for subclass specific reset.
* @protected
*/
goog.graphics.ext.Element.prototype.redraw = goog.nullFunction;
// PARENT DEPENDENCY
/**
* Computes whether the element is still parent dependent.
* @param {goog.graphics.ext.Element.Position_} position The recently changed
* position object.
* @private
*/
goog.graphics.ext.Element.prototype.computeIsParentDependent_ = function(
position) {
this.parentDependent_ = position.isParentDependent() ||
this.xPosition_.isParentDependent() ||
this.yPosition_.isParentDependent() ||
this.checkParentDependent();
};
/**
* Returns whether this element's bounds depend on its parents.
*
* This function should be treated as if it has package scope.
* @return {boolean} Whether this element's bounds depend on its parents.
*/
goog.graphics.ext.Element.prototype.isParentDependent = function() {
return this.parentDependent_;
};
/**
* Overridable function for subclass specific parent dependency.
* @return {boolean} Whether this shape's bounds depends on its parent's.
* @protected
*/
goog.graphics.ext.Element.prototype.checkParentDependent =
goog.functions.FALSE;
// ROTATION
/**
* Set the rotation of this element.
* @param {number} angle The angle of rotation, in degrees.
*/
goog.graphics.ext.Element.prototype.setRotation = function(angle) {
if (this.rotation_ != angle) {
this.rotation_ = angle;
this.needsTransform_ = true;
this.transform();
}
};
/**
* @return {number} The angle of rotation of this element, in degrees.
*/
goog.graphics.ext.Element.prototype.getRotation = function() {
return this.rotation_;
};
// TRANSFORMS
/**
* Called by the parent when the parent has transformed.
*
* Should be treated as package scope.
*/
goog.graphics.ext.Element.prototype.parentTransform = function() {
this.needsTransform_ = this.needsTransform_ || this.parentDependent_;
};
/**
* @return {boolean} Whether this element has pending transforms.
*/
goog.graphics.ext.Element.prototype.isPendingTransform = function() {
return this.needsTransform_;
};
/**
* Performs a pending transform.
* @protected
*/
goog.graphics.ext.Element.prototype.transform = function() {
if (this.isPendingTransform()) {
this.needsTransform_ = false;
this.wrapper_.setTransformation(
this.getLeft(),
this.getTop(),
this.rotation_,
(this.getWidth() || 1) / 2,
(this.getHeight() || 1) / 2);
// TODO(robbyw): this._fireEvent('transform', [ this ]);
}
};
// PIXEL SCALE
/**
* @return {number} Returns the number of pixels per unit in the x direction.
*/
goog.graphics.ext.Element.prototype.getPixelScaleX = function() {
return this.getGraphics().getPixelScaleX();
};
/**
* @return {number} Returns the number of pixels per unit in the y direction.
*/
goog.graphics.ext.Element.prototype.getPixelScaleY = function() {
return this.getGraphics().getPixelScaleY();
};
// EVENT HANDLING
/** @override */
goog.graphics.ext.Element.prototype.disposeInternal = function() {
goog.graphics.ext.Element.superClass_.disposeInternal.call();
this.wrapper_.dispose();
};
// INTERNAL POSITION OBJECT
/**
* Position specification types. Start corresponds to left/top, middle to
* center/middle, and end to right/bottom.
* @enum {number}
* @private
*/
goog.graphics.ext.Element.PositionType_ = {
START: 0,
MIDDLE: 1,
END: 2
};
/**
* Manages a position and size, either horizontal or vertical.
* @param {goog.graphics.ext.Element} element The element the position applies
* to.
* @param {boolean} horizontal Whether the position is horizontal or vertical.
* @constructor
* @private
*/
goog.graphics.ext.Element.Position_ = function(element, horizontal) {
this.element_ = element;
this.horizontal_ = horizontal;
};
/**
* @return {Object} The coordinate value computation cache.
* @private
*/
goog.graphics.ext.Element.Position_.prototype.getCoordinateCache_ = function() {
return this.coordinateCache_ || (this.coordinateCache_ = {});
};
/**
* @return {number} The size of the parent's coordinate space.
* @private
*/
goog.graphics.ext.Element.Position_.prototype.getParentSize_ = function() {
var parent = this.element_.getParent();
return this.horizontal_ ?
parent.getCoordinateWidth() :
parent.getCoordinateHeight();
};
/**
* @return {number} The minimum width/height of the element.
*/
goog.graphics.ext.Element.Position_.prototype.getMinSize = function() {
return this.getValue_(this.minSize_);
};
/**
* Sets the minimum width/height of the element.
* @param {string|number} minSize The minimum width/height of the element.
*/
goog.graphics.ext.Element.Position_.prototype.setMinSize = function(minSize) {
this.minSize_ = minSize;
this.resetCache();
};
/**
* @return {number} The width/height of the element.
*/
goog.graphics.ext.Element.Position_.prototype.getSize = function() {
return Math.max(this.getValue_(this.size_), this.getMinSize());
};
/**
* Sets the width/height of the element.
* @param {string|number} size The width/height of the element.
* @return {boolean} Whether the value was changed.
*/
goog.graphics.ext.Element.Position_.prototype.setSize = function(size) {
if (size != this.size_) {
this.size_ = size;
this.resetCache();
return true;
}
return false;
};
/**
* Converts the given x coordinate to a number value in units.
* @param {string|number} v The coordinate to retrieve the value for.
* @param {boolean=} opt_forMaximum Whether we are computing the largest value
* this coordinate would be in a parent of no size.
* @return {number} The correct number of coordinate space units.
* @private
*/
goog.graphics.ext.Element.Position_.prototype.getValue_ = function(v,
opt_forMaximum) {
if (!goog.graphics.ext.coordinates.isSpecial(v)) {
return parseFloat(String(v));
}
var cache = this.getCoordinateCache_();
var scale = this.horizontal_ ?
this.element_.getPixelScaleX() :
this.element_.getPixelScaleY();
var containerSize;
if (opt_forMaximum) {
containerSize = goog.graphics.ext.coordinates.computeValue(
this.size_ || 0, 0, scale);
} else {
var parent = this.element_.getParent();
containerSize = this.horizontal_ ? parent.getWidth() : parent.getHeight();
}
return goog.graphics.ext.coordinates.getValue(v, opt_forMaximum,
containerSize, scale, cache);
};
/**
* @return {number} The distance from the left/top edge of this element to the
* left/top edge of its parent, specified in units of the parent's
* coordinate system.
*/
goog.graphics.ext.Element.Position_.prototype.getStart = function() {
if (this.cachedValue_ == null) {
var value = this.getValue_(this.distance_);
if (this.distanceType_ == goog.graphics.ext.Element.PositionType_.START) {
this.cachedValue_ = value;
} else if (this.distanceType_ ==
goog.graphics.ext.Element.PositionType_.MIDDLE) {
this.cachedValue_ = value + (this.getParentSize_() - this.getSize()) / 2;
} else {
this.cachedValue_ = this.getParentSize_() - value - this.getSize();
}
}
return this.cachedValue_;
};
/**
* @return {number} The middle coordinate of the element, in units of the
* parent's coordinate system.
*/
goog.graphics.ext.Element.Position_.prototype.getMiddle = function() {
return this.distanceType_ == goog.graphics.ext.Element.PositionType_.MIDDLE ?
this.getValue_(this.distance_) :
(this.getParentSize_() - this.getSize()) / 2 - this.getStart();
};
/**
* @return {number} The end coordinate of the element, in units of the
* parent's coordinate system.
*/
goog.graphics.ext.Element.Position_.prototype.getEnd = function() {
return this.distanceType_ == goog.graphics.ext.Element.PositionType_.END ?
this.getValue_(this.distance_) :
this.getParentSize_() - this.getStart() - this.getSize();
};
/**
* Sets the position, either as a left/top, center/middle, or right/bottom
* value.
* @param {number|string} value The value of the coordinate.
* @param {goog.graphics.ext.Element.PositionType_} type The type of the
* coordinate.
*/
goog.graphics.ext.Element.Position_.prototype.setPosition = function(value,
type) {
this.distance_ = value;
this.distanceType_ = type;
// Clear cached value.
this.cachedValue_ = null;
};
/**
* @return {number} An estimate of the maximum x/y extent this element would
* have in a parent of no width/height.
*/
goog.graphics.ext.Element.Position_.prototype.getMaxPosition = function() {
// TODO(robbyw): Handle transformed or rotated coordinates
// TODO(robbyw): Handle pixel based sizes?
return this.getValue_(this.distance_ || 0) + (
goog.graphics.ext.coordinates.isSpecial(this.size_) ? 0 : this.getSize());
};
/**
* Resets the caches of position values and coordinate values.
*/
goog.graphics.ext.Element.Position_.prototype.resetCache = function() {
this.coordinateCache_ = null;
this.cachedValue_ = null;
};
/**
* @return {boolean} Whether the size or position of this element depends on
* the size of the parent element.
*/
goog.graphics.ext.Element.Position_.prototype.isParentDependent = function() {
return this.distanceType_ != goog.graphics.ext.Element.PositionType_.START ||
goog.graphics.ext.coordinates.isSpecial(this.size_) ||
goog.graphics.ext.coordinates.isSpecial(this.minSize_) ||
goog.graphics.ext.coordinates.isSpecial(this.distance_);
};
/**
* The lazy loaded distance from the parent's top/left edge to this element's
* top/left edge expressed in the parent's coordinate system. We cache this
* because it is most freqeuently requested by the element and it is easy to
* compute middle and end values from it.
* @type {?number}
* @private
*/
goog.graphics.ext.Element.Position_.prototype.cachedValue_ = null;
/**
* A cache of computed x coordinates.
* @type {Object}
* @private
*/
goog.graphics.ext.Element.Position_.prototype.coordinateCache_ = null;
/**
* The minimum width/height of this element, as specified by the caller.
* @type {string|number}
* @private
*/
goog.graphics.ext.Element.Position_.prototype.minSize_ = 0;
/**
* The width/height of this object, as specified by the caller.
* @type {string|number}
* @private
*/
goog.graphics.ext.Element.Position_.prototype.size_ = 0;
/**
* The coordinate of this object, as specified by the caller. The type of
* coordinate is specified by distanceType_.
* @type {string|number}
* @private
*/
goog.graphics.ext.Element.Position_.prototype.distance_ = 0;
/**
* The coordinate type specified by distance_.
* @type {goog.graphics.ext.Element.PositionType_}
* @private
*/
goog.graphics.ext.Element.Position_.prototype.distanceType_ =
goog.graphics.ext.Element.PositionType_.START;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Thin wrappers around the DOM element returned from
* the different draw methods of the graphics. This is the SVG implementation.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.SvgEllipseElement');
goog.provide('goog.graphics.SvgGroupElement');
goog.provide('goog.graphics.SvgImageElement');
goog.provide('goog.graphics.SvgPathElement');
goog.provide('goog.graphics.SvgRectElement');
goog.provide('goog.graphics.SvgTextElement');
goog.require('goog.dom');
goog.require('goog.graphics.EllipseElement');
goog.require('goog.graphics.GroupElement');
goog.require('goog.graphics.ImageElement');
goog.require('goog.graphics.PathElement');
goog.require('goog.graphics.RectElement');
goog.require('goog.graphics.TextElement');
/**
* Thin wrapper for SVG group elements.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.SvgGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.GroupElement}
*/
goog.graphics.SvgGroupElement = function(element, graphics) {
goog.graphics.GroupElement.call(this, element, graphics);
};
goog.inherits(goog.graphics.SvgGroupElement, goog.graphics.GroupElement);
/**
* Remove all drawing elements from the group.
* @override
*/
goog.graphics.SvgGroupElement.prototype.clear = function() {
goog.dom.removeChildren(this.getElement());
};
/**
* Set the size of the group element.
* @param {number|string} width The width of the group element.
* @param {number|string} height The height of the group element.
* @override
*/
goog.graphics.SvgGroupElement.prototype.setSize = function(width, height) {
this.getGraphics().setElementAttributes(this.getElement(),
{'width': width, 'height': height});
};
/**
* Thin wrapper for SVG ellipse elements.
* This is an implementation of the goog.graphics.EllipseElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.SvgGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.EllipseElement}
*/
goog.graphics.SvgEllipseElement = function(element, graphics, stroke, fill) {
goog.graphics.EllipseElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.SvgEllipseElement, goog.graphics.EllipseElement);
/**
* Update the center point of the ellipse.
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @override
*/
goog.graphics.SvgEllipseElement.prototype.setCenter = function(cx, cy) {
this.getGraphics().setElementAttributes(this.getElement(),
{'cx': cx, 'cy': cy});
};
/**
* Update the radius of the ellipse.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @override
*/
goog.graphics.SvgEllipseElement.prototype.setRadius = function(rx, ry) {
this.getGraphics().setElementAttributes(this.getElement(),
{'rx': rx, 'ry': ry});
};
/**
* Thin wrapper for SVG rectangle elements.
* This is an implementation of the goog.graphics.RectElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.SvgGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.RectElement}
*/
goog.graphics.SvgRectElement = function(element, graphics, stroke, fill) {
goog.graphics.RectElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.SvgRectElement, goog.graphics.RectElement);
/**
* Update the position of the rectangle.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @override
*/
goog.graphics.SvgRectElement.prototype.setPosition = function(x, y) {
this.getGraphics().setElementAttributes(this.getElement(), {'x': x, 'y': y});
};
/**
* Update the size of the rectangle.
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @override
*/
goog.graphics.SvgRectElement.prototype.setSize = function(width, height) {
this.getGraphics().setElementAttributes(this.getElement(),
{'width': width, 'height': height});
};
/**
* Thin wrapper for SVG path elements.
* This is an implementation of the goog.graphics.PathElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.SvgGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.PathElement}
*/
goog.graphics.SvgPathElement = function(element, graphics, stroke, fill) {
goog.graphics.PathElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.SvgPathElement, goog.graphics.PathElement);
/**
* Update the underlying path.
* @param {!goog.graphics.Path} path The path object to draw.
* @override
*/
goog.graphics.SvgPathElement.prototype.setPath = function(path) {
this.getGraphics().setElementAttributes(this.getElement(),
{'d': goog.graphics.SvgGraphics.getSvgPath(path)});
};
/**
* Thin wrapper for SVG text elements.
* This is an implementation of the goog.graphics.TextElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.SvgGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.TextElement}
*/
goog.graphics.SvgTextElement = function(element, graphics, stroke, fill) {
goog.graphics.TextElement.call(this, element, graphics, stroke, fill);
};
goog.inherits(goog.graphics.SvgTextElement, goog.graphics.TextElement);
/**
* Update the displayed text of the element.
* @param {string} text The text to draw.
* @override
*/
goog.graphics.SvgTextElement.prototype.setText = function(text) {
this.getElement().firstChild.data = text;
};
/**
* Thin wrapper for SVG image elements.
* This is an implementation of the goog.graphics.ImageElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.SvgGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.ImageElement}
*/
goog.graphics.SvgImageElement = function(element, graphics) {
goog.graphics.ImageElement.call(this, element, graphics);
};
goog.inherits(goog.graphics.SvgImageElement, goog.graphics.ImageElement);
/**
* Update the position of the image.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @override
*/
goog.graphics.SvgImageElement.prototype.setPosition = function(x, y) {
this.getGraphics().setElementAttributes(this.getElement(), {'x': x, 'y': y});
};
/**
* Update the size of the image.
* @param {number} width Width of image.
* @param {number} height Height of image.
* @override
*/
goog.graphics.SvgImageElement.prototype.setSize = function(width, height) {
this.getGraphics().setElementAttributes(this.getElement(),
{'width': width, 'height': height});
};
/**
* Update the source of the image.
* @param {string} src Source of the image.
* @override
*/
goog.graphics.SvgImageElement.prototype.setSource = function(src) {
this.getGraphics().setElementAttributes(this.getElement(),
{'xlink:href': src});
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a path used with a Graphics implementation.
* @author arv@google.com (Erik Arvidsson)
* @author glenning@google.com (Anthony Glenning)
*/
goog.provide('goog.graphics.Path');
goog.provide('goog.graphics.Path.Segment');
goog.require('goog.array');
goog.require('goog.math');
/**
* Creates a path object. A path is a sequence of segments and may be open or
* closed. Path uses the EVEN-ODD fill rule for determining the interior of the
* path. A path must start with a moveTo command.
*
* A "simple" path does not contain any arcs and may be transformed using
* the {@code transform} method.
*
* @constructor
*/
goog.graphics.Path = function() {
/**
* The segment types that constitute this path.
* @type {!Array.<number>}
* @private
*/
this.segments_ = [];
/**
* The number of repeated segments of the current type.
* @type {!Array.<number>}
* @private
*/
this.count_ = [];
/**
* The arguments corresponding to each of the segments.
* @type {!Array.<number>}
* @private
*/
this.arguments_ = [];
};
/**
* The coordinates of the point which closes the path (the point of the
* last moveTo command).
* @type {Array.<number>?}
* @private
*/
goog.graphics.Path.prototype.closePoint_ = null;
/**
* The coordinates most recently added to the end of the path.
* @type {Array.<number>?}
* @private
*/
goog.graphics.Path.prototype.currentPoint_ = null;
/**
* Flag for whether this is a simple path (contains no arc segments).
* @type {boolean}
* @private
*/
goog.graphics.Path.prototype.simple_ = true;
/**
* Path segment types.
* @enum {number}
*/
goog.graphics.Path.Segment = {
MOVETO: 0,
LINETO: 1,
CURVETO: 2,
ARCTO: 3,
CLOSE: 4
};
/**
* The number of points for each segment type.
* @type {!Array.<number>}
* @private
*/
goog.graphics.Path.segmentArgCounts_ = (function() {
var counts = [];
counts[goog.graphics.Path.Segment.MOVETO] = 2;
counts[goog.graphics.Path.Segment.LINETO] = 2;
counts[goog.graphics.Path.Segment.CURVETO] = 6;
counts[goog.graphics.Path.Segment.ARCTO] = 6;
counts[goog.graphics.Path.Segment.CLOSE] = 0;
return counts;
})();
/**
* Returns the number of points for a segment type.
*
* @param {number} segment The segment type.
* @return {number} The number of points.
*/
goog.graphics.Path.getSegmentCount = function(segment) {
return goog.graphics.Path.segmentArgCounts_[segment];
};
/**
* Appends another path to the end of this path.
*
* @param {!goog.graphics.Path} path The path to append.
* @return {!goog.graphics.Path} This path.
*/
goog.graphics.Path.prototype.appendPath = function(path) {
if (path.currentPoint_) {
Array.prototype.push.apply(this.segments_, path.segments_);
Array.prototype.push.apply(this.count_, path.count_);
Array.prototype.push.apply(this.arguments_, path.arguments_);
this.currentPoint_ = path.currentPoint_.concat();
this.closePoint_ = path.closePoint_.concat();
this.simple_ = this.simple_ && path.simple_;
}
return this;
};
/**
* Clears the path.
*
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.clear = function() {
this.segments_.length = 0;
this.count_.length = 0;
this.arguments_.length = 0;
delete this.closePoint_;
delete this.currentPoint_;
delete this.simple_;
return this;
};
/**
* Adds a point to the path by moving to the specified point. Repeated moveTo
* commands are collapsed into a single moveTo.
*
* @param {number} x X coordinate of destination point.
* @param {number} y Y coordinate of destination point.
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.moveTo = function(x, y) {
if (goog.array.peek(this.segments_) == goog.graphics.Path.Segment.MOVETO) {
this.arguments_.length -= 2;
} else {
this.segments_.push(goog.graphics.Path.Segment.MOVETO);
this.count_.push(1);
}
this.arguments_.push(x, y);
this.currentPoint_ = this.closePoint_ = [x, y];
return this;
};
/**
* Adds points to the path by drawing a straight line to each point.
*
* @param {...number} var_args The coordinates of each destination point as x, y
* value pairs.
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.lineTo = function(var_args) {
var lastSegment = goog.array.peek(this.segments_);
if (lastSegment == null) {
throw Error('Path cannot start with lineTo');
}
if (lastSegment != goog.graphics.Path.Segment.LINETO) {
this.segments_.push(goog.graphics.Path.Segment.LINETO);
this.count_.push(0);
}
for (var i = 0; i < arguments.length; i += 2) {
var x = arguments[i];
var y = arguments[i + 1];
this.arguments_.push(x, y);
}
this.count_[this.count_.length - 1] += i / 2;
this.currentPoint_ = [x, y];
return this;
};
/**
* Adds points to the path by drawing cubic Bezier curves. Each curve is
* specified using 3 points (6 coordinates) - two control points and the end
* point of the curve.
*
* @param {...number} var_args The coordinates specifiying each curve in sets of
* 6 points: {@code [x1, y1]} the first control point, {@code [x2, y2]} the
* second control point and {@code [x, y]} the end point.
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.curveTo = function(var_args) {
var lastSegment = goog.array.peek(this.segments_);
if (lastSegment == null) {
throw Error('Path cannot start with curve');
}
if (lastSegment != goog.graphics.Path.Segment.CURVETO) {
this.segments_.push(goog.graphics.Path.Segment.CURVETO);
this.count_.push(0);
}
for (var i = 0; i < arguments.length; i += 6) {
var x = arguments[i + 4];
var y = arguments[i + 5];
this.arguments_.push(arguments[i], arguments[i + 1],
arguments[i + 2], arguments[i + 3], x, y);
}
this.count_[this.count_.length - 1] += i / 6;
this.currentPoint_ = [x, y];
return this;
};
/**
* Adds a path command to close the path by connecting the
* last point to the first point.
*
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.close = function() {
var lastSegment = goog.array.peek(this.segments_);
if (lastSegment == null) {
throw Error('Path cannot start with close');
}
if (lastSegment != goog.graphics.Path.Segment.CLOSE) {
this.segments_.push(goog.graphics.Path.Segment.CLOSE);
this.count_.push(1);
this.currentPoint_ = this.closePoint_;
}
return this;
};
/**
* Adds a path command to draw an arc centered at the point {@code (cx, cy)}
* with radius {@code rx} along the x-axis and {@code ry} along the y-axis from
* {@code startAngle} through {@code extent} degrees. Positive rotation is in
* the direction from positive x-axis to positive y-axis.
*
* @param {number} cx X coordinate of center of ellipse.
* @param {number} cy Y coordinate of center of ellipse.
* @param {number} rx Radius of ellipse on x axis.
* @param {number} ry Radius of ellipse on y axis.
* @param {number} fromAngle Starting angle measured in degrees from the
* positive x-axis.
* @param {number} extent The span of the arc in degrees.
* @param {boolean} connect If true, the starting point of the arc is connected
* to the current point.
* @return {!goog.graphics.Path} The path itself.
* @deprecated Use {@code arcTo} or {@code arcToAsCurves} instead.
*/
goog.graphics.Path.prototype.arc = function(cx, cy, rx, ry,
fromAngle, extent, connect) {
var startX = cx + goog.math.angleDx(fromAngle, rx);
var startY = cy + goog.math.angleDy(fromAngle, ry);
if (connect) {
if (!this.currentPoint_ || startX != this.currentPoint_[0] ||
startY != this.currentPoint_[1]) {
this.lineTo(startX, startY);
}
} else {
this.moveTo(startX, startY);
}
return this.arcTo(rx, ry, fromAngle, extent);
};
/**
* Adds a path command to draw an arc starting at the path's current point,
* with radius {@code rx} along the x-axis and {@code ry} along the y-axis from
* {@code startAngle} through {@code extent} degrees. Positive rotation is in
* the direction from positive x-axis to positive y-axis.
*
* This method makes the path non-simple.
*
* @param {number} rx Radius of ellipse on x axis.
* @param {number} ry Radius of ellipse on y axis.
* @param {number} fromAngle Starting angle measured in degrees from the
* positive x-axis.
* @param {number} extent The span of the arc in degrees.
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.arcTo = function(rx, ry, fromAngle, extent) {
var cx = this.currentPoint_[0] - goog.math.angleDx(fromAngle, rx);
var cy = this.currentPoint_[1] - goog.math.angleDy(fromAngle, ry);
var ex = cx + goog.math.angleDx(fromAngle + extent, rx);
var ey = cy + goog.math.angleDy(fromAngle + extent, ry);
this.segments_.push(goog.graphics.Path.Segment.ARCTO);
this.count_.push(1);
this.arguments_.push(rx, ry, fromAngle, extent, ex, ey);
this.simple_ = false;
this.currentPoint_ = [ex, ey];
return this;
};
/**
* Same as {@code arcTo}, but approximates the arc using bezier curves.
.* As a result, this method does not affect the simplified status of this path.
* The algorithm is adapted from {@code java.awt.geom.ArcIterator}.
*
* @param {number} rx Radius of ellipse on x axis.
* @param {number} ry Radius of ellipse on y axis.
* @param {number} fromAngle Starting angle measured in degrees from the
* positive x-axis.
* @param {number} extent The span of the arc in degrees.
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.arcToAsCurves = function(
rx, ry, fromAngle, extent) {
var cx = this.currentPoint_[0] - goog.math.angleDx(fromAngle, rx);
var cy = this.currentPoint_[1] - goog.math.angleDy(fromAngle, ry);
var extentRad = goog.math.toRadians(extent);
var arcSegs = Math.ceil(Math.abs(extentRad) / Math.PI * 2);
var inc = extentRad / arcSegs;
var angle = goog.math.toRadians(fromAngle);
for (var j = 0; j < arcSegs; j++) {
var relX = Math.cos(angle);
var relY = Math.sin(angle);
var z = 4 / 3 * Math.sin(inc / 2) / (1 + Math.cos(inc / 2));
var c0 = cx + (relX - z * relY) * rx;
var c1 = cy + (relY + z * relX) * ry;
angle += inc;
relX = Math.cos(angle);
relY = Math.sin(angle);
this.curveTo(c0, c1,
cx + (relX + z * relY) * rx,
cy + (relY - z * relX) * ry,
cx + relX * rx,
cy + relY * ry);
}
return this;
};
/**
* Iterates over the path calling the supplied callback once for each path
* segment. The arguments to the callback function are the segment type and
* an array of its arguments.
*
* The {@code LINETO} and {@code CURVETO} arrays can contain multiple
* segments of the same type. The number of segments is the length of the
* array divided by the segment length (2 for lines, 6 for curves).
*
* As a convenience the {@code ARCTO} segment also includes the end point as the
* last two arguments: {@code rx, ry, fromAngle, extent, x, y}.
*
* @param {function(number, Array)} callback The function to call with each
* path segment.
*/
goog.graphics.Path.prototype.forEachSegment = function(callback) {
var points = this.arguments_;
var index = 0;
for (var i = 0, length = this.segments_.length; i < length; i++) {
var seg = this.segments_[i];
var n = goog.graphics.Path.segmentArgCounts_[seg] * this.count_[i];
callback(seg, points.slice(index, index + n));
index += n;
}
};
/**
* Returns the coordinates most recently added to the end of the path.
*
* @return {Array.<number>?} An array containing the ending coordinates of the
* path of the form {@code [x, y]}.
*/
goog.graphics.Path.prototype.getCurrentPoint = function() {
return this.currentPoint_ && this.currentPoint_.concat();
};
/**
* @return {!goog.graphics.Path} A copy of this path.
*/
goog.graphics.Path.prototype.clone = function() {
var path = new this.constructor();
path.segments_ = this.segments_.concat();
path.count_ = this.count_.concat();
path.arguments_ = this.arguments_.concat();
path.closePoint_ = this.closePoint_ && this.closePoint_.concat();
path.currentPoint_ = this.currentPoint_ && this.currentPoint_.concat();
path.simple_ = this.simple_;
return path;
};
/**
* Returns true if this path contains no arcs. Simplified paths can be
* created using {@code createSimplifiedPath}.
*
* @return {boolean} True if the path contains no arcs.
*/
goog.graphics.Path.prototype.isSimple = function() {
return this.simple_;
};
/**
* A map from segment type to the path function to call to simplify a path.
* @type {!Object}
* @private
*/
goog.graphics.Path.simplifySegmentMap_ = (function() {
var map = {};
map[goog.graphics.Path.Segment.MOVETO] = goog.graphics.Path.prototype.moveTo;
map[goog.graphics.Path.Segment.LINETO] = goog.graphics.Path.prototype.lineTo;
map[goog.graphics.Path.Segment.CLOSE] = goog.graphics.Path.prototype.close;
map[goog.graphics.Path.Segment.CURVETO] =
goog.graphics.Path.prototype.curveTo;
map[goog.graphics.Path.Segment.ARCTO] =
goog.graphics.Path.prototype.arcToAsCurves;
return map;
})();
/**
* Creates a copy of the given path, replacing {@code arcTo} with
* {@code arcToAsCurves}. The resulting path is simplified and can
* be transformed.
*
* @param {!goog.graphics.Path} src The path to simplify.
* @return {!goog.graphics.Path} A new simplified path.
*/
goog.graphics.Path.createSimplifiedPath = function(src) {
if (src.isSimple()) {
return src.clone();
}
var path = new goog.graphics.Path();
src.forEachSegment(function(segment, args) {
goog.graphics.Path.simplifySegmentMap_[segment].apply(path, args);
});
return path;
};
// TODO(chrisn): Delete this method
/**
* Creates a transformed copy of this path. The path is simplified
* {@see #createSimplifiedPath} prior to transformation.
*
* @param {!goog.graphics.AffineTransform} tx The transformation to perform.
* @return {!goog.graphics.Path} A new, transformed path.
*/
goog.graphics.Path.prototype.createTransformedPath = function(tx) {
var path = goog.graphics.Path.createSimplifiedPath(this);
path.transform(tx);
return path;
};
/**
* Transforms the path. Only simple paths are transformable. Attempting
* to transform a non-simple path will throw an error.
*
* @param {!goog.graphics.AffineTransform} tx The transformation to perform.
* @return {!goog.graphics.Path} The path itself.
*/
goog.graphics.Path.prototype.transform = function(tx) {
if (!this.isSimple()) {
throw Error('Non-simple path');
}
tx.transform(this.arguments_, 0, this.arguments_, 0,
this.arguments_.length / 2);
if (this.closePoint_) {
tx.transform(this.closePoint_, 0, this.closePoint_, 0, 1);
}
if (this.currentPoint_ && this.closePoint_ != this.currentPoint_) {
tx.transform(this.currentPoint_, 0, this.currentPoint_, 0, 1);
}
return this;
};
/**
* @return {boolean} Whether the path is empty.
*/
goog.graphics.Path.prototype.isEmpty = function() {
return this.segments_.length == 0;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Objects representing shapes drawn on a canvas.
* @author robbyw@google.com (Robby Walker)
* @author wcrosby@google.com (Wayne Crosby)
*/
goog.provide('goog.graphics.CanvasEllipseElement');
goog.provide('goog.graphics.CanvasGroupElement');
goog.provide('goog.graphics.CanvasImageElement');
goog.provide('goog.graphics.CanvasPathElement');
goog.provide('goog.graphics.CanvasRectElement');
goog.provide('goog.graphics.CanvasTextElement');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.graphics.EllipseElement');
goog.require('goog.graphics.GroupElement');
goog.require('goog.graphics.ImageElement');
goog.require('goog.graphics.Path');
goog.require('goog.graphics.PathElement');
goog.require('goog.graphics.RectElement');
goog.require('goog.graphics.TextElement');
goog.require('goog.math');
goog.require('goog.string');
/**
* Object representing a group of objects in a canvas.
* This is an implementation of the goog.graphics.GroupElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {goog.graphics.CanvasGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.GroupElement}
*/
goog.graphics.CanvasGroupElement = function(graphics) {
goog.graphics.GroupElement.call(this, null, graphics);
/**
* Children contained by this group.
* @type {Array.<goog.graphics.Element>}
* @private
*/
this.children_ = [];
};
goog.inherits(goog.graphics.CanvasGroupElement, goog.graphics.GroupElement);
/**
* Remove all drawing elements from the group.
* @override
*/
goog.graphics.CanvasGroupElement.prototype.clear = function() {
if (this.children_.length) {
this.children_.length = 0;
this.getGraphics().redraw();
}
};
/**
* Set the size of the group element.
* @param {number|string} width The width of the group element.
* @param {number|string} height The height of the group element.
* @override
*/
goog.graphics.CanvasGroupElement.prototype.setSize = function(width, height) {
// Do nothing.
};
/**
* Append a child to the group. Does not draw it
* @param {goog.graphics.Element} element The child to append.
*/
goog.graphics.CanvasGroupElement.prototype.appendChild = function(element) {
this.children_.push(element);
};
/**
* Draw the group.
* @param {CanvasRenderingContext2D} ctx The context to draw the element in.
*/
goog.graphics.CanvasGroupElement.prototype.draw = function(ctx) {
for (var i = 0, len = this.children_.length; i < len; i++) {
this.getGraphics().drawElement(this.children_[i]);
}
};
/**
* Thin wrapper for canvas ellipse elements.
* This is an implementation of the goog.graphics.EllipseElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.CanvasGraphics} graphics The graphics creating
* this element.
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @param {goog.graphics.Stroke} stroke The stroke to use for this element.
* @param {goog.graphics.Fill} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.EllipseElement}
*/
goog.graphics.CanvasEllipseElement = function(element, graphics,
cx, cy, rx, ry, stroke, fill) {
goog.graphics.EllipseElement.call(this, element, graphics, stroke, fill);
/**
* X coordinate of the ellipse center.
* @type {number}
* @private
*/
this.cx_ = cx;
/**
* Y coordinate of the ellipse center.
* @type {number}
* @private
*/
this.cy_ = cy;
/**
* Radius length for the x-axis.
* @type {number}
* @private
*/
this.rx_ = rx;
/**
* Radius length for the y-axis.
* @type {number}
* @private
*/
this.ry_ = ry;
/**
* Internal path approximating an ellipse.
* @type {goog.graphics.Path}
* @private
*/
this.path_ = new goog.graphics.Path();
this.setUpPath_();
/**
* Internal path element that actually does the drawing.
* @type {goog.graphics.CanvasPathElement}
* @private
*/
this.pathElement_ = new goog.graphics.CanvasPathElement(null, graphics,
this.path_, stroke, fill);
};
goog.inherits(goog.graphics.CanvasEllipseElement, goog.graphics.EllipseElement);
/**
* Sets up the path.
* @private
*/
goog.graphics.CanvasEllipseElement.prototype.setUpPath_ = function() {
this.path_.clear();
this.path_.moveTo(this.cx_ + goog.math.angleDx(0, this.rx_),
this.cy_ + goog.math.angleDy(0, this.ry_));
this.path_.arcTo(this.rx_, this.ry_, 0, 360);
this.path_.close();
};
/**
* Update the center point of the ellipse.
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @override
*/
goog.graphics.CanvasEllipseElement.prototype.setCenter = function(cx, cy) {
this.cx_ = cx;
this.cy_ = cy;
this.setUpPath_();
this.pathElement_.setPath(/** @type {!goog.graphics.Path} */ (this.path_));
};
/**
* Update the radius of the ellipse.
* @param {number} rx Center X coordinate.
* @param {number} ry Center Y coordinate.
* @override
*/
goog.graphics.CanvasEllipseElement.prototype.setRadius = function(rx, ry) {
this.rx_ = rx;
this.ry_ = ry;
this.setUpPath_();
this.pathElement_.setPath(/** @type {!goog.graphics.Path} */ (this.path_));
};
/**
* Draw the ellipse. Should be treated as package scope.
* @param {CanvasRenderingContext2D} ctx The context to draw the element in.
*/
goog.graphics.CanvasEllipseElement.prototype.draw = function(ctx) {
this.pathElement_.draw(ctx);
};
/**
* Thin wrapper for canvas rectangle elements.
* This is an implementation of the goog.graphics.RectElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.CanvasGraphics} graphics The graphics creating
* this element.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} w Width of rectangle.
* @param {number} h Height of rectangle.
* @param {goog.graphics.Stroke} stroke The stroke to use for this element.
* @param {goog.graphics.Fill} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.RectElement}
*/
goog.graphics.CanvasRectElement = function(element, graphics, x, y, w, h,
stroke, fill) {
goog.graphics.RectElement.call(this, element, graphics, stroke, fill);
/**
* X coordinate of the top left corner.
* @type {number}
* @private
*/
this.x_ = x;
/**
* Y coordinate of the top left corner.
* @type {number}
* @private
*/
this.y_ = y;
/**
* Width of the rectangle.
* @type {number}
* @private
*/
this.w_ = w;
/**
* Height of the rectangle.
* @type {number}
* @private
*/
this.h_ = h;
};
goog.inherits(goog.graphics.CanvasRectElement, goog.graphics.RectElement);
/**
* Update the position of the rectangle.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @override
*/
goog.graphics.CanvasRectElement.prototype.setPosition = function(x, y) {
this.x_ = x;
this.y_ = y;
if (this.drawn_) {
this.getGraphics().redraw();
}
};
/**
* Whether the rectangle has been drawn yet.
* @type {boolean}
* @private
*/
goog.graphics.CanvasRectElement.prototype.drawn_ = false;
/**
* Update the size of the rectangle.
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @override
*/
goog.graphics.CanvasRectElement.prototype.setSize = function(width, height) {
this.w_ = width;
this.h_ = height;
if (this.drawn_) {
this.getGraphics().redraw();
}
};
/**
* Draw the rectangle. Should be treated as package scope.
* @param {CanvasRenderingContext2D} ctx The context to draw the element in.
*/
goog.graphics.CanvasRectElement.prototype.draw = function(ctx) {
this.drawn_ = true;
ctx.beginPath();
ctx.moveTo(this.x_, this.y_);
ctx.lineTo(this.x_, this.y_ + this.h_);
ctx.lineTo(this.x_ + this.w_, this.y_ + this.h_);
ctx.lineTo(this.x_ + this.w_, this.y_);
ctx.closePath();
};
/**
* Thin wrapper for canvas path elements.
* This is an implementation of the goog.graphics.PathElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.CanvasGraphics} graphics The graphics creating
* this element.
* @param {!goog.graphics.Path} path The path object to draw.
* @param {goog.graphics.Stroke} stroke The stroke to use for this element.
* @param {goog.graphics.Fill} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.PathElement}
*/
goog.graphics.CanvasPathElement = function(element, graphics, path, stroke,
fill) {
goog.graphics.PathElement.call(this, element, graphics, stroke, fill);
this.setPath(path);
};
goog.inherits(goog.graphics.CanvasPathElement, goog.graphics.PathElement);
/**
* Whether the shape has been drawn yet.
* @type {boolean}
* @private
*/
goog.graphics.CanvasPathElement.prototype.drawn_ = false;
/**
* The path to draw.
* @type {goog.graphics.Path}
* @private
*/
goog.graphics.CanvasPathElement.prototype.path_;
/**
* Update the underlying path.
* @param {!goog.graphics.Path} path The path object to draw.
* @override
*/
goog.graphics.CanvasPathElement.prototype.setPath = function(path) {
this.path_ = path.isSimple() ? path :
goog.graphics.Path.createSimplifiedPath(path);
if (this.drawn_) {
this.getGraphics().redraw();
}
};
/**
* Draw the path. Should be treated as package scope.
* @param {CanvasRenderingContext2D} ctx The context to draw the element in.
*/
goog.graphics.CanvasPathElement.prototype.draw = function(ctx) {
this.drawn_ = true;
ctx.beginPath();
this.path_.forEachSegment(function(segment, args) {
switch (segment) {
case goog.graphics.Path.Segment.MOVETO:
ctx.moveTo(args[0], args[1]);
break;
case goog.graphics.Path.Segment.LINETO:
for (var i = 0; i < args.length; i += 2) {
ctx.lineTo(args[i], args[i + 1]);
}
break;
case goog.graphics.Path.Segment.CURVETO:
for (var i = 0; i < args.length; i += 6) {
ctx.bezierCurveTo(args[i], args[i + 1], args[i + 2],
args[i + 3], args[i + 4], args[i + 5]);
}
break;
case goog.graphics.Path.Segment.ARCTO:
throw Error('Canvas paths cannot contain arcs');
case goog.graphics.Path.Segment.CLOSE:
ctx.closePath();
break;
}
});
};
/**
* Thin wrapper for canvas text elements.
* This is an implementation of the goog.graphics.TextElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {!goog.graphics.CanvasGraphics} graphics The graphics creating
* this element.
* @param {string} text The text to draw.
* @param {number} x1 X coordinate of start of line.
* @param {number} y1 Y coordinate of start of line.
* @param {number} x2 X coordinate of end of line.
* @param {number} y2 Y coordinate of end of line.
* @param {?string} align Horizontal alignment: left (default), center, right.
* @param {!goog.graphics.Font} font Font describing the font properties.
* @param {goog.graphics.Stroke} stroke The stroke to use for this element.
* @param {goog.graphics.Fill} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.TextElement}
*/
goog.graphics.CanvasTextElement = function(graphics, text, x1, y1, x2, y2,
align, font, stroke, fill) {
var element = goog.dom.createDom(goog.dom.TagName.DIV, {
'style': 'display:table;position:absolute;padding:0;margin:0;border:0'
});
goog.graphics.TextElement.call(this, element, graphics, stroke, fill);
/**
* The text to draw.
* @type {string}
* @private
*/
this.text_ = text;
/**
* X coordinate of the start of the line the text is drawn on.
* @type {number}
* @private
*/
this.x1_ = x1;
/**
* Y coordinate of the start of the line the text is drawn on.
* @type {number}
* @private
*/
this.y1_ = y1;
/**
* X coordinate of the end of the line the text is drawn on.
* @type {number}
* @private
*/
this.x2_ = x2;
/**
* Y coordinate of the end of the line the text is drawn on.
* @type {number}
* @private
*/
this.y2_ = y2;
/**
* Horizontal alignment: left (default), center, right.
* @type {string}
* @private
*/
this.align_ = align || 'left';
/**
* Font object describing the font properties.
* @type {goog.graphics.Font}
* @private
*/
this.font_ = font;
/**
* The inner element that contains the text.
* @type {Element}
* @private
*/
this.innerElement_ = goog.dom.createDom('DIV', {
'style': 'display:table-cell;padding: 0;margin: 0;border: 0'
});
this.updateStyle_();
this.updateText_();
// Append to the DOM.
graphics.getElement().appendChild(element);
element.appendChild(this.innerElement_);
};
goog.inherits(goog.graphics.CanvasTextElement, goog.graphics.TextElement);
/**
* Update the displayed text of the element.
* @param {string} text The text to draw.
* @override
*/
goog.graphics.CanvasTextElement.prototype.setText = function(text) {
this.text_ = text;
this.updateText_();
};
/**
* Sets the fill for this element.
* @param {goog.graphics.Fill} fill The fill object.
* @override
*/
goog.graphics.CanvasTextElement.prototype.setFill = function(fill) {
this.fill = fill;
var element = this.getElement();
if (element) {
element.style.color = fill.getColor() || fill.getColor1();
}
};
/**
* Sets the stroke for this element.
* @param {goog.graphics.Stroke} stroke The stroke object.
* @override
*/
goog.graphics.CanvasTextElement.prototype.setStroke = function(stroke) {
// Ignore stroke
};
/**
* Draw the text. Should be treated as package scope.
* @param {CanvasRenderingContext2D} ctx The context to draw the element in.
*/
goog.graphics.CanvasTextElement.prototype.draw = function(ctx) {
// Do nothing - the text is already drawn.
};
/**
* Update the styles of the DIVs.
* @private
*/
goog.graphics.CanvasTextElement.prototype.updateStyle_ = function() {
var x1 = this.x1_;
var x2 = this.x2_;
var y1 = this.y1_;
var y2 = this.y2_;
var align = this.align_;
var font = this.font_;
var style = this.getElement().style;
var scaleX = this.getGraphics().getPixelScaleX();
var scaleY = this.getGraphics().getPixelScaleY();
if (x1 == x2) {
// Special case vertical text
style.lineHeight = '90%';
this.innerElement_.style.verticalAlign = align == 'center' ? 'middle' :
align == 'left' ? (y1 < y2 ? 'top' : 'bottom') :
y1 < y2 ? 'bottom' : 'top';
style.textAlign = 'center';
var w = font.size * scaleX;
style.top = Math.round(Math.min(y1, y2) * scaleY) + 'px';
style.left = Math.round((x1 - w / 2) * scaleX) + 'px';
style.width = Math.round(w) + 'px';
style.height = Math.abs(y1 - y2) * scaleY + 'px';
style.fontSize = font.size * 0.6 * scaleY + 'pt';
} else {
style.lineHeight = '100%';
this.innerElement_.style.verticalAlign = 'top';
style.textAlign = align;
style.top = Math.round(((y1 + y2) / 2 - font.size * 2 / 3) * scaleY) + 'px';
style.left = Math.round(x1 * scaleX) + 'px';
style.width = Math.round(Math.abs(x2 - x1) * scaleX) + 'px';
style.height = 'auto';
style.fontSize = font.size * scaleY + 'pt';
}
style.fontWeight = font.bold ? 'bold' : 'normal';
style.fontStyle = font.italic ? 'italic' : 'normal';
style.fontFamily = font.family;
var fill = this.getFill();
style.color = fill.getColor() || fill.getColor1();
};
/**
* Update the text content.
* @private
*/
goog.graphics.CanvasTextElement.prototype.updateText_ = function() {
if (this.x1_ == this.x2_) {
// Special case vertical text
this.innerElement_.innerHTML =
goog.array.map(this.text_.split(''),
function(entry) { return goog.string.htmlEscape(entry); }).
join('<br>');
} else {
this.innerElement_.innerHTML = goog.string.htmlEscape(this.text_);
}
};
/**
* Thin wrapper for canvas image elements.
* This is an implementation of the goog.graphics.ImageElement interface.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.CanvasGraphics} graphics The graphics creating
* this element.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} w Width of rectangle.
* @param {number} h Height of rectangle.
* @param {string} src Source of the image.
* @constructor
* @extends {goog.graphics.ImageElement}
*/
goog.graphics.CanvasImageElement = function(element, graphics, x, y, w, h,
src) {
goog.graphics.ImageElement.call(this, element, graphics);
/**
* X coordinate of the top left corner.
* @type {number}
* @private
*/
this.x_ = x;
/**
* Y coordinate of the top left corner.
* @type {number}
* @private
*/
this.y_ = y;
/**
* Width of the rectangle.
* @type {number}
* @private
*/
this.w_ = w;
/**
* Height of the rectangle.
* @type {number}
* @private
*/
this.h_ = h;
/**
* URL of the image source.
* @type {string}
* @private
*/
this.src_ = src;
};
goog.inherits(goog.graphics.CanvasImageElement, goog.graphics.ImageElement);
/**
* Whether the image has been drawn yet.
* @type {boolean}
* @private
*/
goog.graphics.CanvasImageElement.prototype.drawn_ = false;
/**
* Update the position of the image.
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @override
*/
goog.graphics.CanvasImageElement.prototype.setPosition = function(x, y) {
this.x_ = x;
this.y_ = y;
if (this.drawn_) {
this.getGraphics().redraw();
}
};
/**
* Update the size of the image.
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @override
*/
goog.graphics.CanvasImageElement.prototype.setSize = function(width, height) {
this.w_ = width;
this.h_ = height;
if (this.drawn_) {
this.getGraphics().redraw();
}
};
/**
* Update the source of the image.
* @param {string} src Source of the image.
* @override
*/
goog.graphics.CanvasImageElement.prototype.setSource = function(src) {
this.src_ = src;
if (this.drawn_) {
// TODO(robbyw): Probably need to reload the image here.
this.getGraphics().redraw();
}
};
/**
* Draw the image. Should be treated as package scope.
* @param {CanvasRenderingContext2D} ctx The context to draw the element in.
*/
goog.graphics.CanvasImageElement.prototype.draw = function(ctx) {
if (this.img_) {
if (this.w_ && this.h_) {
// If the image is already loaded, draw it.
ctx.drawImage(this.img_, this.x_, this.y_, this.w_, this.h_);
}
this.drawn_ = true;
} else {
// Otherwise, load it.
var img = new Image();
img.onload = goog.bind(this.handleImageLoad_, this, img);
// TODO(robbyw): Handle image load errors.
img.src = this.src_;
}
};
/**
* Handle an image load.
* @param {Element} img The image element that finished loading.
* @private
*/
goog.graphics.CanvasImageElement.prototype.handleImageLoad_ = function(img) {
this.img_ = img;
// TODO(robbyw): Add a small delay to catch batched images
this.getGraphics().redraw();
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for elements with a
* stroke and fill.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.StrokeAndFillElement');
goog.require('goog.graphics.Element');
/**
* Interface for a graphics element with a stroke and fill.
* This is the base interface for ellipse, rectangle and other
* shape interfaces.
* You should not construct objects from this constructor. The graphics
* will return an implementation of this interface for you.
*
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.Element}
*/
goog.graphics.StrokeAndFillElement = function(element, graphics, stroke, fill) {
goog.graphics.Element.call(this, element, graphics);
this.setStroke(stroke);
this.setFill(fill);
};
goog.inherits(goog.graphics.StrokeAndFillElement, goog.graphics.Element);
/**
* The latest fill applied to this element.
* @type {goog.graphics.Fill?}
* @protected
*/
goog.graphics.StrokeAndFillElement.prototype.fill = null;
/**
* The latest stroke applied to this element.
* @type {goog.graphics.Stroke?}
* @private
*/
goog.graphics.StrokeAndFillElement.prototype.stroke_ = null;
/**
* Sets the fill for this element.
* @param {goog.graphics.Fill?} fill The fill object.
*/
goog.graphics.StrokeAndFillElement.prototype.setFill = function(fill) {
this.fill = fill;
this.getGraphics().setElementFill(this, fill);
};
/**
* @return {goog.graphics.Fill?} fill The fill object.
*/
goog.graphics.StrokeAndFillElement.prototype.getFill = function() {
return this.fill;
};
/**
* Sets the stroke for this element.
* @param {goog.graphics.Stroke?} stroke The stroke object.
*/
goog.graphics.StrokeAndFillElement.prototype.setStroke = function(stroke) {
this.stroke_ = stroke;
this.getGraphics().setElementStroke(this, stroke);
};
/**
* @return {goog.graphics.Stroke?} stroke The stroke object.
*/
goog.graphics.StrokeAndFillElement.prototype.getStroke = function() {
return this.stroke_;
};
/**
* Re-strokes the element to react to coordinate size changes.
*/
goog.graphics.StrokeAndFillElement.prototype.reapplyStroke = function() {
if (this.stroke_) {
this.setStroke(this.stroke_);
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a solid color fill goog.graphics.
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.graphics.SolidFill');
goog.require('goog.graphics.Fill');
/**
* Creates an immutable solid color fill object.
*
* @param {string} color The color of the background.
* @param {number=} opt_opacity The opacity of the background fill. The value
* must be greater than or equal to zero (transparent) and less than or
* equal to 1 (opaque).
* @constructor
* @extends {goog.graphics.Fill}
*/
goog.graphics.SolidFill = function(color, opt_opacity) {
/**
* The color with which to fill.
* @type {string}
* @private
*/
this.color_ = color;
/**
* The opacity of the fill.
* @type {number}
* @private
*/
this.opacity_ = opt_opacity == null ? 1.0 : opt_opacity;
};
goog.inherits(goog.graphics.SolidFill, goog.graphics.Fill);
/**
* @return {string} The color of this fill.
*/
goog.graphics.SolidFill.prototype.getColor = function() {
return this.color_;
};
/**
* @return {number} The opacity of this fill.
*/
goog.graphics.SolidFill.prototype.getOpacity = function() {
return this.opacity_;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for images.
*/
goog.provide('goog.graphics.ImageElement');
goog.require('goog.graphics.Element');
/**
* Interface for a graphics image element.
* You should not construct objects from this constructor. Instead,
* you should use {@code goog.graphics.Graphics.drawImage} and it
* will return an implementation of this interface for you.
*
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.Element}
*/
goog.graphics.ImageElement = function(element, graphics) {
goog.graphics.Element.call(this, element, graphics);
};
goog.inherits(goog.graphics.ImageElement, goog.graphics.Element);
/**
* Update the position of the image.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
*/
goog.graphics.ImageElement.prototype.setPosition = goog.abstractMethod;
/**
* Update the size of the image.
*
* @param {number} width Width of image.
* @param {number} height Height of image.
*/
goog.graphics.ImageElement.prototype.setSize = goog.abstractMethod;
/**
* Update the source of the image.
* @param {string} src Source of the image.
*/
goog.graphics.ImageElement.prototype.setSource = goog.abstractMethod;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview CanvasGraphics sub class that uses the canvas tag for drawing.
* @author robbyw@google.com (Robby Walker)
* @author wcrosby@google.com (Wayne Crosby)
*/
goog.provide('goog.graphics.CanvasGraphics');
goog.require('goog.dom');
goog.require('goog.events.EventType');
goog.require('goog.graphics.AbstractGraphics');
goog.require('goog.graphics.CanvasEllipseElement');
goog.require('goog.graphics.CanvasGroupElement');
goog.require('goog.graphics.CanvasImageElement');
goog.require('goog.graphics.CanvasPathElement');
goog.require('goog.graphics.CanvasRectElement');
goog.require('goog.graphics.CanvasTextElement');
goog.require('goog.graphics.Font');
goog.require('goog.graphics.LinearGradient');
goog.require('goog.graphics.SolidFill');
goog.require('goog.graphics.Stroke');
goog.require('goog.math.Size');
/**
* A Graphics implementation for drawing using canvas.
* @param {string|number} width The (non-zero) width in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {string|number} height The (non-zero) height in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {?number=} opt_coordWidth The coordinate width - if
* omitted or null, defaults to same as width.
* @param {?number=} opt_coordHeight The coordinate height - if
* omitted or null, defaults to same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @constructor
* @extends {goog.graphics.AbstractGraphics}
*/
goog.graphics.CanvasGraphics = function(width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper) {
goog.graphics.AbstractGraphics.call(this, width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper);
};
goog.inherits(goog.graphics.CanvasGraphics, goog.graphics.AbstractGraphics);
/**
* Sets the fill for the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element
* wrapper.
* @param {goog.graphics.Fill} fill The fill object.
* @override
*/
goog.graphics.CanvasGraphics.prototype.setElementFill = function(element,
fill) {
this.redraw();
};
/**
* Sets the stroke for the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element
* wrapper.
* @param {goog.graphics.Stroke} stroke The stroke object.
* @override
*/
goog.graphics.CanvasGraphics.prototype.setElementStroke = function(
element, stroke) {
this.redraw();
};
/**
* Set the transformation of an element.
* @param {goog.graphics.Element} element The element wrapper.
* @param {number} x The x coordinate of the translation transform.
* @param {number} y The y coordinate of the translation transform.
* @param {number} angle The angle of the rotation transform.
* @param {number} centerX The horizontal center of the rotation transform.
* @param {number} centerY The vertical center of the rotation transform.
* @override
*/
goog.graphics.CanvasGraphics.prototype.setElementTransform = function(element,
x, y, angle, centerX, centerY) {
this.redraw();
};
/**
* Push an element transform on to the transform stack.
* @param {goog.graphics.Element} element The transformed element.
*/
goog.graphics.CanvasGraphics.prototype.pushElementTransform = function(
element) {
var ctx = this.getContext();
ctx.save();
var transform = element.getTransform();
// TODO(robbyw): Test for unsupported transforms i.e. skews.
var tx = transform.getTranslateX();
var ty = transform.getTranslateY();
if (tx || ty) {
ctx.translate(tx, ty);
}
var sinTheta = transform.getShearY();
if (sinTheta) {
ctx.rotate(Math.asin(sinTheta));
}
};
/**
* Pop an element transform off of the transform stack.
*/
goog.graphics.CanvasGraphics.prototype.popElementTransform = function() {
this.getContext().restore();
};
/**
* Creates the DOM representation of the graphics area.
* @override
*/
goog.graphics.CanvasGraphics.prototype.createDom = function() {
var element = this.dom_.createDom('div',
{'style': 'position:relative;overflow:hidden'});
this.setElementInternal(element);
this.canvas_ = this.dom_.createDom('canvas');
element.appendChild(this.canvas_);
/**
* The main canvas element.
* @type {goog.graphics.CanvasGroupElement}
*/
this.canvasElement = new goog.graphics.CanvasGroupElement(this);
this.lastGroup_ = this.canvasElement;
this.redrawTimeout_ = 0;
this.updateSize();
};
/**
* Clears the drawing context object in response to actions that make the old
* context invalid - namely resize of the canvas element.
* @private
*/
goog.graphics.CanvasGraphics.prototype.clearContext_ = function() {
this.context_ = null;
};
/**
* Returns the drawing context.
* @return {Object} The canvas element rendering context.
*/
goog.graphics.CanvasGraphics.prototype.getContext = function() {
if (!this.getElement()) {
this.createDom();
}
if (!this.context_) {
this.context_ = this.canvas_.getContext('2d');
this.context_.save();
}
return this.context_;
};
/**
* Changes the coordinate system position.
* @param {number} left The coordinate system left bound.
* @param {number} top The coordinate system top bound.
* @override
*/
goog.graphics.CanvasGraphics.prototype.setCoordOrigin = function(left, top) {
this.coordLeft = left;
this.coordTop = top;
this.redraw();
};
/**
* Changes the coordinate size.
* @param {number} coordWidth The coordinate width.
* @param {number} coordHeight The coordinate height.
* @override
*/
goog.graphics.CanvasGraphics.prototype.setCoordSize = function(coordWidth,
coordHeight) {
goog.graphics.CanvasGraphics.superClass_.setCoordSize.apply(this, arguments);
this.redraw();
};
/**
* Change the size of the canvas.
* @param {number} pixelWidth The width in pixels.
* @param {number} pixelHeight The height in pixels.
* @override
*/
goog.graphics.CanvasGraphics.prototype.setSize = function(pixelWidth,
pixelHeight) {
this.width = pixelWidth;
this.height = pixelHeight;
this.updateSize();
this.redraw();
};
/** @override */
goog.graphics.CanvasGraphics.prototype.getPixelSize = function() {
// goog.style.getSize does not work for Canvas elements. We
// have to compute the size manually if it is percentage based.
var width = this.width;
var height = this.height;
var computeWidth = goog.isString(width) && width.indexOf('%') != -1;
var computeHeight = goog.isString(height) && height.indexOf('%') != -1;
if (!this.isInDocument() && (computeWidth || computeHeight)) {
return null;
}
var parent;
var parentSize;
if (computeWidth) {
parent = /** @type {Element} */ (this.getElement().parentNode);
parentSize = goog.style.getSize(parent);
width = parseFloat(/** @type {string} */ (width)) * parentSize.width / 100;
}
if (computeHeight) {
parent = parent || /** @type {Element} */ (this.getElement().parentNode);
parentSize = parentSize || goog.style.getSize(parent);
height = parseFloat(/** @type {string} */ (height)) * parentSize.height /
100;
}
return new goog.math.Size(/** @type {number} */ (width),
/** @type {number} */ (height));
};
/**
* Update the size of the canvas.
*/
goog.graphics.CanvasGraphics.prototype.updateSize = function() {
goog.style.setSize(this.getElement(), this.width, this.height);
var pixels = this.getPixelSize();
if (pixels) {
goog.style.setSize(this.canvas_,
/** @type {number} */ (pixels.width),
/** @type {number} */ (pixels.height));
this.canvas_.width = pixels.width;
this.canvas_.height = pixels.height;
this.clearContext_();
}
};
/**
* Reset the canvas.
*/
goog.graphics.CanvasGraphics.prototype.reset = function() {
var ctx = this.getContext();
ctx.restore();
var size = this.getPixelSize();
if (size.width && size.height) {
ctx.clearRect(0, 0, size.width, size.height);
}
ctx.save();
};
/**
* Remove all drawing elements from the graphics.
* @override
*/
goog.graphics.CanvasGraphics.prototype.clear = function() {
this.reset();
this.canvasElement.clear();
var el = this.getElement();
// Remove all children (text nodes) except the canvas (which is at index 0)
while (el.childNodes.length > 1) {
el.removeChild(el.lastChild);
}
};
/**
* Redraw the entire canvas.
*/
goog.graphics.CanvasGraphics.prototype.redraw = function() {
if (this.preventRedraw_) {
this.needsRedraw_ = true;
return;
}
if (this.isInDocument()) {
this.reset();
if (this.coordWidth) {
var pixels = this.getPixelSize();
this.getContext().scale(pixels.width / this.coordWidth,
pixels.height / this.coordHeight);
}
if (this.coordLeft || this.coordTop) {
this.getContext().translate(-this.coordLeft, -this.coordTop);
}
this.pushElementTransform(this.canvasElement);
this.canvasElement.draw(this.context_);
this.popElementTransform();
}
};
/**
* Draw an element, including any stroke or fill.
* @param {goog.graphics.Element} element The element to draw.
*/
goog.graphics.CanvasGraphics.prototype.drawElement = function(element) {
if (element instanceof goog.graphics.CanvasTextElement) {
// Don't draw text since that is not implemented using canvas.
return;
}
var ctx = this.getContext();
this.pushElementTransform(element);
if (!element.getFill || !element.getStroke) {
// Draw without stroke or fill (e.g. the element is an image or group).
element.draw(ctx);
this.popElementTransform();
return;
}
var fill = element.getFill();
if (fill) {
if (fill instanceof goog.graphics.SolidFill) {
if (fill.getOpacity() != 0) {
ctx.globalAlpha = fill.getOpacity();
ctx.fillStyle = fill.getColor();
element.draw(ctx);
ctx.fill();
ctx.globalAlpha = 1;
}
} else { // (fill instanceof goog.graphics.LinearGradient)
var linearGradient = ctx.createLinearGradient(fill.getX1(), fill.getY1(),
fill.getX2(), fill.getY2());
linearGradient.addColorStop(0.0, fill.getColor1());
linearGradient.addColorStop(1.0, fill.getColor2());
ctx.fillStyle = linearGradient;
element.draw(ctx);
ctx.fill();
}
}
var stroke = element.getStroke();
if (stroke) {
element.draw(ctx);
ctx.strokeStyle = stroke.getColor();
var width = stroke.getWidth();
if (goog.isString(width) && width.indexOf('px') != -1) {
width = parseFloat(width) / this.getPixelScaleX();
}
ctx.lineWidth = width;
ctx.stroke();
}
this.popElementTransform();
};
/**
* Append an element.
*
* @param {goog.graphics.Element} element The element to draw.
* @param {goog.graphics.CanvasGroupElement|undefined} group The group to draw
* it in. If null or undefined, defaults to the root group.
* @private
* @deprecated Use append instead.
*/
goog.graphics.CanvasGraphics.prototype.append_ = function(element, group) {
this.append(element, group);
};
/**
* Append an element.
*
* @param {goog.graphics.Element} element The element to draw.
* @param {goog.graphics.GroupElement|undefined} group The group to draw
* it in. If null or undefined, defaults to the root group.
* @protected
*/
goog.graphics.CanvasGraphics.prototype.append = function(element, group) {
group = group || this.canvasElement;
group.appendChild(element);
if (this.isDrawable(group)) {
this.drawElement(element);
}
};
/**
* Draw an ellipse.
*
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @param {goog.graphics.Stroke} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper
* element to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.EllipseElement} The newly created element.
* @override
*/
goog.graphics.CanvasGraphics.prototype.drawEllipse = function(cx, cy, rx, ry,
stroke, fill, opt_group) {
var element = new goog.graphics.CanvasEllipseElement(null, this,
cx, cy, rx, ry, stroke, fill);
this.append(element, opt_group);
return element;
};
/**
* Draw a rectangle.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @param {goog.graphics.Stroke} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper
* element to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.RectElement} The newly created element.
* @override
*/
goog.graphics.CanvasGraphics.prototype.drawRect = function(x, y, width, height,
stroke, fill, opt_group) {
var element = new goog.graphics.CanvasRectElement(null, this,
x, y, width, height, stroke, fill);
this.append(element, opt_group);
return element;
};
/**
* Draw an image.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of image.
* @param {number} height Height of image.
* @param {string} src Source of the image.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper
* element to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.ImageElement} The newly created element.
*/
goog.graphics.CanvasGraphics.prototype.drawImage = function(x, y, width, height,
src, opt_group) {
var element = new goog.graphics.CanvasImageElement(null, this, x, y, width,
height, src);
this.append(element, opt_group);
return element;
};
/**
* Draw a text string vertically centered on a given line.
*
* @param {string} text The text to draw.
* @param {number} x1 X coordinate of start of line.
* @param {number} y1 Y coordinate of start of line.
* @param {number} x2 X coordinate of end of line.
* @param {number} y2 Y coordinate of end of line.
* @param {?string} align Horizontal alignment: left (default), center, right.
* @param {goog.graphics.Font} font Font describing the font properties.
* @param {goog.graphics.Stroke} stroke Stroke object describing the stroke.
* @param {goog.graphics.Fill} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper
* element to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.TextElement} The newly created element.
* @override
*/
goog.graphics.CanvasGraphics.prototype.drawTextOnLine = function(
text, x1, y1, x2, y2, align, font, stroke, fill, opt_group) {
var element = new goog.graphics.CanvasTextElement(this,
text, x1, y1, x2, y2, align, /** @type {!goog.graphics.Font} */ (font),
stroke, fill);
this.append(element, opt_group);
return element;
};
/**
* Draw a path.
* @param {!goog.graphics.Path} path The path object to draw.
* @param {goog.graphics.Stroke} stroke Stroke object describing the stroke.
* @param {goog.graphics.Fill} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper
* element to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.PathElement} The newly created element.
* @override
*/
goog.graphics.CanvasGraphics.prototype.drawPath = function(path, stroke, fill,
opt_group) {
var element = new goog.graphics.CanvasPathElement(null, this,
path, stroke, fill);
this.append(element, opt_group);
return element;
};
/**
* @param {goog.graphics.GroupElement} group The group to possibly
* draw to.
* @return {boolean} Whether drawing can occur now.
*/
goog.graphics.CanvasGraphics.prototype.isDrawable = function(group) {
return this.isInDocument() && !this.redrawTimeout_ &&
!this.isRedrawRequired(group);
};
/**
* Returns true if drawing to the given group means a redraw is required.
* @param {goog.graphics.GroupElement} group The group to draw to.
* @return {boolean} Whether drawing to this group should force a redraw.
*/
goog.graphics.CanvasGraphics.prototype.isRedrawRequired = function(group) {
// TODO(robbyw): Moving up to any parent of lastGroup should not force redraw.
return group != this.canvasElement && group != this.lastGroup_;
};
/**
* Create an empty group of drawing elements.
*
* @param {goog.graphics.GroupElement=} opt_group The group wrapper
* element to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.CanvasGroupElement} The newly created group.
* @override
*/
goog.graphics.CanvasGraphics.prototype.createGroup = function(opt_group) {
var group = new goog.graphics.CanvasGroupElement(this);
opt_group = opt_group || this.canvasElement;
// TODO(robbyw): Moving up to any parent group should not force redraw.
if (opt_group == this.canvasElement || opt_group == this.lastGroup_) {
this.lastGroup_ = group;
}
this.append(group, opt_group);
return group;
};
/**
* Measure and return the width (in pixels) of a given text string.
* Text measurement is needed to make sure a text can fit in the allocated
* area. The way text length is measured is by writing it into a div that is
* after the visible area, measure the div width, and immediatly erase the
* written value.
*
* @param {string} text The text string to measure.
* @param {goog.graphics.Font} font The font object describing the font style.
* @override
*/
goog.graphics.CanvasGraphics.prototype.getTextWidth = goog.abstractMethod;
/**
* Disposes of the component by removing event handlers, detacing DOM nodes from
* the document body, and removing references to them.
* @override
* @protected
*/
goog.graphics.CanvasGraphics.prototype.disposeInternal = function() {
this.context_ = null;
goog.graphics.CanvasGraphics.superClass_.disposeInternal.call(this);
};
/** @override */
goog.graphics.CanvasGraphics.prototype.enterDocument = function() {
var oldPixelSize = this.getPixelSize();
goog.graphics.CanvasGraphics.superClass_.enterDocument.call(this);
if (!oldPixelSize) {
this.updateSize();
this.dispatchEvent(goog.events.EventType.RESIZE);
}
this.redraw();
};
/**
* Start preventing redraws - useful for chaining large numbers of changes
* together. Not guaranteed to do anything - i.e. only use this for
* optimization of a single code path.
* @override
*/
goog.graphics.CanvasGraphics.prototype.suspend = function() {
this.preventRedraw_ = true;
};
/**
* Stop preventing redraws. If any redraws had been prevented, a redraw will
* be done now.
* @override
*/
goog.graphics.CanvasGraphics.prototype.resume = function() {
this.preventRedraw_ = false;
if (this.needsRedraw_) {
this.redraw();
this.needsRedraw_ = false;
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a font to be used with a Renderer.
* @author arv@google.com (Erik Arvidsson)
* @see ../demos/graphics/basicelements.html
*/
goog.provide('goog.graphics.Font');
/**
* This class represents a font to be used with a renderer.
* @param {number} size The font size.
* @param {string} family The font family.
* @constructor
*/
goog.graphics.Font = function(size, family) {
/**
* Font size.
* @type {number}
*/
this.size = size;
// TODO(arv): Is this in pixels or drawing units based on the coord size?
/**
* The name of the font family to use, can be a comma separated string.
* @type {string}
*/
this.family = family;
};
/**
* Indication if text should be bolded
* @type {boolean}
*/
goog.graphics.Font.prototype.bold = false;
/**
* Indication if text should be in italics
* @type {boolean}
*/
goog.graphics.Font.prototype.italic = false;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for paths.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.PathElement');
goog.require('goog.graphics.StrokeAndFillElement');
/**
* Interface for a graphics path element.
* You should not construct objects from this constructor. The graphics
* will return an implementation of this interface for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @param {goog.graphics.Stroke?} stroke The stroke to use for this element.
* @param {goog.graphics.Fill?} fill The fill to use for this element.
* @constructor
* @extends {goog.graphics.StrokeAndFillElement}
*/
goog.graphics.PathElement = function(element, graphics, stroke, fill) {
goog.graphics.StrokeAndFillElement.call(this, element, graphics, stroke,
fill);
};
goog.inherits(goog.graphics.PathElement, goog.graphics.StrokeAndFillElement);
/**
* Update the underlying path.
* @param {!goog.graphics.Path} path The path object to draw.
*/
goog.graphics.PathElement.prototype.setPath = goog.abstractMethod;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview SvgGraphics sub class that uses SVG to draw the graphics.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.SvgGraphics');
goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.graphics.AbstractGraphics');
goog.require('goog.graphics.LinearGradient');
goog.require('goog.graphics.Path');
goog.require('goog.graphics.SolidFill');
goog.require('goog.graphics.Stroke');
goog.require('goog.graphics.SvgEllipseElement');
goog.require('goog.graphics.SvgGroupElement');
goog.require('goog.graphics.SvgImageElement');
goog.require('goog.graphics.SvgPathElement');
goog.require('goog.graphics.SvgRectElement');
goog.require('goog.graphics.SvgTextElement');
goog.require('goog.math');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* A Graphics implementation for drawing using SVG.
* @param {string|number} width The width in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {string|number} height The height in pixels. Strings
* expressing percentages of parent with (e.g. '80%') are also accepted.
* @param {?number=} opt_coordWidth The coordinate width - if
* omitted or null, defaults to same as width.
* @param {?number=} opt_coordHeight The coordinate height - if
* omitted or null, defaults to same as height.
* @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
* document we want to render in.
* @constructor
* @extends {goog.graphics.AbstractGraphics}
*/
goog.graphics.SvgGraphics = function(width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper) {
goog.graphics.AbstractGraphics.call(this, width, height,
opt_coordWidth, opt_coordHeight,
opt_domHelper);
/**
* Map from def key to id of def root element.
* Defs are global "defines" of svg that are used to share common attributes,
* for example gradients.
* @type {Object}
* @private
*/
this.defs_ = {};
/**
* Whether to manually implement viewBox by using a coordinate transform.
* As of 1/11/08 this is necessary for Safari 3 but not for the nightly
* WebKit build. Apply to webkit versions < 526. 525 is the
* last version used by Safari 3.1.
* @type {boolean}
* @private
*/
this.useManualViewbox_ = goog.userAgent.WEBKIT &&
!goog.userAgent.isVersion(526);
/**
* Event handler.
* @type {goog.events.EventHandler}
* @private
*/
this.handler_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.graphics.SvgGraphics, goog.graphics.AbstractGraphics);
/**
* The SVG namespace URN
* @private
* @type {string}
*/
goog.graphics.SvgGraphics.SVG_NS_ = 'http://www.w3.org/2000/svg';
/**
* The name prefix for def entries
* @private
* @type {string}
*/
goog.graphics.SvgGraphics.DEF_ID_PREFIX_ = '_svgdef_';
/**
* The next available unique identifier for a def entry.
* This is a static variable, so that when multiple graphics are used in one
* document, the same def id can not be re-defined by another SvgGraphics.
* @type {number}
* @private
*/
goog.graphics.SvgGraphics.nextDefId_ = 0;
/**
* Svg element for definitions for other elements, e.g. linear gradients.
* @type {Element}
* @private
*/
goog.graphics.SvgGraphics.prototype.defsElement_;
/**
* Creates an SVG element. Used internally and by different SVG classes.
* @param {string} tagName The type of element to create.
* @param {Object=} opt_attributes Map of name-value pairs for attributes.
* @return {Element} The created element.
* @private
*/
goog.graphics.SvgGraphics.prototype.createSvgElement_ = function(tagName,
opt_attributes) {
var element = this.dom_.getDocument().createElementNS(
goog.graphics.SvgGraphics.SVG_NS_, tagName);
if (opt_attributes) {
this.setElementAttributes(element, opt_attributes);
}
return element;
};
/**
* Sets properties to an SVG element. Used internally and by different
* SVG elements.
* @param {Element} element The svg element.
* @param {Object} attributes Map of name-value pairs for attributes.
*/
goog.graphics.SvgGraphics.prototype.setElementAttributes = function(element,
attributes) {
for (var key in attributes) {
element.setAttribute(key, attributes[key]);
}
};
/**
* Appends an element.
*
* @param {goog.graphics.Element} element The element wrapper.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
* @private
*/
goog.graphics.SvgGraphics.prototype.append_ = function(element, opt_group) {
var parent = opt_group || this.canvasElement;
parent.getElement().appendChild(element.getElement());
};
/**
* Sets the fill of the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element wrapper.
* @param {goog.graphics.Fill?} fill The fill object.
* @override
*/
goog.graphics.SvgGraphics.prototype.setElementFill = function(element, fill) {
var svgElement = element.getElement();
if (fill instanceof goog.graphics.SolidFill) {
svgElement.setAttribute('fill', fill.getColor());
svgElement.setAttribute('fill-opacity', fill.getOpacity());
} else if (fill instanceof goog.graphics.LinearGradient) {
// create a def key which is just a concat of all the relevant fields
var defKey = 'lg-' +
fill.getX1() + '-' + fill.getY1() + '-' +
fill.getX2() + '-' + fill.getY2() + '-' +
fill.getColor1() + '-' + fill.getColor2();
// It seems that the SVG version accepts opacity where the VML does not
var id = this.getDef(defKey);
if (!id) { // No def for this yet, create it
// Create the gradient def entry (only linear gradient are supported)
var gradient = this.createSvgElement_('linearGradient', {
'x1': fill.getX1(),
'y1': fill.getY1(),
'x2': fill.getX2(),
'y2': fill.getY2(),
'gradientUnits': 'userSpaceOnUse'
});
var gstyle = 'stop-color:' + fill.getColor1();
if (goog.isNumber(fill.getOpacity1())) {
gstyle += ';stop-opacity:' + fill.getOpacity1();
}
var stop1 = this.createSvgElement_(
'stop', {'offset': '0%', 'style': gstyle});
gradient.appendChild(stop1);
// LinearGradients don't have opacity in VML so implement that before
// enabling the following code.
// if (fill.getOpacity() != null) {
// gstyles += 'opacity:' + fill.getOpacity() + ';'
// }
gstyle = 'stop-color:' + fill.getColor2();
if (goog.isNumber(fill.getOpacity2())) {
gstyle += ';stop-opacity:' + fill.getOpacity2();
}
var stop2 = this.createSvgElement_(
'stop', {'offset': '100%', 'style': gstyle});
gradient.appendChild(stop2);
// LinearGradients don't have opacity in VML so implement that before
// enabling the following code.
// if (fill.getOpacity() != null) {
// gstyles += 'opacity:' + fill.getOpacity() + ';'
// }
id = this.addDef(defKey, gradient);
}
// Link element to linearGradient definition
svgElement.setAttribute('fill', 'url(#' + id + ')');
} else {
svgElement.setAttribute('fill', 'none');
}
};
/**
* Sets the stroke of the given element.
* @param {goog.graphics.StrokeAndFillElement} element The element wrapper.
* @param {goog.graphics.Stroke?} stroke The stroke object.
* @override
*/
goog.graphics.SvgGraphics.prototype.setElementStroke = function(element,
stroke) {
var svgElement = element.getElement();
if (stroke) {
svgElement.setAttribute('stroke', stroke.getColor());
var width = stroke.getWidth();
if (goog.isString(width) && width.indexOf('px') != -1) {
svgElement.setAttribute('stroke-width',
parseFloat(width) / this.getPixelScaleX());
} else {
svgElement.setAttribute('stroke-width', width);
}
} else {
svgElement.setAttribute('stroke', 'none');
}
};
/**
* Set the transformation of an element.
* @param {goog.graphics.Element} element The element wrapper.
* @param {number} x The x coordinate of the translation transform.
* @param {number} y The y coordinate of the translation transform.
* @param {number} angle The angle of the rotation transform.
* @param {number} centerX The horizontal center of the rotation transform.
* @param {number} centerY The vertical center of the rotation transform.
* @override
*/
goog.graphics.SvgGraphics.prototype.setElementTransform = function(element, x,
y, angle, centerX, centerY) {
element.getElement().setAttribute('transform', 'translate(' + x + ',' + y +
') rotate(' + angle + ' ' + centerX + ' ' + centerY + ')');
};
/**
* Creates the DOM representation of the graphics area.
* @override
*/
goog.graphics.SvgGraphics.prototype.createDom = function() {
// Set up the standard attributes.
var attributes = {
'width': this.width,
'height': this.height,
'overflow': 'hidden'
};
var svgElement = this.createSvgElement_('svg', attributes);
var groupElement = this.createSvgElement_('g');
this.defsElement_ = this.createSvgElement_('defs');
this.canvasElement = new goog.graphics.SvgGroupElement(groupElement, this);
svgElement.appendChild(this.defsElement_);
svgElement.appendChild(groupElement);
// Use the svgElement as the root element.
this.setElementInternal(svgElement);
// Set up the coordinate system.
this.setViewBox_();
};
/**
* Changes the coordinate system position.
* @param {number} left The coordinate system left bound.
* @param {number} top The coordinate system top bound.
* @override
*/
goog.graphics.SvgGraphics.prototype.setCoordOrigin = function(left, top) {
this.coordLeft = left;
this.coordTop = top;
this.setViewBox_();
};
/**
* Changes the coordinate size.
* @param {number} coordWidth The coordinate width.
* @param {number} coordHeight The coordinate height.
* @override
*/
goog.graphics.SvgGraphics.prototype.setCoordSize = function(coordWidth,
coordHeight) {
goog.graphics.SvgGraphics.superClass_.setCoordSize.apply(
this, arguments);
this.setViewBox_();
};
/**
* @return {string} The view box string.
* @private
*/
goog.graphics.SvgGraphics.prototype.getViewBox_ = function() {
return this.coordLeft + ' ' + this.coordTop + ' ' +
(this.coordWidth ? this.coordWidth + ' ' + this.coordHeight : '');
};
/**
* Sets up the view box.
* @private
*/
goog.graphics.SvgGraphics.prototype.setViewBox_ = function() {
if (this.coordWidth || this.coordLeft || this.coordTop) {
this.getElement().setAttribute('preserveAspectRatio', 'none');
if (this.useManualViewbox_) {
this.updateManualViewBox_();
} else {
this.getElement().setAttribute('viewBox', this.getViewBox_());
}
}
};
/**
* Updates the transform of the root element to fake a viewBox. Should only
* be called when useManualViewbox_ is set.
* @private
*/
goog.graphics.SvgGraphics.prototype.updateManualViewBox_ = function() {
if (!this.isInDocument() ||
!(this.coordWidth || this.coordLeft || !this.coordTop)) {
return;
}
var size = this.getPixelSize();
if (size.width == 0) {
// In Safari, invisible SVG is sometimes shown. Explicitly hide it.
this.getElement().style.visibility = 'hidden';
return;
}
this.getElement().style.visibility = '';
var offsetX = - this.coordLeft;
var offsetY = - this.coordTop;
var scaleX = size.width / this.coordWidth;
var scaleY = size.height / this.coordHeight;
this.canvasElement.getElement().setAttribute('transform',
'scale(' + scaleX + ' ' + scaleY + ') ' +
'translate(' + offsetX + ' ' + offsetY + ')');
};
/**
* Change the size of the canvas.
* @param {number} pixelWidth The width in pixels.
* @param {number} pixelHeight The height in pixels.
* @override
*/
goog.graphics.SvgGraphics.prototype.setSize = function(pixelWidth,
pixelHeight) {
goog.style.setSize(this.getElement(), pixelWidth, pixelHeight);
};
/** @override */
goog.graphics.SvgGraphics.prototype.getPixelSize = function() {
if (!goog.userAgent.GECKO) {
return this.isInDocument() ?
goog.style.getSize(this.getElement()) :
goog.base(this, 'getPixelSize');
}
// In Gecko, goog.style.getSize does not work for SVG elements. We have to
// compute the size manually if it is percentage based.
var width = this.width;
var height = this.height;
var computeWidth = goog.isString(width) && width.indexOf('%') != -1;
var computeHeight = goog.isString(height) && height.indexOf('%') != -1;
if (!this.isInDocument() && (computeWidth || computeHeight)) {
return null;
}
var parent;
var parentSize;
if (computeWidth) {
parent = /** @type {Element} */ (this.getElement().parentNode);
parentSize = goog.style.getSize(parent);
width = parseFloat(/** @type {string} */ (width)) * parentSize.width / 100;
}
if (computeHeight) {
parent = parent || /** @type {Element} */ (this.getElement().parentNode);
parentSize = parentSize || goog.style.getSize(parent);
height = parseFloat(/** @type {string} */ (height)) * parentSize.height /
100;
}
return new goog.math.Size(/** @type {number} */ (width),
/** @type {number} */ (height));
};
/**
* Remove all drawing elements from the graphics.
* @override
*/
goog.graphics.SvgGraphics.prototype.clear = function() {
this.canvasElement.clear();
goog.dom.removeChildren(this.defsElement_);
this.defs_ = {};
};
/**
* Draw an ellipse.
*
* @param {number} cx Center X coordinate.
* @param {number} cy Center Y coordinate.
* @param {number} rx Radius length for the x-axis.
* @param {number} ry Radius length for the y-axis.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.EllipseElement} The newly created element.
* @override
*/
goog.graphics.SvgGraphics.prototype.drawEllipse = function(
cx, cy, rx, ry, stroke, fill, opt_group) {
var element = this.createSvgElement_('ellipse',
{'cx': cx, 'cy': cy, 'rx': rx, 'ry': ry});
var wrapper = new goog.graphics.SvgEllipseElement(element, this, stroke,
fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw a rectangle.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of rectangle.
* @param {number} height Height of rectangle.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.RectElement} The newly created element.
* @override
*/
goog.graphics.SvgGraphics.prototype.drawRect = function(x, y, width, height,
stroke, fill, opt_group) {
var element = this.createSvgElement_('rect',
{'x': x, 'y': y, 'width': width, 'height': height});
var wrapper = new goog.graphics.SvgRectElement(element, this, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw an image.
*
* @param {number} x X coordinate (left).
* @param {number} y Y coordinate (top).
* @param {number} width Width of the image.
* @param {number} height Height of the image.
* @param {string} src The source fo the image.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.ImageElement} The newly created image wrapped in a
* rectangle element.
*/
goog.graphics.SvgGraphics.prototype.drawImage = function(x, y, width, height,
src, opt_group) {
var element = this.createSvgElement_('image', {
'x': x,
'y': y,
'width': width,
'height': height,
'image-rendering': 'optimizeQuality',
'preserveAspectRatio': 'none'
});
element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src);
var wrapper = new goog.graphics.SvgImageElement(element, this);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw a text string vertically centered on a given line.
*
* @param {string} text The text to draw.
* @param {number} x1 X coordinate of start of line.
* @param {number} y1 Y coordinate of start of line.
* @param {number} x2 X coordinate of end of line.
* @param {number} y2 Y coordinate of end of line.
* @param {string} align Horizontal alignment: left (default), center, right.
* @param {goog.graphics.Font} font Font describing the font properties.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.TextElement} The newly created element.
* @override
*/
goog.graphics.SvgGraphics.prototype.drawTextOnLine = function(
text, x1, y1, x2, y2, align, font, stroke, fill, opt_group) {
var angle = Math.round(goog.math.angle(x1, y1, x2, y2));
var dx = x2 - x1;
var dy = y2 - y1;
var lineLength = Math.round(Math.sqrt(dx * dx + dy * dy)); // Length of line
// SVG baseline is on the glyph's base line. We estimate it as 85% of the
// font height. This is just a rough estimate, but do not have a better way.
var fontSize = font.size;
var attributes = {'font-family': font.family, 'font-size': fontSize};
var baseline = Math.round(fontSize * 0.85);
var textY = Math.round(y1 - (fontSize / 2) + baseline);
var textX = x1;
if (align == 'center') {
textX += Math.round(lineLength / 2);
attributes['text-anchor'] = 'middle';
} else if (align == 'right') {
textX += lineLength;
attributes['text-anchor'] = 'end';
}
attributes['x'] = textX;
attributes['y'] = textY;
if (font.bold) {
attributes['font-weight'] = 'bold';
}
if (font.italic) {
attributes['font-style'] = 'italic';
}
if (angle != 0) {
attributes['transform'] = 'rotate(' + angle + ' ' + x1 + ' ' + y1 + ')';
}
var element = this.createSvgElement_('text', attributes);
element.appendChild(this.dom_.getDocument().createTextNode(text));
// Bypass a Firefox-Mac bug where text fill is ignored. If text has no stroke,
// set a stroke, otherwise the text will not be visible.
if (stroke == null && goog.userAgent.GECKO && goog.userAgent.MAC) {
var color = 'black';
// For solid fills, use the fill color
if (fill instanceof goog.graphics.SolidFill) {
color = fill.getColor();
}
stroke = new goog.graphics.Stroke(1, color);
}
var wrapper = new goog.graphics.SvgTextElement(element, this, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Draw a path.
*
* @param {!goog.graphics.Path} path The path object to draw.
* @param {goog.graphics.Stroke?} stroke Stroke object describing the
* stroke.
* @param {goog.graphics.Fill?} fill Fill object describing the fill.
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.PathElement} The newly created element.
* @override
*/
goog.graphics.SvgGraphics.prototype.drawPath = function(
path, stroke, fill, opt_group) {
var element = this.createSvgElement_('path',
{'d': goog.graphics.SvgGraphics.getSvgPath(path)});
var wrapper = new goog.graphics.SvgPathElement(element, this, stroke, fill);
this.append_(wrapper, opt_group);
return wrapper;
};
/**
* Returns a string representation of a logical path suitable for use in
* an SVG element.
*
* @param {goog.graphics.Path} path The logical path.
* @return {string} The SVG path representation.
*/
goog.graphics.SvgGraphics.getSvgPath = function(path) {
var list = [];
path.forEachSegment(function(segment, args) {
switch (segment) {
case goog.graphics.Path.Segment.MOVETO:
list.push('M');
Array.prototype.push.apply(list, args);
break;
case goog.graphics.Path.Segment.LINETO:
list.push('L');
Array.prototype.push.apply(list, args);
break;
case goog.graphics.Path.Segment.CURVETO:
list.push('C');
Array.prototype.push.apply(list, args);
break;
case goog.graphics.Path.Segment.ARCTO:
var extent = args[3];
var toAngle = args[2] + extent;
list.push('A', args[0], args[1],
0, Math.abs(extent) > 180 ? 1 : 0, extent > 0 ? 1 : 0,
args[4], args[5]);
break;
case goog.graphics.Path.Segment.CLOSE:
list.push('Z');
break;
}
});
return list.join(' ');
};
/**
* Create an empty group of drawing elements.
*
* @param {goog.graphics.GroupElement=} opt_group The group wrapper element
* to append to. If not specified, appends to the main canvas.
*
* @return {goog.graphics.GroupElement} The newly created group.
* @override
*/
goog.graphics.SvgGraphics.prototype.createGroup = function(opt_group) {
var element = this.createSvgElement_('g');
var parent = opt_group || this.canvasElement;
parent.getElement().appendChild(element);
return new goog.graphics.SvgGroupElement(element, this);
};
/**
* Measure and return the width (in pixels) of a given text string.
* Text measurement is needed to make sure a text can fit in the allocated area.
* The way text length is measured is by writing it into a div that is after
* the visible area, measure the div width, and immediatly erase the written
* value.
*
* @param {string} text The text string to measure.
* @param {goog.graphics.Font} font The font object describing the font style.
* @override
*/
goog.graphics.SvgGraphics.prototype.getTextWidth = function(text, font) {
// TODO(user) Implement
};
/**
* Adds a defintion of an element to the global definitions.
* @param {string} defKey This is a key that should be unique in a way that
* if two definitions are equal the should have the same key.
* @param {Element} defElement DOM element to add as a definition. It must
* have an id attribute set.
* @return {string} The assigned id of the defElement.
*/
goog.graphics.SvgGraphics.prototype.addDef = function(defKey, defElement) {
if (defKey in this.defs_) {
return this.defs_[defKey];
}
var id = goog.graphics.SvgGraphics.DEF_ID_PREFIX_ +
goog.graphics.SvgGraphics.nextDefId_++;
defElement.setAttribute('id', id);
this.defs_[defKey] = id;
// Add the def defElement of the defs list.
var defs = this.defsElement_;
defs.appendChild(defElement);
return id;
};
/**
* Returns the id of a definition element.
* @param {string} defKey This is a key that should be unique in a way that
* if two definitions are equal the should have the same key.
* @return {?string} The id of the found definition element or null if
* not found.
*/
goog.graphics.SvgGraphics.prototype.getDef = function(defKey) {
return defKey in this.defs_ ? this.defs_[defKey] : null;
};
/**
* Removes a definition of an elemnt from the global definitions.
* @param {string} defKey This is a key that should be unique in a way that
* if two definitions are equal they should have the same key.
*/
goog.graphics.SvgGraphics.prototype.removeDef = function(defKey) {
var id = this.getDef(defKey);
if (id) {
var element = this.dom_.getElement(id);
this.defsElement_.removeChild(element);
delete this.defs_[defKey];
}
};
/** @override */
goog.graphics.SvgGraphics.prototype.enterDocument = function() {
var oldPixelSize = this.getPixelSize();
goog.graphics.SvgGraphics.superClass_.enterDocument.call(this);
// Dispatch a resize if this is the first time the size value is accurate.
if (!oldPixelSize) {
this.dispatchEvent(goog.events.EventType.RESIZE);
}
// For percentage based heights, listen for changes to size.
if (this.useManualViewbox_) {
var width = this.width;
var height = this.height;
if (typeof width == 'string' && width.indexOf('%') != -1 &&
typeof height == 'string' && height.indexOf('%') != -1) {
// SVG elements don't behave well with respect to size events, so we
// resort to polling.
this.handler_.listen(goog.graphics.SvgGraphics.getResizeCheckTimer_(),
goog.Timer.TICK, this.updateManualViewBox_);
}
this.updateManualViewBox_();
}
};
/** @override */
goog.graphics.SvgGraphics.prototype.exitDocument = function() {
goog.graphics.SvgGraphics.superClass_.exitDocument.call(this);
// Stop polling.
if (this.useManualViewbox_) {
this.handler_.unlisten(goog.graphics.SvgGraphics.getResizeCheckTimer_(),
goog.Timer.TICK, this.updateManualViewBox_);
}
};
/**
* Disposes of the component by removing event handlers, detacing DOM nodes from
* the document body, and removing references to them.
* @override
* @protected
*/
goog.graphics.SvgGraphics.prototype.disposeInternal = function() {
delete this.defs_;
delete this.defsElement_;
delete this.canvasElement;
goog.graphics.SvgGraphics.superClass_.disposeInternal.call(this);
};
/**
* The centralized resize checking timer.
* @type {goog.Timer|undefined}
* @private
*/
goog.graphics.SvgGraphics.resizeCheckTimer_;
/**
* @return {goog.Timer} The centralized timer object used for interval timing.
* @private
*/
goog.graphics.SvgGraphics.getResizeCheckTimer_ = function() {
if (!goog.graphics.SvgGraphics.resizeCheckTimer_) {
goog.graphics.SvgGraphics.resizeCheckTimer_ = new goog.Timer(400);
goog.graphics.SvgGraphics.resizeCheckTimer_.start();
}
return /** @type {goog.Timer} */ (
goog.graphics.SvgGraphics.resizeCheckTimer_);
};
/** @override */
goog.graphics.SvgGraphics.prototype.isDomClonable = function() {
return true;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Represents a gradient to be used with a Graphics implementor.
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.graphics.LinearGradient');
goog.require('goog.asserts');
goog.require('goog.graphics.Fill');
/**
* Creates an immutable linear gradient fill object.
*
* @param {number} x1 Start X position of the gradient.
* @param {number} y1 Start Y position of the gradient.
* @param {number} x2 End X position of the gradient.
* @param {number} y2 End Y position of the gradient.
* @param {string} color1 Start color of the gradient.
* @param {string} color2 End color of the gradient.
* @param {?number=} opt_opacity1 Start opacity of the gradient, both or neither
* of opt_opacity1 and opt_opacity2 have to be set.
* @param {?number=} opt_opacity2 End opacity of the gradient.
* @constructor
* @extends {goog.graphics.Fill}
*/
goog.graphics.LinearGradient =
function(x1, y1, x2, y2, color1, color2, opt_opacity1, opt_opacity2) {
/**
* Start X position of the gradient.
* @type {number}
* @private
*/
this.x1_ = x1;
/**
* Start Y position of the gradient.
* @type {number}
* @private
*/
this.y1_ = y1;
/**
* End X position of the gradient.
* @type {number}
* @private
*/
this.x2_ = x2;
/**
* End Y position of the gradient.
* @type {number}
* @private
*/
this.y2_ = y2;
/**
* Start color of the gradient.
* @type {string}
* @private
*/
this.color1_ = color1;
/**
* End color of the gradient.
* @type {string}
* @private
*/
this.color2_ = color2;
goog.asserts.assert(
goog.isNumber(opt_opacity1) == goog.isNumber(opt_opacity2),
'Both or neither of opt_opacity1 and opt_opacity2 have to be set.');
/**
* Start opacity of the gradient.
* @type {?number}
* @private
*/
this.opacity1_ = goog.isDef(opt_opacity1) ? opt_opacity1 : null;
/**
* End opacity of the gradient.
* @type {?number}
* @private
*/
this.opacity2_ = goog.isDef(opt_opacity2) ? opt_opacity2 : null;
};
goog.inherits(goog.graphics.LinearGradient, goog.graphics.Fill);
/**
* @return {number} The start X position of the gradient.
*/
goog.graphics.LinearGradient.prototype.getX1 = function() {
return this.x1_;
};
/**
* @return {number} The start Y position of the gradient.
*/
goog.graphics.LinearGradient.prototype.getY1 = function() {
return this.y1_;
};
/**
* @return {number} The end X position of the gradient.
*/
goog.graphics.LinearGradient.prototype.getX2 = function() {
return this.x2_;
};
/**
* @return {number} The end Y position of the gradient.
*/
goog.graphics.LinearGradient.prototype.getY2 = function() {
return this.y2_;
};
/**
* @return {string} The start color of the gradient.
*/
goog.graphics.LinearGradient.prototype.getColor1 = function() {
return this.color1_;
};
/**
* @return {string} The end color of the gradient.
*/
goog.graphics.LinearGradient.prototype.getColor2 = function() {
return this.color2_;
};
/**
* @return {?number} The start opacity of the gradient.
*/
goog.graphics.LinearGradient.prototype.getOpacity1 = function() {
return this.opacity1_;
};
/**
* @return {?number} The end opacity of the gradient.
*/
goog.graphics.LinearGradient.prototype.getOpacity2 = function() {
return this.opacity2_;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element for graphics groups.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.GroupElement');
goog.require('goog.graphics.Element');
/**
* Interface for a graphics group element.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.graphics.Element}
*/
goog.graphics.GroupElement = function(element, graphics) {
goog.graphics.Element.call(this, element, graphics);
};
goog.inherits(goog.graphics.GroupElement, goog.graphics.Element);
/**
* Remove all drawing elements from the group.
*/
goog.graphics.GroupElement.prototype.clear = goog.abstractMethod;
/**
* Set the size of the group element.
* @param {number|string} width The width of the group element.
* @param {number|string} height The height of the group element.
*/
goog.graphics.GroupElement.prototype.setSize = goog.abstractMethod;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A thin wrapper around the DOM element returned from
* the different draw methods of the graphics implementation, and
* all interfaces that the various element types support.
* @author arv@google.com (Erik Arvidsson)
* @author yoah@google.com (Yoah Bar-David)
*/
goog.provide('goog.graphics.Element');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.graphics.AffineTransform');
goog.require('goog.math');
/**
* Base class for a thin wrapper around the DOM element returned from
* the different draw methods of the graphics.
* You should not construct objects from this constructor. The graphics
* will return the object for you.
* @param {Element} element The DOM element to wrap.
* @param {goog.graphics.AbstractGraphics} graphics The graphics creating
* this element.
* @constructor
* @extends {goog.events.EventTarget}
* @suppress {visibility} Accessing private field of superclass (see TODO).
*/
goog.graphics.Element = function(element, graphics) {
goog.events.EventTarget.call(this);
this.element_ = element;
this.graphics_ = graphics;
// Overloading EventTarget field to state that this is not a custom event.
// TODO(user) Should be handled in EventTarget.js (see bug 846824).
this.customEvent_ = false;
};
goog.inherits(goog.graphics.Element, goog.events.EventTarget);
/**
* The graphics object that contains this element.
* @type {goog.graphics.AbstractGraphics?}
* @private
*/
goog.graphics.Element.prototype.graphics_ = null;
/**
* The native browser element this class wraps.
* @type {Element}
* @private
*/
goog.graphics.Element.prototype.element_ = null;
/**
* The transformation applied to this element.
* @type {goog.graphics.AffineTransform?}
* @private
*/
goog.graphics.Element.prototype.transform_ = null;
/**
* Returns the underlying object.
* @return {Element} The underlying element.
*/
goog.graphics.Element.prototype.getElement = function() {
return this.element_;
};
/**
* Returns the graphics.
* @return {goog.graphics.AbstractGraphics} The graphics that created the
* element.
*/
goog.graphics.Element.prototype.getGraphics = function() {
return this.graphics_;
};
/**
* Set the transformation of the element.
* @param {number} x The x coordinate of the translation transform.
* @param {number} y The y coordinate of the translation transform.
* @param {number} rotate The angle of the rotation transform.
* @param {number} centerX The horizontal center of the rotation transform.
* @param {number} centerY The vertical center of the rotation transform.
*/
goog.graphics.Element.prototype.setTransformation = function(x, y, rotate,
centerX, centerY) {
// TODO(robbyw): Add skew and scale.
this.transform_ = goog.graphics.AffineTransform.getRotateInstance(
goog.math.toRadians(rotate), centerX, centerY).translate(x, y);
this.getGraphics().setElementTransform(this, x, y, rotate, centerX, centerY);
};
/**
* @return {goog.graphics.AffineTransform} The transformation applied to
* this element.
*/
goog.graphics.Element.prototype.getTransform = function() {
return this.transform_ ? this.transform_.clone() :
new goog.graphics.AffineTransform();
};
/** @override */
goog.graphics.Element.prototype.addEventListener = function(
type, handler, opt_capture, opt_handlerScope) {
goog.events.listen(this.element_, type, handler, opt_capture,
opt_handlerScope);
};
/** @override */
goog.graphics.Element.prototype.removeEventListener = function(
type, handler, opt_capture, opt_handlerScope) {
goog.events.unlisten(this.element_, type, handler, opt_capture,
opt_handlerScope);
};
/** @override */
goog.graphics.Element.prototype.disposeInternal = function() {
goog.graphics.Element.superClass_.disposeInternal.call(this);
goog.events.removeAll(this.element_);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Topic-based publish/subscribe channel implementation.
*
*/
goog.provide('goog.pubsub.PubSub');
goog.require('goog.Disposable');
goog.require('goog.array');
/**
* Topic-based publish/subscribe channel. Maintains a map of topics to
* subscriptions. When a message is published to a topic, all functions
* subscribed to that topic are invoked in the order they were added.
* Uncaught errors abort publishing.
*
* Topics may be identified by any nonempty string, <strong>except</strong>
* strings corresponding to native Object properties, e.g. "constructor",
* "toString", "hasOwnProperty", etc.
*
* @constructor
* @extends {goog.Disposable}
*/
goog.pubsub.PubSub = function() {
goog.Disposable.call(this);
this.subscriptions_ = [];
this.topics_ = {};
};
goog.inherits(goog.pubsub.PubSub, goog.Disposable);
/**
* Sparse array of subscriptions. Each subscription is represented by a tuple
* comprising a topic identifier, a function, and an optional context object.
* Each tuple occupies three consecutive positions in the array, with the topic
* identifier at index n, the function at index (n + 1), the context object at
* index (n + 2), the next topic at index (n + 3), etc. (This representation
* minimizes the number of object allocations and has been shown to be faster
* than an array of objects with three key-value pairs or three parallel arrays,
* especially on IE.) Once a subscription is removed via {@link #unsubscribe}
* or {@link #unsubscribeByKey}, the three corresponding array elements are
* deleted, and never reused. This means the total number of subscriptions
* during the lifetime of the pubsub channel is limited by the maximum length
* of a JavaScript array to (2^32 - 1) / 3 = 1,431,655,765 subscriptions, which
* should suffice for most applications.
*
* @type {!Array}
* @private
*/
goog.pubsub.PubSub.prototype.subscriptions_;
/**
* The next available subscription key. Internally, this is an index into the
* sparse array of subscriptions.
*
* @type {number}
* @private
*/
goog.pubsub.PubSub.prototype.key_ = 1;
/**
* Map of topics to arrays of subscription keys.
*
* @type {!Object.<!Array.<number>>}
* @private
*/
goog.pubsub.PubSub.prototype.topics_;
/**
* Array of subscription keys pending removal once publishing is done.
*
* @type {Array.<number>}
* @private
*/
goog.pubsub.PubSub.prototype.pendingKeys_;
/**
* Lock to prevent the removal of subscriptions during publishing. Incremented
* at the beginning of {@link #publish}, and decremented at the end.
*
* @type {number}
* @private
*/
goog.pubsub.PubSub.prototype.publishDepth_ = 0;
/**
* Subscribes a function to a topic. The function is invoked as a method on
* the given {@code opt_context} object, or in the global scope if no context
* is specified. Subscribing the same function to the same topic multiple
* times will result in multiple function invocations while publishing.
* Returns a subscription key that can be used to unsubscribe the function from
* the topic via {@link #unsubscribeByKey}.
*
* @param {string} topic Topic to subscribe to.
* @param {Function} fn Function to be invoked when a message is published to
* the given topic.
* @param {Object=} opt_context Object in whose context the function is to be
* called (the global scope if none).
* @return {number} Subscription key.
*/
goog.pubsub.PubSub.prototype.subscribe = function(topic, fn, opt_context) {
var keys = this.topics_[topic];
if (!keys) {
// First subscription to this topic; initialize subscription key array.
keys = this.topics_[topic] = [];
}
// Push the tuple representing the subscription onto the subscription array.
var key = this.key_;
this.subscriptions_[key] = topic;
this.subscriptions_[key + 1] = fn;
this.subscriptions_[key + 2] = opt_context;
this.key_ = key + 3;
// Push the subscription key onto the list of subscriptions for the topic.
keys.push(key);
// Return the subscription key.
return key;
};
/**
* Subscribes a single-use function to a topic. The function is invoked as a
* method on the given {@code opt_context} object, or in the global scope if
* no context is specified, and is then unsubscribed. Returns a subscription
* key that can be used to unsubscribe the function from the topic via
* {@link #unsubscribeByKey}.
*
* @param {string} topic Topic to subscribe to.
* @param {Function} fn Function to be invoked once and then unsubscribed when
* a message is published to the given topic.
* @param {Object=} opt_context Object in whose context the function is to be
* called (the global scope if none).
* @return {number} Subscription key.
*/
goog.pubsub.PubSub.prototype.subscribeOnce = function(topic, fn, opt_context) {
// Behold the power of lexical closures!
var key = this.subscribe(topic, function(var_args) {
fn.apply(opt_context, arguments);
this.unsubscribeByKey(key);
}, this);
return key;
};
/**
* Unsubscribes a function from a topic. Only deletes the first match found.
* Returns a Boolean indicating whether a subscription was removed.
*
* @param {string} topic Topic to unsubscribe from.
* @param {Function} fn Function to unsubscribe.
* @param {Object=} opt_context Object in whose context the function was to be
* called (the global scope if none).
* @return {boolean} Whether a matching subscription was removed.
*/
goog.pubsub.PubSub.prototype.unsubscribe = function(topic, fn, opt_context) {
var keys = this.topics_[topic];
if (keys) {
// Find the subscription key for the given combination of topic, function,
// and context object.
var subscriptions = this.subscriptions_;
var key = goog.array.find(keys, function(k) {
return subscriptions[k + 1] == fn && subscriptions[k + 2] == opt_context;
});
// Zero is not a valid key.
if (key) {
return this.unsubscribeByKey(/** @type {number} */ (key));
}
}
return false;
};
/**
* Removes a subscription based on the key returned by {@link #subscribe}.
* No-op if no matching subscription is found. Returns a Boolean indicating
* whether a subscription was removed.
*
* @param {number} key Subscription key.
* @return {boolean} Whether a matching subscription was removed.
*/
goog.pubsub.PubSub.prototype.unsubscribeByKey = function(key) {
if (this.publishDepth_ != 0) {
// Defer removal until after publishing is complete.
if (!this.pendingKeys_) {
this.pendingKeys_ = [];
}
this.pendingKeys_.push(key);
return false;
}
var topic = this.subscriptions_[key];
if (topic) {
// Subscription tuple found.
var keys = this.topics_[topic];
if (keys) {
goog.array.remove(keys, key);
}
delete this.subscriptions_[key];
delete this.subscriptions_[key + 1];
delete this.subscriptions_[key + 2];
}
return !!topic;
};
/**
* Publishes a message to a topic. Calls functions subscribed to the topic in
* the order in which they were added, passing all arguments along. If any of
* the functions throws an uncaught error, publishing is aborted.
*
* @param {string} topic Topic to publish to.
* @param {...*} var_args Arguments that are applied to each subscription
* function.
* @return {boolean} Whether any subscriptions were called.
*/
goog.pubsub.PubSub.prototype.publish = function(topic, var_args) {
var keys = this.topics_[topic];
if (keys) {
// We must lock subscriptions and remove them at the end, so we don't
// adversely affect the performance of the common case by cloning the key
// array.
this.publishDepth_++;
// For each key in the list of subscription keys for the topic, apply the
// function to the arguments in the appropriate context. The length of the
// array mush be fixed during the iteration, since subscribers may add new
// subscribers during publishing.
var args = goog.array.slice(arguments, 1);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
this.subscriptions_[key + 1].apply(this.subscriptions_[key + 2], args);
}
// Unlock subscriptions.
this.publishDepth_--;
if (this.pendingKeys_ && this.publishDepth_ == 0) {
var pendingKey;
while ((pendingKey = this.pendingKeys_.pop())) {
this.unsubscribeByKey(pendingKey);
}
}
// At least one subscriber was called.
return i != 0;
}
// No subscribers were found.
return false;
};
/**
* Clears the subscription list for a topic, or all topics if unspecified.
* @param {string=} opt_topic Topic to clear (all topics if unspecified).
*/
goog.pubsub.PubSub.prototype.clear = function(opt_topic) {
if (opt_topic) {
var keys = this.topics_[opt_topic];
if (keys) {
goog.array.forEach(keys, this.unsubscribeByKey, this);
delete this.topics_[opt_topic];
}
} else {
this.subscriptions_.length = 0;
this.topics_ = {};
// We don't reset key_ on purpose, because we want subscription keys to be
// unique throughout the lifetime of the application. Reusing subscription
// keys could lead to subtle errors in client code.
}
};
/**
* Returns the number of subscriptions to the given topic (or all topics if
* unspecified).
* @param {string=} opt_topic The topic (all topics if unspecified).
* @return {number} Number of subscriptions to the topic.
*/
goog.pubsub.PubSub.prototype.getCount = function(opt_topic) {
if (opt_topic) {
var keys = this.topics_[opt_topic];
return keys ? keys.length : 0;
}
var count = 0;
for (var topic in this.topics_) {
count += this.getCount(topic);
}
return count;
};
/** @override */
goog.pubsub.PubSub.prototype.disposeInternal = function() {
goog.pubsub.PubSub.superClass_.disposeInternal.call(this);
delete this.subscriptions_;
delete this.topics_;
delete this.pendingKeys_;
};
| JavaScript |
window.onload = function() {
myHeight = new fx.Height('nav', {duration: 400});
myHeight.hide();
} | JavaScript |
/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
10/24/2005
v(1.0.2)
*/
//base
var fx = new Object();
fx.Base = function(){};
fx.Base.prototype = {
setOptions: function(options) {
this.options = {
duration: 500,
onComplete: ''
}
Object.extend(this.options, options || {});
},
go: function() {
this.duration = this.options.duration;
this.startTime = (new Date).getTime();
this.timer = setInterval (this.step.bind(this), 13);
},
step: function() {
var time = (new Date).getTime();
var Tpos = (time - this.startTime) / (this.duration);
if (time >= this.duration+this.startTime) {
this.now = this.to;
clearInterval (this.timer);
this.timer = null;
if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
}
else {
this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;
//this time-position, sinoidal transition thing is from script.aculo.us
}
this.increase();
},
custom: function(from, to) {
if (this.timer != null) return;
this.from = from;
this.to = to;
this.go();
},
hide: function() {
this.now = 0;
this.increase();
},
clearTimer: function() {
clearInterval(this.timer);
this.timer = null;
}
}
//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.el.style.overflow = "hidden";
this.el.iniWidth = this.el.offsetWidth;
this.el.iniHeight = this.el.offsetHeight;
this.setOptions(options);
}
});
fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {
increase: function() {
this.el.style.height = this.now + "px";
},
toggle: function() {
if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
else this.custom(0, this.el.scrollHeight);
}
});
| JavaScript |
function create_menu(basepath)
{
var base = (basepath == 'null') ? '' : basepath;
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<ul>' +
'<li><a href="'+base+'index.html">User Guide Home</a></li>' +
'<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' +
'</ul>' +
'<h3>Basic Info</h3>' +
'<ul>' +
'<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' +
'<li><a href="'+base+'license.html">License Agreement</a></li>' +
'<li><a href="'+base+'changelog.html">Change Log</a></li>' +
'<li><a href="'+base+'general/credits.html">Credits</a></li>' +
'</ul>' +
'<h3>Installation</h3>' +
'<ul>' +
'<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' +
'<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' +
'<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' +
'<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' +
'</ul>' +
'<h3>Introduction</h3>' +
'<ul>' +
'<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' +
'<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' +
'<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' +
'<li><a href="'+base+'overview/features.html">Supported Features</a></li>' +
'<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' +
'<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' +
'<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' +
'</ul>' +
'<h3>Tutorial</h3>' +
'<ul>' +
'<li><a href="'+base+'tutorial/index.html">Introduction</a></li>' +
'<li><a href="'+base+'tutorial/static_pages.html">Static pages</a></li>' +
'<li><a href="'+base+'tutorial/news_section.html">News section</a></li>' +
'<li><a href="'+base+'tutorial/create_news_items.html">Create news items</a></li>' +
'<li><a href="'+base+'tutorial/conclusion.html">Conclusion</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>General Topics</h3>' +
'<ul>' +
'<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' +
'<li><a href="'+base+'general/controllers.html">Controllers</a></li>' +
'<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' +
'<li><a href="'+base+'general/views.html">Views</a></li>' +
'<li><a href="'+base+'general/models.html">Models</a></li>' +
'<li><a href="'+base+'general/helpers.html">Helpers</a></li>' +
'<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' +
'<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' +
'<li><a href="'+base+'general/drivers.html">Using CodeIgniter Drivers</a></li>' +
'<li><a href="'+base+'general/creating_drivers.html">Creating Your Own Drivers</a></li>' +
'<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' +
'<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' +
'<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' +
'<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' +
'<li><a href="'+base+'general/routing.html">URI Routing</a></li>' +
'<li><a href="'+base+'general/errors.html">Error Handling</a></li>' +
'<li><a href="'+base+'general/caching.html">Caching</a></li>' +
'<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' +
'<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' +
'<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' +
'<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' +
'<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' +
'<li><a href="'+base+'general/security.html">Security</a></li>' +
'<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' +
'<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' +
'</ul>' +
'<h3>Additional Resources</h3>' +
'<ul>' +
'<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' +
'<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Class Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' +
'<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' +
'<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' +
'<li><a href="'+base+'libraries/config.html">Config Class</a></li>' +
'<li><a href="'+base+'libraries/email.html">Email Class</a></li>' +
'<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' +
'<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' +
'<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' +
'<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' +
'<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' +
'<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' +
'<li><a href="'+base+'libraries/input.html">Input Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' +
'<li><a href="'+base+'libraries/language.html">Language Class</a></li>' +
'<li><a href="'+base+'libraries/migration.html">Migration Class</a></li>' +
'<li><a href="'+base+'libraries/output.html">Output Class</a></li>' +
'<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' +
'<li><a href="'+base+'libraries/security.html">Security Class</a></li>' +
'<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' +
'<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' +
'<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' +
'<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' +
'<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' +
'<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' +
'<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' +
'<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' +
'<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Driver Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' +
'<li><a href="'+base+'database/index.html">Database Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'</ul>' +
'<h3>Helper Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' +
'<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' +
'<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' +
'<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' +
'<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' +
'<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' +
'<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' +
'<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' +
'<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' +
'<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' +
'<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' +
'<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' +
'<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' +
'<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' +
'<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' +
'<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' +
'<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' +
'<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' +
'<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' +
'<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' +
'<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' +
'</ul>' +
'</td></tr></table>');
} | JavaScript |
window.onload = function() {
myHeight = new fx.Height('nav', {duration: 400});
myHeight.hide();
} | JavaScript |
/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
10/24/2005
v(1.0.2)
*/
//base
var fx = new Object();
fx.Base = function(){};
fx.Base.prototype = {
setOptions: function(options) {
this.options = {
duration: 500,
onComplete: ''
}
Object.extend(this.options, options || {});
},
go: function() {
this.duration = this.options.duration;
this.startTime = (new Date).getTime();
this.timer = setInterval (this.step.bind(this), 13);
},
step: function() {
var time = (new Date).getTime();
var Tpos = (time - this.startTime) / (this.duration);
if (time >= this.duration+this.startTime) {
this.now = this.to;
clearInterval (this.timer);
this.timer = null;
if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
}
else {
this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;
//this time-position, sinoidal transition thing is from script.aculo.us
}
this.increase();
},
custom: function(from, to) {
if (this.timer != null) return;
this.from = from;
this.to = to;
this.go();
},
hide: function() {
this.now = 0;
this.increase();
},
clearTimer: function() {
clearInterval(this.timer);
this.timer = null;
}
}
//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.el.style.overflow = "hidden";
this.el.iniWidth = this.el.offsetWidth;
this.el.iniHeight = this.el.offsetHeight;
this.setOptions(options);
}
});
fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {
increase: function() {
this.el.style.height = this.now + "px";
},
toggle: function() {
if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
else this.custom(0, this.el.scrollHeight);
}
});
| JavaScript |
function create_menu(basepath)
{
var base = (basepath == 'null') ? '' : basepath;
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<ul>' +
'<li><a href="'+base+'index.html">User Guide Home</a></li>' +
'<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' +
'</ul>' +
'<h3>Basic Info</h3>' +
'<ul>' +
'<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' +
'<li><a href="'+base+'license.html">License Agreement</a></li>' +
'<li><a href="'+base+'changelog.html">Change Log</a></li>' +
'<li><a href="'+base+'general/credits.html">Credits</a></li>' +
'</ul>' +
'<h3>Installation</h3>' +
'<ul>' +
'<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' +
'<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' +
'<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' +
'<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' +
'</ul>' +
'<h3>Introduction</h3>' +
'<ul>' +
'<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' +
'<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' +
'<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' +
'<li><a href="'+base+'overview/features.html">Supported Features</a></li>' +
'<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' +
'<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' +
'<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' +
'</ul>' +
'<h3>Tutorial</h3>' +
'<ul>' +
'<li><a href="'+base+'tutorial/index.html">Introduction</a></li>' +
'<li><a href="'+base+'tutorial/static_pages.html">Static pages</a></li>' +
'<li><a href="'+base+'tutorial/news_section.html">News section</a></li>' +
'<li><a href="'+base+'tutorial/create_news_items.html">Create news items</a></li>' +
'<li><a href="'+base+'tutorial/conclusion.html">Conclusion</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>General Topics</h3>' +
'<ul>' +
'<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' +
'<li><a href="'+base+'general/controllers.html">Controllers</a></li>' +
'<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' +
'<li><a href="'+base+'general/views.html">Views</a></li>' +
'<li><a href="'+base+'general/models.html">Models</a></li>' +
'<li><a href="'+base+'general/helpers.html">Helpers</a></li>' +
'<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' +
'<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' +
'<li><a href="'+base+'general/drivers.html">Using CodeIgniter Drivers</a></li>' +
'<li><a href="'+base+'general/creating_drivers.html">Creating Your Own Drivers</a></li>' +
'<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' +
'<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' +
'<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' +
'<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' +
'<li><a href="'+base+'general/routing.html">URI Routing</a></li>' +
'<li><a href="'+base+'general/errors.html">Error Handling</a></li>' +
'<li><a href="'+base+'general/caching.html">Caching</a></li>' +
'<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' +
'<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' +
'<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' +
'<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' +
'<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' +
'<li><a href="'+base+'general/security.html">Security</a></li>' +
'<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' +
'<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' +
'</ul>' +
'<h3>Additional Resources</h3>' +
'<ul>' +
'<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' +
'<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Class Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' +
'<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' +
'<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' +
'<li><a href="'+base+'libraries/config.html">Config Class</a></li>' +
'<li><a href="'+base+'libraries/email.html">Email Class</a></li>' +
'<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' +
'<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' +
'<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' +
'<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' +
'<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' +
'<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' +
'<li><a href="'+base+'libraries/input.html">Input Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' +
'<li><a href="'+base+'libraries/language.html">Language Class</a></li>' +
'<li><a href="'+base+'libraries/migration.html">Migration Class</a></li>' +
'<li><a href="'+base+'libraries/output.html">Output Class</a></li>' +
'<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' +
'<li><a href="'+base+'libraries/security.html">Security Class</a></li>' +
'<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' +
'<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' +
'<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' +
'<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' +
'<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' +
'<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' +
'<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' +
'<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' +
'<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Driver Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' +
'<li><a href="'+base+'database/index.html">Database Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'</ul>' +
'<h3>Helper Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' +
'<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' +
'<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' +
'<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' +
'<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' +
'<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' +
'<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' +
'<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' +
'<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' +
'<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' +
'<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' +
'<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' +
'<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' +
'<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' +
'<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' +
'<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' +
'<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' +
'<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' +
'<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' +
'<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' +
'<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' +
'</ul>' +
'</td></tr></table>');
} | JavaScript |
//Loads the header and footer xhtmls into #header and #footer directly
$(function(){
$("#header").load("header.xhtml");
$("#footer").load("footer.xhtml");
});
function showRemaining() {
var oneMinute = 60 * 1000
var oneHour = oneMinute * 60
var oneDay = oneHour * 24
var today = new Date()
var nextXmas = new Date()
nextXmas.setMonth(11)
nextXmas.setDate(24)
if (today.getMonth() == 11 && today.getDate() > 24) {
nextXmas.setFullYear(nextXmas.getFullYear() + 1)
}
var diff = nextXmas.getTime() - today.getTime()
diff = Math.floor(diff/oneDay)
return diff
}
| JavaScript |
//Loads the header and footer xhtmls into #header and #footer directly
$(function(){
$("#header").load("header.xhtml");
$("#footer").load("footer.xhtml");
});
function showRemaining() {
var oneMinute = 60 * 1000
var oneHour = oneMinute * 60
var oneDay = oneHour * 24
var today = new Date()
var nextXmas = new Date()
nextXmas.setMonth(11)
nextXmas.setDate(24)
if (today.getMonth() == 11 && today.getDate() > 24) {
nextXmas.setFullYear(nextXmas.getFullYear() + 1)
}
var diff = nextXmas.getTime() - today.getTime()
diff = Math.floor(diff/oneDay)
return diff
}
| JavaScript |
/*!
Colorbox 1.5.14
license: MIT
http://www.jacklmoore.com/colorbox
*/
(function ($, document, window) {
var
// Default settings object.
// See http://jacklmoore.com/colorbox for details.
defaults = {
// data sources
html: false,
photo: false,
iframe: false,
inline: false,
// behavior and appearance
transition: "elastic",
speed: 300,
fadeOut: 300,
width: false,
initialWidth: "600",
innerWidth: false,
maxWidth: false,
height: false,
initialHeight: "450",
innerHeight: false,
maxHeight: false,
scalePhotos: true,
scrolling: true,
opacity: 0.9,
preloading: true,
className: false,
overlayClose: true,
escKey: true,
arrowKey: true,
top: false,
bottom: false,
left: false,
right: false,
fixed: false,
data: undefined,
closeButton: true,
fastIframe: true,
open: false,
reposition: true,
loop: true,
slideshow: false,
slideshowAuto: true,
slideshowSpeed: 2500,
slideshowStart: "start slideshow",
slideshowStop: "stop slideshow",
photoRegex: /\.(gif|png|jp(e|g|eg)|bmp|ico|webp|jxr|svg)((#|\?).*)?$/i,
// alternate image paths for high-res displays
retinaImage: false,
retinaUrl: false,
retinaSuffix: '@2x.$1',
// internationalization
current: "image {current} of {total}",
previous: "previous",
next: "next",
close: "close",
xhrError: "This content failed to load.",
imgError: "This image failed to load.",
// accessbility
returnFocus: true,
trapFocus: true,
// callbacks
onOpen: false,
onLoad: false,
onComplete: false,
onCleanup: false,
onClosed: false,
rel: function() {
return this.rel;
},
href: function() {
// using this.href would give the absolute url, when the href may have been inteded as a selector (e.g. '#container')
return $(this).attr('href');
},
title: function() {
return this.title;
}
},
// Abstracting the HTML and event identifiers for easy rebranding
colorbox = 'colorbox',
prefix = 'cbox',
boxElement = prefix + 'Element',
// Events
event_open = prefix + '_open',
event_load = prefix + '_load',
event_complete = prefix + '_complete',
event_cleanup = prefix + '_cleanup',
event_closed = prefix + '_closed',
event_purge = prefix + '_purge',
// Cached jQuery Object Variables
$overlay,
$box,
$wrap,
$content,
$topBorder,
$leftBorder,
$rightBorder,
$bottomBorder,
$related,
$window,
$loaded,
$loadingBay,
$loadingOverlay,
$title,
$current,
$slideshow,
$next,
$prev,
$close,
$groupControls,
$events = $('<a/>'), // $({}) would be prefered, but there is an issue with jQuery 1.4.2
// Variables for cached values or use across multiple functions
settings,
interfaceHeight,
interfaceWidth,
loadedHeight,
loadedWidth,
index,
photo,
open,
active,
closing,
loadingTimer,
publicMethod,
div = "div",
requests = 0,
previousCSS = {},
init;
// ****************
// HELPER FUNCTIONS
// ****************
// Convenience function for creating new jQuery objects
function $tag(tag, id, css) {
var element = document.createElement(tag);
if (id) {
element.id = prefix + id;
}
if (css) {
element.style.cssText = css;
}
return $(element);
}
// Get the window height using innerHeight when available to avoid an issue with iOS
// http://bugs.jquery.com/ticket/6724
function winheight() {
return window.innerHeight ? window.innerHeight : $(window).height();
}
function Settings(element, options) {
if (options !== Object(options)) {
options = {};
}
this.cache = {};
this.el = element;
this.value = function(key) {
var dataAttr;
if (this.cache[key] === undefined) {
dataAttr = $(this.el).attr('data-cbox-'+key);
if (dataAttr !== undefined) {
this.cache[key] = dataAttr;
} else if (options[key] !== undefined) {
this.cache[key] = options[key];
} else if (defaults[key] !== undefined) {
this.cache[key] = defaults[key];
}
}
return this.cache[key];
};
this.get = function(key) {
var value = this.value(key);
return $.isFunction(value) ? value.call(this.el, this) : value;
};
}
// Determine the next and previous members in a group.
function getIndex(increment) {
var
max = $related.length,
newIndex = (index + increment) % max;
return (newIndex < 0) ? max + newIndex : newIndex;
}
// Convert '%' and 'px' values to integers
function setSize(size, dimension) {
return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10));
}
// Checks an href to see if it is a photo.
// There is a force photo option (photo: true) for hrefs that cannot be matched by the regex.
function isImage(settings, url) {
return settings.get('photo') || settings.get('photoRegex').test(url);
}
function retinaUrl(settings, url) {
return settings.get('retinaUrl') && window.devicePixelRatio > 1 ? url.replace(settings.get('photoRegex'), settings.get('retinaSuffix')) : url;
}
function trapFocus(e) {
if ('contains' in $box[0] && !$box[0].contains(e.target) && e.target !== $overlay[0]) {
e.stopPropagation();
$box.focus();
}
}
function setClass(str) {
if (setClass.str !== str) {
$box.add($overlay).removeClass(setClass.str).addClass(str);
setClass.str = str;
}
}
function getRelated(rel) {
index = 0;
if (rel && rel !== false && rel !== 'nofollow') {
$related = $('.' + boxElement).filter(function () {
var options = $.data(this, colorbox);
var settings = new Settings(this, options);
return (settings.get('rel') === rel);
});
index = $related.index(settings.el);
// Check direct calls to Colorbox.
if (index === -1) {
$related = $related.add(settings.el);
index = $related.length - 1;
}
} else {
$related = $(settings.el);
}
}
function trigger(event) {
// for external use
$(document).trigger(event);
// for internal use
$events.triggerHandler(event);
}
var slideshow = (function(){
var active,
className = prefix + "Slideshow_",
click = "click." + prefix,
timeOut;
function clear () {
clearTimeout(timeOut);
}
function set() {
if (settings.get('loop') || $related[index + 1]) {
clear();
timeOut = setTimeout(publicMethod.next, settings.get('slideshowSpeed'));
}
}
function start() {
$slideshow
.html(settings.get('slideshowStop'))
.unbind(click)
.one(click, stop);
$events
.bind(event_complete, set)
.bind(event_load, clear);
$box.removeClass(className + "off").addClass(className + "on");
}
function stop() {
clear();
$events
.unbind(event_complete, set)
.unbind(event_load, clear);
$slideshow
.html(settings.get('slideshowStart'))
.unbind(click)
.one(click, function () {
publicMethod.next();
start();
});
$box.removeClass(className + "on").addClass(className + "off");
}
function reset() {
active = false;
$slideshow.hide();
clear();
$events
.unbind(event_complete, set)
.unbind(event_load, clear);
$box.removeClass(className + "off " + className + "on");
}
return function(){
if (active) {
if (!settings.get('slideshow')) {
$events.unbind(event_cleanup, reset);
reset();
}
} else {
if (settings.get('slideshow') && $related[1]) {
active = true;
$events.one(event_cleanup, reset);
if (settings.get('slideshowAuto')) {
start();
} else {
stop();
}
$slideshow.show();
}
}
};
}());
function launch(element) {
var options;
if (!closing) {
options = $(element).data(colorbox);
settings = new Settings(element, options);
getRelated(settings.get('rel'));
if (!open) {
open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
setClass(settings.get('className'));
// Show colorbox so the sizes can be calculated in older versions of jQuery
$box.css({visibility:'hidden', display:'block', opacity:''});
$loaded = $tag(div, 'LoadedContent', 'width:0; height:0; overflow:hidden; visibility:hidden');
$content.css({width:'', height:''}).append($loaded);
// Cache values needed for size calculations
interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();
interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
loadedHeight = $loaded.outerHeight(true);
loadedWidth = $loaded.outerWidth(true);
// Opens inital empty Colorbox prior to content being loaded.
var initialWidth = setSize(settings.get('initialWidth'), 'x');
var initialHeight = setSize(settings.get('initialHeight'), 'y');
var maxWidth = settings.get('maxWidth');
var maxHeight = settings.get('maxHeight');
settings.w = (maxWidth !== false ? Math.min(initialWidth, setSize(maxWidth, 'x')) : initialWidth) - loadedWidth - interfaceWidth;
settings.h = (maxHeight !== false ? Math.min(initialHeight, setSize(maxHeight, 'y')) : initialHeight) - loadedHeight - interfaceHeight;
$loaded.css({width:'', height:settings.h});
publicMethod.position();
trigger(event_open);
settings.get('onOpen');
$groupControls.add($title).hide();
$box.focus();
if (settings.get('trapFocus')) {
// Confine focus to the modal
// Uses event capturing that is not supported in IE8-
if (document.addEventListener) {
document.addEventListener('focus', trapFocus, true);
$events.one(event_closed, function () {
document.removeEventListener('focus', trapFocus, true);
});
}
}
// Return focus on closing
if (settings.get('returnFocus')) {
$events.one(event_closed, function () {
$(settings.el).focus();
});
}
}
var opacity = parseFloat(settings.get('opacity'));
$overlay.css({
opacity: opacity === opacity ? opacity : '',
cursor: settings.get('overlayClose') ? 'pointer' : '',
visibility: 'visible'
}).show();
if (settings.get('closeButton')) {
$close.html(settings.get('close')).appendTo($content);
} else {
$close.appendTo('<div/>'); // replace with .detach() when dropping jQuery < 1.4
}
load();
}
}
// Colorbox's markup needs to be added to the DOM prior to being called
// so that the browser will go ahead and load the CSS background images.
function appendHTML() {
if (!$box) {
init = false;
$window = $(window);
$box = $tag(div).attr({
id: colorbox,
'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS.
role: 'dialog',
tabindex: '-1'
}).hide();
$overlay = $tag(div, "Overlay").hide();
$loadingOverlay = $([$tag(div, "LoadingOverlay")[0],$tag(div, "LoadingGraphic")[0]]);
$wrap = $tag(div, "Wrapper");
$content = $tag(div, "Content").append(
$title = $tag(div, "Title"),
$current = $tag(div, "Current"),
$prev = $('<button type="button"/>').attr({id:prefix+'Previous'}),
$next = $('<button type="button"/>').attr({id:prefix+'Next'}),
$slideshow = $tag('button', "Slideshow"),
$loadingOverlay
);
$close = $('<button type="button"/>').attr({id:prefix+'Close'});
$wrap.append( // The 3x3 Grid that makes up Colorbox
$tag(div).append(
$tag(div, "TopLeft"),
$topBorder = $tag(div, "TopCenter"),
$tag(div, "TopRight")
),
$tag(div, false, 'clear:left').append(
$leftBorder = $tag(div, "MiddleLeft"),
$content,
$rightBorder = $tag(div, "MiddleRight")
),
$tag(div, false, 'clear:left').append(
$tag(div, "BottomLeft"),
$bottomBorder = $tag(div, "BottomCenter"),
$tag(div, "BottomRight")
)
).find('div div').css({'float': 'left'});
$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none; max-width:none;');
$groupControls = $next.add($prev).add($current).add($slideshow);
}
if (document.body && !$box.parent().length) {
$(document.body).append($overlay, $box.append($wrap, $loadingBay));
}
}
// Add Colorbox's event bindings
function addBindings() {
function clickHandler(e) {
// ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt.
// See: http://jacklmoore.com/notes/click-events/
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey)) {
e.preventDefault();
launch(this);
}
}
if ($box) {
if (!init) {
init = true;
// Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.
$next.click(function () {
publicMethod.next();
});
$prev.click(function () {
publicMethod.prev();
});
$close.click(function () {
publicMethod.close();
});
$overlay.click(function () {
if (settings.get('overlayClose')) {
publicMethod.close();
}
});
// Key Bindings
$(document).bind('keydown.' + prefix, function (e) {
var key = e.keyCode;
if (open && settings.get('escKey') && key === 27) {
e.preventDefault();
publicMethod.close();
}
if (open && settings.get('arrowKey') && $related[1] && !e.altKey) {
if (key === 37) {
e.preventDefault();
$prev.click();
} else if (key === 39) {
e.preventDefault();
$next.click();
}
}
});
if ($.isFunction($.fn.on)) {
// For jQuery 1.7+
$(document).on('click.'+prefix, '.'+boxElement, clickHandler);
} else {
// For jQuery 1.3.x -> 1.6.x
// This code is never reached in jQuery 1.9, so do not contact me about 'live' being removed.
// This is not here for jQuery 1.9, it's here for legacy users.
$('.'+boxElement).live('click.'+prefix, clickHandler);
}
}
return true;
}
return false;
}
// Don't do anything if Colorbox already exists.
if ($[colorbox]) {
return;
}
// Append the HTML when the DOM loads
$(appendHTML);
// ****************
// PUBLIC FUNCTIONS
// Usage format: $.colorbox.close();
// Usage from within an iframe: parent.jQuery.colorbox.close();
// ****************
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
var settings;
var $obj = this;
options = options || {};
if ($.isFunction($obj)) { // assume a call to $.colorbox
$obj = $('<a/>');
options.open = true;
} else if (!$obj[0]) { // colorbox being applied to empty collection
return $obj;
}
if (!$obj[0]) { // colorbox being applied to empty collection
return $obj;
}
appendHTML();
if (addBindings()) {
if (callback) {
options.onComplete = callback;
}
$obj.each(function () {
var old = $.data(this, colorbox) || {};
$.data(this, colorbox, $.extend(old, options));
}).addClass(boxElement);
settings = new Settings($obj[0], options);
if (settings.get('open')) {
launch($obj[0]);
}
}
return $obj;
};
publicMethod.position = function (speed, loadedCallback) {
var
css,
top = 0,
left = 0,
offset = $box.offset(),
scrollTop,
scrollLeft;
$window.unbind('resize.' + prefix);
// remove the modal so that it doesn't influence the document width/height
$box.css({top: -9e4, left: -9e4});
scrollTop = $window.scrollTop();
scrollLeft = $window.scrollLeft();
if (settings.get('fixed')) {
offset.top -= scrollTop;
offset.left -= scrollLeft;
$box.css({position: 'fixed'});
} else {
top = scrollTop;
left = scrollLeft;
$box.css({position: 'absolute'});
}
// keeps the top and left positions within the browser's viewport.
if (settings.get('right') !== false) {
left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.get('right'), 'x'), 0);
} else if (settings.get('left') !== false) {
left += setSize(settings.get('left'), 'x');
} else {
left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
}
if (settings.get('bottom') !== false) {
top += Math.max(winheight() - settings.h - loadedHeight - interfaceHeight - setSize(settings.get('bottom'), 'y'), 0);
} else if (settings.get('top') !== false) {
top += setSize(settings.get('top'), 'y');
} else {
top += Math.round(Math.max(winheight() - settings.h - loadedHeight - interfaceHeight, 0) / 2);
}
$box.css({top: offset.top, left: offset.left, visibility:'visible'});
// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
// but it has to be shrank down around the size of div#colorbox when it's done. If not,
// it can invoke an obscure IE bug when using iframes.
$wrap[0].style.width = $wrap[0].style.height = "9999px";
function modalDimensions() {
$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = (parseInt($box[0].style.width,10) - interfaceWidth)+'px';
$content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = (parseInt($box[0].style.height,10) - interfaceHeight)+'px';
}
css = {width: settings.w + loadedWidth + interfaceWidth, height: settings.h + loadedHeight + interfaceHeight, top: top, left: left};
// setting the speed to 0 if the content hasn't changed size or position
if (speed) {
var tempSpeed = 0;
$.each(css, function(i){
if (css[i] !== previousCSS[i]) {
tempSpeed = speed;
return;
}
});
speed = tempSpeed;
}
previousCSS = css;
if (!speed) {
$box.css(css);
}
$box.dequeue().animate(css, {
duration: speed || 0,
complete: function () {
modalDimensions();
active = false;
// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
if (settings.get('reposition')) {
setTimeout(function () { // small delay before binding onresize due to an IE8 bug.
$window.bind('resize.' + prefix, publicMethod.position);
}, 1);
}
if ($.isFunction(loadedCallback)) {
loadedCallback();
}
},
step: modalDimensions
});
};
publicMethod.resize = function (options) {
var scrolltop;
if (open) {
options = options || {};
if (options.width) {
settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
}
if (options.innerWidth) {
settings.w = setSize(options.innerWidth, 'x');
}
$loaded.css({width: settings.w});
if (options.height) {
settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
}
if (options.innerHeight) {
settings.h = setSize(options.innerHeight, 'y');
}
if (!options.innerHeight && !options.height) {
scrolltop = $loaded.scrollTop();
$loaded.css({height: "auto"});
settings.h = $loaded.height();
}
$loaded.css({height: settings.h});
if(scrolltop) {
$loaded.scrollTop(scrolltop);
}
publicMethod.position(settings.get('transition') === "none" ? 0 : settings.get('speed'));
}
};
publicMethod.prep = function (object) {
if (!open) {
return;
}
var callback, speed = settings.get('transition') === "none" ? 0 : settings.get('speed');
$loaded.remove();
$loaded = $tag(div, 'LoadedContent').append(object);
function getWidth() {
settings.w = settings.w || $loaded.width();
settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
return settings.w;
}
function getHeight() {
settings.h = settings.h || $loaded.height();
settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
return settings.h;
}
$loaded.hide()
.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
.css({width: getWidth(), overflow: settings.get('scrolling') ? 'auto' : 'hidden'})
.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
.prependTo($content);
$loadingBay.hide();
// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
$(photo).css({'float': 'none'});
setClass(settings.get('className'));
callback = function () {
var total = $related.length,
iframe,
complete;
if (!open) {
return;
}
function removeFilter() { // Needed for IE8 in versions of jQuery prior to 1.7.2
if ($.support.opacity === false) {
$box[0].style.removeAttribute('filter');
}
}
complete = function () {
clearTimeout(loadingTimer);
$loadingOverlay.hide();
trigger(event_complete);
settings.get('onComplete');
};
$title.html(settings.get('title')).show();
$loaded.show();
if (total > 1) { // handle grouping
if (typeof settings.get('current') === "string") {
$current.html(settings.get('current').replace('{current}', index + 1).replace('{total}', total)).show();
}
$next[(settings.get('loop') || index < total - 1) ? "show" : "hide"]().html(settings.get('next'));
$prev[(settings.get('loop') || index) ? "show" : "hide"]().html(settings.get('previous'));
slideshow();
// Preloads images within a rel group
if (settings.get('preloading')) {
$.each([getIndex(-1), getIndex(1)], function(){
var img,
i = $related[this],
settings = new Settings(i, $.data(i, colorbox)),
src = settings.get('href');
if (src && isImage(settings, src)) {
src = retinaUrl(settings, src);
img = document.createElement('img');
img.src = src;
}
});
}
} else {
$groupControls.hide();
}
if (settings.get('iframe')) {
iframe = document.createElement('iframe');
if ('frameBorder' in iframe) {
iframe.frameBorder = 0;
}
if ('allowTransparency' in iframe) {
iframe.allowTransparency = "true";
}
if (!settings.get('scrolling')) {
iframe.scrolling = "no";
}
$(iframe)
.attr({
src: settings.get('href'),
name: (new Date()).getTime(), // give the iframe a unique name to prevent caching
'class': prefix + 'Iframe',
allowFullScreen : true // allow HTML5 video to go fullscreen
})
.one('load', complete)
.appendTo($loaded);
$events.one(event_purge, function () {
iframe.src = "//about:blank";
});
if (settings.get('fastIframe')) {
$(iframe).trigger('load');
}
} else {
complete();
}
if (settings.get('transition') === 'fade') {
$box.fadeTo(speed, 1, removeFilter);
} else {
removeFilter();
}
};
if (settings.get('transition') === 'fade') {
$box.fadeTo(speed, 0, function () {
publicMethod.position(0, callback);
});
} else {
publicMethod.position(speed, callback);
}
};
function load () {
var href, setResize, prep = publicMethod.prep, $inline, request = ++requests;
active = true;
photo = false;
trigger(event_purge);
trigger(event_load);
settings.get('onLoad');
settings.h = settings.get('height') ?
setSize(settings.get('height'), 'y') - loadedHeight - interfaceHeight :
settings.get('innerHeight') && setSize(settings.get('innerHeight'), 'y');
settings.w = settings.get('width') ?
setSize(settings.get('width'), 'x') - loadedWidth - interfaceWidth :
settings.get('innerWidth') && setSize(settings.get('innerWidth'), 'x');
// Sets the minimum dimensions for use in image scaling
settings.mw = settings.w;
settings.mh = settings.h;
// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
if (settings.get('maxWidth')) {
settings.mw = setSize(settings.get('maxWidth'), 'x') - loadedWidth - interfaceWidth;
settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
}
if (settings.get('maxHeight')) {
settings.mh = setSize(settings.get('maxHeight'), 'y') - loadedHeight - interfaceHeight;
settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
}
href = settings.get('href');
loadingTimer = setTimeout(function () {
$loadingOverlay.show();
}, 100);
if (settings.get('inline')) {
var $target = $(href);
// Inserts an empty placeholder where inline content is being pulled from.
// An event is bound to put inline content back when Colorbox closes or loads new content.
$inline = $('<div>').hide().insertBefore($target);
$events.one(event_purge, function () {
$inline.replaceWith($target);
});
prep($target);
} else if (settings.get('iframe')) {
// IFrame element won't be added to the DOM until it is ready to be displayed,
// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
prep(" ");
} else if (settings.get('html')) {
prep(settings.get('html'));
} else if (isImage(settings, href)) {
href = retinaUrl(settings, href);
photo = new Image();
$(photo)
.addClass(prefix + 'Photo')
.bind('error',function () {
prep($tag(div, 'Error').html(settings.get('imgError')));
})
.one('load', function () {
if (request !== requests) {
return;
}
// A small pause because some browsers will occassionaly report a
// img.width and img.height of zero immediately after the img.onload fires
setTimeout(function(){
var percent;
$.each(['alt', 'longdesc', 'aria-describedby'], function(i,val){
var attr = $(settings.el).attr(val) || $(settings.el).attr('data-'+val);
if (attr) {
photo.setAttribute(val, attr);
}
});
if (settings.get('retinaImage') && window.devicePixelRatio > 1) {
photo.height = photo.height / window.devicePixelRatio;
photo.width = photo.width / window.devicePixelRatio;
}
if (settings.get('scalePhotos')) {
setResize = function () {
photo.height -= photo.height * percent;
photo.width -= photo.width * percent;
};
if (settings.mw && photo.width > settings.mw) {
percent = (photo.width - settings.mw) / photo.width;
setResize();
}
if (settings.mh && photo.height > settings.mh) {
percent = (photo.height - settings.mh) / photo.height;
setResize();
}
}
if (settings.h) {
photo.style.marginTop = Math.max(settings.mh - photo.height, 0) / 2 + 'px';
}
if ($related[1] && (settings.get('loop') || $related[index + 1])) {
photo.style.cursor = 'pointer';
photo.onclick = function () {
publicMethod.next();
};
}
photo.style.width = photo.width + 'px';
photo.style.height = photo.height + 'px';
prep(photo);
}, 1);
});
photo.src = href;
} else if (href) {
$loadingBay.load(href, settings.get('data'), function (data, status) {
if (request === requests) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.get('xhrError')) : $(this).contents());
}
});
}
}
// Navigates to the next page/image in a set.
publicMethod.next = function () {
if (!active && $related[1] && (settings.get('loop') || $related[index + 1])) {
index = getIndex(1);
launch($related[index]);
}
};
publicMethod.prev = function () {
if (!active && $related[1] && (settings.get('loop') || index)) {
index = getIndex(-1);
launch($related[index]);
}
};
// Note: to use this within an iframe use the following format: parent.jQuery.colorbox.close();
publicMethod.close = function () {
if (open && !closing) {
closing = true;
open = false;
trigger(event_cleanup);
settings.get('onCleanup');
$window.unbind('.' + prefix);
$overlay.fadeTo(settings.get('fadeOut') || 0, 0);
$box.stop().fadeTo(settings.get('fadeOut') || 0, 0, function () {
$box.hide();
$overlay.hide();
trigger(event_purge);
$loaded.remove();
setTimeout(function () {
closing = false;
trigger(event_closed);
settings.get('onClosed');
}, 1);
});
}
};
// Removes changes Colorbox made to the document, but does not remove the plugin.
publicMethod.remove = function () {
if (!$box) { return; }
$box.stop();
$[colorbox].close();
$box.stop(false, true).remove();
$overlay.remove();
closing = false;
$box = null;
$('.' + boxElement)
.removeData(colorbox)
.removeClass(boxElement);
$(document).unbind('click.'+prefix).unbind('keydown.'+prefix);
};
// A method for fetching the current element Colorbox is referencing.
// returns a jQuery object.
publicMethod.element = function () {
return $(settings.el);
};
publicMethod.settings = defaults;
}(jQuery, document, window));
| JavaScript |
// when the DOM is ready...
$(document).ready(function () {
var $panels = $('#slider .scrollContainer > div');
var $container = $('#slider .scrollContainer');
// if false, we'll float all the panels left and fix the width
// of the container
var horizontal = true;
// float the panels left if we're going horizontal
if (horizontal) {
$panels.css({
'float' : 'left',
'position' : 'relative' // IE fix to ensure overflow is hidden
});
// calculate a new width for the container (so it holds all panels)
$container.css('width', $panels[0].offsetWidth * $panels.length);
}
// collect the scroll object, at the same time apply the hidden overflow
// to remove the default scrollbars that will appear
var $scroll = $('#slider .scroll').css('overflow', 'hidden');
// apply our left + right buttons
/* $scroll
.before('<img class="scrollButtons left" src="images/scroll_left.png" />')
.after('<img class="scrollButtons right" src="images/scroll_right.png" />');
*/
// handle nav selection
function selectNav() {
$(this)
.parents('ul:first')
.find('a')
.removeClass('selected')
.end()
.end()
.addClass('selected');
}
$('#slider .navigation').find('a').click(selectNav);
// go find the navigation link that has this target and select the nav
function trigger(data) {
var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
selectNav.call(el);
}
if (window.location.hash) {
trigger({ id : window.location.hash.substr(1) });
} else {
$('ul.navigation a:first').click();
}
// offset is used to move to *exactly* the right place, since I'm using
// padding on my example, I need to subtract the amount of padding to
// the offset. Try removing this to get a good idea of the effect
var offset = parseInt((horizontal ?
$container.css('paddingTop') :
$container.css('paddingLeft'))
|| 0) * -1;
var scrollOptions = {
target: $scroll, // the element that has the overflow
// can be a selector which will be relative to the target
items: $panels,
navigation: '.navigation a',
// selectors are NOT relative to document, i.e. make sure they're unique
prev: 'img.left',
next: 'img.right',
// allow the scroll effect to run both directions
axis: 'xy',
onAfter: trigger, // our final callback
offset: offset,
// duration of the sliding effect
duration: 500,
// easing - can be used with the easing plugin:
// http://gsgd.co.uk/sandbox/jquery/easing/
easing: 'swing'
};
// apply serialScroll to the slider - we chose this plugin because it
// supports// the indexed next and previous scroll along with hooking
// in to our navigation.
$('#slider').serialScroll(scrollOptions);
// now apply localScroll to hook any other arbitrary links to trigger
// the effect
$.localScroll(scrollOptions);
// finally, if the URL has a hash, move the slider in to position,
// setting the duration to 1 because I don't want it to scroll in the
// very first page load. We don't always need this, but it ensures
// the positioning is absolutely spot on when the pages loads.
scrollOptions.duration = 1;
$.localScroll.hash(scrollOptions);
}); | JavaScript |
/**
* jQuery.LocalScroll
* Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 3/10/2008
*
* @projectDescription Animated scrolling navigation, using anchors.
* http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html
* @author Ariel Flesler
* @version 1.2.5
*
* @id jQuery.fn.localScroll
* @param {Object} settings Hash of settings, it is passed in to jQuery.ScrollTo, none is required.
* @return {jQuery} Returns the same jQuery object, for chaining.
*
* @example $('ul.links').localScroll();
*
* @example $('ul.links').localScroll({ filter:'.animated', duration:400, axis:'x' });
*
* @example $.localScroll({ target:'#pane', axis:'xy', queue:true, event:'mouseover' });
*
* Notes:
* - The plugin requires jQuery.ScrollTo.
* - The hash of settings, is passed to jQuery.ScrollTo, so the settings are valid for that plugin as well.
* - jQuery.localScroll can be used if the desired links, are all over the document, it accepts the same settings.
* - If the setting 'lazy' is set to true, then the binding will still work for later added anchors.
* - The setting 'speed' is deprecated, use 'duration' instead.
* - If onBefore returns false, the event is ignored.
**/
;(function( $ ){
var URI = location.href.replace(/#.*/,'');//local url without hash
var $localScroll = $.localScroll = function( settings ){
$('body').localScroll( settings );
};
//Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
//@see http://www.freewebs.com/flesler/jQuery.ScrollTo/
$localScroll.defaults = {//the defaults are public and can be overriden.
duration:1000, //how long to animate.
axis:'y',//which of top and left should be modified.
event:'click',//on which event to react.
stop:true//avoid queuing animations
/*
lock:false,//ignore events if already animating
lazy:false,//if true, links can be added later, and will still work.
target:null, //what to scroll (selector or element). Keep it null if want to scroll the whole window.
filter:null, //filter some anchors out of the matched elements.
hash: false//if true, the hash of the selected link, will appear on the address bar.
*/
};
//if the URL contains a hash, it will scroll to the pointed element
$localScroll.hash = function( settings ){
settings = $.extend( {}, $localScroll.defaults, settings );
settings.hash = false;//can't be true
if( location.hash )
setTimeout(function(){ scroll( 0, location, settings ); }, 0 );//better wrapped with a setTimeout
};
$.fn.localScroll = function( settings ){
settings = $.extend( {}, $localScroll.defaults, settings );
return ( settings.persistent || settings.lazy )
? this.bind( settings.event, function( e ){//use event delegation, more links can be added later.
var a = $([e.target, e.target.parentNode]).filter(filter)[0];//if a valid link was clicked.
a && scroll( e, a, settings );//do scroll.
})
: this.find('a')//bind concretely, to each matching link
.filter( filter ).bind( settings.event, function(e){
scroll( e, this, settings );
}).end()
.end();
function filter(){//is this a link that points to an anchor and passes a possible filter ? href is checked to avoid a bug in FF.
return !!this.href && !!this.hash && this.href.replace(this.hash,'') == URI && (!settings.filter || $(this).is( settings.filter ));
};
};
function scroll( e, link, settings ){
var id = link.hash.slice(1),
elem = document.getElementById(id) || document.getElementsByName(id)[0];
if ( elem ){
e && e.preventDefault();
var $target = $( settings.target || $.scrollTo.window() );//if none specified, then the window.
if( settings.lock && $target.is(':animated') ||
settings.onBefore && settings.onBefore.call(link, e, elem, $target) === false ) return;
if( settings.stop )
$target.queue('fx',[]).stop();//remove all its animations
$target
.scrollTo( elem, settings )//do scroll
.trigger('notify.serialScroll',[elem]);//notify serialScroll about this change
if( settings.hash )
$target.queue(function(){
location = link.hash;
});
}
};
})( jQuery ); | JavaScript |
/**
* jQuery.ScrollTo
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* Date: 2/19/2008
*
* @projectDescription Easy element scrolling using jQuery.
* Tested with jQuery 1.2.1. On FF 2.0.0.11, IE 6, Opera 9.22 and Safari 3 beta. on Windows.
*
* @author Ariel Flesler
* @version 1.3.3
*
* @id jQuery.scrollTo
* @id jQuery.fn.scrollTo
* @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
* The different options for target are:
* - A number position (will be applied to all axes).
* - A string position ('44', '100px', '+=90', etc ) will be applied to all axes
* - A jQuery/DOM element ( logically, child of the element to scroll )
* - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
* - A hash { top:x, left:y }, x and y can be any kind of number/string like above.
* @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
* @param {Object} settings Hash of settings, optional.
* @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
* @option {Number} duration The OVERALL length of the animation.
* @option {String} easing The easing method for the animation.
* @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
* @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
* @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
* @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
* @option {Function} onAfter Function to be called after the scrolling ends.
* @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
* @return {jQuery} Returns the same jQuery object, for chaining.
*
* @example $('div').scrollTo( 340 );
*
* @example $('div').scrollTo( '+=340px', { axis:'y' } );
*
* @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
*
* @example var second_child = document.getElementById('container').firstChild.nextSibling;
* $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
* alert('scrolled!!');
* }});
*
* @example $('div').scrollTo( { top: 300, left:'+=200' }, { offset:-20 } );
*
* Notes:
* - jQuery.scrollTo will make the whole window scroll, it accepts the same arguments as jQuery.fn.scrollTo.
* - If you are interested in animated anchor navigation, check http://jquery.com/plugins/project/LocalScroll.
* - The options margin, offset and over are ignored, if the target is not a jQuery object or a DOM element.
* - The option 'queue' won't be taken into account, if only 1 axis is given.
*/
;(function( $ ){
var $scrollTo = $.scrollTo = function( target, duration, settings ){
$scrollTo.window().scrollTo( target, duration, settings );
};
$scrollTo.defaults = {
axis:'y',
duration:1
};
//returns the element that needs to be animated to scroll the window
$scrollTo.window = function(){
return $( $.browser.safari ? 'body' : 'html' );
};
$.fn.scrollTo = function( target, duration, settings ){
if( typeof duration == 'object' ){
settings = duration;
duration = 0;
}
settings = $.extend( {}, $scrollTo.defaults, settings );
duration = duration || settings.speed || settings.duration;//speed is still recognized for backwards compatibility
settings.queue = settings.queue && settings.axis.length > 1;//make sure the settings are given right
if( settings.queue )
duration /= 2;//let's keep the overall speed, the same.
settings.offset = both( settings.offset );
settings.over = both( settings.over );
return this.each(function(){
var elem = this, $elem = $(elem),
t = target, toff, attr = {},
win = $elem.is('html,body');
switch( typeof t ){
case 'number'://will pass the regex
case 'string':
if( /^([+-]=)?\d+(px)?$/.test(t) ){
t = both( t );
break;//we are done
}
t = $(t,this);// relative selector, no break!
case 'object':
if( t.is || t.style )//DOM/jQuery
toff = (t = $(t)).offset();//get the real position of the target
}
$.each( settings.axis.split(''), function( i, axis ){
var Pos = axis == 'x' ? 'Left' : 'Top',
pos = Pos.toLowerCase(),
key = 'scroll' + Pos,
act = elem[key],
Dim = axis == 'x' ? 'Width' : 'Height',
dim = Dim.toLowerCase();
if( toff ){//jQuery/DOM
attr[key] = toff[pos] + ( win ? 0 : act - $elem.offset()[pos] );
if( settings.margin ){//if it's a dom element, reduce the margin
attr[key] -= parseInt(t.css('margin'+Pos)) || 0;
attr[key] -= parseInt(t.css('border'+Pos+'Width')) || 0;
}
attr[key] += settings.offset[pos] || 0;//add/deduct the offset
if( settings.over[pos] )//scroll to a fraction of its width/height
attr[key] += t[dim]() * settings.over[pos];
}else
attr[key] = t[pos];//remove the unnecesary 'px'
if( /^\d+$/.test(attr[key]) )//number or 'number'
attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );//check the limits
if( !i && settings.queue ){//queueing each axis is required
if( act != attr[key] )//don't waste time animating, if there's no need.
animate( settings.onAfterFirst );//intermediate animation
delete attr[key];//don't animate this axis again in the next iteration.
}
});
animate( settings.onAfter );
function animate( callback ){
$elem.animate( attr, duration, settings.easing, callback && function(){
callback.call(this, target);
});
};
function max( Dim ){
var el = win ? $.browser.opera ? document.body : document.documentElement : elem;
return el['scroll'+Dim] - el['client'+Dim];
};
});
};
function both( val ){
return typeof val == 'object' ? val : { top:val, left:val };
};
})( jQuery ); | JavaScript |
var url = "utilitaire.php";
// On rajoute 150 car hauteur du header
var hauteur = 500;
var lastid = 0;
var timer = setInterval(getMessages,5000);
var lastIdCommentaire = 0;
var nbMessage = 0;
$(function(){
$('.placeholder').each(function(){
var label = $(this).find('label');
var input = $(this).find('input');
if(input.val() != ''){
label.hide();
}
input.focus(function(){
if(input.val() == ''){
label.stop().fadeTo(500,0.5);
}
});
input.blur(function(){
if(input.val() == ''){
label.stop().fadeTo(500,1);
}
});
input.keypress(function(){
label.stop().hide();
});
input.keyup(function(){
if(input.val() == ''){
label.stop().fadeTo(500,0.5);
}
})
});
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef=' + recherche;
if(recherche.length>2){
$.ajax({
type : "GET",
url : url,
data : data,
success: function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
$("#button").toggle(
function() {
$("#header").animate({
height: hauteur + 150
//height: 400
}, 1000 );
$(".more").animate({
height: hauteur + 54
//height: 304
}, 1000 , function() {
$(".more").css({"background" : "url(images/moreH.png) center bottom no-repeat"});
$("#slider").css({"visibility" : "visible"});
// showLoader(".detail");
});
}, function() {
$("#slider").css({"visibility" : "hidden"});
hideLoader();
$("#header").animate({
height: 150
}, 1000 );
$(".more").animate({
height: 54
}, 1000 , function() {
$(".more").css({"background" : "url(images/more.png) center bottom no-repeat"});
});
}
);
$('.msg form').submit(function(){
clearInterval(timer);
showLoader("#commentaire #formCom input");
var commentaire = $("#message"+nbMessage+" #commentaire #formCom #inputExprimate"+nbMessage).val();
if(commentaire != ""){
$.post(url, {action:"addCommentaire", message:commentaire, nombre:nbMessage}, function(data){
if(data.erreur == "ok"){
getCommentaire();
$("#commentaire #formCom input").val("");
$("#commentaire").empty();
}else{
alert(data.erreur);
}
timer = setInterval(getCommentaire, 5000);
}, "json");
}else{
alert("Commentaire vide");
}
hideLoader();
return false;
})
$("#all_param form").submit(function(){
var idForm = $(this).prop('id');
var champs = $("#all_param #"+idForm+" input").val();
if (idForm == "PASSWD"){
var info = idForm;
champs += ";" + $("#all_param #"+idForm+" .newMdp").val();
}else if ((idForm == "COMP") || (idForm == "FORMA") || (idForm == "EXP")){
var info = idForm;
var champs = $("#all_param #"+idForm+" input").val();
if (idForm == "COMP")
{
champs += ";" + $("#all_param #"+idForm+" select").val();
}else{
champs += ";" + $("#all_param #"+idForm+" .poste").val();
}
champs += ";" + $("#all_param #"+idForm+" textarea").val();
}
if (champs != ""){
$.post(url,{action:"modifParams",champs:champs, idForm:idForm, info:info},function(data){
if (data.result == "ERROR1"){
alert("Mauvais mot de passe");
location.reload();
}
if(data.erreur=="ok"){
location.reload();
}
else{
alert(data.erreur);
}
}, "json");
return false;
}else{
alert("Le champs est vide !");
}
});
$("#fil_actu #formMess").submit(function(){
clearInterval(timer)
showLoader("#fil_actu form textarea");
var message = $("#fil_actu form textarea").val();
$.post(url,{action:"addMessage",message:message},function(data){
if(data.erreur=="ok"){
getMessages();
$("#fil_actu form textarea").val("");
}
else{
alert(data.erreur);
}
timer = setInterval(getMessages,5000);
hideLoader();
},"json");
return false;
})
$("#btnNew_message").click(function(){
$("#fil_actu .good-title").html("Mail | Nouveau message");
$("#afficheMessages").html('<form method="post" action="" id="form_mail"><span class="un_newMessage">Nouveau message</span><br><p>Adresse email</p><input style="width:300px; height:20px;" type="email" name="nom_mail" required><br><p>Objet</p><input style="width:300px; height:20px;" type="email" name="nom_mail"><br><p>Votre message</p><textarea style="width:90%; height:200px;" ></textarea><br><input type="submit" name="ok" value="Envoyer" /></form>');
$(".more_mail").css({"color" : "#7E7E7E"});
$(".new_mess").css({"color" : "black"});
});
});
function ouvreBoite(){
$(function() {
$("#header").animate({
height: hauteur + 150
//height: 400
}, 1000 );
$(".more").animate({
height: hauteur + 54
//height: 304
}, 1000 , function() {
$(".more").css({"background" : "url(images/moreH.png) center bottom no-repeat"});
$("#slider").css({"visibility" : "visible"});
// showLoader(".detail");
});
}), function() {
$("#slider").css({"visibility" : "hidden"});
hideLoader();
$("#header").animate({
height: 150
}, 1000 );
$(".more").animate({
height: 54
}, 1000 , function() {
$(".more").css({"background" : "url(images/more.png) center bottom no-repeat"});
});
}
}
function getMessages(){
$.post(url,{action:"getMessages",lastid:lastid},function(data){
if(data.erreur=="ok"){
$("#afficheMessages").prepend(data.result);
lastid = data.lastid;
}
else{
alert(data.erreur);
}
},"json");
return false;
}
function getCommentaire(){
$.post(url, {action:"getCommentaire", lastIdCommentaire: lastIdCommentaire, nombre: nbMessage}, function(data){
if(data.erreur == "ok"){
$("#message" +nbMessage+" ul").after(data.result);
lastIdCommentaire = data.lastIdCommentaire;
location.reload();
}else{
alert(data.erreur);
}
}, "json");
return false;
}
function deleteInfo(obj){
var idInfo = obj.id;
var nomInfo = obj.name;
$.post(url, {action:"deleteInfo", idInfo: idInfo, nomInfo:nomInfo}, function(data){
if(data.erreur == "ok"){
location.reload();
}else{
alert(data.erreur);
}
}, "json");
return false;
}
function showLoader(div){
$(div).append('<div class="loader"></div>');
$(".loader").fadeTo(500,0.6);
}
function hideLoader(){
$(".loader").fadeOut(500,function(){
$(".loader").remove();
});
}
function ajouteCommentaire(id){
if($("#message"+ id + " #commentaire #" + id + " #inputExprimate" + id).size() == "1"){ // si input existe déjà alors on supprime input + texte
$("#message"+ id + " #commentaire #" + id + " #inputExprimate" + id).remove();
$("#message"+ id + " #commentaire #" + id + " #pText").remove();
}else{
$("#message"+ id + " #commentaire #" + id).append('<input type="text" id="inputExprimate' +id +'" name="textCommentaire" style="margin: 15px 0 0 80px; height: 50px; width:83%;" /><p id="pText" style="text-align: center; font-size: 12px; margin: 5px 0 10px 0;" ><i>Appuyez sur la touche entrée pour valider</i></p>');
nbMessage = id;
}
}
function suppr(id, type){
// Si type = 1 => com sinon message
$.post(url, {action:"suppr", id: id, type: type}, function(data){
if(data.erreur == "ok"){
location.reload();
}else{
alert(data.erreur);
}
}, "json");
}
/* Fredo */
function afficheMenu(obj){
var idMenu = obj.id;
var idSousMenu = 'sous' + idMenu;
var sousMenu = document.getElementById(idSousMenu);
for(var i = 1; i <= 8; i++){
if(document.getElementById('sousmenu' + i) && document.getElementById('sousmenu' + i) != sousMenu){
document.getElementById('sousmenu' + i).style.display = "none";
}
}
if(sousMenu){
//alert(sousMenu.style.display);
if(sousMenu.style.display == "block"){
sousMenu.style.display = "none";
}
else{
sousMenu.style.display = "block";
}
}
}
function checkPswd(ext) {
if ((document.pswdForm.pswd.value == null) || (document.pswdForm.pswd.value == ''))
alert('Mot de passé invalid.');
else this.location.href = document.pswdForm.pswd.value + ext;
}
function create_groupe(pseudo, nom) {
var nom = document.getElementById('group_name').value;
$.post(url, {action:"create_group", pseudo: pseudo, nom: nom}, function(data){
if(data.erreur == "ok"){
location.reload();
}else{
alert(data.erreur);
}
}, "json");
} | JavaScript |
/**
* jQuery Opacity Rollover plugin
*
* Copyright (c) 2009 Trent Foley (http://trentacular.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
;(function($) {
var defaults = {
mouseOutOpacity: 0.67,
mouseOverOpacity: 1.0,
fadeSpeed: 'fast',
exemptionSelector: '.selected'
};
$.fn.opacityrollover = function(settings) {
// Initialize the effect
$.extend(this, defaults, settings);
var config = this;
function fadeTo(element, opacity) {
var $target = $(element);
if (config.exemptionSelector)
$target = $target.not(config.exemptionSelector);
$target.fadeTo(config.fadeSpeed, opacity);
}
this.css('opacity', this.mouseOutOpacity)
.hover(
function () {
fadeTo(this, config.mouseOverOpacity);
},
function () {
fadeTo(this, config.mouseOutOpacity);
});
return this;
};
})(jQuery);
| JavaScript |
/**
* jQuery Galleriffic plugin
*
* Copyright (c) 2008 Trent Foley (http://trentacular.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Much thanks to primary contributer Ponticlaro (http://www.ponticlaro.com)
*/
;(function($) {
// Globally keep track of all images by their unique hash. Each item is an image data object.
var allImages = {};
var imageCounter = 0;
// Galleriffic static class
$.galleriffic = {
version: '2.0.1',
// Strips invalid characters and any leading # characters
normalizeHash: function(hash) {
return hash.replace(/^.*#/, '').replace(/\?.*$/, '');
},
getImage: function(hash) {
if (!hash)
return undefined;
hash = $.galleriffic.normalizeHash(hash);
return allImages[hash];
},
// Global function that looks up an image by its hash and displays the image.
// Returns false when an image is not found for the specified hash.
// @param {String} hash This is the unique hash value assigned to an image.
gotoImage: function(hash) {
var imageData = $.galleriffic.getImage(hash);
if (!imageData)
return false;
var gallery = imageData.gallery;
gallery.gotoImage(imageData);
return true;
},
// Removes an image from its respective gallery by its hash.
// Returns false when an image is not found for the specified hash or the
// specified owner gallery does match the located images gallery.
// @param {String} hash This is the unique hash value assigned to an image.
// @param {Object} ownerGallery (Optional) When supplied, the located images
// gallery is verified to be the same as the specified owning gallery before
// performing the remove operation.
removeImageByHash: function(hash, ownerGallery) {
var imageData = $.galleriffic.getImage(hash);
if (!imageData)
return false;
var gallery = imageData.gallery;
if (ownerGallery && ownerGallery != gallery)
return false;
return gallery.removeImageByIndex(imageData.index);
}
};
var defaults = {
delay: 3000,
numThumbs: 20,
preloadAhead: 40, // Set to -1 to preload all images
enableTopPager: false,
enableBottomPager: true,
maxPagesToShow: 7,
imageContainerSel: '',
captionContainerSel: '',
controlsContainerSel: '',
loadingContainerSel: '',
renderSSControls: true,
renderNavControls: true,
playLinkText: 'Play',
pauseLinkText: 'Pause',
prevLinkText: 'Previous',
nextLinkText: 'Next',
nextPageLinkText: 'Next ›',
prevPageLinkText: '‹ Prev',
enableHistory: false,
enableKeyboardNavigation: true,
autoStart: false,
syncTransitions: false,
defaultTransitionDuration: 1000,
onSlideChange: undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
onTransitionOut: undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
onTransitionIn: undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
onPageTransitionOut: undefined, // accepts a delegate like such: function(callback) { ... }
onPageTransitionIn: undefined, // accepts a delegate like such: function() { ... }
onImageAdded: undefined, // accepts a delegate like such: function(imageData, $li) { ... }
onImageRemoved: undefined // accepts a delegate like such: function(imageData, $li) { ... }
};
// Primary Galleriffic initialization function that should be called on the thumbnail container.
$.fn.galleriffic = function(settings) {
// Extend Gallery Object
$.extend(this, {
// Returns the version of the script
version: $.galleriffic.version,
// Current state of the slideshow
isSlideshowRunning: false,
slideshowTimeout: undefined,
// This function is attached to the click event of generated hyperlinks within the gallery
clickHandler: function(e, link) {
this.pause();
if (!this.enableHistory) {
// The href attribute holds the unique hash for an image
var hash = $.galleriffic.normalizeHash($(link).attr('href'));
$.galleriffic.gotoImage(hash);
e.preventDefault();
}
},
// Appends an image to the end of the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html.
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
appendImage: function(listItem) {
this.addImage(listItem, false, false);
return this;
},
// Inserts an image into the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html.
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
// @param {Integer} position The index within the gallery where the item shouold be added.
insertImage: function(listItem, position) {
this.addImage(listItem, false, true, position);
return this;
},
// Adds an image to the gallery and optionally inserts/appends it to the DOM (thumbExists)
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
// @param {Boolean} thumbExists Specifies whether the thumbnail already exists in the DOM or if it needs to be added.
// @param {Boolean} insert Specifies whether the the image is appended to the end or inserted into the gallery.
// @param {Integer} position The index within the gallery where the item shouold be added.
addImage: function(listItem, thumbExists, insert, position) {
var $li = ( typeof listItem === "string" ) ? $(listItem) : listItem;
var $aThumb = $li.find('a.thumb');
var slideUrl = $aThumb.attr('href');
var title = $aThumb.attr('title');
var $caption = $li.find('.caption').remove();
var hash = $aThumb.attr('name');
// Increment the image counter
imageCounter++;
// Autogenerate a hash value if none is present or if it is a duplicate
if (!hash || allImages[''+hash]) {
hash = imageCounter;
}
// Set position to end when not specified
if (!insert)
position = this.data.length;
var imageData = {
title:title,
slideUrl:slideUrl,
caption:$caption,
hash:hash,
gallery:this,
index:position
};
// Add the imageData to this gallery's array of images
if (insert) {
this.data.splice(position, 0, imageData);
// Reset index value on all imageData objects
this.updateIndices(position);
}
else {
this.data.push(imageData);
}
var gallery = this;
// Add the element to the DOM
if (!thumbExists) {
// Update thumbs passing in addition post transition out handler
this.updateThumbs(function() {
var $thumbsUl = gallery.find('ul.thumbs');
if (insert)
$thumbsUl.children(':eq('+position+')').before($li);
else
$thumbsUl.append($li);
if (gallery.onImageAdded)
gallery.onImageAdded(imageData, $li);
});
}
// Register the image globally
allImages[''+hash] = imageData;
// Setup attributes and click handler
$aThumb.attr('rel', 'history')
.attr('href', '#'+hash)
.removeAttr('name')
.click(function(e) {
gallery.clickHandler(e, this);
});
return this;
},
// Removes an image from the gallery based on its index.
// Returns false when the index is out of range.
removeImageByIndex: function(index) {
if (index < 0 || index >= this.data.length)
return false;
var imageData = this.data[index];
if (!imageData)
return false;
this.removeImage(imageData);
return true;
},
// Convenience method that simply calls the global removeImageByHash method.
removeImageByHash: function(hash) {
return $.galleriffic.removeImageByHash(hash, this);
},
// Removes an image from the gallery.
removeImage: function(imageData) {
var index = imageData.index;
// Remove the image from the gallery data array
this.data.splice(index, 1);
// Remove the global registration
delete allImages[''+imageData.hash];
// Remove the image's list item from the DOM
this.updateThumbs(function() {
var $li = gallery.find('ul.thumbs')
.children(':eq('+index+')')
.remove();
if (gallery.onImageRemoved)
gallery.onImageRemoved(imageData, $li);
});
// Update each image objects index value
this.updateIndices(index);
return this;
},
// Updates the index values of the each of the images in the gallery after the specified index
updateIndices: function(startIndex) {
for (i = startIndex; i < this.data.length; i++) {
this.data[i].index = i;
}
return this;
},
// Scraped the thumbnail container for thumbs and adds each to the gallery
initializeThumbs: function() {
this.data = [];
var gallery = this;
this.find('ul.thumbs > li').each(function(i) {
gallery.addImage($(this), true, false);
});
return this;
},
isPreloadComplete: false,
// Initalizes the image preloader
preloadInit: function() {
if (this.preloadAhead == 0) return this;
this.preloadStartIndex = this.currentImage.index;
var nextIndex = this.getNextIndex(this.preloadStartIndex);
return this.preloadRecursive(this.preloadStartIndex, nextIndex);
},
// Changes the location in the gallery the preloader should work
// @param {Integer} index The index of the image where the preloader should restart at.
preloadRelocate: function(index) {
// By changing this startIndex, the current preload script will restart
this.preloadStartIndex = index;
return this;
},
// Recursive function that performs the image preloading
// @param {Integer} startIndex The index of the first image the current preloader started on.
// @param {Integer} currentIndex The index of the current image to preload.
preloadRecursive: function(startIndex, currentIndex) {
// Check if startIndex has been relocated
if (startIndex != this.preloadStartIndex) {
var nextIndex = this.getNextIndex(this.preloadStartIndex);
return this.preloadRecursive(this.preloadStartIndex, nextIndex);
}
var gallery = this;
// Now check for preloadAhead count
var preloadCount = currentIndex - startIndex;
if (preloadCount < 0)
preloadCount = this.data.length-1-startIndex+currentIndex;
if (this.preloadAhead >= 0 && preloadCount > this.preloadAhead) {
// Do this in order to keep checking for relocated start index
setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500);
return this;
}
var imageData = this.data[currentIndex];
if (!imageData)
return this;
// If already loaded, continue
if (imageData.image)
return this.preloadNext(startIndex, currentIndex);
// Preload the image
var image = new Image();
image.onload = function() {
imageData.image = this;
gallery.preloadNext(startIndex, currentIndex);
};
image.alt = imageData.title;
image.src = imageData.slideUrl;
return this;
},
// Called by preloadRecursive in order to preload the next image after the previous has loaded.
// @param {Integer} startIndex The index of the first image the current preloader started on.
// @param {Integer} currentIndex The index of the current image to preload.
preloadNext: function(startIndex, currentIndex) {
var nextIndex = this.getNextIndex(currentIndex);
if (nextIndex == startIndex) {
this.isPreloadComplete = true;
} else {
// Use setTimeout to free up thread
var gallery = this;
setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100);
}
return this;
},
// Safe way to get the next image index relative to the current image.
// If the current image is the last, returns 0
getNextIndex: function(index) {
var nextIndex = index+1;
if (nextIndex >= this.data.length)
nextIndex = 0;
return nextIndex;
},
// Safe way to get the previous image index relative to the current image.
// If the current image is the first, return the index of the last image in the gallery.
getPrevIndex: function(index) {
var prevIndex = index-1;
if (prevIndex < 0)
prevIndex = this.data.length-1;
return prevIndex;
},
// Pauses the slideshow
pause: function() {
this.isSlideshowRunning = false;
if (this.slideshowTimeout) {
clearTimeout(this.slideshowTimeout);
this.slideshowTimeout = undefined;
}
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.ss-controls a').removeClass().addClass('play')
.attr('title', this.playLinkText)
.attr('href', '#play')
.html(this.playLinkText);
}
return this;
},
// Plays the slideshow
play: function() {
this.isSlideshowRunning = true;
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.ss-controls a').removeClass().addClass('pause')
.attr('title', this.pauseLinkText)
.attr('href', '#pause')
.html(this.pauseLinkText);
}
if (!this.slideshowTimeout) {
var gallery = this;
this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay);
}
return this;
},
// Toggles the state of the slideshow (playing/paused)
toggleSlideshow: function() {
if (this.isSlideshowRunning)
this.pause();
else
this.play();
return this;
},
// Advances the slideshow to the next image and delegates navigation to the
// history plugin when history is enabled
// enableHistory is true
ssAdvance: function() {
if (this.isSlideshowRunning)
this.next(true);
return this;
},
// Advances the gallery to the next image.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
next: function(dontPause, bypassHistory) {
this.gotoIndex(this.getNextIndex(this.currentImage.index), dontPause, bypassHistory);
return this;
},
// Navigates to the previous image in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
previous: function(dontPause, bypassHistory) {
this.gotoIndex(this.getPrevIndex(this.currentImage.index), dontPause, bypassHistory);
return this;
},
// Navigates to the next page in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
nextPage: function(dontPause, bypassHistory) {
var page = this.getCurrentPage();
var lastPage = this.getNumPages() - 1;
if (page < lastPage) {
var startIndex = page * this.numThumbs;
var nextPage = startIndex + this.numThumbs;
this.gotoIndex(nextPage, dontPause, bypassHistory);
}
return this;
},
// Navigates to the previous page in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
previousPage: function(dontPause, bypassHistory) {
var page = this.getCurrentPage();
if (page > 0) {
var startIndex = page * this.numThumbs;
var prevPage = startIndex - this.numThumbs;
this.gotoIndex(prevPage, dontPause, bypassHistory);
}
return this;
},
// Navigates to the image at the specified index in the gallery
// @param {Integer} index The index of the image in the gallery to display.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
gotoIndex: function(index, dontPause, bypassHistory) {
if (!dontPause)
this.pause();
if (index < 0) index = 0;
else if (index >= this.data.length) index = this.data.length-1;
var imageData = this.data[index];
if (!bypassHistory && this.enableHistory)
$.historyLoad(String(imageData.hash)); // At the moment, historyLoad only accepts string arguments
else
this.gotoImage(imageData);
return this;
},
// This function is garaunteed to be called anytime a gallery slide changes.
// @param {Object} imageData An object holding the image metadata of the image to navigate to.
gotoImage: function(imageData) {
var index = imageData.index;
if (this.onSlideChange)
this.onSlideChange(this.currentImage.index, index);
this.currentImage = imageData;
this.preloadRelocate(index);
this.refresh();
return this;
},
// Returns the default transition duration value. The value is halved when not
// performing a synchronized transition.
// @param {Boolean} isSync Specifies whether the transitions are synchronized.
getDefaultTransitionDuration: function(isSync) {
if (isSync)
return this.defaultTransitionDuration;
return this.defaultTransitionDuration / 2;
},
// Rebuilds the slideshow image and controls and performs transitions
refresh: function() {
var imageData = this.currentImage;
if (!imageData)
return this;
var index = imageData.index;
// Update Controls
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.nav-controls a.prev').attr('href', '#'+this.data[this.getPrevIndex(index)].hash).end()
.find('div.nav-controls a.next').attr('href', '#'+this.data[this.getNextIndex(index)].hash);
}
var previousSlide = this.$imageContainer.find('span.current').addClass('previous').removeClass('current');
var previousCaption = 0;
if (this.$captionContainer) {
previousCaption = this.$captionContainer.find('span.current').addClass('previous').removeClass('current');
}
// Perform transitions simultaneously if syncTransitions is true and the next image is already preloaded
var isSync = this.syncTransitions && imageData.image;
// Flag we are transitioning
var isTransitioning = true;
var gallery = this;
var transitionOutCallback = function() {
// Flag that the transition has completed
isTransitioning = false;
// Remove the old slide
previousSlide.remove();
// Remove old caption
if (previousCaption)
previousCaption.remove();
if (!isSync) {
if (imageData.image && imageData.hash == gallery.data[gallery.currentImage.index].hash) {
gallery.buildImage(imageData, isSync);
} else {
// Show loading container
if (gallery.$loadingContainer) {
gallery.$loadingContainer.show();
}
}
}
};
if (previousSlide.length == 0) {
// For the first slide, the previous slide will be empty, so we will call the callback immediately
transitionOutCallback();
} else {
if (this.onTransitionOut) {
this.onTransitionOut(previousSlide, previousCaption, isSync, transitionOutCallback);
} else {
previousSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0, transitionOutCallback);
if (previousCaption)
previousCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0);
}
}
// Go ahead and begin transitioning in of next image
if (isSync)
this.buildImage(imageData, isSync);
if (!imageData.image) {
var image = new Image();
// Wire up mainImage onload event
image.onload = function() {
imageData.image = this;
// Only build image if the out transition has completed and we are still on the same image hash
if (!isTransitioning && imageData.hash == gallery.data[gallery.currentImage.index].hash) {
gallery.buildImage(imageData, isSync);
}
};
// set alt and src
image.alt = imageData.title;
image.src = imageData.slideUrl;
}
// This causes the preloader (if still running) to relocate out from the currentIndex
this.relocatePreload = true;
return this.syncThumbs();
},
// Called by the refresh method after the previous image has been transitioned out or at the same time
// as the out transition when performing a synchronous transition.
// @param {Object} imageData An object holding the image metadata of the image to build.
// @param {Boolean} isSync Specifies whether the transitions are synchronized.
buildImage: function(imageData, isSync) {
var gallery = this;
var nextIndex = this.getNextIndex(imageData.index);
// Construct new hidden span for the image
var newSlide = this.$imageContainer
.append('<span class="image-wrapper current"><a class="advance-link" rel="history" href="#'+this.data[nextIndex].hash+'" title="'+imageData.title+'"> </a></span>')
.find('span.current').css('opacity', '0');
newSlide.find('a')
.append(imageData.image)
.click(function(e) {
gallery.clickHandler(e, this);
});
var newCaption = 0;
if (this.$captionContainer) {
// Construct new hidden caption for the image
newCaption = this.$captionContainer
.append('<span class="image-caption current"></span>')
.find('span.current').css('opacity', '0')
.append(imageData.caption);
}
// Hide the loading conatiner
if (this.$loadingContainer) {
this.$loadingContainer.hide();
}
// Transition in the new image
if (this.onTransitionIn) {
this.onTransitionIn(newSlide, newCaption, isSync);
} else {
newSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
if (newCaption)
newCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
}
if (this.isSlideshowRunning) {
if (this.slideshowTimeout)
clearTimeout(this.slideshowTimeout);
this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay);
}
return this;
},
// Returns the current page index that should be shown for the currentImage
getCurrentPage: function() {
return Math.floor(this.currentImage.index / this.numThumbs);
},
// Applies the selected class to the current image's corresponding thumbnail.
// Also checks if the current page has changed and updates the displayed page of thumbnails if necessary.
syncThumbs: function() {
var page = this.getCurrentPage();
if (page != this.displayedPage)
this.updateThumbs();
// Remove existing selected class and add selected class to new thumb
var $thumbs = this.find('ul.thumbs').children();
$thumbs.filter('.selected').removeClass('selected');
$thumbs.eq(this.currentImage.index).addClass('selected');
return this;
},
// Performs transitions on the thumbnails container and updates the set of
// thumbnails that are to be displayed and the navigation controls.
// @param {Delegate} postTransitionOutHandler An optional delegate that is called after
// the thumbnails container has transitioned out and before the thumbnails are rebuilt.
updateThumbs: function(postTransitionOutHandler) {
var gallery = this;
var transitionOutCallback = function() {
// Call the Post-transition Out Handler
if (postTransitionOutHandler)
postTransitionOutHandler();
gallery.rebuildThumbs();
// Transition In the thumbsContainer
if (gallery.onPageTransitionIn)
gallery.onPageTransitionIn();
else
gallery.show();
};
// Transition Out the thumbsContainer
if (this.onPageTransitionOut) {
this.onPageTransitionOut(transitionOutCallback);
} else {
this.hide();
transitionOutCallback();
}
return this;
},
// Updates the set of thumbnails that are to be displayed and the navigation controls.
rebuildThumbs: function() {
var needsPagination = this.data.length > this.numThumbs;
// Rebuild top pager
if (this.enableTopPager) {
var $topPager = this.find('div.top');
if ($topPager.length == 0)
$topPager = this.prepend('<div class="top pagination"></div>').find('div.top');
else
$topPager.empty();
if (needsPagination)
this.buildPager($topPager);
}
// Rebuild bottom pager
if (this.enableBottomPager) {
var $bottomPager = this.find('div.bottom');
if ($bottomPager.length == 0)
$bottomPager = this.append('<div class="bottom pagination"></div>').find('div.bottom');
else
$bottomPager.empty();
if (needsPagination)
this.buildPager($bottomPager);
}
var page = this.getCurrentPage();
var startIndex = page*this.numThumbs;
var stopIndex = startIndex+this.numThumbs-1;
if (stopIndex >= this.data.length)
stopIndex = this.data.length-1;
// Show/Hide thumbs
var $thumbsUl = this.find('ul.thumbs');
$thumbsUl.find('li').each(function(i) {
var $li = $(this);
if (i >= startIndex && i <= stopIndex) {
$li.show();
} else {
$li.hide();
}
});
this.displayedPage = page;
// Remove the noscript class from the thumbs container ul
$thumbsUl.removeClass('noscript');
return this;
},
// Returns the total number of pages required to display all the thumbnails.
getNumPages: function() {
return Math.ceil(this.data.length/this.numThumbs);
},
// Rebuilds the pager control in the specified matched element.
// @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt.
buildPager: function(pager) {
var gallery = this;
var numPages = this.getNumPages();
var page = this.getCurrentPage();
var startIndex = page * this.numThumbs;
var pagesRemaining = this.maxPagesToShow - 1;
var pageNum = page - Math.floor((this.maxPagesToShow - 1) / 2) + 1;
if (pageNum > 0) {
var remainingPageCount = numPages - pageNum;
if (remainingPageCount < pagesRemaining) {
pageNum = pageNum - (pagesRemaining - remainingPageCount);
}
}
if (pageNum < 0) {
pageNum = 0;
}
// Prev Page Link
if (page > 0) {
var prevPage = startIndex - this.numThumbs;
pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.prevPageLinkText+'">'+this.prevPageLinkText+'</a>');
}
// Create First Page link if needed
if (pageNum > 0) {
this.buildPageLink(pager, 0, numPages);
if (pageNum > 1)
pager.append('<span class="ellipsis">…</span>');
pagesRemaining--;
}
// Page Index Links
while (pagesRemaining > 0) {
this.buildPageLink(pager, pageNum, numPages);
pagesRemaining--;
pageNum++;
}
// Create Last Page link if needed
if (pageNum < numPages) {
var lastPageNum = numPages - 1;
if (pageNum < lastPageNum)
pager.append('<span class="ellipsis">…</span>');
this.buildPageLink(pager, lastPageNum, numPages);
}
// Next Page Link
var nextPage = startIndex + this.numThumbs;
if (nextPage < this.data.length) {
pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.nextPageLinkText+'">'+this.nextPageLinkText+'</a>');
}
pager.find('a').click(function(e) {
gallery.clickHandler(e, this);
});
return this;
},
// Builds a single page link within a pager. This function is called by buildPager
// @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt.
// @param {Integer} pageNum The page number of the page link to build.
// @param {Integer} numPages The total number of pages required to display all thumbnails.
buildPageLink: function(pager, pageNum, numPages) {
var pageLabel = pageNum + 1;
var currentPage = this.getCurrentPage();
if (pageNum == currentPage)
pager.append('<span class="current">'+pageLabel+'</span>');
else if (pageNum < numPages) {
var imageIndex = pageNum*this.numThumbs;
pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageLabel+'">'+pageLabel+'</a>');
}
return this;
}
});
// Now initialize the gallery
$.extend(this, defaults, settings);
// Verify the history plugin is available
if (this.enableHistory && !$.historyInit)
this.enableHistory = false;
// Select containers
if (this.imageContainerSel) this.$imageContainer = $(this.imageContainerSel);
if (this.captionContainerSel) this.$captionContainer = $(this.captionContainerSel);
if (this.loadingContainerSel) this.$loadingContainer = $(this.loadingContainerSel);
// Initialize the thumbails
this.initializeThumbs();
if (this.maxPagesToShow < 3)
this.maxPagesToShow = 3;
this.displayedPage = -1;
this.currentImage = this.data[0];
var gallery = this;
// Hide the loadingContainer
if (this.$loadingContainer)
this.$loadingContainer.hide();
// Setup controls
if (this.controlsContainerSel) {
this.$controlsContainer = $(this.controlsContainerSel).empty();
if (this.renderSSControls) {
if (this.autoStart) {
this.$controlsContainer
.append('<div class="ss-controls"><a href="#pause" class="pause" title="'+this.pauseLinkText+'">'+this.pauseLinkText+'</a></div>');
} else {
this.$controlsContainer
.append('<div class="ss-controls"><a href="#play" class="play" title="'+this.playLinkText+'">'+this.playLinkText+'</a></div>');
}
this.$controlsContainer.find('div.ss-controls a')
.click(function(e) {
gallery.toggleSlideshow();
e.preventDefault();
return false;
});
}
if (this.renderNavControls) {
this.$controlsContainer
.append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.prevLinkText+'">'+this.prevLinkText+'</a><a class="next" rel="history" title="'+this.nextLinkText+'">'+this.nextLinkText+'</a></div>')
.find('div.nav-controls a')
.click(function(e) {
gallery.clickHandler(e, this);
});
}
}
var initFirstImage = !this.enableHistory || !location.hash;
if (this.enableHistory && location.hash) {
var hash = $.galleriffic.normalizeHash(location.hash);
var imageData = allImages[hash];
if (!imageData)
initFirstImage = true;
}
// Setup gallery to show the first image
if (initFirstImage)
this.gotoIndex(0, false, true);
// Setup Keyboard Navigation
if (this.enableKeyboardNavigation) {
$(document).keydown(function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
switch(key) {
case 32: // space
gallery.next();
e.preventDefault();
break;
case 33: // Page Up
gallery.previousPage();
e.preventDefault();
break;
case 34: // Page Down
gallery.nextPage();
e.preventDefault();
break;
case 35: // End
gallery.gotoIndex(gallery.data.length-1);
e.preventDefault();
break;
case 36: // Home
gallery.gotoIndex(0);
e.preventDefault();
break;
case 37: // left arrow
gallery.previous();
e.preventDefault();
break;
case 39: // right arrow
gallery.next();
e.preventDefault();
break;
}
});
}
// Auto start the slideshow
if (this.autoStart)
this.play();
// Kickoff Image Preloader after 1 second
setTimeout(function() { gallery.preloadInit(); }, 1000);
return this;
};
})(jQuery);
| JavaScript |
/**
* jQuery.serialScroll
* Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 3/20/2008
*
* @projectDescription Animated scrolling of series.
* @author Ariel Flesler
* @version 1.2.1
*
* @id jQuery.serialScroll
* @id jQuery.fn.serialScroll
* @param {Object} settings Hash of settings, it is passed in to jQuery.ScrollTo, none is required.
* @return {jQuery} Returns the same jQuery object, for chaining.
*
* http://flesler.blogspot.com/2008/02/jqueryserialscroll.html
*
* Notes:
* - The plugin requires jQuery.ScrollTo.
* - The hash of settings, is passed to jQuery.ScrollTo, so its settings can be used as well.
*/
;(function( $ ){
var $serialScroll = $.serialScroll = function( settings ){
$.scrollTo.window().serialScroll( settings );
};
//Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
//@see http://flesler.webs/jQuery.ScrollTo/
$serialScroll.defaults = {//the defaults are public and can be overriden.
duration:1000, //how long to animate.
axis:'x', //which of top and left should be scrolled
event:'click', //on which event to react.
start:0, //first element (zero-based index)
step:1, //how many elements to scroll on each action
lock:true,//ignore events if already animating
cycle:true, //cycle endlessly ( constant velocity )
constant:true //use contant speed ?
/*
navigation:null,//if specified, it's a selector a collection of items to navigate the container
target:null, //if specified, it's a selector to the element to be scrolled.
interval:0, //it's the number of milliseconds to automatically go to the next
lazy:false,//go find the elements each time (allows AJAX or JS content, or reordering)
stop:false, //stop any previous animations to avoid queueing
force:false,//force the scroll to the first element on start ?
jump: false,//if true, when the event is triggered on an element, the pane scrolls to it
items:null, //selector to the items (relative to the matched elements)
prev:null, //selector to the 'prev' button
next:null, //selector to the 'next' button
onBefore: function(){}, //function called before scrolling, if it returns false, the event is ignored
exclude:0 //exclude the last x elements, so we cannot scroll past the end
*/
};
$.fn.serialScroll = function( settings ){
settings = $.extend( {}, $serialScroll.defaults, settings );
var event = settings.event, //this one is just to get shorter code when compressed
step = settings.step, // idem
lazy = settings.lazy;//idem
return this.each(function(){
var
context = settings.target ? this : document, //if a target is specified, then everything's relative to 'this'.
$pane = $(settings.target || this, context),//the element to be scrolled (will carry all the events)
pane = $pane[0], //will be reused, save it into a variable
items = settings.items, //will hold a lazy list of elements
active = settings.start, //active index
auto = settings.interval, //boolean, do auto or not
nav = settings.navigation, //save it now to make the code shorter
timer; //holds the interval id
if( !lazy )//if not lazy, go get the items now
items = getItems();
if( settings.force )
jump( {}, active );//generate an initial call
// Button binding, optionall
$(settings.prev||[], context).bind( event, -step, move );
$(settings.next||[], context).bind( event, step, move );
// Custom events bound to the container
if( !pane.ssbound )//don't bind more than once
$pane
.bind('prev.serialScroll', -step, move ) //you can trigger with just 'prev'
.bind('next.serialScroll', step, move ) //for example: $(container).trigger('next');
.bind('goto.serialScroll', jump ); //for example: $(container).trigger('goto', [4] );
if( auto )
$pane
.bind('start.serialScroll', function(e){
if( !auto ){
clear();
auto = true;
next();
}
})
.bind('stop.serialScroll', function(){//stop a current animation
clear();
auto = false;
});
$pane.bind('notify.serialScroll', function(e, elem){//let serialScroll know that the index changed externally
var i = index(elem);
if( i > -1 )
active = i;
});
pane.ssbound = true;//avoid many bindings
if( settings.jump )//can't use jump if using lazy items and a non-bubbling event
(lazy ? $pane : getItems()).bind( event, function( e ){
jump( e, index(e.target) );
});
if( nav )
nav = $(nav, context).bind(event, function( e ){
e.data = Math.round(getItems().length / nav.length) * nav.index(this);
jump( e, this );
});
function move( e ){
e.data += active;
jump( e, this );
};
function jump( e, button ){
if( !isNaN(button) ){//initial or special call from the outside $(container).trigger('goto',[index]);
e.data = button;
button = pane;
}
var
pos = e.data, n,
real = e.type, //is a real event triggering ?
$items = settings.exclude ? getItems().slice(0,-settings.exclude) : getItems(),//handle a possible exclude
limit = $items.length,
elem = $items[pos],
duration = settings.duration;
if( real )//real event object
e.preventDefault();
if( auto ){
clear();//clear any possible automatic scrolling.
timer = setTimeout( next, settings.interval );
}
if( !elem ){ //exceeded the limits
n = pos < 0 ? 0 : limit - 1;
if( active != n )//we exceeded for the first time
pos = n;
else if( !settings.cycle )//this is a bad case
return;
else
pos = limit - n - 1;//invert, go to the other side
elem = $items[pos];
}
if( !elem || real && active == pos || //could happen, save some CPU cycles in vain
settings.lock && $pane.is(':animated') || //no animations while busy
real && settings.onBefore && //callback returns false ?
settings.onBefore.call(button, e, elem, $pane, getItems(), pos) === false ) return;
if( settings.stop )
$pane.queue('fx',[]).stop();//remove all its animations
if( settings.constant )
duration = Math.abs(duration/step * (active - pos ));//keep constant velocity
$pane
.scrollTo( elem, duration, settings )//do scroll
.trigger('notify.serialScroll',[pos]);//in case serialScroll was called on this elem more than once.
};
function next(){//I'll use the namespace to avoid conflicts
$pane.trigger('next.serialScroll');
};
function clear(){
clearTimeout(timer);
};
function getItems(){
return $( items, pane );
};
function index( elem ){
if( !isNaN(elem) ) return elem;//number
var $items = getItems(), i;
while(( i = $items.index(elem)) == -1 && elem != pane )//see if it matches or one of its ancestors
elem = elem.parentNode;
return i;
};
});
};
})( jQuery ); | JavaScript |
(function($) {
$.fn.extend({
jCountdown:function(){
var Flip = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 50;
this._height = 64;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
}
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
}
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
}
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
}
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = -(9-this.value())*this.width();
var top = -(this.frame()-1)*this.height();
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px");
}
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
}
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
}
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Slide = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 50;
this._height = 64;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
}
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = 0;
var top = -((1+this.value())*this.height()) + (Math.sin((this.frame()-1)/(this.totalFrames()-1)*Math.PI/2)*this.height());
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px");
};
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Metal = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 60;
this._height = 60;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
};
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var lastValue = this.value()+1;
if(lastValue>9){
lastValue = 0;
};
var progress = this.frame()/this.totalFrames();
var opacity;
if(progress>=.4 && progress<=.6){
opacity = 0;
}else if(progress<=.4){
opacity = 1-progress/.4;
}else if(progress>=.6){
opacity = (progress-.6)/.4;
};
var left = 0;
var top = -(progress>.5 ? this.value() : lastValue)*this.height();
top -= (1-opacity)*3;
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px").css("opacity",opacity);
this._target.children(".cover").css("opacity",opacity);
}
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Crystal = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 60;
this._height = 60;
this._widthSmall= 42;
this._heightSmall = 42;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
};
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = 0;
var top = -this.value()*this.height();
var opacity = Math.sin((this.frame()-1)/(this.totalFrames()-1)*Math.PI/2);
if(opacity>0 && opacity<0.001){
opacity = 0;
}else if(opacity<0 && opacity>-0.001){
opacity = 0;
};
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px").css("opacity",opacity);
};
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Countdown = function(){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._days = [];
this._hours = [];
this._minutes = [];
this._seconds = [];
this._tickId = -1;
this._tickDelay = 100;
this._timeText = "";
this._timeZone = 0;
this._time = null;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
//check time
this.checkTime = function(update){
var currentTime = new Date();
if(this._time.getTime()<(currentTime.getTime())){
for(var i=0; i<this._days.length; i++){
this._days[i].value(0);
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].value(0);
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].value(0);
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].value(0);
};
this.stop();
this.onFinish();
return true;
}else{
var currentTimeText = this.timeFormat(this._time.getTime()-(currentTime.getTime()), this._days.length, this._hours.length, this._minutes.length, this._seconds.length);
var currentTimeChars = currentTimeText.split("");
if (!isNaN(this._time)){
for(var i=0; i<this._days.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._days[i].value()){
this._days[i].value(v, update);
};
};
for(var i=0; i<this._hours.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._hours[i].value()){
this._hours[i].value(v, update);
};
};
for(var i=0; i<this._minutes.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._minutes[i].value()){
this._minutes[i].value(v, update);
};
};
for(var i=0; i<this._seconds.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._seconds[i].value()){
this._seconds[i].value(v, update);
};
};
};
return false;
};
};
//text format
this.textFormat = function(text, length, fillChar){
text = text.toString();
while (text.length<length){
text = fillChar+text;
};
if(text.length>length){
text = text.substr(text.length-length,length);
};
return text;
};
//time format
this.timeFormat = function(msec, dayTextNumber, hourTextNumber, minuteTextNumber, secondTextNumber){
var time = Math.floor(msec/1000);
var s = time%60;
var i = Math.floor(time%(60*60)/60);
var h = Math.floor(time%(24*60*60)/(60*60));
var d = Math.floor(time/(24*60*60));
return this.textFormat(d, dayTextNumber, "0")+this.textFormat(h, hourTextNumber, "0")+this.textFormat(i, minuteTextNumber, "0")+this.textFormat(s, secondTextNumber, "0");
};
//start
this.start = function(){
this.stop();
for(var i=0; i<this._days.length; i++){
this._days[i].update();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].update();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].update();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].update();
};
var finish = this.checkTime(false);
if(!finish){
var target = this;
this._tickId = setInterval(function(){
target.checkTime(true);
}, this._tickDelay);
};
};
//stop
this.stop = function(){
for(var i=0; i<this._days.length; i++){
this._days[i].stop();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].stop();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].stop();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].stop();
};
clearInterval(this._tickId);
};
this.onFinish = function(){
};
this.destroy = function(){
for(var i=0; i<this._days.length; i++){
this._days[i].destroy();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].destroy();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].destroy();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].destroy();
};
this._days = [];
this._hours = [];
this._minutes = [];
this._seconds = [];
this.stop();
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.items = function(days, hours, minutes, seconds){
this._days = days;
this._hours = hours;
this._minutes = minutes;
this._seconds = seconds;
};
this.timeText = function(v){
if(v==undefined){
return this._timeText;
}else{
this._timeText = v;
this.time(this.timeText(), this.timeZone());
};
};
this.timeZone = function(v){
if(v==undefined){
return this._timeZone;
}else{
this._timeZone = v;
this.time(this.timeText(), this.timeZone());
};
};
//time
this.time = function(tt,tz){
this._timeText = tt;
this._timeZone = tz;
var time = this._timeText.split("/").join(" ").split(":").join(" ").split(" ");
var y = parseInt(time[0],10);
var m = parseInt(time[1],10)-1;
var d = parseInt(time[2],10);
var h = parseInt(time[3],10);
var i = parseInt(time[4],10)-this._timeZone*60;
var s = parseInt(time[5],10);
this._time = new Date(y, m, d, h, i, s, 0);
this.start();
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
var getCountdown = function(){
return target.data("countdown");
};
var initCountdown = function(){
if(getCountdown()==undefined){
var countdown = new Countdown();
target.data("countdown", countdown);
return getCountdown();
};
};
var destroyCountdown = function(){
if(getCountdown()!=undefined){
getCountdown().destroy();
target.removeData("countdown");
};
};
var init = function(setting){
countdown = initCountdown();
var browserVersion = parseInt($.browser.version,10);
var timeText = typeof(setting.timeText)=="string" ? setting.timeText : "";
var timeZone = parseFloat(setting.timeZone);
if(isNaN(timeZone)){
timeZone = 0;
};
var style = typeof(setting.style)=="string" ? setting.style.toLowerCase() : "";
switch(style){
case "flip":
break;
case "slide":
break;
case "crystal":
break;
case "metal":
break;
default:
style = "flip";
};
var color = typeof(setting.color)=="string" ? setting.color.toLowerCase() : "";
switch(color){
case "black":
break;
case "white":
break;
default:
color = "black";
};
var width = parseInt(setting.width,10);
if(width>=10){
}else{
width = 0;
};
var textGroupSpace = parseInt(setting.textGroupSpace,10);
if(textGroupSpace>=0){
}else{
textGroupSpace = 15;
};
var textSpace = parseInt(setting.textSpace,10);
if(textSpace>0){
}else{
textSpace = 0;
};
var reflection = setting.reflection!=false;
var reflectionOpacity = parseFloat(setting.reflectionOpacity);
if(reflectionOpacity>0){
if(reflectionOpacity>100){
reflectionOpacity = 100;
}
}else{
reflectionOpacity = 10;
};
var reflectionBlur = parseInt(setting.reflectionBlur,10);
if(reflectionBlur>0){
if(reflectionBlur>10){
reflectionBlur = 10;
}
}else{
reflectionBlur = 0;
};
var dayTextNumber = parseInt(setting.dayTextNumber,10)>2 ? parseInt(setting.dayTextNumber,10) : 2;
var hourTextNumber = 2;
var minuteTextNumber = 2;
var secondTextNumber = 2;
var displayDay = setting.displayDay!=false;
var displayHour = setting.displayHour!=false;
var displayMinute = setting.displayMinute!=false;
var displaySecond = setting.displaySecond!=false;
var displayLabel = setting.displayLabel!=false;
var onFinish = typeof(setting.onFinish)=="function" ? setting.onFinish : function(){};
var html = "";
var itemClass = "";
var lastClass = "";
html += '<div class="jCountdown">';
if(displayDay){
var lastItem = (!displayHour && !displayMinute && !displaySecond) ? " lastItem" : "";
html += '<div class="group day'+lastItem+'">';
for(var i=0; i<dayTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(dayTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displayHour){
var lastItem = (!displayMinute && !displaySecond) ? " lastItem" : "";
html += '<div class="group hour'+lastItem+'">';
for(var i=0; i<hourTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(hourTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displayMinute){
var lastItem = (!displaySecond) ? " lastItem" : "";
html += '<div class="group minute'+lastItem+'">';
for(var i=0; i<minuteTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(minuteTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displaySecond){
html += '<div class="group second lastItem">';
for(var i=0; i<secondTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(secondTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
html += '</div>';
target.html(html);
var countdownObject = target.children(".jCountdown");
countdownObject.addClass(style);
countdownObject.addClass(color);
countdownObject.children(".group").css("margin-right",textGroupSpace+"px");
countdownObject.children(".group.lastItem").css("margin-right","0px");
countdownObject.children(".group").children(".container").css("margin-right",textSpace+"px");
countdownObject.children(".group").children(".container.lastItem").css("margin-right","0px");
if(reflection){
if(($.browser.msie && browserVersion<10)){
}else{
reflectionObject = countdownObject.clone();
reflectionObject.addClass("reflection");
if(displayLabel){
reflectionObject.addClass("displayLabel");
};
if(reflectionOpacity!=100){
reflectionObject.css("opacity",reflectionOpacity/100);
};
if(reflectionBlur!=0){
reflectionObject.addClass("blur"+reflectionBlur);
};
countdownObject = countdownObject.add(reflectionObject);
}
};
var countdownContainer = $('<div class="jCountdownContainer"></div>');
countdownContainer.append(countdownObject);
target.append(countdownContainer);
if(width!=0){
var countdownScaleObject = $('<div class="jCountdownScale"></div>');
countdownScaleObject.append(countdownObject);
countdownContainer.append(countdownScaleObject);
var countdownScaleObjectWidth = countdownScaleObject.width();
var countdownScaleObjectHeight = countdownScaleObject.height();
var scale = width/countdownScaleObjectWidth;
var left = -(1-scale)*countdownScaleObjectWidth/2;
var top = -(1-scale)*countdownScaleObjectHeight/2;
var scaleCss = "scale("+scale+")";
countdownContainer.width(countdownScaleObjectWidth*scale);
countdownContainer.height(countdownScaleObjectHeight*scale);
if($.browser.msie && browserVersion<=8){
countdownScaleObject.css("zoom", scale);
}else{
countdownScaleObject.css("transform", scaleCss).
css("-moz-transform", scaleCss).
css("-webkit-transform", scaleCss).
css("-o-transform", scaleCss).
css("-ms-transform", scaleCss);
countdownScaleObject.css("left",left).css("top",top);
};
};
var selector = "";
var index = 0;
var days = [];
var hours = [];
var minutes = [];
var seconds = [];
var itemClass = function(){};
switch(style){
case "flip":
itemClass = Flip;
break;
case "slide":
itemClass = Slide;
break;
case "crystal":
itemClass = Crystal;
break;
case "metal":
itemClass = Metal;
break;
default:
};
index = 1;
selector = ".group.day>.container.item";
while(countdownObject.find(selector+index).length){
days.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.hour>.container.item";
while(countdownObject.find(selector+index).length){
hours.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.minute>.container.item";
while(countdownObject.find(selector+index).length){
minutes.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.second>.container.item";
while(countdownObject.find(selector+index).length){
seconds.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
countdown.items(days, hours, minutes, seconds);
countdown.onFinish = onFinish;
countdown.time(timeText, timeZone);
};
var destroy = function(){
destroyCountdown();
target.children().remove();
};
var start = function(){
countdown.start();
};
var stop = function(){
countdown.stop();
};
if(arguments.length>0){
var target = this;
var countdown = getCountdown();
if(arguments.length==1 && typeof(arguments[0])=="object"){
//destroy the old countdown
if(countdown!=undefined){
destroy();
};
//init new countdown
init(arguments[0]);
}else if(typeof(arguments[0])=="string"){
//set setting & call method
if(countdown!=undefined){
switch(arguments[0]){
case "stop":
stop();
break;
case "start":
start();
break;
case "destroy":
destroy();
break;
default:
};
};
};
};
return this;
}
});
})(sexyJ);
| JavaScript |
sexyJ(function(e,i){function j(){var a=e("script:first"),b=a.css("color"),c=false;if(/^rgba/.test(b))c=true;else try{c=b!=a.css("color","rgba(0, 0, 0, 0.5)").css("color");a.css("color",b)}catch(d){}return c}function k(a,b,c){var d=[];a.c&&d.push("inset");typeof b.left!="undefined"&&d.push(parseInt(a.left+c*(b.left-a.left),10)+"px "+parseInt(a.top+c*(b.top-a.top),10)+"px");typeof b.blur!="undefined"&&d.push(parseInt(a.blur+c*(b.blur-a.blur),10)+"px");typeof b.a!="undefined"&&d.push(parseInt(a.a+c*
(b.a-a.a),10)+"px");if(typeof b.color!="undefined"){var g="rgb"+(e.support.rgba?"a":"")+"("+parseInt(a.color[0]+c*(b.color[0]-a.color[0]),10)+","+parseInt(a.color[1]+c*(b.color[1]-a.color[1]),10)+","+parseInt(a.color[2]+c*(b.color[2]-a.color[2]),10);if(e.support.rgba)g+=","+parseFloat(a.color[3]+c*(b.color[3]-a.color[3]));g+=")";d.push(g)}return d.join(" ")}function h(a){var b,c,d={};if(b=/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(a))c=[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],
16),1];else if(b=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(a))c=[parseInt(b[1],16)*17,parseInt(b[2],16)*17,parseInt(b[3],16)*17,1];else if(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),1];else if(b=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),parseFloat(b[4])];d=(b=/(-?[0-9]+)(?:px)?\s+(-?[0-9]+)(?:px)?(?:\s+(-?[0-9]+)(?:px)?)?(?:\s+(-?[0-9]+)(?:px)?)?/.exec(a))?
{left:parseInt(b[1],10),top:parseInt(b[2],10),blur:b[3]?parseInt(b[3],10):0,a:b[4]?parseInt(b[4],10):0}:{left:0,top:0,blur:0,a:0};d.c=/inset/.test(a);d.color=c;return d}e.extend(true,e,{support:{rgba:j()}});var f;e.each(["boxShadow","MozBoxShadow","WebkitBoxShadow"],function(a,b){a=e("html").css(b);if(typeof a=="string"&&a!=""){f=b;return false}});if(f)e.fx.step.boxShadow=function(a){if(!a.init){a.b=h(e(a.elem).get(0).style[f]||e(a.elem).css(f));a.end=e.extend({},a.b,h(a.end));if(a.b.color==i)a.b.color=
a.end.color||[0,0,0];a.init=true}a.elem.style[f]=k(a.b,a.end,a.pos)}});
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(sexyJ); | JavaScript |
/*
* --------------------------------------------------------------------
* jQuery-Plugin - selectToUISlider - creates a UI slider component from a select element(s)
* by Scott Jehl, scott@filamentgroup.com
* http://www.filamentgroup.com
* reference article: http://www.filamentgroup.com/lab/update_jquery_ui_16_slider_from_a_select_element/
* demo page: http://www.filamentgroup.com/examples/slider_v2/index.html
*
* Copyright (c) 2008 Filament Group, Inc
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Usage Notes: please refer to our article above for documentation
*
* --------------------------------------------------------------------
*/
(function(jQuery) {
jQuery.fn.selectToUISlider = function(settings){
var selects = jQuery(this);
//accessible slider options
var options = jQuery.extend({
labels: 3, //number of visible labels
tooltip: true, //show tooltips, boolean
tooltipSrc: 'text',//accepts 'value' as well
labelSrc: 'value',//accepts 'value' as well ,
sliderOptions: null
}, settings);
//handle ID attrs - selects each need IDs for handles to find them
var handleIds = (function(){
var tempArr = [];
selects.each(function(){
tempArr.push('handle_'+jQuery(this).attr('id'));
});
return tempArr;
})();
//array of all option elements in select element (ignores optgroups)
var selectOptions = (function(){
var opts = [];
selects.eq(0).find('option').each(function(){
opts.push({
value: jQuery(this).attr('value'),
text: jQuery(this).text()
});
});
return opts;
})();
//array of opt groups if present
var groups = (function(){
if(selects.eq(0).find('optgroup').size()>0){
var groupedData = [];
selects.eq(0).find('optgroup').each(function(i){
groupedData[i] = {};
groupedData[i].label = jQuery(this).attr('label');
groupedData[i].options = [];
jQuery(this).find('option').each(function(){
groupedData[i].options.push({text: jQuery(this).text(), value: jQuery(this).attr('value')});
});
});
return groupedData;
}
else return null;
})();
//check if obj is array
function isArray(obj) {
return obj.constructor == Array;
}
//return tooltip text from option index
function ttText(optIndex){
return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
}
//plugin-generated slider options (can be overridden)
var sliderOptions = {
step: 1,
min: 0,
orientation: 'horizontal',
max: selectOptions.length-1,
range: selects.length > 1,//multiple select elements = true
slide: function(e, ui) {//slide function
var thisHandle = jQuery(ui.handle);
//handle feedback
var textval = ttText(ui.value);
thisHandle
.attr('aria-valuetext', textval)
.attr('aria-valuenow', ui.value)
.find('.ui-slider-tooltip .ttContent')
.text( textval );
//control original select menu
var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
currSelect.find('option').eq(ui.value).attr('selected', 'selected');
},
values: (function(){
var values = [];
selects.each(function(){
values.push( jQuery(this).get(0).selectedIndex );
});
return values;
})()
};
//slider options from settings
options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;
//select element change event
selects.bind('change keyup click', function(){
var thisIndex = jQuery(this).get(0).selectedIndex;
var thisHandle = jQuery('#handle_'+ jQuery(this).attr('id'));
var handleIndex = thisHandle.data('handleNum');
thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
});
//create slider component div
var sliderComponent = jQuery('<div></div>');
//CREATE HANDLES
selects.each(function(i){
var hidett = '';
//associate label for ARIA
var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') +']');
//labelled by aria doesn't seem to work on slider handle. Using title attr as backup
var labelText = (thisLabel.size()>0) ? 'Slider control for '+ thisLabel.text()+'' : '';
var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_'+handleIds[i]).attr('id');
if( options.tooltip == false ){hidett = ' style="display: none;"';}
jQuery('<a '+
'href="#" tabindex="0" '+
'id="'+handleIds[i]+'" '+
'class="ui-slider-handle" '+
'role="slider" '+
'aria-labelledby="'+thisLabelId+'" '+
'aria-valuemin="'+options.sliderOptions.min+'" '+
'aria-valuemax="'+options.sliderOptions.max+'" '+
'aria-valuenow="'+options.sliderOptions.values[i]+'" '+
'aria-valuetext="'+ttText(options.sliderOptions.values[i])+'" '+
'><span class="screenReaderContext">'+labelText+'</span>'+
'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"'+ hidett +'><span class="ttContent"></span>'+
'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>'+
'</span></a>')
.data('handleNum',i)
.appendTo(sliderComponent);
});
//CREATE SCALE AND TICS
//write dl if there are optgroups
if(groups) {
var inc = 0;
var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
jQuery(groups).each(function(h){
scale.append('<dt style="width: '+ (100/groups.length).toFixed(2) +'%' +'; left:'+ (h/(groups.length-1) * 100).toFixed(2) +'%' +'"><span>'+this.label+'</span></dt>');//class name becomes camelCased label
var groupOpts = this.options;
jQuery(this.options).each(function(i){
var style = (inc == selectOptions.length-1 || inc == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
scale.append('<dd style="left:'+ leftVal(inc) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></dd>');
inc++;
});
});
}
//write ol
else {
var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
jQuery(selectOptions).each(function(i){
var style = (i == selectOptions.length-1 || i == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? this.text : this.value;
scale.append('<li style="left:'+ leftVal(i) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></li>');
});
}
function leftVal(i){
return (i/(selectOptions.length-1) * 100).toFixed(2) +'%';
}
//show and hide labels depending on labels pref
//show the last one if there are more than 1 specified
if(options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');
//set increment
var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
//show em based on inc
for(var j=0; j<selectOptions.length; j+=increm){
if((selectOptions.length - j) > increm){//don't show if it's too close to the end label
sliderComponent.find('.ui-slider-scale li:eq('+ j +') span.ui-slider-label, .ui-slider-scale dd:eq('+ j +') span.ui-slider-label').addClass('ui-slider-label-show');
}
}
//style the dt's
sliderComponent.find('.ui-slider-scale dt').each(function(i){
jQuery(this).css({
'left': ((100 /( groups.length))*i).toFixed(2) + '%'
});
});
//inject and return
sliderComponent
.insertAfter(jQuery(this).eq(this.length-1))
.slider(options.sliderOptions)
.attr('role','application')
.find('.ui-slider-label')
.each(function(){
jQuery(this).css('marginLeft', -jQuery(this).width()/2);
});
//update tooltip arrow inner color
sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function(){
var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
jQuery(this).css('border-top', bWidth+' solid '+bColor);
});
var values = sliderComponent.slider('values');
if(isArray(values)){
jQuery(values).each(function(i){
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text( ttText(this) );
});
}
else {
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text( ttText(values) );
}
return this;
}
})(sexyJ);
| JavaScript |
(function($) {
$(window).load(function() {
function sp_make_li_h() {
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
};
sp_make_li_h();
function sp_make_ul_h() {
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
};
sp_make_ul_h();
});
$(document).ready(function() {
var sexyCountry = '',
sexyCountryCode = '',
sexyCity = '',
sexyRegion = '';
var offset_padding = 2;
function sp_make_li_h_() {
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
};
function sp_make_ul_h_() {
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
};
setTimeout(function() {
sp_make_li_h_();
sp_make_ul_h_();
},1000);
function check_pro_version($elem) {
return true;
$elem_1 = $elem.find('.powered_by');
$elem_2 = $elem.find('.powered_by a');
var sexy_font_size_1 = parseInt($elem_1.css('font-size'));
var sexy_top_1 = parseInt($elem_1.css('top'));
var sexy_left_1 = parseInt($elem_1.css('left'));
var sexy_bottom_1 = parseInt($elem_1.css('bottom'));
var sexy_right_1 = parseInt($elem_1.css('right'));
var sexy_text_indent_1 = parseInt($elem_1.css('text-indent'));
var sexy_margin_top_1 = parseInt($elem_1.css('margin-top'));
var sexy_margin_bottom_1 = parseInt($elem_1.css('margin-bottom'));
var sexy_margin_left_1 = parseInt($elem_1.css('margin-left'));
var sexy_margin_right_1 = parseInt($elem_1.css('margin-right'));
var sexy_display_1 = $elem_1.css('display');
var sexy_position_1 = $elem_1.css('position');
var sexy_width_1 = parseInt($elem_1.css('width'));
var sexy_height_1 = parseInt($elem_1.css('height'));
var sexy_visibility_1 = $elem_1.css('visibility');
var sexy_overflow_1 = $elem_1.css('overflow');
var sexy_zindex_1 = parseInt($elem_1.css('z-index'));
var sexy_font_size_2 = parseInt($elem_2.css('font-size'));
var sexy_top_2 = parseInt($elem_2.css('top'));
var sexy_left_2 = parseInt($elem_2.css('left'));
var sexy_bottom_2 = parseInt($elem_2.css('bottom'));
var sexy_right_2 = parseInt($elem_2.css('right'));
var sexy_text_indent_2 = parseInt($elem_2.css('text-indent'));
var sexy_margin_top_2 = parseInt($elem_2.css('margin-top'));
var sexy_margin_right_2 = parseInt($elem_2.css('margin-right'));
var sexy_margin_bottom_2 = parseInt($elem_2.css('margin-bottom'));
var sexy_margin_left_2 = parseInt($elem_2.css('margin-left'));
var sexy_display_2 = $elem_2.css('display');
var sexy_position_2 = $elem_2.css('position');
var sexy_width_2 = parseInt($elem_2.css('width'));
var sexy_height_2 = parseInt($elem_2.css('height'));
var sexy_visibility_2 = $elem_2.css('visibility');
var sexy_overflow_2 = $elem_2.css('overflow');
var sexy_zindex_2 = parseInt($elem_2.css('z-index'));
var txt1 = $.trim($elem_1.html().replace(/<[^>]+>.*?<\/[^>]+>/gi, ''));
var txt2 = $.trim($elem_2.html().replace(/<[^>]+>.*?<\/[^>]+>/gi, ''));
var txt1_l = parseInt(txt1.length);
var txt2_l = parseInt(txt2.length);
var a_href = $elem_2.attr("href").replace('http://','');
a_href = a_href.replace('www.','');
a_href = $.trim(a_href.replace('www',''));
a_href_l = parseInt(a_href.length);
if(
sexy_font_size_1 == '13' && sexy_top_1 == '0' && sexy_left_1 == '0' && sexy_bottom_1 == '0' && sexy_right_1 == '0' && sexy_text_indent_1 == '0' && sexy_margin_top_1 == '-1' && sexy_margin_right_1 == '8' && sexy_margin_bottom_1 == '13' && sexy_margin_left_1 == '0' &&
sexy_display_1 == 'block' && sexy_position_1 == 'relative' && sexy_width_1 > '20' && sexy_height_1 > '10' && sexy_visibility_1 == 'visible' && sexy_overflow_1 == 'visible' && sexy_zindex_1 == '10' &&
sexy_font_size_2 == '13' && sexy_top_2 == '0' && sexy_left_2 == '0' && sexy_bottom_2 == '0' && sexy_right_2 == '0' && sexy_text_indent_2 == '0' && sexy_margin_top_2 == '0' && sexy_margin_right_2 == '0' && sexy_margin_bottom_2 == '0' && sexy_margin_left_2 == '0' &&
sexy_display_2 != 'none' && sexy_position_2 == 'relative' && sexy_width_2 > '20' && sexy_height_2 > '10' && sexy_visibility_2 == 'visible' && sexy_overflow_2 == 'visible' && sexy_zindex_2 == '10' &&
txt1 != '' && txt2 == 'Sexy Polling' && txt1_l > 1 && txt2_l == '12' && a_href_l == '30' && a_href == '2glux.com/projects/sexypolling'
)
return true;
return false;
};
$.ajax
({
url: sexyPath + 'components/com_sexypolling/geoip.php?ip=' + sexyIp,
type: "get",
dataType: "json",
success: function(data)
{
if(data != null) {
sexyCountry = data.countryName;
sexyCountryCode = data.countryCode;
sexyCity = data.cityName;
sexyRegion = data.regionName;
}
},
error: function()
{
}
});
setTimeout(function() {
$(".polling_container_wrapper").each(function() {
var w = $(this).width();
$(this).css("width",w);
var curr_h = $(this).find('.answer_wrapper').height();
$(this).find('.answer_wrapper').attr("h",curr_h);
});
},100);
var estimated_seconds = new Array();
function create_seconds_timers() {
var onlyVotedIds = new Array();
for(t in votedIds) {
var poll_id = votedIds[t][0];
estimated_seconds[poll_id] = parseInt(votedIds[t][2] * 3600);
};
setInterval(function() {
for(t in estimated_seconds) {
if(estimated_seconds[t] > 0)
estimated_seconds[t] -= 1;
};
},1000);
};
create_seconds_timers();
var estimated_seconds_start_poll = new Array();
function create_start_poll_seconds_timers() {
//check start dates
var s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var poll_id = startDisabledIds[i][0];
estimated_seconds_start_poll[poll_id] = parseInt(startDisabledIds[i][3] * 3600);
};
};
setInterval(function() {
for(tt in estimated_seconds_start_poll) {
if(estimated_seconds_start_poll[tt] > 0)
estimated_seconds_start_poll[tt] -= 1;
};
},1000);
};
create_start_poll_seconds_timers();
//alert box ////////////////////////////////////////////////////////////////////////////////////////
//function to create shadow
function create_shadow() {
var $shadow = '<div id="sexy_shadow"></div>';
$('body').css('position','relative').append($shadow);
$("#sexy_shadow")
.css( {
'position' : 'absolute',
'top' : '0',
'right' : '0',
'bottom' : '0',
'left' : '0',
'z-index' : '10000',
'opacity' : '0',
'backgroundColor' : '#000'
})
.fadeTo(200,'0.7');
};
function make_alert(txt,type) {
//create shadow
create_shadow();
//make alert
var $alert_body = '<div id="sexy_alert_wrapper"><div id="sexy_alert_body" class="' + type + '">' + txt + '</div><input type="button" id="close_sexy_alert" value="' + sexyPolling_words[21] + '" /></div>';
$('body').append($alert_body);
var scollTop = $(window).scrollTop();
var w_width = $(window).width();
var w_height = $(window).height();
var s_height = $("#sexy_alert_wrapper").height();
var alert_left = (w_width - 420) / 2;
var alert_top = (w_height - s_height) / 2;
$("#sexy_alert_wrapper")
.css( {
'top' : -1 * (s_height + 55 * 1) + scollTop * 1,
'left' : alert_left
})
.stop()
.animate({
'top' : alert_top + scollTop * 1
},450,'easeOutBack',function() {
//$(this).css('position','fixed');
});
};
function remove_alert_box() {
$("#sexy_shadow").stop().fadeTo(200,0,function() {$(this).remove();});
$("#sexy_alert_wrapper").stop().fadeTo(200,0,function() {$(this).remove();});
};
function move_alert_box() {
var scollTop = $(window).scrollTop();
var w_width = $(window).width();
var w_height = $(window).height();
var s_height = $("#sexy_alert_wrapper").height();
var alert_left = (w_width - 420) / 2;
var alert_top = (w_height - s_height) / 2;
$("#sexy_alert_wrapper")
.stop()
.animate({
'top' : alert_top + scollTop * 1,
'left' : alert_left
},450,'easeOutBack',function() {
//$(this).css('position','fixed');
});
};
$('#close_sexy_alert').live('click', function() {
remove_alert_box();
});
$(window).resize(function() {
move_alert_box();
});
$(window).scroll(function() {
move_alert_box();
});
setTimeout(function() {
$(".polling_bottom_wrapper1").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".polling_loading").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".answer_input").each(function() {
var w = $(this).width();
$(this).attr("w",w);
});
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
$(".answer_navigation").each(function() {
var b = parseInt($(this).css("borderWidth"));
$(this).attr("b",b);
});
},50);
function create_timer(seconds_diff, show_date) {
var newdate = new Date();
newdate.setSeconds(newdate.getSeconds() + seconds_diff);
var dd = newdate.getDate();
var mm = newdate.getMonth()+1;
var hh = newdate.getHours();
var ii = newdate.getMinutes();
var ss = newdate.getSeconds();
var yyyy = newdate.getFullYear();
if(dd<10) dd='0'+dd;
if(mm<10) mm='0'+mm;
if(hh<10) hh='0'+hh;
if(ii<10) ii='0'+ii;
if(ss<10) ss='0'+ss;
var time_text = yyyy+'/'+mm+'/'+dd + ' ' + hh + ':' + ii + ':' + ss;
var timezone = new Date().getTimezoneOffset();
$("#sexy_timer").jCountdown({
timeText:time_text,
timeZone:0,
style:"slide",
color:"black",
width:350,
textGroupSpace:15,
textSpace:0,
reflection:true,
reflectionOpacity:20,
reflectionBlur:1,
dayTextNumber:2,
displayDay:show_date,
displayHour:true,
displayMinute:true,
displaySecond:true,
displayLabel:true,
onFinish:function(){
remove_alert_box();
}
});
};
$('.polling_submit').click(function() {
$elem = $(this).parents('.polling_container');
if(!check_pro_version($elem)) {
make_alert('To hide a backlink please purchase a Sexy Polling PRO version','sexy_error');
return false;
}
if($(this).hasClass('voted_button')) {
make_alert(sexyPolling_words[9],'sexy_error');
return;
}
var t_id = $(this).attr("id");
var polling_id = $(this).parent('span').parent('div').find('.poll_answer').attr('name');
if(votingPermissions[polling_id] != 'allow_voting') {
make_alert(votingPermissions[polling_id],'sexy_error');
return false;
};
//check if already voted
var onlyVotedIds = new Array();
var estimated_seconds_item = estimated_seconds[polling_id];
for(t in votedIds) {
onlyVotedIds.push(votedIds[t][0]);
if(votedIds[t][0] == polling_id)
var estimated_ours = votedIds[t][2];
};
if(estimated_seconds_item > 0 || estimated_ours == 'never') {
if($.inArray(polling_id,onlyVotedIds) != -1) {
if(estimated_ours == 'never') {
make_alert(sexyPolling_words[9],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(sexyPolling_words[9] + '<div id="estimated_time_message">' + sexyPolling_words[20] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_item, show_date);
return false;
}
}
};
//check start dates
var estimated_seconds_start_poll_item = estimated_seconds_start_poll[polling_id];
s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + startDisabledIds[i][2] + "_" + startDisabledIds[i][0];
if(c_id == t_id) {
var estimated_ours = startDisabledIds[i][3];
if(estimated_seconds_start_poll_item > 0 || estimated_ours == 'never') {
if(estimated_ours == 'never') {
make_alert(startDisabledIds[i][1],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(startDisabledIds[i][1] + '<div id="estimated_time_message">' + sexyPolling_words[22] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_start_poll_item, show_date);
return false;
}
}
}
}
};
//check end dates
e_length = endDisabledIds.length;
for(var i = 0;i <= e_length; i++) {
if(typeof endDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + endDisabledIds[i][2] + "_" + endDisabledIds[i][0];
if(c_id == t_id) {
make_alert(endDisabledIds[i][1],'sexy_normal');
return false;
}
}
};
var polling_checked_value = $(this).parent('span').parent('div').find('.poll_answer:checked').val();
if(polling_checked_value == undefined) {
make_alert(sexyPolling_words[8],'sexy_normal');
return false;
};
var $t = $(this);
vote_polling($t);
});
$('.polling_result').click(function() {
$elem = $(this).parents('.polling_container');
if(!check_pro_version($elem)) {
make_alert('To hide a backlink please purchase a Sexy Polling PRO version','sexy_error');
return false;
}
var $t = $(this);
show_polling($t);
});
$('.polling_select2,.polling_select1').change(function() {
var $t = $(this).parents('.polling_container');
show_polling_by_date($t);
});
function show_polling($t) {
var polling_id = $t.parent('span').parent('div').find('.poll_answer').attr('name');
var module_id = $t.parent('span').parent('div').parent('div').attr('roll');
$container = $t.parent('span').parent('div');
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
//function to remove user added input boxes
$container.find('.doNotUncheck').parent('div').parent('div').parent('li').remove();
//hide all radio buttons
$t.parent('span').parent('div').find('.answer_input').animate({
width:0,
opacity:0
},1000);
//animate answers
$t.parent('span').parent('div').find('.answer_name label').animate({
marginLeft:0
},1000);
//show navigation bar
//TODO: when animating border, there is jquery issue with animation. Find the way to fix that!
var b = $t.parent('span').parent('div').find('.answer_navigation').attr("b");
$t.parent('span').parent('div').find('.answer_navigation').css("borderWidth","0").show().animate({
height:animation_styles[module_id+"_"+polling_id][9],
borderWidth: b,
opacity:1
},1000);
//animate loading
var l_h = $t.parent('span').parent('div').find('.polling_loading').height();
$t.parent('span').parent('div').find('.polling_loading').css({display:'block',opacity:0,height:0});
$t.parent('span').parent('div').find('.polling_loading').animate({
opacity:0.85,
height: l_h
},1000);
//send request
var h = $container.find('.answer_votes_data').height();
var min_date = $container.find('.polling_select1').val();
var max_date = $container.find('.polling_select2').val();
//total time = 1000;
setTimeout(function() {
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id + '&mode=view_by_date&min_date=' + min_date + '&max_date=' + max_date + '&dateformat=' + dateFormat[polling_id] + '&module_id=' + module_id+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
$container = $("#mod_" + data[0].module_id + "_" + data[0].poll_id);
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
data_length = data.length;
max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = parseFloat(this.percent_formated);
response_votes = this.votes;
order = this.order;
order_start = this.order_start;
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
if(max_percent == 'none')
max_percent = percent;
answers_array.push(parseInt(answer_id));
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title',sexyPolling_words[0] + ': ' + response_votes);
//start animating navigation bar
$nav_width = $container.find(".polling_li").width();
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
$current_width_tobeset = $container.find('.scale_icon').hasClass('opened') ? $current_width_rel : $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
//set the value
$container.find('#answer_votes_data_count_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_count_val_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_percent_' + answer_id).html(percent_formated);
$container.find('#answer_votes_data_percent_val_' + answer_id).html(percent_formated);
//show answer data
$container.find('.answer_votes_data').css({'display':'block','height':0}).animate({height:h},1000);
//set to absolute
if(i == data_length - 1) {
animate_poll_items($container,answers_array,polling_id,module_id,total_votes,min_date,max_date,orders_array,orders_array_start);
}
});
},
error: function()
{
}
});
},1000);
};
//function to animate elements
function animate_poll_items($container,answers_array,polling_id,module_id,total_votes,min_date,max_date,orders_array,orders_array_start) {
var s_timeout = 2700;
if(
$container.find('.polling_info').attr("rell") == 'noanimate' &&
$container.find('.sexyback_icon').attr("rell") == 'noanimate' &&
$container.find('.timeline_icon').attr("rell") == 'noanimate' &&
$container.find('.scale_icon').attr("rell") == 'noanimate' &&
$container.find('.add_answer_icon').attr("rell") == 'noanimate'
)
s_timeout = 1200;
setTimeout(function(){
var offset_0_ = $container.find('.polling_ul').offset();
offset_0 = offset_0_.top;
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
$container.find('.polling_ul').css('height',$container.find('.polling_ul').height());
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
});
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},s_timeout,function() {
});
//show total votes, min and max dates
$container.find('.total_votes').html(total_votes);
$container.find('.total_votes_val').html(total_votes);
$container.find('.first_vote').html(min_date);
$container.find('.last_vote').html(max_date);
//hide submit button and loading
$container.find('.polling_bottom_wrapper1')
.stop(true,true).animate({
height:0
},
1000,
function(){
$container.find('.polling_bottom_wrapper1').hide();
$container.find('.polling_loading').hide();
});
setTimeout(function() {
//show polling info
$container.find('.polling_info').css({'display':'block'});
var h = $container.find('.polling_info').height();
$container.find('.polling_info').css({'display':'none'});
$container.find('.polling_info')
.css({'height': 0,'display':'block'})
.animate({height:h},1000);
//show timeline
$container.find('.timeline_icon').animate({height:32},1000);
//show add answer
$container.find('.add_answer_icon').animate({height:32},1000);
//show add answer
$container.find('.sexyback_icon').animate({height:32},1000);
//show add answer
$container.find('.scale_icon').animate({height:32},1000);
},1700);
if(autoOpenTimeline[polling_id] == 1) {
setTimeout(function() {
$container.find('.timeline_icon').trigger("click");
},s_timeout);
}
}
//global variable, to store digit animations
$digit_int = new Array();
$digit_int_percent = new Array();
$digit_int_total = '';
function show_polling_by_date($t,use_current_date) {
use_current_date = typeof use_current_date !== 'undefined' ? use_current_date : 'no';
var polling_id = $t.find('.poll_answer').attr('name');
var module_id = $t.parent('div').attr('roll');
var min_date = $t.find('.polling_select1').val();
var max_date = $t.find('.polling_select2').val();
$container = $t;
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
//clear all intervals
for(i_v in $digit_int) {
clearInterval($digit_int[i_v]);
}
//clear all intervals
for(i_v in $digit_int_percent) {
clearInterval($digit_int_percent[i_v]);
}
clearInterval($digit_int_total);
setTimeout(function() {
$nav_width = $container.find(".polling_li").width();
//send request
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id + '&mode=view_by_date&min_date=' + min_date + '&max_date=' + max_date + '&dateformat=' + dateFormat[polling_id] + '&curr_date=' + use_current_date+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
//count of json objects
data_length = data.length;
//assign variables
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
$curr_count = new Array();
$new_count = new Array();
$step_sign = new Array();
$steps = new Array();
$interval_value = new Array();
$curr_count_ = new Array();
$curr_step = new Array();
$curr_percent = new Array();
$new_percent = new Array();
$step_sign_percent = new Array();
$steps_percent = new Array();
$interval_value_percent = new Array();
$curr_percent_ = new Array();
$curr_step_percent = new Array();
var max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = parseFloat(this.percent_formated);
response_votes = parseInt(this.votes);
order = this.order;
order_start = this.order_start;
if(max_percent == 'none')
max_percent = percent;
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
answers_array.push(answer_id);
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title','Votes: ' + response_votes);
//start animating navigation bar
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
if($container.find('.scale_icon').hasClass('opened'))
new_w = $current_width_rel;
else
new_w = $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).stop(true,false).animate({
width: new_w
},1000,sexyAnimationTypeBar[polling_id]);
//ie box shadow animation
if($container.find('#answer_navigation_' + answer_id).next(".ie-shadow").width() != $current_width + 4*1)
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").stop(true,false).animate({
width: new_w
},1000,sexyAnimationTypeBar[polling_id]);
//digit animation //remember min_count_of_votes / $steps_count_percent must have influance on tofixed(it's value) ...
//animate percents
$curr_percent[answer_id] = parseFloat($container.find('#answer_votes_data_percent_' + answer_id).html());
$new_percent[answer_id] = percent_formated;
$steps_percent[answer_id] = Math.abs($curr_percent[answer_id] - $new_percent[answer_id]);
$steps_count_percent = 20;
$step_item_percent = $steps_percent[answer_id] / $steps_count_percent;
//get sign
$step_sign_percent[answer_id] = ($new_percent[answer_id] > $curr_percent[answer_id]) ? 1 * $step_item_percent : (($new_percent[answer_id] < $curr_percent[answer_id]) ? -1 * $step_item_percent : 0);
$interval_value_percent[answer_id] = parseFloat(1000 / $steps_count_percent);
//animate total count
$curr_total = parseInt($t.find('.total_votes').html());
$new_total = total_votes;
$steps_total = Math.abs($curr_total - $new_total);
$steps_count_total = 20;
$step_item_total = $steps_total / $steps_count_total;
//get sign
$step_sign_total = ($new_total > $curr_total) ? 1 * $step_item_total : (($new_total < $curr_total) ? -1 * $step_item_total : 0);
$interval_value_total = parseFloat(1000 / $steps_count_total);
//animate answer votes count
$curr_count[answer_id] = parseInt($container.find('#answer_votes_data_count_' + answer_id).html());
$new_count[answer_id] = response_votes;
$steps[answer_id] = Math.abs($curr_count[answer_id] - $new_count[answer_id]);
$steps_count = 15;
$step_item = $steps[answer_id] / $steps_count;
//get sign
$step_sign[answer_id] = ($new_count[answer_id] > $curr_count[answer_id]) ? 1 * $step_item : (($new_count[answer_id] < $curr_count[answer_id]) ? -1 * $step_item : 0);
$interval_value[answer_id] = parseFloat(1000 / $steps_count);
if(i == data_length - 1) {
//show total votes, min and max dates
$t.find('.first_vote').html(min_date);
$t.find('.last_vote').html(max_date);
function animate_total() {
if($step_sign_total != 0) {
$digit_int_total = setInterval(function(){
$curr_total_ = parseFloat($t.find('.total_votes_val').html());
$curr_total_ = $curr_total_ + 1 * $step_sign_total;
$t.find('.total_votes').html($curr_total_.toFixed(1));
$t.find('.total_votes_val').html($curr_total_);
if($step_sign_total > 0) {
if($curr_total_ >= $new_total) {
clearInterval($digit_int_total);
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
}
else {
if($curr_total_ <= $new_total) {
clearInterval($digit_int_total);
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
}
},$interval_value_total);
}
else {
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
};
animate_total();
var animate_percent = function(ans_id) {
if($step_sign_percent[ans_id] !== 0) {
$digit_int_percent[ans_id] = setInterval(function(){
$curr_percent_[ans_id] = parseFloat($container.find('#answer_votes_data_percent_val_' + ans_id).html());
$curr_percent_[ans_id] = $curr_percent_[ans_id] + 1 * $step_sign_percent[ans_id];
$container.find('#answer_votes_data_percent_val_' + ans_id).html($curr_percent_[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($curr_percent_[ans_id].toFixed(2));
if($step_sign_percent[ans_id] > 0) {
if($curr_percent_[ans_id] >= $new_percent[ans_id]) {
clearInterval($digit_int_percent[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
}
else {
if($curr_percent_[ans_id] <= $new_percent[ans_id]) {
clearInterval($digit_int_percent[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
}
},$interval_value_percent[ans_id]);
}
else {
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
};
var animate_digit = function(ans_id) {
if($step_sign[ans_id] != 0) {
$digit_int[ans_id] = setInterval(function(){
$curr_count_[ans_id] = parseFloat($container.find('#answer_votes_data_count_val_' + ans_id).html());
$curr_count_[ans_id] = $curr_count_[ans_id] + 1 * $step_sign[ans_id];
$container.find('#answer_votes_data_count_' + ans_id).html($curr_count_[ans_id].toFixed(1));
$container.find('#answer_votes_data_count_val_' + ans_id).html($curr_count_[ans_id]);
if($step_sign[ans_id] > 0) {
if($curr_count_[ans_id] >= $new_count[ans_id]) {
clearInterval($digit_int[ans_id]);
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
}
else {
if($curr_count_[ans_id] <= $new_count[ans_id]) {
clearInterval($digit_int[ans_id]);
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
}
},$interval_value[ans_id]);
}
else {
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
};
for(var b = 0; b < answers_array.length; b++) {
animate_digit(answers_array[b]);
animate_percent(answers_array[b]);
}
};
//set to absolute
if(i == data_length - 1) {
var offset_0_ = $t.find('.polling_ul').offset();
offset_0 = offset_0_.top;
setTimeout(function(){
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block'})
.stop(false,false)
.animate( {
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],
function() {
$(this).animate( {
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
})
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},1);
}
});
},
error: function()
{
}
})
},1);
};
function vote_polling($t) {
var polling_id = $t.parent('span').parent('div').find('.poll_answer').attr('name');
var module_id = $t.parent('span').parent('div').parent('div').attr('roll');
$container = $t.parent('span').parent('div');
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
var voting_period = voting_periods[module_id + '_' + polling_id];
//close answer
$container.find('.answer_wrapper')
.css({'overflow':'hidden'})
.animate({
height:0
},600);
$container.find('.add_answer_icon').removeClass('opened').addClass('voted_button');
$container.find('.polling_submit').addClass('voted_button');
//recalculate ul height
$ul_height = $container.children("ul").height();
$container.children("ul").attr("h",$ul_height);
//if we have added answers, add them to post
var additionalAnswers = '';
$container.find('.doNotUncheck').each(function(i) {
var htm = $(this).parents('li').find('label').html();
htm = htm.replace(/\?\?/g,'sexydoublequestionmark');
additionalAnswers += '&answers[]=' + htm;
});
//hide all radio buttons
$container.find('.answer_input').animate({
width:0,
opacity:0
},1000);
//animate answers
$container.find('.answer_name label').animate({
marginLeft:0
},1000);
//show navigation bar
var b = $container.find('.answer_navigation').attr("b");
$container.find('.answer_navigation').css("borderWidth","0").show().animate({
height:animation_styles[module_id+"_"+polling_id][9],
borderWidth: b,
opacity:1
},1000);
//animate loading
var l_h = $t.parent('span').parent('div').find('.polling_loading').height();
$t.parent('span').parent('div').find('.polling_loading').attr("h",l_h).css({display:'block',opacity:0,height:0});
$t.parent('span').parent('div').find('.polling_loading').animate({
opacity:0.85,
height: l_h
},1000);
//send request
$nav_width = $container.find(".polling_li").width();
var h = $container.find('.answer_votes_data').height();
var ch_data = '';
$t.parent('span').parent('div').find('.poll_answer:checked').not('.doNotUncheck').each(function() {
ch_data += '&answer_id[]=' + $(this).val();
});
var min_date = $container.find('.polling_select1').val();
var max_date = $container.find('.polling_select2').val();
setTimeout(function() {
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id +ch_data + '&dateformat=' + dateFormat[polling_id] + additionalAnswers + '&min_date=' + min_date + '&max_date=' + max_date + '&country_name=' + sexyCountry + '&country_code=' + sexyCountryCode + '&city_name=' + sexyCity + '®ion_name=' + sexyRegion + '&voting_period='+voting_period+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
if((data[0].invalid) == 'invalid_token')
make_alert('Invalid Token','sexy_error');
$container.find('.doNotUncheck').each(function(i) {
if(typeof data[0].addedanswers !== 'undefined') {
$(this).parents('li').attr("id",'answer_' + data[0].addedanswers[i]);
$(this).parents('li').find('.answer_navigation').attr("id",'answer_navigation_' + data[0].addedanswers[i]);
$(this).parents('li').find('.answer_votes_data').attr("id",'answer_votes_data_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_count_0').attr("id",'answer_votes_data_count_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_count_val_0').attr("id",'answer_votes_data_count_val_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_percent_0').attr("id",'answer_votes_data_percent_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_percent_val_0').attr("id",'answer_votes_data_percent_val_' + data[0].addedanswers[i]);
}
});
$container.find('.doNotUncheck').removeClass('doNotUncheck');
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = this.percent_formated;
response_votes = this.votes;
order = this.order;
order_start = this.order_start;
if(max_percent == 'none')
max_percent = percent;
answers_array.push(answer_id);
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title','Votes: ' + response_votes);
//start animating navigation bar
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
$current_width_tobeset = $container.find('.scale_icon').hasClass('opened') ? $current_width_rel : $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
//set the value
$container.find('#answer_votes_data_count_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_count_val_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_percent_' + answer_id).html(percent_formated);
$container.find('#answer_votes_data_percent_val_' + answer_id).html(percent_formated);
//show answer data
$container.find('.answer_votes_data').css({'display':'block','height':0}).animate({height:h},1000);
var s_timeout = 2700;
if(
$container.find('.polling_info').attr("rell") == 'noanimate' &&
$container.find('.sexyback_icon').attr("rell") == 'noanimate' &&
$container.find('.timeline_icon').attr("rell") == 'noanimate' &&
$container.find('.scale_icon').attr("rell") == 'noanimate' &&
$container.find('.add_answer_icon').attr("rell") == 'noanimate'
)
s_timeout = 1200;
//set to absolute
if(i == 0) {
var offset_0_ = $container.find('.polling_ul').offset();
offset_0 = offset_0_.top;
setTimeout(function(){
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
$container.find('.polling_ul').css('height',$container.find('.polling_ul').height());
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
});
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},s_timeout);
//show total votes, min and max dates
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
$container.find('.total_votes').html(total_votes);
$container.find('.total_votes_val').html(total_votes);
$container.find('.first_vote').html(min_date);
$container.find('.last_vote').html(max_date);
//hide submit button and loading
$container.find('.polling_bottom_wrapper1')
.animate({
height:0
},
1000,
function(){
$container.find('.polling_bottom_wrapper1').hide();
$container.find('.polling_loading').hide();
});
setTimeout(function() {
//show polling info
$container.find('.polling_info').css({'display':'block'});
var h = $container.find('.polling_info').height();
$container.find('.polling_info').css({'display':'none'});
$container.find('.polling_info')
.css({'height': 0,'display':'block'})
.animate({height:h},1000);
//show timeline
$container.find('.timeline_icon').animate({height:32},1000);
//show add answer
$container.find('.add_answer_icon').animate({height:32},1000);
//show add answer
$container.find('.sexyback_icon').animate({height:32},1000);
//show add answer
$container.find('.scale_icon').animate({height:32},1000);
},1700);
if(autoOpenTimeline[polling_id] == 1) {
setTimeout(function() {
$container.find('.timeline_icon').trigger("click");
},s_timeout);
};
};
});
},
error: function()
{
}
})
},1000);
};
$('.timeline_icon').click(function() {
var $c = $(this).parent('div').children('.timeline_select_wrapper');
var curr_h = 90;
var new_class = $c.hasClass('opened') ? 'closed' : 'opened';
if(new_class == 'opened') {
$(this).addClass('opened');
$c.removeClass('closed');
$c.addClass('opened');
$(this).attr('title',sexyPolling_words[5]);
}
else {
$(this).removeClass('opened');
$c.removeClass('opened');
$c.addClass('closed');
$(this).attr('title',sexyPolling_words[4]);
}
//open timeline
$(this).parent('div').children('.timeline_select_wrapper.opened')
.css({'overflow':'hidden','height':0})
.stop(true,true)
.animate({
height:curr_h
},
1000,
function(){
$(this).css({'overflow':'visible'})
});
//close timeline
$(this).parent('div').children('.timeline_select_wrapper.closed')
.css({'overflow':'hidden'})
.stop(true,true)
.animate({
height:0
},1000,function() {
$(this).css({'overflow':'hidden'});
});
});
function make_relative($t) {
var module_id = $t.parent('div').parent('div').parent('div').attr('roll');
var polling_id = $t.parent('div').parent('div').parent('div').find(".poll_answer").attr('name');
$t.parent('div').parent('div').find('.answer_navigation').each(function() {
var rel_width = $(this).attr("rel_width");
$(this).stop(true,false).animate({
width: rel_width
},1000,sexyAnimationTypeBar[polling_id]);
});
};
function make_absolute($t) {
var module_id = $t.parent('div').parent('div').parent('div').attr('roll');
var polling_id = $t.parent('div').parent('div').parent('div').find(".poll_answer").attr('name');
$t.parent('div').parent('div').find('.answer_navigation').each(function() {
var ab_width = $(this).attr("ab_width");
$(this).stop(true,false).animate({
width: ab_width
},1000,sexyAnimationTypeBar[polling_id]);
});
};
function animate_back($t) {
$container = $t.parents('.polling_container');
//show results button
$container.find('.polling_result').removeClass('hide_sexy_button');
//uncheck all inpust
$container.find('.poll_answer').attr("checked",false);
$container.find('.twoglux_styled_element').removeClass("twoglux_checked");
$container.find('.checkbox_part1').css("height",0);
$container.find('.checkbox_part2').css("height",0);
$container.find('.radio_part1').css("opacity",0);
//hide polling info
$container.find('.polling_info')
.stop()
.stop(true,true).animate({height:0},1000,
function() {
//$(this).css({'display':'none'});
$(this).removeAttr("style");
});
//hide timeline
$container.find('.timeline_select_wrapper')
.stop()
.stop(true,true).animate({height:0},1000,
function() {
$(this).css({'overflow':'hidden'});
});
$('.timeline_icon').removeClass('opened');
$('.timeline_select_wrapper').removeClass('opened');
//hide loading
var l_h = $container.find('.polling_loading').attr("h");
$container.find('.polling_loading').css({'display':'none'});
//show bottons
var h = $container.find('.polling_bottom_wrapper1').attr("h");
$container.find('.polling_bottom_wrapper1')
.css({'display':'block'})
.stop()
.stop(true,true).animate({height:h},1000,function() {
$(this).css('height','auto');
});
var answer_w = $container.find('.answer_input').attr("w");
var ratio_h = $container.find('.answer_result').height();
var ul_h = $container.find('.polling_ul').attr("h");
//hide timeline
$container.find('.timeline_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.add_answer_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.sexyback_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.scale_icon').stop(true,true).animate({height:0},1000);
$container.find('.answer_votes_data').stop(true,true).animate({height:0},1000,function(){$(this).removeAttr("style");});
$container.find('.answer_input').stop(true,true).animate({width:answer_w,opacity:1},1000);
$container.find('.answer_name label').stop(true,true).animate({marginLeft:answer_w},1000);
$container.find('.answer_navigation').stop(true,true).animate({height:0,borderWidth:0},1000,function() {$(this).hide();});
var total_h = 0;
$container.find('.polling_li').each(function(k) {
var h = $(this).attr("h_start")*1;
$(this).stop(true,true).animate({"top" :total_h},1000,function() {
$(this).removeAttr("style");
});
total_h = total_h + h*1;
});
$container.find('.polling_ul').stop(true,true).animate({height:ul_h},1000,function(){$(this).removeAttr("style");});
};
$('.scale_icon').click(function() {
if($(this).hasClass('opened') ) {
$(this).removeClass('opened');
$(this).attr("title",sexyPolling_words[16]);
make_absolute($(this));
}
else {
$(this).addClass('opened');
$(this).attr("title",sexyPolling_words[15]);
make_relative($(this));
}
});
$('.sexyback_icon').click(function() {
animate_back($(this));
});
$('.add_answer_icon').click(function() {
if($(this).hasClass('voted_button')) {
make_alert(sexyPolling_words[9],'sexy_error');
return;
}
if($(this).hasClass('disabled'))
return;
var $c = $(this).parents('.polling_container').find('.answer_wrapper');
var curr_h = $(this).parents('.polling_container').find('.answer_wrapper').attr("h");
//open answer
$(this).parents('.polling_container').find('.answer_wrapper.closed')
.css({'overflow':'hidden','height':0})
.animate({
height:curr_h
},
600,
function(){
$(this).css({'overflow':'visible'});
});
//close answer
$(this).parents('.polling_container').find('.answer_wrapper.opened')
.css({'overflow':'hidden'})
.animate({
height:0
},600);
var new_class = $c.hasClass('opened') ? 'closed' : 'opened';
if(new_class == 'opened') {
$(this).addClass('opened');
$c.removeClass('closed');
$c.addClass('opened');
}
else {
$(this).removeClass('opened');
$c.removeClass('opened');
$c.addClass('closed');
}
});
//add new answer
$('.add_ans_name').focus(function() {
var polling_id = $(this).parents('.polling_container').find('.poll_answer').attr('name');
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
if($(this).val() == sexyPolling_words[11]) {
$(this).val('');
$(this).css('color',animation_styles[module_id+"_"+polling_id][11]);
$(this).parent('div').children('.add_ans_submit').show();
var s_w = $(this).parent('div').children('.add_ans_submit').width();
s_w += 14;
$(this).parent('.add_answer').css('paddingRight',s_w);
}
});
$('.add_ans_name').blur(function() {
var polling_id = $(this).parents('.polling_container').find('.poll_answer').attr('name');
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
if($.trim($(this).val()) == '') {
$(this).val(sexyPolling_words[11]);
$(this).css('color',animation_styles[module_id+"_"+polling_id][10]);
$(this).parent('div').children('.add_ans_submit').hide();
$(this).parent('.add_answer').css('paddingRight',0);
}
else {
$(this).val($.trim($(this).val()));
}
});
$(".add_ans_name").keydown(function(e) {
if(e.keyCode == 13) {
var dis = $(this).parent('div').children('.add_ans_submit').css("display");
if(dis == 'block' || dis == 'inline-block') {
$(this).parent('div').children('.add_ans_submit').trigger('click');
$(this).blur();
}
}
});
//add new answer functions
$('.add_ans_submit').click(function() {
var sexypolling_token = $(this).parents('.polling_container_wrapper').find('.sexypolling_token').attr("name");
var answers_count = parseInt($(this).parents('.polling_container_wrapper').find('.answer_input').length);
if(answers_count >= 5) {
make_alert('This poll can not have more than 5 answers','sexy_error');
return false;
}
//check count allowed options
if(!check_allowed_answers_count($(this).parents('.polling_container_wrapper')))
return false;
$this = $(this);
$ans_name = $.trim($this.parent('div').children('.add_ans_name').val());
$ans_name = $ans_name.replace(/\\/g, "");
if($ans_name == '')
return false;
$poll_id = $this.parent('div').children('.poll_id').val();
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
var voting_period = voting_periods[module_id + '_' + $poll_id];
//check if already voted
var onlyVotedIds = new Array();
var estimated_seconds_item = estimated_seconds[$poll_id];
for(t in votedIds) {
onlyVotedIds.push(votedIds[t][0]);
if(votedIds[t][0] == $poll_id)
var estimated_ours = votedIds[t][2];
};
if(estimated_seconds_item > 0 || estimated_ours == 'never') {
if($.inArray($poll_id,onlyVotedIds) != -1) {
if(estimated_ours == 'never') {
make_alert(sexyPolling_words[9],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(sexyPolling_words[9] + '<div id="estimated_time_message">' + sexyPolling_words[20] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_item, show_date);
return false;
}
}
};
//check start dates
var t_id = $this.parents('.polling_container').find('.polling_submit').attr("id");
var estimated_seconds_start_poll_item = estimated_seconds_start_poll[$poll_id];
s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + startDisabledIds[i][2] + "_" + startDisabledIds[i][0];
if(c_id == t_id) {
var estimated_ours = startDisabledIds[i][3];
if(estimated_seconds_start_poll_item > 0 || estimated_ours == 'never') {
if(estimated_ours == 'never') {
make_alert(startDisabledIds[i][1],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(startDisabledIds[i][1] + '<div id="estimated_time_message">' + sexyPolling_words[22] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_start_poll_item, show_date);
return false;
}
}
}
}
};
//check end dates
e_length = endDisabledIds.length;
for(var i = 0;i <= e_length; i++) {
if(typeof endDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + endDisabledIds[i][2] + "_" + endDisabledIds[i][0];
if(c_id == t_id) {
make_alert(endDisabledIds[i][1],'sexy_normal');
return false;
}
}
};
//check if opened
var cOpened = false;
var position = $this.parents('.polling_container').find('.polling_li').css('position');
if (position == 'absolute') {
cOpened = true;
};
var buttonType = multipleAnswersInfoArray[$poll_id] == 1 ? 'checkbox' : 'radio';
//if we have checkboxes and sexy poll is closed, then we do not write answer to database, untill user do not vote vor it
var writeInto = (buttonType == 'checkbox' && !cOpened) ? 0 : 1;
var added_answer = $ans_name.replace(/\?\?/g,'sexydoublequestionmark');
$this.parent('div').children('.loading_small').fadeIn(400);
$this.fadeOut(400);
$.ajax
({
url: sexyPath + 'components/com_sexypolling/addanswer.php',
type: "post",
data: 'polling_id=' + $poll_id + '&answer=' + added_answer + '&autopublish=' + sexyAutoPublish[$poll_id] + '&writeinto=' + writeInto + '&country_name=' + sexyCountry + '&country_code=' + sexyCountryCode + '&city_name=' + sexyCity + '®ion_name=' + sexyRegion + '&voting_period='+voting_period+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
if((data[0].invalid) == 'invalid_token')
make_alert('Invalid Token','sexy_error');
if(buttonType == 'radio' || (buttonType == 'checkbox' && cOpened)) {
$this.parents('.polling_container').find('.add_answer_icon').addClass('voted_button');
$this.parents('.polling_container').find('.polling_submit').addClass('voted_button');
}
$this.parent('div').children('.loading_small').fadeOut(400);
if(sexyAutoPublish[$poll_id] == 1) {
//disable icon clicking
$this.parents('.polling_container').find('.add_answer_icon').addClass('disabled');
setTimeout(function() {
/*we keep add answer box opened only if
* 1. we have checkboxes
* 2. poll box is closed
*/
if((buttonType == 'checkbox' && !cOpened)) {
//close add answer box
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
//reset padding
$this.parent('.add_answer').css('paddingRight',0);
}
else {
$this.parents('.polling_container').find('.add_answer_icon').removeClass('opened');
//close add answer box
$this.parents('.answer_wrapper')
.removeClass('opened')
.addClass('closed')
.css({'overflow':'hidden'})
.animate({
height:0
},600,function() {
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
//reset padding
$this.parent('.add_answer').css('paddingRight',0);
});
};
},1);
//add new answer
add_answer($this.parents('.polling_container'),data[0].answer,data[0].id);
}
else {
//show moderation message
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.attr("readonly","readonly")
.val(sexyPolling_words[13]);
make_alert(sexyPolling_words[13],'sexy_normal');
$this.parent('.add_answer').css('paddingRight',0);
$this.parents('.polling_container').find('.add_answer_icon').addClass('disabled');
setTimeout(function() {
//change icon background
$this.parents('.polling_container').find('.add_answer_icon').removeClass('opened');
//close add answer box
$this.parents('.answer_wrapper')
.removeClass('opened')
.addClass('closed')
.css({'overflow':'hidden'})
.animate({
height:0
},600,function() {
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
});
},3000)
}
}
});
//function to add new answer to the answers list
function add_answer($c,$answer,$id) {
//check if opened
var cOpened = false;
var position = $c.find('.polling_li').css('position');
if (position == 'absolute') {
cOpened = true;
};
var polling_id = $c.find('.poll_answer').attr('name');
var module_id = $c.parent('div').attr('roll');
var h = $c.find('.answer_votes_data').height();
var buttonType = multipleAnswersInfoArray[polling_id] == 1 ? 'checkbox' : 'radio';
var color = 'blue';
if(buttonType == 'radio')
var inner_img_html = '<div class="radio_part1 ' + color + '_radio_part1 unselectable" style="opacity: 1;" > </div>';
else
var inner_img_html = '<div class="checkbox_part1 ' + color + '_checkbox_part1 unselectable" style="height: 9px;" > </div><div class="checkbox_part2 ' + color + '_checkbox_part2 unselectable" style="height: 12px;"> </div>';
//create new element html
if(cOpened) {
var t_votes = $c.find('.total_votes_val').html();
var t_votes_new = ++t_votes;
$c.find('.total_votes_val').html(t_votes_new);
$c.find('.total_votes').html(t_votes_new);
var new_percent = parseFloat(100 / t_votes).toFixed(1);
$new_li = '<li id="answer_' + $id + '" class="polling_li"><div class="animation_block"></div><div class="answer_name"><label style="margin-left:0" uniq_index="' + $id + '" class="twoglux_label">' + $answer + '</label></div><div class="answer_input" style="width: 0px; opacity: 0; "><div class="twoglux_styled_input_wrapper" ><input name="' + polling_id + '" id="' + $id + '" type="' + buttonType + '" checked="checked" class="poll_answer ' + $id + ' twoglux_styled" style="display:none" value="' + $id + '" /><a id="twoglux_styled_elem_' + $id + '_' + added_length + '" class="twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + buttonType + ' unselectable name_' + polling_id + ' twoglux_checked">' + inner_img_html + '</a></div></div><div class="sexy_clear"></div><div class="answer_result"><div class="answer_navigation polling_bar_' + newAnswerBarIndex + '" id="answer_navigation_' + $id + '" style=" opacity: 1; width: 1px;display:block;"><div class="grad"></div></div><div class="answer_votes_data" id="answer_votes_data_' + $id + '" style="height: ' + h + 'px;display:block; ">' + sexyPolling_words[0] + ': <span id="answer_votes_data_count_' + $id + '">1</span><span id="answer_votes_data_count_val_' + $id + '" style="display:none">1</span> (<span id="answer_votes_data_percent_' + $id + '">' + new_percent + '</span><span style="display:none" id="answer_votes_data_percent_val_' + $id + '">' + new_percent + '</span>%)</div><div class="sexy_clear"></div></div></li>';
//add html to DOM
$c.find("li").last().after($new_li);
//set height
$("#answer_navigation_" + $id).css('height',animation_styles[module_id+"_"+polling_id][9]);
$new_height = $("#answer_" + $id).height() + offset_padding;
$ul_height = $c.children("ul").height();
$("#answer_" + $id).css({"position":"absolute","top":$ul_height});
$c.children("ul").stop(true,false).animate( {
height: "+=" + $new_height
},600,function() {
show_polling_by_date($c,'yes');
});
}
else {
var user_class = buttonType == 'checkbox' ? 'doNotUncheck' : '';
var added_length = $c.find(".doNotUncheck").length;
$new_li = '<li id="answer_' + $id + '" class="polling_li"><div class="animation_block"></div><div class="answer_name"><label uniq_index="elem_' + $id + '_' + added_length + '" class="twoglux_label">' + $answer + '</label></div><div class="answer_input"><div class="twoglux_styled_input_wrapper" ><input name="' + polling_id + '" id="elem_' + $id + '_' + added_length + '" type="' + buttonType + '" checked="checked" class="poll_answer ' + $id + ' twoglux_styled" style="display:none" value="' + $id + '" /><a id="twoglux_styled_elem_' + $id + '_' + added_length + '" class="' + user_class + ' twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + buttonType + ' unselectable name_' + polling_id + ' twoglux_checked">' + inner_img_html + '</a></div></div><div class="sexy_clear"></div><div class="answer_result"><div class="answer_navigation polling_bar_' + newAnswerBarIndex + '" id="answer_navigation_' + $id + '"><div class="grad"></div></div><div class="answer_votes_data" id="answer_votes_data_' + $id + '">' + sexyPolling_words[0] + ': <span id="answer_votes_data_count_' + $id + '"></span><span id="answer_votes_data_count_val_' + $id + '" style="display:none">0</span> (<span id="answer_votes_data_percent_' + $id + '">0</span><span style="display:none" id="answer_votes_data_percent_val_' + $id + '">0</span>%)</div><div class="sexy_clear"></div></div></li>';
//add html to DOM
$c.find("li").last().after($new_li);
$ul_height = $c.children("ul").height();
$c.children("ul").attr("h",$ul_height);
};
if(cOpened)
$("#answer_" + $id + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
})
});
//show polling
if(!cOpened && buttonType == 'radio') {
var sub_object = $c.find(".polling_submit");
show_polling(sub_object);
}
}
});
//slider function
s_length = sexyPollingIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof sexyPollingIds[i] !== 'undefined') {
var select1 = sexyPollingIds[i][0];
var select2 = sexyPollingIds[i][1];
$("#" + select1 + ",#" + select2).selectToUISlider(
{
labels:0,
sliderOptions:
{
stop: function(e,ui)
{
show_polling_by_date($(this).parents('.polling_container'));
}
}
});
}
};
//autoanimate
v_length = votedIds.length;
for(var i = 0;i <= v_length; i++) {
if(typeof votedIds[i] !== 'undefined' && autoAnimate[votedIds[i][0]] == '1') {
var time = (i * 1 + 1) * 10;
var t = $("#res_" + votedIds[i][1] + "_" + votedIds[i][0]);
animate_poll(t,time);
}
};
function animate_poll(t,time) {
setTimeout(function() {
show_polling(t);
},time)
}
///////////////////////////////////////////////////////////////Sexy Checkboxes/////////////////////////////////////////////////////////////////////////////////
$('.twoglux_styled').each(function() {
var $this = $(this);
var type = $this.attr("type");
var color = $this.attr("data-color");
var name = $this.attr("name");
var id = $this.attr("id");
$this.wrap('<div class="twoglux_styled_input_wrapper" />');
if(type == 'radio')
var inner_img_html = '<div class="radio_part1 ' + color + '_radio_part1 unselectable" > </div>';
else
var inner_img_html = '<div class="checkbox_part1 ' + color + '_checkbox_part1 unselectable" > </div><div class="checkbox_part2 ' + color + '_checkbox_part2 unselectable"> </div>';
var twoglux_styled_html = '<a id="twoglux_styled_' + id + '" class="twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + type + ' unselectable name_' + name + '">' + inner_img_html + '</a>';
$this.after(twoglux_styled_html);
$this.hide();
});
$('.twoglux_styled_element').live('mouseenter', function() {
make_mouseenter($(this));
});
$('.twoglux_styled_element').live('mouseleave', function() {
make_mouseleave($(this))
});
function make_mouseenter($elem) {
if($elem.hasClass('twoglux_styled_radio'))
$elem.addClass('twoglux_styled_radio_hovered');
else
$elem.addClass('twoglux_styled_checkbox_hovered');
};
function make_mouseleave($elem) {
if($elem.hasClass('twoglux_styled_radio'))
$elem.removeClass('twoglux_styled_radio_hovered');
else
$elem.removeClass('twoglux_styled_checkbox_hovered');
};
var sexyanimatetime = 150;
var last_event = 'up';
var last_event_radio = 'up';
var body_mouse_up_enabled = false;
//////////////////////////////////////////////////////////////////////MOVE FUNCTIONS////////////////////////////////////////
function animate_checkbox1_down($elem) {
$elem.animate({height: 9},sexyanimatetime);
};
function animate_checkbox1_up($elem) {
//uncheck element
$elem.parent('a').removeClass('twoglux_checked');
$elem.parent('a').prev('input').attr("checked",false);
$elem.animate({height: 0},sexyanimatetime);
};
function animate_checkbox2_up($elem) {
$elem.animate({height: 12},sexyanimatetime);
//check element
$elem.parent('a').addClass('twoglux_checked');
$elem.parent('a').prev('input').attr("checked",true);
};
function animate_checkbox2_down($elem) {
$elem.animate({height: 0},sexyanimatetime);
};
//////////////////////////////////////////////////////////////////////MOUSEDOWN////////////////////////////////////////
$('.twoglux_styled_checkbox').live('mousedown',function() {
//check if checkbox checked
if($(this).hasClass('twoglux_checked'))
animate_checkbox2_down($(this).find('.checkbox_part2'));
else
animate_checkbox1_down($(this).find('.checkbox_part1'));
last_event = 'down';
body_mouse_up_enabled = true;
});
//////////////////////////////////////////////////////////////////////MOUSEUP//////////////////////////////////////////
$('.twoglux_styled_checkbox').live('mouseup',function() {
if(!($(this).hasClass('twoglux_checked'))) {
if(!check_allowed_answers_count($(this).parents('.polling_container'))) {
last_event = 'up';
body_mouse_up_enabled = false;
animate_checkbox1_up($(this).find('.checkbox_part1'));
return false;
}
}
if(last_event == 'down') {
//check if checkbox checked
if($(this).hasClass('twoglux_checked'))
animate_checkbox1_up($(this).find('.checkbox_part1'));
else
animate_checkbox2_up($(this).find('.checkbox_part2'));
}
last_event = 'up';
body_mouse_up_enabled = false;
});
function check_allowed_answers_count($c) {
var poll_id = $c.find('.poll_answer').attr('name');
var alloewd_answers = allowedNumberAnswers[poll_id];
if(alloewd_answers == 0)
return true;
var checked_options_count = $c.find('input[type="checkbox"]:checked').length;
if(parseInt(checked_options_count) == alloewd_answers) {
make_alert(sexyPolling_words[23] + ' <span class="max_allowed_checkox_limit">' + alloewd_answers + '</span>','sexy_normal');
return false;
}
return true;
}
//////////////////////////////////////////////////////////RADIOBUTTONS//////////////////////////////////////////////////////////////
$('.radio_part1').css('opacity','0');
$('.twoglux_styled_radio').live('mousedown',function() {
//check if checkbox checked
if(!($(this).hasClass('twoglux_checked'))) {
$(this).find('.radio_part1').fadeTo(sexyanimatetime, 0.5);
}
last_event_radio = 'down';
body_mouse_up_enabled = true;
});
$('.twoglux_styled_radio').live('mouseup',function() {
if(last_event_radio == 'down') {
//check if checkbox checked
if(!($(this).hasClass('twoglux_checked'))) {
$(this).addClass('twoglux_checked');
var name = $(this).prev('input').attr("name");
$('input[name="' + name + '"]').attr("checked",false);
$(this).prev('input').attr("checked",true);
$('.name_' + name).removeClass('twoglux_checked');
$(this).addClass('twoglux_checked');
$('.name_' + name).not($(this)).find('.radio_part1').fadeTo(sexyanimatetime, 0);
$(this).find('.radio_part1').fadeTo(sexyanimatetime, 1);
}
}
last_event_radio = 'up';
body_mouse_up_enabled = false;
});
//////////////////////////////////////////////////////////////OTHER////////////////////////////////////////////////////////////////////////////////
//fixing bug in firefox
$('.twoglux_styled_input_wrapper').bind("dragstart", function() {
return false;
});
$("body").live('mouseup',function() {
if(body_mouse_up_enabled) {
//checkbox
var $elems = $('.twoglux_styled_element').not('.twoglux_checked').find('.checkbox_part1');
animate_checkbox1_up($elems);
var $elems = $('.twoglux_styled_element.twoglux_checked').find('.checkbox_part2');
animate_checkbox2_up($elems);
var $elems = $('.twoglux_styled_element').not('.twoglux_checked').find('.radio_part1');
$elems.fadeTo(sexyanimatetime, 0);
}
});
//trigger events for label
$('.twoglux_label').live('mouseenter', function() {
var uniq_index = $(this).attr("uniq_index");
make_mouseenter($("#twoglux_styled_" + uniq_index));
});
$('.twoglux_label').live('mouseleave',function() {
var uniq_index = $(this).attr("uniq_index");
make_mouseleave($("#twoglux_styled_" + uniq_index));
});
$('.twoglux_label').live('mousedown',function() {
var uniq_index = $(this).attr("uniq_index");
$("#twoglux_styled_" + uniq_index).trigger("mousedown");
});
$('.twoglux_label').live('mouseup',function() {
var uniq_index = $(this).attr("uniq_index");
$("#twoglux_styled_" + uniq_index).trigger("mouseup");
});
//function to prevent uncheck user added input boxes
$('.doNotUncheck').live('mouseup',function() {
if(! $(this).hasClass('twoglux_checked') ) {
$(this).parent('div').parent('div').parent('li').remove();
};
});
})
})(sexyJ); | JavaScript |
/**
*
* Utilities
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($) {
EYE.extend({
getPosition : function(e, forceIt)
{
var x = 0;
var y = 0;
var es = e.style;
var restoreStyles = false;
if (forceIt && sexyJ.curCSS(e,'display') == 'none') {
var oldVisibility = es.visibility;
var oldPosition = es.position;
restoreStyles = true;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
}
var el = e;
if (el.getBoundingClientRect) { // IE
var box = el.getBoundingClientRect();
x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2;
y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2;
} else {
x = el.offsetLeft;
y = el.offsetTop;
el = el.offsetParent;
if (e != el) {
while (el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
}
if (sexyJ.browser.safari && sexyJ.curCSS(e, 'position') == 'absolute' ) {
x -= document.body.offsetLeft;
y -= document.body.offsetTop;
}
el = e.parentNode;
while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML')
{
if (sexyJ.curCSS(el, 'display') != 'inline') {
x -= el.scrollLeft;
y -= el.scrollTop;
}
el = el.parentNode;
}
}
if (restoreStyles == true) {
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {x:x, y:y};
},
getSize : function(e)
{
var w = parseInt(sexyJ.curCSS(e,'width'), 10);
var h = parseInt(sexyJ.curCSS(e,'height'), 10);
var wb = 0;
var hb = 0;
if (sexyJ.curCSS(e, 'display') != 'none') {
wb = e.offsetWidth;
hb = e.offsetHeight;
} else {
var es = e.style;
var oldVisibility = es.visibility;
var oldPosition = es.position;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
wb = e.offsetWidth;
hb = e.offsetHeight;
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {w:w, h:h, wb:wb, hb:hb};
},
getClient : function(e)
{
var h, w;
if (e) {
w = e.clientWidth;
h = e.clientHeight;
} else {
var de = document.documentElement;
w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
}
return {w:w,h:h};
},
getScroll : function (e)
{
var t=0, l=0, w=0, h=0, iw=0, ih=0;
if (e && e.nodeName.toLowerCase() != 'body') {
t = e.scrollTop;
l = e.scrollLeft;
w = e.scrollWidth;
h = e.scrollHeight;
} else {
if (document.documentElement) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
if (typeof pageYOffset != 'undefined') {
t = pageYOffset;
l = pageXOffset;
}
iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
}
return { t: t, l: l, w: w, h: h, iw: iw, ih: ih };
},
getMargins : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'marginTop') || '';
var r = sexyJ.curCSS(e,'marginRight') || '';
var b = sexyJ.curCSS(e,'marginBottom') || '';
var l = sexyJ.curCSS(e,'marginLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getPadding : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'paddingTop') || '';
var r = sexyJ.curCSS(e,'paddingRight') || '';
var b = sexyJ.curCSS(e,'paddingBottom') || '';
var l = sexyJ.curCSS(e,'paddingLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getBorder : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'borderTopWidth') || '';
var r = sexyJ.curCSS(e,'borderRightWidth') || '';
var b = sexyJ.curCSS(e,'borderBottomWidth') || '';
var l = sexyJ.curCSS(e,'borderLeftWidth') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)||0
};
else
return {t: t, r: r, b: b, l: l};
},
traverseDOM : function(nodeEl, func)
{
func(nodeEl);
nodeEl = nodeEl.firstChild;
while(nodeEl){
EYE.traverseDOM(nodeEl, func);
nodeEl = nodeEl.nextSibling;
}
},
getInnerWidth : function(el, scroll) {
var offsetW = el.offsetWidth;
return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth;
},
getInnerHeight : function(el, scroll) {
var offsetH = el.offsetHeight;
return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight;
},
getExtraWidth : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingLeft'))||0)
+ (parseInt($.curCSS(el, 'paddingRight'))||0)
+ (parseInt($.curCSS(el, 'borderLeftWidth'))||0)
+ (parseInt($.curCSS(el, 'borderRightWidth'))||0);
return 0;
},
getExtraHeight : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingTop'))||0)
+ (parseInt($.curCSS(el, 'paddingBottom'))||0)
+ (parseInt($.curCSS(el, 'borderTopWidth'))||0)
+ (parseInt($.curCSS(el, 'borderBottomWidth'))||0);
return 0;
},
isChildOf: function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (!el || !el.nodeType || el.nodeType != 1) {
return false;
}
if (parentEl.contains && !$.browser.safari) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
centerEl : function(el, axis)
{
var clientScroll = EYE.getScroll();
var size = EYE.getSize(el);
if (!axis || axis == 'vertically')
$(el).css(
{
top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px'
}
);
if (!axis || axis == 'horizontally')
$(el).css(
{
left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px'
}
);
}
});
if (!$.easing.easeout) {
$.easing.easeout = function(p, n, firstNum, delta, duration) {
return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum;
};
}
})(sexyJ); | JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(sexyJ) | JavaScript |
(function($){
var initLayout = function() {
var hash = window.location.hash.replace('#', '');
var currentTab = $('ul.navigationTabs a')
.bind('click', showTab)
.filter('a[rel=' + hash + ']');
if (currentTab.size() == 0) {
currentTab = $('ul.navigationTabs a:first');
}
showTab.apply(currentTab.get(0));
$('#colorpickerHolder').ColorPicker({flat: true});
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerField1, #colorpickerField2, #colorpickerField3').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
$('#colorSelector').ColorPicker({
color: '#0000ff',
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
$('#colorSelector div').css('backgroundColor', '#' + hex);
}
});
};
var showTab = function(e) {
var tabIndex = $('ul.navigationTabs a')
.removeClass('active')
.index(this);
$(this)
.addClass('active')
.blur();
$('div.tab')
.hide()
.eq(tabIndex)
.show();
};
EYE.register(initLayout, 'init');
})(jQuery) | JavaScript |
/**
*
* Zoomimage
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($){
var EYE = window.EYE = function() {
var _registered = {
init: []
};
return {
init: function() {
$.each(_registered.init, function(nr, fn){
fn.call();
});
},
extend: function(prop) {
for (var i in prop) {
if (prop[i] != undefined) {
this[i] = prop[i];
}
}
},
register: function(fn, type) {
if (!_registered[type]) {
_registered[type] = [];
}
_registered[type].push(fn);
}
};
}();
$(EYE.init);
})(sexyJ);
| JavaScript |
(function($) {
$.fn.extend({
jCountdown:function(){
var Flip = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 50;
this._height = 64;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
}
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
}
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
}
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
}
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = -(9-this.value())*this.width();
var top = -(this.frame()-1)*this.height();
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px");
}
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
}
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
}
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Slide = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 50;
this._height = 64;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
}
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = 0;
var top = -((1+this.value())*this.height()) + (Math.sin((this.frame()-1)/(this.totalFrames()-1)*Math.PI/2)*this.height());
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px");
};
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Metal = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 60;
this._height = 60;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
};
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var lastValue = this.value()+1;
if(lastValue>9){
lastValue = 0;
};
var progress = this.frame()/this.totalFrames();
var opacity;
if(progress>=.4 && progress<=.6){
opacity = 0;
}else if(progress<=.4){
opacity = 1-progress/.4;
}else if(progress>=.6){
opacity = (progress-.6)/.4;
};
var left = 0;
var top = -(progress>.5 ? this.value() : lastValue)*this.height();
top -= (1-opacity)*3;
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px").css("opacity",opacity);
this._target.children(".cover").css("opacity",opacity);
}
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Crystal = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 60;
this._height = 60;
this._widthSmall= 42;
this._heightSmall = 42;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
};
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = 0;
var top = -this.value()*this.height();
var opacity = Math.sin((this.frame()-1)/(this.totalFrames()-1)*Math.PI/2);
if(opacity>0 && opacity<0.001){
opacity = 0;
}else if(opacity<0 && opacity>-0.001){
opacity = 0;
};
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px").css("opacity",opacity);
};
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Countdown = function(){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._days = [];
this._hours = [];
this._minutes = [];
this._seconds = [];
this._tickId = -1;
this._tickDelay = 100;
this._timeText = "";
this._timeZone = 0;
this._time = null;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
//check time
this.checkTime = function(update){
var currentTime = new Date();
if(this._time.getTime()<(currentTime.getTime())){
for(var i=0; i<this._days.length; i++){
this._days[i].value(0);
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].value(0);
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].value(0);
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].value(0);
};
this.stop();
this.onFinish();
return true;
}else{
var currentTimeText = this.timeFormat(this._time.getTime()-(currentTime.getTime()), this._days.length, this._hours.length, this._minutes.length, this._seconds.length);
var currentTimeChars = currentTimeText.split("");
if (!isNaN(this._time)){
for(var i=0; i<this._days.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._days[i].value()){
this._days[i].value(v, update);
};
};
for(var i=0; i<this._hours.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._hours[i].value()){
this._hours[i].value(v, update);
};
};
for(var i=0; i<this._minutes.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._minutes[i].value()){
this._minutes[i].value(v, update);
};
};
for(var i=0; i<this._seconds.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._seconds[i].value()){
this._seconds[i].value(v, update);
};
};
};
return false;
};
};
//text format
this.textFormat = function(text, length, fillChar){
text = text.toString();
while (text.length<length){
text = fillChar+text;
};
if(text.length>length){
text = text.substr(text.length-length,length);
};
return text;
};
//time format
this.timeFormat = function(msec, dayTextNumber, hourTextNumber, minuteTextNumber, secondTextNumber){
var time = Math.floor(msec/1000);
var s = time%60;
var i = Math.floor(time%(60*60)/60);
var h = Math.floor(time%(24*60*60)/(60*60));
var d = Math.floor(time/(24*60*60));
return this.textFormat(d, dayTextNumber, "0")+this.textFormat(h, hourTextNumber, "0")+this.textFormat(i, minuteTextNumber, "0")+this.textFormat(s, secondTextNumber, "0");
};
//start
this.start = function(){
this.stop();
for(var i=0; i<this._days.length; i++){
this._days[i].update();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].update();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].update();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].update();
};
var finish = this.checkTime(false);
if(!finish){
var target = this;
this._tickId = setInterval(function(){
target.checkTime(true);
}, this._tickDelay);
};
};
//stop
this.stop = function(){
for(var i=0; i<this._days.length; i++){
this._days[i].stop();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].stop();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].stop();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].stop();
};
clearInterval(this._tickId);
};
this.onFinish = function(){
};
this.destroy = function(){
for(var i=0; i<this._days.length; i++){
this._days[i].destroy();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].destroy();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].destroy();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].destroy();
};
this._days = [];
this._hours = [];
this._minutes = [];
this._seconds = [];
this.stop();
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.items = function(days, hours, minutes, seconds){
this._days = days;
this._hours = hours;
this._minutes = minutes;
this._seconds = seconds;
};
this.timeText = function(v){
if(v==undefined){
return this._timeText;
}else{
this._timeText = v;
this.time(this.timeText(), this.timeZone());
};
};
this.timeZone = function(v){
if(v==undefined){
return this._timeZone;
}else{
this._timeZone = v;
this.time(this.timeText(), this.timeZone());
};
};
//time
this.time = function(tt,tz){
this._timeText = tt;
this._timeZone = tz;
var time = this._timeText.split("/").join(" ").split(":").join(" ").split(" ");
var y = parseInt(time[0],10);
var m = parseInt(time[1],10)-1;
var d = parseInt(time[2],10);
var h = parseInt(time[3],10);
var i = parseInt(time[4],10)-this._timeZone*60;
var s = parseInt(time[5],10);
this._time = new Date(y, m, d, h, i, s, 0);
this.start();
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
var getCountdown = function(){
return target.data("countdown");
};
var initCountdown = function(){
if(getCountdown()==undefined){
var countdown = new Countdown();
target.data("countdown", countdown);
return getCountdown();
};
};
var destroyCountdown = function(){
if(getCountdown()!=undefined){
getCountdown().destroy();
target.removeData("countdown");
};
};
var init = function(setting){
countdown = initCountdown();
var browserVersion = parseInt($.browser.version,10);
var timeText = typeof(setting.timeText)=="string" ? setting.timeText : "";
var timeZone = parseFloat(setting.timeZone);
if(isNaN(timeZone)){
timeZone = 0;
};
var style = typeof(setting.style)=="string" ? setting.style.toLowerCase() : "";
switch(style){
case "flip":
break;
case "slide":
break;
case "crystal":
break;
case "metal":
break;
default:
style = "flip";
};
var color = typeof(setting.color)=="string" ? setting.color.toLowerCase() : "";
switch(color){
case "black":
break;
case "white":
break;
default:
color = "black";
};
var width = parseInt(setting.width,10);
if(width>=10){
}else{
width = 0;
};
var textGroupSpace = parseInt(setting.textGroupSpace,10);
if(textGroupSpace>=0){
}else{
textGroupSpace = 15;
};
var textSpace = parseInt(setting.textSpace,10);
if(textSpace>0){
}else{
textSpace = 0;
};
var reflection = setting.reflection!=false;
var reflectionOpacity = parseFloat(setting.reflectionOpacity);
if(reflectionOpacity>0){
if(reflectionOpacity>100){
reflectionOpacity = 100;
}
}else{
reflectionOpacity = 10;
};
var reflectionBlur = parseInt(setting.reflectionBlur,10);
if(reflectionBlur>0){
if(reflectionBlur>10){
reflectionBlur = 10;
}
}else{
reflectionBlur = 0;
};
var dayTextNumber = parseInt(setting.dayTextNumber,10)>2 ? parseInt(setting.dayTextNumber,10) : 2;
var hourTextNumber = 2;
var minuteTextNumber = 2;
var secondTextNumber = 2;
var displayDay = setting.displayDay!=false;
var displayHour = setting.displayHour!=false;
var displayMinute = setting.displayMinute!=false;
var displaySecond = setting.displaySecond!=false;
var displayLabel = setting.displayLabel!=false;
var onFinish = typeof(setting.onFinish)=="function" ? setting.onFinish : function(){};
var html = "";
var itemClass = "";
var lastClass = "";
html += '<div class="jCountdown">';
if(displayDay){
var lastItem = (!displayHour && !displayMinute && !displaySecond) ? " lastItem" : "";
html += '<div class="group day'+lastItem+'">';
for(var i=0; i<dayTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(dayTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displayHour){
var lastItem = (!displayMinute && !displaySecond) ? " lastItem" : "";
html += '<div class="group hour'+lastItem+'">';
for(var i=0; i<hourTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(hourTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displayMinute){
var lastItem = (!displaySecond) ? " lastItem" : "";
html += '<div class="group minute'+lastItem+'">';
for(var i=0; i<minuteTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(minuteTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displaySecond){
html += '<div class="group second lastItem">';
for(var i=0; i<secondTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(secondTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
html += '</div>';
target.html(html);
var countdownObject = target.children(".jCountdown");
countdownObject.addClass(style);
countdownObject.addClass(color);
countdownObject.children(".group").css("margin-right",textGroupSpace+"px");
countdownObject.children(".group.lastItem").css("margin-right","0px");
countdownObject.children(".group").children(".container").css("margin-right",textSpace+"px");
countdownObject.children(".group").children(".container.lastItem").css("margin-right","0px");
if(reflection){
if(($.browser.msie && browserVersion<10)){
}else{
reflectionObject = countdownObject.clone();
reflectionObject.addClass("reflection");
if(displayLabel){
reflectionObject.addClass("displayLabel");
};
if(reflectionOpacity!=100){
reflectionObject.css("opacity",reflectionOpacity/100);
};
if(reflectionBlur!=0){
reflectionObject.addClass("blur"+reflectionBlur);
};
countdownObject = countdownObject.add(reflectionObject);
}
};
var countdownContainer = $('<div class="jCountdownContainer"></div>');
countdownContainer.append(countdownObject);
target.append(countdownContainer);
if(width!=0){
var countdownScaleObject = $('<div class="jCountdownScale"></div>');
countdownScaleObject.append(countdownObject);
countdownContainer.append(countdownScaleObject);
var countdownScaleObjectWidth = countdownScaleObject.width();
var countdownScaleObjectHeight = countdownScaleObject.height();
var scale = width/countdownScaleObjectWidth;
var left = -(1-scale)*countdownScaleObjectWidth/2;
var top = -(1-scale)*countdownScaleObjectHeight/2;
var scaleCss = "scale("+scale+")";
countdownContainer.width(countdownScaleObjectWidth*scale);
countdownContainer.height(countdownScaleObjectHeight*scale);
if($.browser.msie && browserVersion<=8){
countdownScaleObject.css("zoom", scale);
}else{
countdownScaleObject.css("transform", scaleCss).
css("-moz-transform", scaleCss).
css("-webkit-transform", scaleCss).
css("-o-transform", scaleCss).
css("-ms-transform", scaleCss);
countdownScaleObject.css("left",left).css("top",top);
};
};
var selector = "";
var index = 0;
var days = [];
var hours = [];
var minutes = [];
var seconds = [];
var itemClass = function(){};
switch(style){
case "flip":
itemClass = Flip;
break;
case "slide":
itemClass = Slide;
break;
case "crystal":
itemClass = Crystal;
break;
case "metal":
itemClass = Metal;
break;
default:
};
index = 1;
selector = ".group.day>.container.item";
while(countdownObject.find(selector+index).length){
days.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.hour>.container.item";
while(countdownObject.find(selector+index).length){
hours.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.minute>.container.item";
while(countdownObject.find(selector+index).length){
minutes.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.second>.container.item";
while(countdownObject.find(selector+index).length){
seconds.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
countdown.items(days, hours, minutes, seconds);
countdown.onFinish = onFinish;
countdown.time(timeText, timeZone);
};
var destroy = function(){
destroyCountdown();
target.children().remove();
};
var start = function(){
countdown.start();
};
var stop = function(){
countdown.stop();
};
if(arguments.length>0){
var target = this;
var countdown = getCountdown();
if(arguments.length==1 && typeof(arguments[0])=="object"){
//destroy the old countdown
if(countdown!=undefined){
destroy();
};
//init new countdown
init(arguments[0]);
}else if(typeof(arguments[0])=="string"){
//set setting & call method
if(countdown!=undefined){
switch(arguments[0]){
case "stop":
stop();
break;
case "start":
start();
break;
case "destroy":
destroy();
break;
default:
};
};
};
};
return this;
}
});
})(sexyJ);
| JavaScript |
sexyJ(function(e,i){function j(){var a=e("script:first"),b=a.css("color"),c=false;if(/^rgba/.test(b))c=true;else try{c=b!=a.css("color","rgba(0, 0, 0, 0.5)").css("color");a.css("color",b)}catch(d){}return c}function k(a,b,c){var d=[];a.c&&d.push("inset");typeof b.left!="undefined"&&d.push(parseInt(a.left+c*(b.left-a.left),10)+"px "+parseInt(a.top+c*(b.top-a.top),10)+"px");typeof b.blur!="undefined"&&d.push(parseInt(a.blur+c*(b.blur-a.blur),10)+"px");typeof b.a!="undefined"&&d.push(parseInt(a.a+c*
(b.a-a.a),10)+"px");if(typeof b.color!="undefined"){var g="rgb"+(e.support.rgba?"a":"")+"("+parseInt(a.color[0]+c*(b.color[0]-a.color[0]),10)+","+parseInt(a.color[1]+c*(b.color[1]-a.color[1]),10)+","+parseInt(a.color[2]+c*(b.color[2]-a.color[2]),10);if(e.support.rgba)g+=","+parseFloat(a.color[3]+c*(b.color[3]-a.color[3]));g+=")";d.push(g)}return d.join(" ")}function h(a){var b,c,d={};if(b=/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(a))c=[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],
16),1];else if(b=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(a))c=[parseInt(b[1],16)*17,parseInt(b[2],16)*17,parseInt(b[3],16)*17,1];else if(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),1];else if(b=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),parseFloat(b[4])];d=(b=/(-?[0-9]+)(?:px)?\s+(-?[0-9]+)(?:px)?(?:\s+(-?[0-9]+)(?:px)?)?(?:\s+(-?[0-9]+)(?:px)?)?/.exec(a))?
{left:parseInt(b[1],10),top:parseInt(b[2],10),blur:b[3]?parseInt(b[3],10):0,a:b[4]?parseInt(b[4],10):0}:{left:0,top:0,blur:0,a:0};d.c=/inset/.test(a);d.color=c;return d}e.extend(true,e,{support:{rgba:j()}});var f;e.each(["boxShadow","MozBoxShadow","WebkitBoxShadow"],function(a,b){a=e("html").css(b);if(typeof a=="string"&&a!=""){f=b;return false}});if(f)e.fx.step.boxShadow=function(a){if(!a.init){a.b=h(e(a.elem).get(0).style[f]||e(a.elem).css(f));a.end=e.extend({},a.b,h(a.end));if(a.b.color==i)a.b.color=
a.end.color||[0,0,0];a.init=true}a.elem.style[f]=k(a.b,a.end,a.pos)}});
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(sexyJ); | JavaScript |
/*
* --------------------------------------------------------------------
* jQuery-Plugin - selectToUISlider - creates a UI slider component from a select element(s)
* by Scott Jehl, scott@filamentgroup.com
* http://www.filamentgroup.com
* reference article: http://www.filamentgroup.com/lab/update_jquery_ui_16_slider_from_a_select_element/
* demo page: http://www.filamentgroup.com/examples/slider_v2/index.html
*
* Copyright (c) 2008 Filament Group, Inc
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Usage Notes: please refer to our article above for documentation
*
* --------------------------------------------------------------------
*/
(function(jQuery) {
jQuery.fn.selectToUISlider = function(settings){
var selects = jQuery(this);
//accessible slider options
var options = jQuery.extend({
labels: 3, //number of visible labels
tooltip: true, //show tooltips, boolean
tooltipSrc: 'text',//accepts 'value' as well
labelSrc: 'value',//accepts 'value' as well ,
sliderOptions: null
}, settings);
//handle ID attrs - selects each need IDs for handles to find them
var handleIds = (function(){
var tempArr = [];
selects.each(function(){
tempArr.push('handle_'+jQuery(this).attr('id'));
});
return tempArr;
})();
//array of all option elements in select element (ignores optgroups)
var selectOptions = (function(){
var opts = [];
selects.eq(0).find('option').each(function(){
opts.push({
value: jQuery(this).attr('value'),
text: jQuery(this).text()
});
});
return opts;
})();
//array of opt groups if present
var groups = (function(){
if(selects.eq(0).find('optgroup').size()>0){
var groupedData = [];
selects.eq(0).find('optgroup').each(function(i){
groupedData[i] = {};
groupedData[i].label = jQuery(this).attr('label');
groupedData[i].options = [];
jQuery(this).find('option').each(function(){
groupedData[i].options.push({text: jQuery(this).text(), value: jQuery(this).attr('value')});
});
});
return groupedData;
}
else return null;
})();
//check if obj is array
function isArray(obj) {
return obj.constructor == Array;
}
//return tooltip text from option index
function ttText(optIndex){
return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
}
//plugin-generated slider options (can be overridden)
var sliderOptions = {
step: 1,
min: 0,
orientation: 'horizontal',
max: selectOptions.length-1,
range: selects.length > 1,//multiple select elements = true
slide: function(e, ui) {//slide function
var thisHandle = jQuery(ui.handle);
//handle feedback
var textval = ttText(ui.value);
thisHandle
.attr('aria-valuetext', textval)
.attr('aria-valuenow', ui.value)
.find('.ui-slider-tooltip .ttContent')
.text( textval );
//control original select menu
var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
currSelect.find('option').eq(ui.value).attr('selected', 'selected');
},
values: (function(){
var values = [];
selects.each(function(){
values.push( jQuery(this).get(0).selectedIndex );
});
return values;
})()
};
//slider options from settings
options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;
//select element change event
selects.bind('change keyup click', function(){
var thisIndex = jQuery(this).get(0).selectedIndex;
var thisHandle = jQuery('#handle_'+ jQuery(this).attr('id'));
var handleIndex = thisHandle.data('handleNum');
thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
});
//create slider component div
var sliderComponent = jQuery('<div></div>');
//CREATE HANDLES
selects.each(function(i){
var hidett = '';
//associate label for ARIA
var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') +']');
//labelled by aria doesn't seem to work on slider handle. Using title attr as backup
var labelText = (thisLabel.size()>0) ? 'Slider control for '+ thisLabel.text()+'' : '';
var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_'+handleIds[i]).attr('id');
if( options.tooltip == false ){hidett = ' style="display: none;"';}
jQuery('<a '+
'href="#" tabindex="0" '+
'id="'+handleIds[i]+'" '+
'class="ui-slider-handle" '+
'role="slider" '+
'aria-labelledby="'+thisLabelId+'" '+
'aria-valuemin="'+options.sliderOptions.min+'" '+
'aria-valuemax="'+options.sliderOptions.max+'" '+
'aria-valuenow="'+options.sliderOptions.values[i]+'" '+
'aria-valuetext="'+ttText(options.sliderOptions.values[i])+'" '+
'><span class="screenReaderContext">'+labelText+'</span>'+
'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"'+ hidett +'><span class="ttContent"></span>'+
'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>'+
'</span></a>')
.data('handleNum',i)
.appendTo(sliderComponent);
});
//CREATE SCALE AND TICS
//write dl if there are optgroups
if(groups) {
var inc = 0;
var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
jQuery(groups).each(function(h){
scale.append('<dt style="width: '+ (100/groups.length).toFixed(2) +'%' +'; left:'+ (h/(groups.length-1) * 100).toFixed(2) +'%' +'"><span>'+this.label+'</span></dt>');//class name becomes camelCased label
var groupOpts = this.options;
jQuery(this.options).each(function(i){
var style = (inc == selectOptions.length-1 || inc == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
scale.append('<dd style="left:'+ leftVal(inc) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></dd>');
inc++;
});
});
}
//write ol
else {
var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
jQuery(selectOptions).each(function(i){
var style = (i == selectOptions.length-1 || i == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? this.text : this.value;
scale.append('<li style="left:'+ leftVal(i) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></li>');
});
}
function leftVal(i){
return (i/(selectOptions.length-1) * 100).toFixed(2) +'%';
}
//show and hide labels depending on labels pref
//show the last one if there are more than 1 specified
if(options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');
//set increment
var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
//show em based on inc
for(var j=0; j<selectOptions.length; j+=increm){
if((selectOptions.length - j) > increm){//don't show if it's too close to the end label
sliderComponent.find('.ui-slider-scale li:eq('+ j +') span.ui-slider-label, .ui-slider-scale dd:eq('+ j +') span.ui-slider-label').addClass('ui-slider-label-show');
}
}
//style the dt's
sliderComponent.find('.ui-slider-scale dt').each(function(i){
jQuery(this).css({
'left': ((100 /( groups.length))*i).toFixed(2) + '%'
});
});
//inject and return
sliderComponent
.insertAfter(jQuery(this).eq(this.length-1))
.slider(options.sliderOptions)
.attr('role','application')
.find('.ui-slider-label')
.each(function(){
jQuery(this).css('marginLeft', -jQuery(this).width()/2);
});
//update tooltip arrow inner color
sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function(){
var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
jQuery(this).css('border-top', bWidth+' solid '+bColor);
});
var values = sliderComponent.slider('values');
if(isArray(values)){
jQuery(values).each(function(i){
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text( ttText(this) );
});
}
else {
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text( ttText(values) );
}
return this;
}
})(sexyJ);
| JavaScript |
(function($) {
$(window).load(function() {
function sp_make_li_h() {
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
};
sp_make_li_h();
function sp_make_ul_h() {
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
};
sp_make_ul_h();
});
$(document).ready(function() {
var sexyCountry = '',
sexyCountryCode = '',
sexyCity = '',
sexyRegion = '';
var offset_padding = 2;
function sp_make_li_h_() {
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
};
function sp_make_ul_h_() {
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
};
setTimeout(function() {
sp_make_li_h_();
sp_make_ul_h_();
},1000);
function check_pro_version($elem) {
$elem_1 = $elem.find('.powered_by');
$elem_2 = $elem.find('.powered_by a');
var sexy_font_size_1 = parseInt($elem_1.css('font-size'));
var sexy_top_1 = parseInt($elem_1.css('top'));
var sexy_left_1 = parseInt($elem_1.css('left'));
var sexy_bottom_1 = parseInt($elem_1.css('bottom'));
var sexy_right_1 = parseInt($elem_1.css('right'));
var sexy_text_indent_1 = parseInt($elem_1.css('text-indent'));
var sexy_margin_top_1 = parseInt($elem_1.css('margin-top'));
var sexy_margin_bottom_1 = parseInt($elem_1.css('margin-bottom'));
var sexy_margin_left_1 = parseInt($elem_1.css('margin-left'));
var sexy_margin_right_1 = parseInt($elem_1.css('margin-right'));
var sexy_display_1 = $elem_1.css('display');
var sexy_position_1 = $elem_1.css('position');
var sexy_width_1 = parseInt($elem_1.css('width'));
var sexy_height_1 = parseInt($elem_1.css('height'));
var sexy_visibility_1 = $elem_1.css('visibility');
var sexy_overflow_1 = $elem_1.css('overflow');
var sexy_zindex_1 = parseInt($elem_1.css('z-index'));
var sexy_font_size_2 = parseInt($elem_2.css('font-size'));
var sexy_top_2 = parseInt($elem_2.css('top'));
var sexy_left_2 = parseInt($elem_2.css('left'));
var sexy_bottom_2 = parseInt($elem_2.css('bottom'));
var sexy_right_2 = parseInt($elem_2.css('right'));
var sexy_text_indent_2 = parseInt($elem_2.css('text-indent'));
var sexy_margin_top_2 = parseInt($elem_2.css('margin-top'));
var sexy_margin_right_2 = parseInt($elem_2.css('margin-right'));
var sexy_margin_bottom_2 = parseInt($elem_2.css('margin-bottom'));
var sexy_margin_left_2 = parseInt($elem_2.css('margin-left'));
var sexy_display_2 = $elem_2.css('display');
var sexy_position_2 = $elem_2.css('position');
var sexy_width_2 = parseInt($elem_2.css('width'));
var sexy_height_2 = parseInt($elem_2.css('height'));
var sexy_visibility_2 = $elem_2.css('visibility');
var sexy_overflow_2 = $elem_2.css('overflow');
var sexy_zindex_2 = parseInt($elem_2.css('z-index'));
var txt1 = $.trim($elem_1.html().replace(/<[^>]+>.*?<\/[^>]+>/gi, ''));
var txt2 = $.trim($elem_2.html().replace(/<[^>]+>.*?<\/[^>]+>/gi, ''));
var txt1_l = parseInt(txt1.length);
var txt2_l = parseInt(txt2.length);
var a_href = $elem_2.attr("href").replace('http://','');
a_href = a_href.replace('www.','');
a_href = $.trim(a_href.replace('www',''));
a_href_l = parseInt(a_href.length);
if(
sexy_font_size_1 == '13' && sexy_top_1 == '0' && sexy_left_1 == '0' && sexy_bottom_1 == '0' && sexy_right_1 == '0' && sexy_text_indent_1 == '0' && sexy_margin_top_1 == '-1' && sexy_margin_right_1 == '8' && sexy_margin_bottom_1 == '13' && sexy_margin_left_1 == '0' &&
sexy_display_1 == 'block' && sexy_position_1 == 'relative' && sexy_width_1 > '20' && sexy_height_1 > '10' && sexy_visibility_1 == 'visible' && sexy_overflow_1 == 'visible' && sexy_zindex_1 == '10' &&
sexy_font_size_2 == '13' && sexy_top_2 == '0' && sexy_left_2 == '0' && sexy_bottom_2 == '0' && sexy_right_2 == '0' && sexy_text_indent_2 == '0' && sexy_margin_top_2 == '0' && sexy_margin_right_2 == '0' && sexy_margin_bottom_2 == '0' && sexy_margin_left_2 == '0' &&
sexy_display_2 != 'none' && sexy_position_2 == 'relative' && sexy_width_2 > '20' && sexy_height_2 > '10' && sexy_visibility_2 == 'visible' && sexy_overflow_2 == 'visible' && sexy_zindex_2 == '10' &&
txt1 != '' && txt2 == 'Sexy Polling' && txt1_l > 1 && txt2_l == '12' && a_href_l == '30' && a_href == '2glux.com/projects/sexypolling'
)
return true;
return false;
};
$.ajax
({
url: sexyPath + 'components/com_sexypolling/geoip.php?ip=' + sexyIp,
type: "get",
dataType: "json",
success: function(data)
{
if(data != null) {
sexyCountry = data.countryName;
sexyCountryCode = data.countryCode;
sexyCity = data.cityName;
sexyRegion = data.regionName;
}
},
error: function()
{
}
});
setTimeout(function() {
$(".polling_container_wrapper").each(function() {
var w = $(this).width();
$(this).css("width",w);
var curr_h = $(this).find('.answer_wrapper').height();
$(this).find('.answer_wrapper').attr("h",curr_h);
});
},100);
var estimated_seconds = new Array();
function create_seconds_timers() {
var onlyVotedIds = new Array();
for(t in votedIds) {
var poll_id = votedIds[t][0];
estimated_seconds[poll_id] = parseInt(votedIds[t][2] * 3600);
};
setInterval(function() {
for(t in estimated_seconds) {
if(estimated_seconds[t] > 0)
estimated_seconds[t] -= 1;
};
},1000);
};
create_seconds_timers();
var estimated_seconds_start_poll = new Array();
function create_start_poll_seconds_timers() {
//check start dates
var s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var poll_id = startDisabledIds[i][0];
estimated_seconds_start_poll[poll_id] = parseInt(startDisabledIds[i][3] * 3600);
};
};
setInterval(function() {
for(tt in estimated_seconds_start_poll) {
if(estimated_seconds_start_poll[tt] > 0)
estimated_seconds_start_poll[tt] -= 1;
};
},1000);
};
create_start_poll_seconds_timers();
//alert box ////////////////////////////////////////////////////////////////////////////////////////
//function to create shadow
function create_shadow() {
var $shadow = '<div id="sexy_shadow"></div>';
$('body').css('position','relative').append($shadow);
$("#sexy_shadow")
.css( {
'position' : 'absolute',
'top' : '0',
'right' : '0',
'bottom' : '0',
'left' : '0',
'z-index' : '10000',
'opacity' : '0',
'backgroundColor' : '#000'
})
.fadeTo(200,'0.7');
};
function make_alert(txt,type) {
//create shadow
create_shadow();
//make alert
var $alert_body = '<div id="sexy_alert_wrapper"><div id="sexy_alert_body" class="' + type + '">' + txt + '</div><input type="button" id="close_sexy_alert" value="' + sexyPolling_words[21] + '" /></div>';
$('body').append($alert_body);
var scollTop = $(window).scrollTop();
var w_width = $(window).width();
var w_height = $(window).height();
var s_height = $("#sexy_alert_wrapper").height();
var alert_left = (w_width - 420) / 2;
var alert_top = (w_height - s_height) / 2;
$("#sexy_alert_wrapper")
.css( {
'top' : -1 * (s_height + 55 * 1) + scollTop * 1,
'left' : alert_left
})
.stop()
.animate({
'top' : alert_top + scollTop * 1
},450,'easeOutBack',function() {
//$(this).css('position','fixed');
});
};
function remove_alert_box() {
$("#sexy_shadow").stop().fadeTo(200,0,function() {$(this).remove();});
$("#sexy_alert_wrapper").stop().fadeTo(200,0,function() {$(this).remove();});
};
function move_alert_box() {
var scollTop = $(window).scrollTop();
var w_width = $(window).width();
var w_height = $(window).height();
var s_height = $("#sexy_alert_wrapper").height();
var alert_left = (w_width - 420) / 2;
var alert_top = (w_height - s_height) / 2;
$("#sexy_alert_wrapper")
.stop()
.animate({
'top' : alert_top + scollTop * 1,
'left' : alert_left
},450,'easeOutBack',function() {
//$(this).css('position','fixed');
});
};
$('#close_sexy_alert').live('click', function() {
remove_alert_box();
});
$(window).resize(function() {
move_alert_box();
});
$(window).scroll(function() {
move_alert_box();
});
setTimeout(function() {
$(".polling_bottom_wrapper1").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".polling_loading").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".answer_input").each(function() {
var w = $(this).width();
$(this).attr("w",w);
});
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
$(".answer_navigation").each(function() {
var b = parseInt($(this).css("borderWidth"));
$(this).attr("b",b);
});
},50);
function create_timer(seconds_diff, show_date) {
var newdate = new Date();
newdate.setSeconds(newdate.getSeconds() + seconds_diff);
var dd = newdate.getDate();
var mm = newdate.getMonth()+1;
var hh = newdate.getHours();
var ii = newdate.getMinutes();
var ss = newdate.getSeconds();
var yyyy = newdate.getFullYear();
if(dd<10) dd='0'+dd;
if(mm<10) mm='0'+mm;
if(hh<10) hh='0'+hh;
if(ii<10) ii='0'+ii;
if(ss<10) ss='0'+ss;
var time_text = yyyy+'/'+mm+'/'+dd + ' ' + hh + ':' + ii + ':' + ss;
var timezone = new Date().getTimezoneOffset();
$("#sexy_timer").jCountdown({
timeText:time_text,
timeZone:0,
style:"slide",
color:"black",
width:350,
textGroupSpace:15,
textSpace:0,
reflection:true,
reflectionOpacity:20,
reflectionBlur:1,
dayTextNumber:2,
displayDay:show_date,
displayHour:true,
displayMinute:true,
displaySecond:true,
displayLabel:true,
onFinish:function(){
remove_alert_box();
}
});
};
$('.polling_submit').click(function() {
$elem = $(this).parents('.polling_container');
if(!check_pro_version($elem)) {
make_alert('To hide a backlink please purchase a Sexy Polling PRO version','sexy_error');
return false;
}
if($(this).hasClass('voted_button')) {
make_alert(sexyPolling_words[9],'sexy_error');
return;
}
var t_id = $(this).attr("id");
var polling_id = $(this).parent('span').parent('div').find('.poll_answer').attr('name');
if(votingPermissions[polling_id] != 'allow_voting') {
make_alert(votingPermissions[polling_id],'sexy_error');
return false;
};
//check if already voted
var onlyVotedIds = new Array();
var estimated_seconds_item = estimated_seconds[polling_id];
for(t in votedIds) {
onlyVotedIds.push(votedIds[t][0]);
if(votedIds[t][0] == polling_id)
var estimated_ours = votedIds[t][2];
};
if(estimated_seconds_item > 0 || estimated_ours == 'never') {
if($.inArray(polling_id,onlyVotedIds) != -1) {
if(estimated_ours == 'never') {
make_alert(sexyPolling_words[9],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(sexyPolling_words[9] + '<div id="estimated_time_message">' + sexyPolling_words[20] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_item, show_date);
return false;
}
}
};
//check start dates
var estimated_seconds_start_poll_item = estimated_seconds_start_poll[polling_id];
s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + startDisabledIds[i][2] + "_" + startDisabledIds[i][0];
if(c_id == t_id) {
var estimated_ours = startDisabledIds[i][3];
if(estimated_seconds_start_poll_item > 0 || estimated_ours == 'never') {
if(estimated_ours == 'never') {
make_alert(startDisabledIds[i][1],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(startDisabledIds[i][1] + '<div id="estimated_time_message">' + sexyPolling_words[22] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_start_poll_item, show_date);
return false;
}
}
}
}
};
//check end dates
e_length = endDisabledIds.length;
for(var i = 0;i <= e_length; i++) {
if(typeof endDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + endDisabledIds[i][2] + "_" + endDisabledIds[i][0];
if(c_id == t_id) {
make_alert(endDisabledIds[i][1],'sexy_normal');
return false;
}
}
};
var polling_checked_value = $(this).parent('span').parent('div').find('.poll_answer:checked').val();
if(polling_checked_value == undefined) {
make_alert(sexyPolling_words[8],'sexy_normal');
return false;
};
var $t = $(this);
vote_polling($t);
});
$('.polling_result').click(function() {
$elem = $(this).parents('.polling_container');
if(!check_pro_version($elem)) {
make_alert('To hide a backlink please purchase a Sexy Polling PRO version','sexy_error');
return false;
}
var $t = $(this);
show_polling($t);
});
$('.polling_select2,.polling_select1').change(function() {
var $t = $(this).parents('.polling_container');
show_polling_by_date($t);
});
function show_polling($t) {
var polling_id = $t.parent('span').parent('div').find('.poll_answer').attr('name');
var module_id = $t.parent('span').parent('div').parent('div').attr('roll');
$container = $t.parent('span').parent('div');
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
//function to remove user added input boxes
$container.find('.doNotUncheck').parent('div').parent('div').parent('li').remove();
//hide all radio buttons
$t.parent('span').parent('div').find('.answer_input').animate({
width:0,
opacity:0
},1000);
//animate answers
$t.parent('span').parent('div').find('.answer_name label').animate({
marginLeft:0
},1000);
//show navigation bar
//TODO: when animating border, there is jquery issue with animation. Find the way to fix that!
var b = $t.parent('span').parent('div').find('.answer_navigation').attr("b");
$t.parent('span').parent('div').find('.answer_navigation').css("borderWidth","0").show().animate({
height:animation_styles[module_id+"_"+polling_id][9],
borderWidth: b,
opacity:1
},1000);
//animate loading
var l_h = $t.parent('span').parent('div').find('.polling_loading').height();
$t.parent('span').parent('div').find('.polling_loading').css({display:'block',opacity:0,height:0});
$t.parent('span').parent('div').find('.polling_loading').animate({
opacity:0.85,
height: l_h
},1000);
//send request
var h = $container.find('.answer_votes_data').height();
var min_date = $container.find('.polling_select1').val();
var max_date = $container.find('.polling_select2').val();
//total time = 1000;
setTimeout(function() {
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id + '&mode=view_by_date&min_date=' + min_date + '&max_date=' + max_date + '&dateformat=' + sexy_dateFormat[polling_id] + '&module_id=' + module_id+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
$container = $("#mod_" + data[0].module_id + "_" + data[0].poll_id);
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
data_length = data.length;
max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = parseFloat(this.percent_formated);
response_votes = this.votes;
order = this.order;
order_start = this.order_start;
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
if(max_percent == 'none')
max_percent = percent;
answers_array.push(parseInt(answer_id));
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title',sexyPolling_words[0] + ': ' + response_votes);
//start animating navigation bar
$nav_width = $container.find(".polling_li").width();
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
$current_width_tobeset = $container.find('.scale_icon').hasClass('opened') ? $current_width_rel : $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
//set the value
$container.find('#answer_votes_data_count_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_count_val_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_percent_' + answer_id).html(percent_formated);
$container.find('#answer_votes_data_percent_val_' + answer_id).html(percent_formated);
//show answer data
$container.find('.answer_votes_data').css({'display':'block','height':0}).animate({height:h},1000);
//set to absolute
if(i == data_length - 1) {
animate_poll_items($container,answers_array,polling_id,module_id,total_votes,min_date,max_date,orders_array,orders_array_start);
}
});
},
error: function()
{
}
});
},1000);
};
//function to animate elements
function animate_poll_items($container,answers_array,polling_id,module_id,total_votes,min_date,max_date,orders_array,orders_array_start) {
var s_timeout = 2700;
if(
$container.find('.polling_info').attr("rell") == 'noanimate' &&
$container.find('.sexyback_icon').attr("rell") == 'noanimate' &&
$container.find('.timeline_icon').attr("rell") == 'noanimate' &&
$container.find('.scale_icon').attr("rell") == 'noanimate' &&
$container.find('.add_answer_icon').attr("rell") == 'noanimate'
)
s_timeout = 1200;
setTimeout(function(){
var offset_0_ = $container.find('.polling_ul').offset();
offset_0 = offset_0_.top;
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
$container.find('.polling_ul').css('height',$container.find('.polling_ul').height());
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
});
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},s_timeout,function() {
});
//show total votes, min and max dates
$container.find('.total_votes').html(total_votes);
$container.find('.total_votes_val').html(total_votes);
$container.find('.first_vote').html(min_date);
$container.find('.last_vote').html(max_date);
//hide submit button and loading
$container.find('.polling_bottom_wrapper1')
.stop(true,true).animate({
height:0
},
1000,
function(){
$container.find('.polling_bottom_wrapper1').hide();
$container.find('.polling_loading').hide();
});
setTimeout(function() {
//show polling info
$container.find('.polling_info').css({'display':'block'});
var h = $container.find('.polling_info').height();
$container.find('.polling_info').css({'display':'none'});
$container.find('.polling_info')
.css({'height': 0,'display':'block'})
.animate({height:h},1000);
//show timeline
$container.find('.timeline_icon').animate({height:32},1000);
//show add answer
$container.find('.add_answer_icon').animate({height:32},1000);
//show add answer
$container.find('.sexyback_icon').animate({height:32},1000);
//show add answer
$container.find('.scale_icon').animate({height:32},1000);
},1700);
if(autoOpenTimeline[polling_id] == 1) {
setTimeout(function() {
$container.find('.timeline_icon').trigger("click");
},s_timeout);
}
}
//global variable, to store digit animations
$digit_int = new Array();
$digit_int_percent = new Array();
$digit_int_total = '';
function show_polling_by_date($t,use_current_date) {
use_current_date = typeof use_current_date !== 'undefined' ? use_current_date : 'no';
var polling_id = $t.find('.poll_answer').attr('name');
var module_id = $t.parent('div').attr('roll');
var min_date = $t.find('.polling_select1').val();
var max_date = $t.find('.polling_select2').val();
$container = $t;
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
//clear all intervals
for(i_v in $digit_int) {
clearInterval($digit_int[i_v]);
}
//clear all intervals
for(i_v in $digit_int_percent) {
clearInterval($digit_int_percent[i_v]);
}
clearInterval($digit_int_total);
setTimeout(function() {
$nav_width = $container.find(".polling_li").width();
//send request
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id + '&mode=view_by_date&min_date=' + min_date + '&max_date=' + max_date + '&dateformat=' + sexy_dateFormat[polling_id] + '&curr_date=' + use_current_date+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
//count of json objects
data_length = data.length;
//assign variables
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
$curr_count = new Array();
$new_count = new Array();
$step_sign = new Array();
$steps = new Array();
$interval_value = new Array();
$curr_count_ = new Array();
$curr_step = new Array();
$curr_percent = new Array();
$new_percent = new Array();
$step_sign_percent = new Array();
$steps_percent = new Array();
$interval_value_percent = new Array();
$curr_percent_ = new Array();
$curr_step_percent = new Array();
var max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = parseFloat(this.percent_formated);
response_votes = parseInt(this.votes);
order = this.order;
order_start = this.order_start;
if(max_percent == 'none')
max_percent = percent;
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
answers_array.push(answer_id);
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title','Votes: ' + response_votes);
//start animating navigation bar
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
if($container.find('.scale_icon').hasClass('opened'))
new_w = $current_width_rel;
else
new_w = $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).stop(true,false).animate({
width: new_w
},1000,sexyAnimationTypeBar[polling_id]);
//ie box shadow animation
if($container.find('#answer_navigation_' + answer_id).next(".ie-shadow").width() != $current_width + 4*1)
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").stop(true,false).animate({
width: new_w
},1000,sexyAnimationTypeBar[polling_id]);
//digit animation //remember min_count_of_votes / $steps_count_percent must have influance on tofixed(it's value) ...
//animate percents
$curr_percent[answer_id] = parseFloat($container.find('#answer_votes_data_percent_' + answer_id).html());
$new_percent[answer_id] = percent_formated;
$steps_percent[answer_id] = Math.abs($curr_percent[answer_id] - $new_percent[answer_id]);
$steps_count_percent = 20;
$step_item_percent = $steps_percent[answer_id] / $steps_count_percent;
//get sign
$step_sign_percent[answer_id] = ($new_percent[answer_id] > $curr_percent[answer_id]) ? 1 * $step_item_percent : (($new_percent[answer_id] < $curr_percent[answer_id]) ? -1 * $step_item_percent : 0);
$interval_value_percent[answer_id] = parseFloat(1000 / $steps_count_percent);
//animate total count
$curr_total = parseInt($t.find('.total_votes').html());
$new_total = total_votes;
$steps_total = Math.abs($curr_total - $new_total);
$steps_count_total = 20;
$step_item_total = $steps_total / $steps_count_total;
//get sign
$step_sign_total = ($new_total > $curr_total) ? 1 * $step_item_total : (($new_total < $curr_total) ? -1 * $step_item_total : 0);
$interval_value_total = parseFloat(1000 / $steps_count_total);
//animate answer votes count
$curr_count[answer_id] = parseInt($container.find('#answer_votes_data_count_' + answer_id).html());
$new_count[answer_id] = response_votes;
$steps[answer_id] = Math.abs($curr_count[answer_id] - $new_count[answer_id]);
$steps_count = 15;
$step_item = $steps[answer_id] / $steps_count;
//get sign
$step_sign[answer_id] = ($new_count[answer_id] > $curr_count[answer_id]) ? 1 * $step_item : (($new_count[answer_id] < $curr_count[answer_id]) ? -1 * $step_item : 0);
$interval_value[answer_id] = parseFloat(1000 / $steps_count);
if(i == data_length - 1) {
//show total votes, min and max dates
$t.find('.first_vote').html(min_date);
$t.find('.last_vote').html(max_date);
function animate_total() {
if($step_sign_total != 0) {
$digit_int_total = setInterval(function(){
$curr_total_ = parseFloat($t.find('.total_votes_val').html());
$curr_total_ = $curr_total_ + 1 * $step_sign_total;
$t.find('.total_votes').html($curr_total_.toFixed(1));
$t.find('.total_votes_val').html($curr_total_);
if($step_sign_total > 0) {
if($curr_total_ >= $new_total) {
clearInterval($digit_int_total);
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
}
else {
if($curr_total_ <= $new_total) {
clearInterval($digit_int_total);
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
}
},$interval_value_total);
}
else {
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
};
animate_total();
var animate_percent = function(ans_id) {
if($step_sign_percent[ans_id] !== 0) {
$digit_int_percent[ans_id] = setInterval(function(){
$curr_percent_[ans_id] = parseFloat($container.find('#answer_votes_data_percent_val_' + ans_id).html());
$curr_percent_[ans_id] = $curr_percent_[ans_id] + 1 * $step_sign_percent[ans_id];
$container.find('#answer_votes_data_percent_val_' + ans_id).html($curr_percent_[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($curr_percent_[ans_id].toFixed(2));
if($step_sign_percent[ans_id] > 0) {
if($curr_percent_[ans_id] >= $new_percent[ans_id]) {
clearInterval($digit_int_percent[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
}
else {
if($curr_percent_[ans_id] <= $new_percent[ans_id]) {
clearInterval($digit_int_percent[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
}
},$interval_value_percent[ans_id]);
}
else {
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
};
var animate_digit = function(ans_id) {
if($step_sign[ans_id] != 0) {
$digit_int[ans_id] = setInterval(function(){
$curr_count_[ans_id] = parseFloat($container.find('#answer_votes_data_count_val_' + ans_id).html());
$curr_count_[ans_id] = $curr_count_[ans_id] + 1 * $step_sign[ans_id];
$container.find('#answer_votes_data_count_' + ans_id).html($curr_count_[ans_id].toFixed(1));
$container.find('#answer_votes_data_count_val_' + ans_id).html($curr_count_[ans_id]);
if($step_sign[ans_id] > 0) {
if($curr_count_[ans_id] >= $new_count[ans_id]) {
clearInterval($digit_int[ans_id]);
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
}
else {
if($curr_count_[ans_id] <= $new_count[ans_id]) {
clearInterval($digit_int[ans_id]);
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
}
},$interval_value[ans_id]);
}
else {
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
};
for(var b = 0; b < answers_array.length; b++) {
animate_digit(answers_array[b]);
animate_percent(answers_array[b]);
}
};
//set to absolute
if(i == data_length - 1) {
var offset_0_ = $t.find('.polling_ul').offset();
offset_0 = offset_0_.top;
setTimeout(function(){
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block'})
.stop(false,false)
.animate( {
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],
function() {
$(this).animate( {
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
})
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},1);
}
});
},
error: function()
{
}
})
},1);
};
function vote_polling($t) {
var polling_id = $t.parent('span').parent('div').find('.poll_answer').attr('name');
var module_id = $t.parent('span').parent('div').parent('div').attr('roll');
$container = $t.parent('span').parent('div');
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
var voting_period = voting_periods[module_id + '_' + polling_id];
//close answer
$container.find('.answer_wrapper')
.css({'overflow':'hidden'})
.animate({
height:0
},600);
$container.find('.add_answer_icon').removeClass('opened').addClass('voted_button');
$container.find('.polling_submit').addClass('voted_button');
//recalculate ul height
$ul_height = $container.children("ul").height();
$container.children("ul").attr("h",$ul_height);
//if we have added answers, add them to post
var additionalAnswers = '';
$container.find('.doNotUncheck').each(function(i) {
var htm = $(this).parents('li').find('label').html();
htm = htm.replace(/\?\?/g,'sexydoublequestionmark');
additionalAnswers += '&answers[]=' + htm;
});
//hide all radio buttons
$container.find('.answer_input').animate({
width:0,
opacity:0
},1000);
//animate answers
$container.find('.answer_name label').animate({
marginLeft:0
},1000);
//show navigation bar
var b = $container.find('.answer_navigation').attr("b");
$container.find('.answer_navigation').css("borderWidth","0").show().animate({
height:animation_styles[module_id+"_"+polling_id][9],
borderWidth: b,
opacity:1
},1000);
//animate loading
var l_h = $t.parent('span').parent('div').find('.polling_loading').height();
$t.parent('span').parent('div').find('.polling_loading').attr("h",l_h).css({display:'block',opacity:0,height:0});
$t.parent('span').parent('div').find('.polling_loading').animate({
opacity:0.85,
height: l_h
},1000);
//send request
$nav_width = $container.find(".polling_li").width();
var h = $container.find('.answer_votes_data').height();
var ch_data = '';
$t.parent('span').parent('div').find('.poll_answer:checked').not('.doNotUncheck').each(function() {
ch_data += '&answer_id[]=' + $(this).val();
});
var min_date = $container.find('.polling_select1').val();
var max_date = $container.find('.polling_select2').val();
setTimeout(function() {
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id +ch_data + '&dateformat=' + sexy_dateFormat[polling_id] + additionalAnswers + '&min_date=' + min_date + '&max_date=' + max_date + '&country_name=' + sexyCountry + '&country_code=' + sexyCountryCode + '&city_name=' + sexyCity + '®ion_name=' + sexyRegion + '&voting_period='+voting_period+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
if((data[0].invalid) == 'invalid_token')
make_alert('Invalid Token','sexy_error');
$container.find('.doNotUncheck').each(function(i) {
if(typeof data[0].addedanswers !== 'undefined') {
$(this).parents('li').attr("id",'answer_' + data[0].addedanswers[i]);
$(this).parents('li').find('.answer_navigation').attr("id",'answer_navigation_' + data[0].addedanswers[i]);
$(this).parents('li').find('.answer_votes_data').attr("id",'answer_votes_data_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_count_0').attr("id",'answer_votes_data_count_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_count_val_0').attr("id",'answer_votes_data_count_val_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_percent_0').attr("id",'answer_votes_data_percent_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_percent_val_0').attr("id",'answer_votes_data_percent_val_' + data[0].addedanswers[i]);
}
});
$container.find('.doNotUncheck').removeClass('doNotUncheck');
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = this.percent_formated;
response_votes = this.votes;
order = this.order;
order_start = this.order_start;
if(max_percent == 'none')
max_percent = percent;
answers_array.push(answer_id);
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title','Votes: ' + response_votes);
//start animating navigation bar
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
$current_width_tobeset = $container.find('.scale_icon').hasClass('opened') ? $current_width_rel : $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
//set the value
$container.find('#answer_votes_data_count_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_count_val_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_percent_' + answer_id).html(percent_formated);
$container.find('#answer_votes_data_percent_val_' + answer_id).html(percent_formated);
//show answer data
$container.find('.answer_votes_data').css({'display':'block','height':0}).animate({height:h},1000);
var s_timeout = 2700;
if(
$container.find('.polling_info').attr("rell") == 'noanimate' &&
$container.find('.sexyback_icon').attr("rell") == 'noanimate' &&
$container.find('.timeline_icon').attr("rell") == 'noanimate' &&
$container.find('.scale_icon').attr("rell") == 'noanimate' &&
$container.find('.add_answer_icon').attr("rell") == 'noanimate'
)
s_timeout = 1200;
//set to absolute
if(i == 0) {
var offset_0_ = $container.find('.polling_ul').offset();
offset_0 = offset_0_.top;
setTimeout(function(){
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
$container.find('.polling_ul').css('height',$container.find('.polling_ul').height());
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
});
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},s_timeout);
//show total votes, min and max dates
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
$container.find('.total_votes').html(total_votes);
$container.find('.total_votes_val').html(total_votes);
$container.find('.first_vote').html(min_date);
$container.find('.last_vote').html(max_date);
//hide submit button and loading
$container.find('.polling_bottom_wrapper1')
.animate({
height:0
},
1000,
function(){
$container.find('.polling_bottom_wrapper1').hide();
$container.find('.polling_loading').hide();
});
setTimeout(function() {
//show polling info
$container.find('.polling_info').css({'display':'block'});
var h = $container.find('.polling_info').height();
$container.find('.polling_info').css({'display':'none'});
$container.find('.polling_info')
.css({'height': 0,'display':'block'})
.animate({height:h},1000);
//show timeline
$container.find('.timeline_icon').animate({height:32},1000);
//show add answer
$container.find('.add_answer_icon').animate({height:32},1000);
//show add answer
$container.find('.sexyback_icon').animate({height:32},1000);
//show add answer
$container.find('.scale_icon').animate({height:32},1000);
},1700);
if(autoOpenTimeline[polling_id] == 1) {
setTimeout(function() {
$container.find('.timeline_icon').trigger("click");
},s_timeout);
};
};
});
},
error: function()
{
}
})
},1000);
};
$('.timeline_icon').click(function() {
var $c = $(this).parent('div').children('.timeline_select_wrapper');
var curr_h = 90;
var new_class = $c.hasClass('opened') ? 'closed' : 'opened';
if(new_class == 'opened') {
$(this).addClass('opened');
$c.removeClass('closed');
$c.addClass('opened');
$(this).attr('title',sexyPolling_words[5]);
}
else {
$(this).removeClass('opened');
$c.removeClass('opened');
$c.addClass('closed');
$(this).attr('title',sexyPolling_words[4]);
}
//open timeline
$(this).parent('div').children('.timeline_select_wrapper.opened')
.css({'overflow':'hidden','height':0})
.stop(true,true)
.animate({
height:curr_h
},
1000,
function(){
$(this).css({'overflow':'visible'})
});
//close timeline
$(this).parent('div').children('.timeline_select_wrapper.closed')
.css({'overflow':'hidden'})
.stop(true,true)
.animate({
height:0
},1000,function() {
$(this).css({'overflow':'hidden'});
});
});
function make_relative($t) {
var module_id = $t.parent('div').parent('div').parent('div').attr('roll');
var polling_id = $t.parent('div').parent('div').parent('div').find(".poll_answer").attr('name');
$t.parent('div').parent('div').find('.answer_navigation').each(function() {
var rel_width = $(this).attr("rel_width");
$(this).stop(true,false).animate({
width: rel_width
},1000,sexyAnimationTypeBar[polling_id]);
});
};
function make_absolute($t) {
var module_id = $t.parent('div').parent('div').parent('div').attr('roll');
var polling_id = $t.parent('div').parent('div').parent('div').find(".poll_answer").attr('name');
$t.parent('div').parent('div').find('.answer_navigation').each(function() {
var ab_width = $(this).attr("ab_width");
$(this).stop(true,false).animate({
width: ab_width
},1000,sexyAnimationTypeBar[polling_id]);
});
};
function animate_back($t) {
$container = $t.parents('.polling_container');
//show results button
$container.find('.polling_result').removeClass('hide_sexy_button');
//uncheck all inpust
$container.find('.poll_answer').attr("checked",false);
$container.find('.twoglux_styled_element').removeClass("twoglux_checked");
$container.find('.checkbox_part1').css("height",0);
$container.find('.checkbox_part2').css("height",0);
$container.find('.radio_part1').css("opacity",0);
//hide polling info
$container.find('.polling_info')
.stop()
.stop(true,true).animate({height:0},1000,
function() {
//$(this).css({'display':'none'});
$(this).removeAttr("style");
});
//hide timeline
$container.find('.timeline_select_wrapper')
.stop()
.stop(true,true).animate({height:0},1000,
function() {
$(this).css({'overflow':'hidden'});
});
$('.timeline_icon').removeClass('opened');
$('.timeline_select_wrapper').removeClass('opened');
//hide loading
var l_h = $container.find('.polling_loading').attr("h");
$container.find('.polling_loading').css({'display':'none'});
//show bottons
var h = $container.find('.polling_bottom_wrapper1').attr("h");
$container.find('.polling_bottom_wrapper1')
.css({'display':'block'})
.stop()
.stop(true,true).animate({height:h},1000,function() {
$(this).css('height','auto');
});
var answer_w = $container.find('.answer_input').attr("w");
var ratio_h = $container.find('.answer_result').height();
var ul_h = $container.find('.polling_ul').attr("h");
//hide timeline
$container.find('.timeline_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.add_answer_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.sexyback_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.scale_icon').stop(true,true).animate({height:0},1000);
$container.find('.answer_votes_data').stop(true,true).animate({height:0},1000,function(){$(this).removeAttr("style");});
$container.find('.answer_input').stop(true,true).animate({width:answer_w,opacity:1},1000);
$container.find('.answer_name label').stop(true,true).animate({marginLeft:answer_w},1000);
$container.find('.answer_navigation').stop(true,true).animate({height:0,borderWidth:0},1000,function() {$(this).hide();});
var total_h = 0;
$container.find('.polling_li').each(function(k) {
var h = $(this).attr("h_start")*1;
$(this).stop(true,true).animate({"top" :total_h},1000,function() {
$(this).removeAttr("style");
});
total_h = total_h + h*1;
});
$container.find('.polling_ul').stop(true,true).animate({height:ul_h},1000,function(){$(this).removeAttr("style");});
};
$('.scale_icon').click(function() {
if($(this).hasClass('opened') ) {
$(this).removeClass('opened');
$(this).attr("title",sexyPolling_words[16]);
make_absolute($(this));
}
else {
$(this).addClass('opened');
$(this).attr("title",sexyPolling_words[15]);
make_relative($(this));
}
});
$('.sexyback_icon').click(function() {
animate_back($(this));
});
$('.add_answer_icon').click(function() {
if($(this).hasClass('voted_button')) {
make_alert(sexyPolling_words[9],'sexy_error');
return;
}
if($(this).hasClass('disabled'))
return;
var $c = $(this).parents('.polling_container').find('.answer_wrapper');
var curr_h = $(this).parents('.polling_container').find('.answer_wrapper').attr("h");
//open answer
$(this).parents('.polling_container').find('.answer_wrapper.closed')
.css({'overflow':'hidden','height':0})
.animate({
height:curr_h
},
600,
function(){
$(this).css({'overflow':'visible'});
});
//close answer
$(this).parents('.polling_container').find('.answer_wrapper.opened')
.css({'overflow':'hidden'})
.animate({
height:0
},600);
var new_class = $c.hasClass('opened') ? 'closed' : 'opened';
if(new_class == 'opened') {
$(this).addClass('opened');
$c.removeClass('closed');
$c.addClass('opened');
}
else {
$(this).removeClass('opened');
$c.removeClass('opened');
$c.addClass('closed');
}
});
//add new answer
$('.add_ans_name').focus(function() {
var polling_id = $(this).parents('.polling_container').find('.poll_answer').attr('name');
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
if($(this).val() == sexyPolling_words[11]) {
$(this).val('');
$(this).css('color',animation_styles[module_id+"_"+polling_id][11]);
$(this).parent('div').children('.add_ans_submit').show();
var s_w = $(this).parent('div').children('.add_ans_submit').width();
s_w += 14;
$(this).parent('.add_answer').css('paddingRight',s_w);
}
});
$('.add_ans_name').blur(function() {
var polling_id = $(this).parents('.polling_container').find('.poll_answer').attr('name');
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
if($.trim($(this).val()) == '') {
$(this).val(sexyPolling_words[11]);
$(this).css('color',animation_styles[module_id+"_"+polling_id][10]);
$(this).parent('div').children('.add_ans_submit').hide();
$(this).parent('.add_answer').css('paddingRight',0);
}
else {
$(this).val($.trim($(this).val()));
}
});
$(".add_ans_name").keydown(function(e) {
if(e.keyCode == 13) {
var dis = $(this).parent('div').children('.add_ans_submit').css("display");
if(dis == 'block' || dis == 'inline-block') {
$(this).parent('div').children('.add_ans_submit').trigger('click');
$(this).blur();
}
}
});
//add new answer functions
$('.add_ans_submit').click(function() {
var sexypolling_token = $(this).parents('.polling_container_wrapper').find('.sexypolling_token').attr("name");
var answers_count = parseInt($(this).parents('.polling_container_wrapper').find('.answer_input').length);
if(answers_count >= 5) {
make_alert('This poll can not have more than 5 answers','sexy_error');
return false;
}
//check count allowed options
if(!check_allowed_answers_count($(this).parents('.polling_container_wrapper')))
return false;
$this = $(this);
$ans_name = $.trim($this.parent('div').children('.add_ans_name').val());
$ans_name = $ans_name.replace(/\\/g, "");
if($ans_name == '')
return false;
$poll_id = $this.parent('div').children('.poll_id').val();
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
var voting_period = voting_periods[module_id + '_' + $poll_id];
//check if already voted
var onlyVotedIds = new Array();
var estimated_seconds_item = estimated_seconds[$poll_id];
for(t in votedIds) {
onlyVotedIds.push(votedIds[t][0]);
if(votedIds[t][0] == $poll_id)
var estimated_ours = votedIds[t][2];
};
if(estimated_seconds_item > 0 || estimated_ours == 'never') {
if($.inArray($poll_id,onlyVotedIds) != -1) {
if(estimated_ours == 'never') {
make_alert(sexyPolling_words[9],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(sexyPolling_words[9] + '<div id="estimated_time_message">' + sexyPolling_words[20] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_item, show_date);
return false;
}
}
};
//check start dates
var t_id = $this.parents('.polling_container').find('.polling_submit').attr("id");
var estimated_seconds_start_poll_item = estimated_seconds_start_poll[$poll_id];
s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + startDisabledIds[i][2] + "_" + startDisabledIds[i][0];
if(c_id == t_id) {
var estimated_ours = startDisabledIds[i][3];
if(estimated_seconds_start_poll_item > 0 || estimated_ours == 'never') {
if(estimated_ours == 'never') {
make_alert(startDisabledIds[i][1],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(startDisabledIds[i][1] + '<div id="estimated_time_message">' + sexyPolling_words[22] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_start_poll_item, show_date);
return false;
}
}
}
}
};
//check end dates
e_length = endDisabledIds.length;
for(var i = 0;i <= e_length; i++) {
if(typeof endDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + endDisabledIds[i][2] + "_" + endDisabledIds[i][0];
if(c_id == t_id) {
make_alert(endDisabledIds[i][1],'sexy_normal');
return false;
}
}
};
//check if opened
var cOpened = false;
var position = $this.parents('.polling_container').find('.polling_li').css('position');
if (position == 'absolute') {
cOpened = true;
};
var buttonType = multipleAnswersInfoArray[$poll_id] == 1 ? 'checkbox' : 'radio';
//if we have checkboxes and sexy poll is closed, then we do not write answer to database, untill user do not vote vor it
var writeInto = (buttonType == 'checkbox' && !cOpened) ? 0 : 1;
var added_answer = $ans_name.replace(/\?\?/g,'sexydoublequestionmark');
$this.parent('div').children('.loading_small').fadeIn(400);
$this.fadeOut(400);
$.ajax
({
url: sexyPath + 'components/com_sexypolling/addanswer.php',
type: "post",
data: 'polling_id=' + $poll_id + '&answer=' + added_answer + '&autopublish=' + sexyAutoPublish[$poll_id] + '&writeinto=' + writeInto + '&country_name=' + sexyCountry + '&country_code=' + sexyCountryCode + '&city_name=' + sexyCity + '®ion_name=' + sexyRegion + '&voting_period='+voting_period+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
if((data[0].invalid) == 'invalid_token')
make_alert('Invalid Token','sexy_error');
if(buttonType == 'radio' || (buttonType == 'checkbox' && cOpened)) {
$this.parents('.polling_container').find('.add_answer_icon').addClass('voted_button');
$this.parents('.polling_container').find('.polling_submit').addClass('voted_button');
}
$this.parent('div').children('.loading_small').fadeOut(400);
if(sexyAutoPublish[$poll_id] == 1) {
//disable icon clicking
$this.parents('.polling_container').find('.add_answer_icon').addClass('disabled');
setTimeout(function() {
/*we keep add answer box opened only if
* 1. we have checkboxes
* 2. poll box is closed
*/
if((buttonType == 'checkbox' && !cOpened)) {
//close add answer box
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
//reset padding
$this.parent('.add_answer').css('paddingRight',0);
}
else {
$this.parents('.polling_container').find('.add_answer_icon').removeClass('opened');
//close add answer box
$this.parents('.answer_wrapper')
.removeClass('opened')
.addClass('closed')
.css({'overflow':'hidden'})
.animate({
height:0
},600,function() {
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
//reset padding
$this.parent('.add_answer').css('paddingRight',0);
});
};
},1);
//add new answer
add_answer($this.parents('.polling_container'),data[0].answer,data[0].id);
}
else {
//show moderation message
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.attr("readonly","readonly")
.val(sexyPolling_words[13]);
make_alert(sexyPolling_words[13],'sexy_normal');
$this.parent('.add_answer').css('paddingRight',0);
$this.parents('.polling_container').find('.add_answer_icon').addClass('disabled');
setTimeout(function() {
//change icon background
$this.parents('.polling_container').find('.add_answer_icon').removeClass('opened');
//close add answer box
$this.parents('.answer_wrapper')
.removeClass('opened')
.addClass('closed')
.css({'overflow':'hidden'})
.animate({
height:0
},600,function() {
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
});
},3000)
}
}
});
//function to add new answer to the answers list
function add_answer($c,$answer,$id) {
//check if opened
var cOpened = false;
var position = $c.find('.polling_li').css('position');
if (position == 'absolute') {
cOpened = true;
};
var polling_id = $c.find('.poll_answer').attr('name');
var module_id = $c.parent('div').attr('roll');
var h = $c.find('.answer_votes_data').height();
var buttonType = multipleAnswersInfoArray[polling_id] == 1 ? 'checkbox' : 'radio';
var color = 'blue';
if(buttonType == 'radio')
var inner_img_html = '<div class="radio_part1 ' + color + '_radio_part1 unselectable" style="opacity: 1;" > </div>';
else
var inner_img_html = '<div class="checkbox_part1 ' + color + '_checkbox_part1 unselectable" style="height: 9px;" > </div><div class="checkbox_part2 ' + color + '_checkbox_part2 unselectable" style="height: 12px;"> </div>';
//create new element html
if(cOpened) {
var t_votes = $c.find('.total_votes_val').html();
var t_votes_new = ++t_votes;
$c.find('.total_votes_val').html(t_votes_new);
$c.find('.total_votes').html(t_votes_new);
var new_percent = parseFloat(100 / t_votes).toFixed(1);
$new_li = '<li id="answer_' + $id + '" class="polling_li"><div class="animation_block"></div><div class="answer_name"><label style="margin-left:0" uniq_index="' + $id + '" class="twoglux_label">' + $answer + '</label></div><div class="answer_input" style="width: 0px; opacity: 0; "><div class="twoglux_styled_input_wrapper" ><input name="' + polling_id + '" id="' + $id + '" type="' + buttonType + '" checked="checked" class="poll_answer ' + $id + ' twoglux_styled" style="display:none" value="' + $id + '" /><a id="twoglux_styled_elem_' + $id + '_' + added_length + '" class="twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + buttonType + ' unselectable name_' + polling_id + ' twoglux_checked">' + inner_img_html + '</a></div></div><div class="sexy_clear"></div><div class="answer_result"><div class="answer_navigation polling_bar_' + newAnswerBarIndex + '" id="answer_navigation_' + $id + '" style=" opacity: 1; width: 1px;display:block;"><div class="grad"></div></div><div class="answer_votes_data" id="answer_votes_data_' + $id + '" style="height: ' + h + 'px;display:block; ">' + sexyPolling_words[0] + ': <span id="answer_votes_data_count_' + $id + '">1</span><span id="answer_votes_data_count_val_' + $id + '" style="display:none">1</span> (<span id="answer_votes_data_percent_' + $id + '">' + new_percent + '</span><span style="display:none" id="answer_votes_data_percent_val_' + $id + '">' + new_percent + '</span>%)</div><div class="sexy_clear"></div></div></li>';
//add html to DOM
$c.find("li").last().after($new_li);
//set height
$("#answer_navigation_" + $id).css('height',animation_styles[module_id+"_"+polling_id][9]);
$new_height = $("#answer_" + $id).height() + offset_padding;
$ul_height = $c.children("ul").height();
$("#answer_" + $id).css({"position":"absolute","top":$ul_height});
$c.children("ul").stop(true,false).animate( {
height: "+=" + $new_height
},600,function() {
show_polling_by_date($c,'yes');
});
}
else {
var user_class = buttonType == 'checkbox' ? 'doNotUncheck' : '';
var added_length = $c.find(".doNotUncheck").length;
$new_li = '<li id="answer_' + $id + '" class="polling_li"><div class="animation_block"></div><div class="answer_name"><label uniq_index="elem_' + $id + '_' + added_length + '" class="twoglux_label">' + $answer + '</label></div><div class="answer_input"><div class="twoglux_styled_input_wrapper" ><input name="' + polling_id + '" id="elem_' + $id + '_' + added_length + '" type="' + buttonType + '" checked="checked" class="poll_answer ' + $id + ' twoglux_styled" style="display:none" value="' + $id + '" /><a id="twoglux_styled_elem_' + $id + '_' + added_length + '" class="' + user_class + ' twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + buttonType + ' unselectable name_' + polling_id + ' twoglux_checked">' + inner_img_html + '</a></div></div><div class="sexy_clear"></div><div class="answer_result"><div class="answer_navigation polling_bar_' + newAnswerBarIndex + '" id="answer_navigation_' + $id + '"><div class="grad"></div></div><div class="answer_votes_data" id="answer_votes_data_' + $id + '">' + sexyPolling_words[0] + ': <span id="answer_votes_data_count_' + $id + '"></span><span id="answer_votes_data_count_val_' + $id + '" style="display:none">0</span> (<span id="answer_votes_data_percent_' + $id + '">0</span><span style="display:none" id="answer_votes_data_percent_val_' + $id + '">0</span>%)</div><div class="sexy_clear"></div></div></li>';
//add html to DOM
$c.find("li").last().after($new_li);
$ul_height = $c.children("ul").height();
$c.children("ul").attr("h",$ul_height);
};
if(cOpened)
$("#answer_" + $id + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
})
});
//show polling
if(!cOpened && buttonType == 'radio') {
var sub_object = $c.find(".polling_submit");
show_polling(sub_object);
}
}
});
//slider function
s_length = sexyPollingIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof sexyPollingIds[i] !== 'undefined') {
var select1 = sexyPollingIds[i][0];
var select2 = sexyPollingIds[i][1];
$("#" + select1 + ",#" + select2).selectToUISlider(
{
labels:0,
sliderOptions:
{
stop: function(e,ui)
{
show_polling_by_date($(this).parents('.polling_container'));
}
}
});
}
};
//autoanimate
v_length = votedIds.length;
for(var i = 0;i <= v_length; i++) {
if(typeof votedIds[i] !== 'undefined' && autoAnimate[votedIds[i][0]] == '1') {
var time = (i * 1 + 1) * 10;
var t = $("#res_" + votedIds[i][1] + "_" + votedIds[i][0]);
animate_poll(t,time);
}
};
function animate_poll(t,time) {
setTimeout(function() {
show_polling(t);
},time)
}
///////////////////////////////////////////////////////////////Sexy Checkboxes/////////////////////////////////////////////////////////////////////////////////
$('.twoglux_styled').each(function() {
var $this = $(this);
var type = $this.attr("type");
var color = $this.attr("data-color");
var name = $this.attr("name");
var id = $this.attr("id");
$this.wrap('<div class="twoglux_styled_input_wrapper" />');
if(type == 'radio')
var inner_img_html = '<div class="radio_part1 ' + color + '_radio_part1 unselectable" > </div>';
else
var inner_img_html = '<div class="checkbox_part1 ' + color + '_checkbox_part1 unselectable" > </div><div class="checkbox_part2 ' + color + '_checkbox_part2 unselectable"> </div>';
var twoglux_styled_html = '<a id="twoglux_styled_' + id + '" class="twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + type + ' unselectable name_' + name + '">' + inner_img_html + '</a>';
$this.after(twoglux_styled_html);
$this.hide();
});
$('.twoglux_styled_element').live('mouseenter', function() {
make_mouseenter($(this));
});
$('.twoglux_styled_element').live('mouseleave', function() {
make_mouseleave($(this))
});
function make_mouseenter($elem) {
if($elem.hasClass('twoglux_styled_radio'))
$elem.addClass('twoglux_styled_radio_hovered');
else
$elem.addClass('twoglux_styled_checkbox_hovered');
};
function make_mouseleave($elem) {
if($elem.hasClass('twoglux_styled_radio'))
$elem.removeClass('twoglux_styled_radio_hovered');
else
$elem.removeClass('twoglux_styled_checkbox_hovered');
};
var sexyanimatetime = 150;
var last_event = 'up';
var last_event_radio = 'up';
var body_mouse_up_enabled = false;
//////////////////////////////////////////////////////////////////////MOVE FUNCTIONS////////////////////////////////////////
function animate_checkbox1_down($elem) {
$elem.animate({height: 9},sexyanimatetime);
};
function animate_checkbox1_up($elem) {
//uncheck element
$elem.parent('a').removeClass('twoglux_checked');
$elem.parent('a').prev('input').attr("checked",false);
$elem.animate({height: 0},sexyanimatetime);
};
function animate_checkbox2_up($elem) {
$elem.animate({height: 12},sexyanimatetime);
//check element
$elem.parent('a').addClass('twoglux_checked');
$elem.parent('a').prev('input').attr("checked",true);
};
function animate_checkbox2_down($elem) {
$elem.animate({height: 0},sexyanimatetime);
};
//////////////////////////////////////////////////////////////////////MOUSEDOWN////////////////////////////////////////
$('.twoglux_styled_checkbox').live('mousedown',function() {
//check if checkbox checked
if($(this).hasClass('twoglux_checked'))
animate_checkbox2_down($(this).find('.checkbox_part2'));
else
animate_checkbox1_down($(this).find('.checkbox_part1'));
last_event = 'down';
body_mouse_up_enabled = true;
});
//////////////////////////////////////////////////////////////////////MOUSEUP//////////////////////////////////////////
$('.twoglux_styled_checkbox').live('mouseup',function() {
if(!($(this).hasClass('twoglux_checked'))) {
if(!check_allowed_answers_count($(this).parents('.polling_container'))) {
last_event = 'up';
body_mouse_up_enabled = false;
animate_checkbox1_up($(this).find('.checkbox_part1'));
return false;
}
}
if(last_event == 'down') {
//check if checkbox checked
if($(this).hasClass('twoglux_checked'))
animate_checkbox1_up($(this).find('.checkbox_part1'));
else
animate_checkbox2_up($(this).find('.checkbox_part2'));
}
last_event = 'up';
body_mouse_up_enabled = false;
});
function check_allowed_answers_count($c) {
var poll_id = $c.find('.poll_answer').attr('name');
var alloewd_answers = allowedNumberAnswers[poll_id];
if(alloewd_answers == 0)
return true;
var checked_options_count = $c.find('input[type="checkbox"]:checked').length;
if(parseInt(checked_options_count) == alloewd_answers) {
make_alert(sexyPolling_words[23] + ' <span class="max_allowed_checkox_limit">' + alloewd_answers + '</span>','sexy_normal');
return false;
}
return true;
}
//////////////////////////////////////////////////////////RADIOBUTTONS//////////////////////////////////////////////////////////////
$('.radio_part1').css('opacity','0');
$('.twoglux_styled_radio').live('mousedown',function() {
//check if checkbox checked
if(!($(this).hasClass('twoglux_checked'))) {
$(this).find('.radio_part1').fadeTo(sexyanimatetime, 0.5);
}
last_event_radio = 'down';
body_mouse_up_enabled = true;
});
$('.twoglux_styled_radio').live('mouseup',function() {
if(last_event_radio == 'down') {
//check if checkbox checked
if(!($(this).hasClass('twoglux_checked'))) {
$(this).addClass('twoglux_checked');
var name = $(this).prev('input').attr("name");
$('input[name="' + name + '"]').attr("checked",false);
$(this).prev('input').attr("checked",true);
$('.name_' + name).removeClass('twoglux_checked');
$(this).addClass('twoglux_checked');
$('.name_' + name).not($(this)).find('.radio_part1').fadeTo(sexyanimatetime, 0);
$(this).find('.radio_part1').fadeTo(sexyanimatetime, 1);
}
}
last_event_radio = 'up';
body_mouse_up_enabled = false;
});
//////////////////////////////////////////////////////////////OTHER////////////////////////////////////////////////////////////////////////////////
//fixing bug in firefox
$('.twoglux_styled_input_wrapper').bind("dragstart", function() {
return false;
});
$("body").live('mouseup',function() {
if(body_mouse_up_enabled) {
//checkbox
var $elems = $('.twoglux_styled_element').not('.twoglux_checked').find('.checkbox_part1');
animate_checkbox1_up($elems);
var $elems = $('.twoglux_styled_element.twoglux_checked').find('.checkbox_part2');
animate_checkbox2_up($elems);
var $elems = $('.twoglux_styled_element').not('.twoglux_checked').find('.radio_part1');
$elems.fadeTo(sexyanimatetime, 0);
}
});
//trigger events for label
$('.twoglux_label').live('mouseenter', function() {
var uniq_index = $(this).attr("uniq_index");
make_mouseenter($("#twoglux_styled_" + uniq_index));
});
$('.twoglux_label').live('mouseleave',function() {
var uniq_index = $(this).attr("uniq_index");
make_mouseleave($("#twoglux_styled_" + uniq_index));
});
$('.twoglux_label').live('mousedown',function() {
var uniq_index = $(this).attr("uniq_index");
$("#twoglux_styled_" + uniq_index).trigger("mousedown");
});
$('.twoglux_label').live('mouseup',function() {
var uniq_index = $(this).attr("uniq_index");
$("#twoglux_styled_" + uniq_index).trigger("mouseup");
});
//function to prevent uncheck user added input boxes
$('.doNotUncheck').live('mouseup',function() {
if(! $(this).hasClass('twoglux_checked') ) {
$(this).parent('div').parent('div').parent('li').remove();
};
});
})
})(sexyJ); | JavaScript |
/**
*
* Utilities
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($) {
EYE.extend({
getPosition : function(e, forceIt)
{
var x = 0;
var y = 0;
var es = e.style;
var restoreStyles = false;
if (forceIt && sexyJ.curCSS(e,'display') == 'none') {
var oldVisibility = es.visibility;
var oldPosition = es.position;
restoreStyles = true;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
}
var el = e;
if (el.getBoundingClientRect) { // IE
var box = el.getBoundingClientRect();
x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2;
y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2;
} else {
x = el.offsetLeft;
y = el.offsetTop;
el = el.offsetParent;
if (e != el) {
while (el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
}
if (sexyJ.browser.safari && sexyJ.curCSS(e, 'position') == 'absolute' ) {
x -= document.body.offsetLeft;
y -= document.body.offsetTop;
}
el = e.parentNode;
while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML')
{
if (sexyJ.curCSS(el, 'display') != 'inline') {
x -= el.scrollLeft;
y -= el.scrollTop;
}
el = el.parentNode;
}
}
if (restoreStyles == true) {
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {x:x, y:y};
},
getSize : function(e)
{
var w = parseInt(sexyJ.curCSS(e,'width'), 10);
var h = parseInt(sexyJ.curCSS(e,'height'), 10);
var wb = 0;
var hb = 0;
if (sexyJ.curCSS(e, 'display') != 'none') {
wb = e.offsetWidth;
hb = e.offsetHeight;
} else {
var es = e.style;
var oldVisibility = es.visibility;
var oldPosition = es.position;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
wb = e.offsetWidth;
hb = e.offsetHeight;
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {w:w, h:h, wb:wb, hb:hb};
},
getClient : function(e)
{
var h, w;
if (e) {
w = e.clientWidth;
h = e.clientHeight;
} else {
var de = document.documentElement;
w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
}
return {w:w,h:h};
},
getScroll : function (e)
{
var t=0, l=0, w=0, h=0, iw=0, ih=0;
if (e && e.nodeName.toLowerCase() != 'body') {
t = e.scrollTop;
l = e.scrollLeft;
w = e.scrollWidth;
h = e.scrollHeight;
} else {
if (document.documentElement) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
if (typeof pageYOffset != 'undefined') {
t = pageYOffset;
l = pageXOffset;
}
iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
}
return { t: t, l: l, w: w, h: h, iw: iw, ih: ih };
},
getMargins : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'marginTop') || '';
var r = sexyJ.curCSS(e,'marginRight') || '';
var b = sexyJ.curCSS(e,'marginBottom') || '';
var l = sexyJ.curCSS(e,'marginLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getPadding : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'paddingTop') || '';
var r = sexyJ.curCSS(e,'paddingRight') || '';
var b = sexyJ.curCSS(e,'paddingBottom') || '';
var l = sexyJ.curCSS(e,'paddingLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getBorder : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'borderTopWidth') || '';
var r = sexyJ.curCSS(e,'borderRightWidth') || '';
var b = sexyJ.curCSS(e,'borderBottomWidth') || '';
var l = sexyJ.curCSS(e,'borderLeftWidth') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)||0
};
else
return {t: t, r: r, b: b, l: l};
},
traverseDOM : function(nodeEl, func)
{
func(nodeEl);
nodeEl = nodeEl.firstChild;
while(nodeEl){
EYE.traverseDOM(nodeEl, func);
nodeEl = nodeEl.nextSibling;
}
},
getInnerWidth : function(el, scroll) {
var offsetW = el.offsetWidth;
return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth;
},
getInnerHeight : function(el, scroll) {
var offsetH = el.offsetHeight;
return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight;
},
getExtraWidth : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingLeft'))||0)
+ (parseInt($.curCSS(el, 'paddingRight'))||0)
+ (parseInt($.curCSS(el, 'borderLeftWidth'))||0)
+ (parseInt($.curCSS(el, 'borderRightWidth'))||0);
return 0;
},
getExtraHeight : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingTop'))||0)
+ (parseInt($.curCSS(el, 'paddingBottom'))||0)
+ (parseInt($.curCSS(el, 'borderTopWidth'))||0)
+ (parseInt($.curCSS(el, 'borderBottomWidth'))||0);
return 0;
},
isChildOf: function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (!el || !el.nodeType || el.nodeType != 1) {
return false;
}
if (parentEl.contains && !$.browser.safari) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
centerEl : function(el, axis)
{
var clientScroll = EYE.getScroll();
var size = EYE.getSize(el);
if (!axis || axis == 'vertically')
$(el).css(
{
top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px'
}
);
if (!axis || axis == 'horizontally')
$(el).css(
{
left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px'
}
);
}
});
if (!$.easing.easeout) {
$.easing.easeout = function(p, n, firstNum, delta, duration) {
return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum;
};
}
})(sexyJ); | JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(sexyJ) | JavaScript |
(function($){
var initLayout = function() {
var hash = window.location.hash.replace('#', '');
var currentTab = $('ul.navigationTabs a')
.bind('click', showTab)
.filter('a[rel=' + hash + ']');
if (currentTab.size() == 0) {
currentTab = $('ul.navigationTabs a:first');
}
showTab.apply(currentTab.get(0));
$('#colorpickerHolder').ColorPicker({flat: true});
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerField1, #colorpickerField2, #colorpickerField3').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
$('#colorSelector').ColorPicker({
color: '#0000ff',
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
$('#colorSelector div').css('backgroundColor', '#' + hex);
}
});
};
var showTab = function(e) {
var tabIndex = $('ul.navigationTabs a')
.removeClass('active')
.index(this);
$(this)
.addClass('active')
.blur();
$('div.tab')
.hide()
.eq(tabIndex)
.show();
};
EYE.register(initLayout, 'init');
})(jQuery) | JavaScript |
/**
*
* Zoomimage
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($){
var EYE = window.EYE = function() {
var _registered = {
init: []
};
return {
init: function() {
$.each(_registered.init, function(nr, fn){
fn.call();
});
},
extend: function(prop) {
for (var i in prop) {
if (prop[i] != undefined) {
this[i] = prop[i];
}
}
},
register: function(fn, type) {
if (!_registered[type]) {
_registered[type] = [];
}
_registered[type].push(fn);
}
};
}();
$(EYE.init);
})(sexyJ);
| JavaScript |
(function($) {
$.fn.extend({
jCountdown:function(){
var Flip = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 50;
this._height = 64;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
}
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
}
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
}
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
}
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = -(9-this.value())*this.width();
var top = -(this.frame()-1)*this.height();
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px");
}
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
}
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
}
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Slide = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 50;
this._height = 64;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
}
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = 0;
var top = -((1+this.value())*this.height()) + (Math.sin((this.frame()-1)/(this.totalFrames()-1)*Math.PI/2)*this.height());
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px");
};
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Metal = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 60;
this._height = 60;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
};
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var lastValue = this.value()+1;
if(lastValue>9){
lastValue = 0;
};
var progress = this.frame()/this.totalFrames();
var opacity;
if(progress>=.4 && progress<=.6){
opacity = 0;
}else if(progress<=.4){
opacity = 1-progress/.4;
}else if(progress>=.6){
opacity = (progress-.6)/.4;
};
var left = 0;
var top = -(progress>.5 ? this.value() : lastValue)*this.height();
top -= (1-opacity)*3;
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px").css("opacity",opacity);
this._target.children(".cover").css("opacity",opacity);
}
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Crystal = function(target){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._target = target;
this._width = 60;
this._height = 60;
this._widthSmall= 42;
this._heightSmall = 42;
this._frame = 1;
this._totalFrames = 15;
this._fps = 24;
this._intervalId = -1;
this._value = 0;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
this.stop = function(){
clearInterval(this._intervalId);
};
this.update = function(flag){
if(flag){
this.frame(1);
this.stop();
var target = this;
this._intervalId = setInterval(function(){
if(target.frame()==target.totalFrames()){
clearInterval(target._intervalId);
target.onFinish();
}else{
target.frame(target.frame()+1);
};
},Math.ceil(1000/this.fps()));
}else{
this.frame(this.totalFrames());
};
};
this.value = function(v,flag){
if(v==undefined){
return this._value;
}else{
this._value = v;
this.update(flag);
};
};
this.onFinish = function(){
};
this.destroy = function(){
this.stop();
this._target = null;
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.width = function(v){
if(v==undefined){
return this._width;
}else{
this._width = v;
};
};
this.height = function(v){
if(v==undefined){
return this._height;
}else{
this._height = v;
};
};
this.frame = function(v){
if(v==undefined){
return this._frame;
}else{
this._frame = v;
var left = 0;
var top = -this.value()*this.height();
var opacity = Math.sin((this.frame()-1)/(this.totalFrames()-1)*Math.PI/2);
if(opacity>0 && opacity<0.001){
opacity = 0;
}else if(opacity<0 && opacity>-0.001){
opacity = 0;
};
this._target.children(".sexy_text").css("background-position", left+"px"+" "+top+"px").css("opacity",opacity);
};
};
this.totalFrames = function(v){
if(v==undefined){
return this._totalFrames;
}else{
this._totalFrames = v;
};
};
this.fps = function(v){
if(v==undefined){
return this._fps;
}else{
this._fps = v;
};
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
this.update(false);
};
var Countdown = function(){
//---------------------------------------------------------------------------------------
//vars
//---------------------------------------------------------------------------------------
this._days = [];
this._hours = [];
this._minutes = [];
this._seconds = [];
this._tickId = -1;
this._tickDelay = 100;
this._timeText = "";
this._timeZone = 0;
this._time = null;
//---------------------------------------------------------------------------------------
//methods
//---------------------------------------------------------------------------------------
//check time
this.checkTime = function(update){
var currentTime = new Date();
if(this._time.getTime()<(currentTime.getTime())){
for(var i=0; i<this._days.length; i++){
this._days[i].value(0);
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].value(0);
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].value(0);
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].value(0);
};
this.stop();
this.onFinish();
return true;
}else{
var currentTimeText = this.timeFormat(this._time.getTime()-(currentTime.getTime()), this._days.length, this._hours.length, this._minutes.length, this._seconds.length);
var currentTimeChars = currentTimeText.split("");
if (!isNaN(this._time)){
for(var i=0; i<this._days.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._days[i].value()){
this._days[i].value(v, update);
};
};
for(var i=0; i<this._hours.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._hours[i].value()){
this._hours[i].value(v, update);
};
};
for(var i=0; i<this._minutes.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._minutes[i].value()){
this._minutes[i].value(v, update);
};
};
for(var i=0; i<this._seconds.length; i++){
var v = parseInt(currentTimeChars.shift(),10);
if(v != this._seconds[i].value()){
this._seconds[i].value(v, update);
};
};
};
return false;
};
};
//text format
this.textFormat = function(text, length, fillChar){
text = text.toString();
while (text.length<length){
text = fillChar+text;
};
if(text.length>length){
text = text.substr(text.length-length,length);
};
return text;
};
//time format
this.timeFormat = function(msec, dayTextNumber, hourTextNumber, minuteTextNumber, secondTextNumber){
var time = Math.floor(msec/1000);
var s = time%60;
var i = Math.floor(time%(60*60)/60);
var h = Math.floor(time%(24*60*60)/(60*60));
var d = Math.floor(time/(24*60*60));
return this.textFormat(d, dayTextNumber, "0")+this.textFormat(h, hourTextNumber, "0")+this.textFormat(i, minuteTextNumber, "0")+this.textFormat(s, secondTextNumber, "0");
};
//start
this.start = function(){
this.stop();
for(var i=0; i<this._days.length; i++){
this._days[i].update();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].update();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].update();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].update();
};
var finish = this.checkTime(false);
if(!finish){
var target = this;
this._tickId = setInterval(function(){
target.checkTime(true);
}, this._tickDelay);
};
};
//stop
this.stop = function(){
for(var i=0; i<this._days.length; i++){
this._days[i].stop();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].stop();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].stop();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].stop();
};
clearInterval(this._tickId);
};
this.onFinish = function(){
};
this.destroy = function(){
for(var i=0; i<this._days.length; i++){
this._days[i].destroy();
};
for(var i=0; i<this._hours.length; i++){
this._hours[i].destroy();
};
for(var i=0; i<this._minutes.length; i++){
this._minutes[i].destroy();
};
for(var i=0; i<this._seconds.length; i++){
this._seconds[i].destroy();
};
this._days = [];
this._hours = [];
this._minutes = [];
this._seconds = [];
this.stop();
};
//---------------------------------------------------------------------------------------
//properties
//---------------------------------------------------------------------------------------
this.items = function(days, hours, minutes, seconds){
this._days = days;
this._hours = hours;
this._minutes = minutes;
this._seconds = seconds;
};
this.timeText = function(v){
if(v==undefined){
return this._timeText;
}else{
this._timeText = v;
this.time(this.timeText(), this.timeZone());
};
};
this.timeZone = function(v){
if(v==undefined){
return this._timeZone;
}else{
this._timeZone = v;
this.time(this.timeText(), this.timeZone());
};
};
//time
this.time = function(tt,tz){
this._timeText = tt;
this._timeZone = tz;
var time = this._timeText.split("/").join(" ").split(":").join(" ").split(" ");
var y = parseInt(time[0],10);
var m = parseInt(time[1],10)-1;
var d = parseInt(time[2],10);
var h = parseInt(time[3],10);
var i = parseInt(time[4],10)-this._timeZone*60;
var s = parseInt(time[5],10);
this._time = new Date(y, m, d, h, i, s, 0);
this.start();
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
};
//---------------------------------------------------------------------------------------
//init
//---------------------------------------------------------------------------------------
var getCountdown = function(){
return target.data("countdown");
};
var initCountdown = function(){
if(getCountdown()==undefined){
var countdown = new Countdown();
target.data("countdown", countdown);
return getCountdown();
};
};
var destroyCountdown = function(){
if(getCountdown()!=undefined){
getCountdown().destroy();
target.removeData("countdown");
};
};
var init = function(setting){
countdown = initCountdown();
var browserVersion = parseInt($.browser.version,10);
var timeText = typeof(setting.timeText)=="string" ? setting.timeText : "";
var timeZone = parseFloat(setting.timeZone);
if(isNaN(timeZone)){
timeZone = 0;
};
var style = typeof(setting.style)=="string" ? setting.style.toLowerCase() : "";
switch(style){
case "flip":
break;
case "slide":
break;
case "crystal":
break;
case "metal":
break;
default:
style = "flip";
};
var color = typeof(setting.color)=="string" ? setting.color.toLowerCase() : "";
switch(color){
case "black":
break;
case "white":
break;
default:
color = "black";
};
var width = parseInt(setting.width,10);
if(width>=10){
}else{
width = 0;
};
var textGroupSpace = parseInt(setting.textGroupSpace,10);
if(textGroupSpace>=0){
}else{
textGroupSpace = 15;
};
var textSpace = parseInt(setting.textSpace,10);
if(textSpace>0){
}else{
textSpace = 0;
};
var reflection = setting.reflection!=false;
var reflectionOpacity = parseFloat(setting.reflectionOpacity);
if(reflectionOpacity>0){
if(reflectionOpacity>100){
reflectionOpacity = 100;
}
}else{
reflectionOpacity = 10;
};
var reflectionBlur = parseInt(setting.reflectionBlur,10);
if(reflectionBlur>0){
if(reflectionBlur>10){
reflectionBlur = 10;
}
}else{
reflectionBlur = 0;
};
var dayTextNumber = parseInt(setting.dayTextNumber,10)>2 ? parseInt(setting.dayTextNumber,10) : 2;
var hourTextNumber = 2;
var minuteTextNumber = 2;
var secondTextNumber = 2;
var displayDay = setting.displayDay!=false;
var displayHour = setting.displayHour!=false;
var displayMinute = setting.displayMinute!=false;
var displaySecond = setting.displaySecond!=false;
var displayLabel = setting.displayLabel!=false;
var onFinish = typeof(setting.onFinish)=="function" ? setting.onFinish : function(){};
var html = "";
var itemClass = "";
var lastClass = "";
html += '<div class="jCountdown">';
if(displayDay){
var lastItem = (!displayHour && !displayMinute && !displaySecond) ? " lastItem" : "";
html += '<div class="group day'+lastItem+'">';
for(var i=0; i<dayTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(dayTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displayHour){
var lastItem = (!displayMinute && !displaySecond) ? " lastItem" : "";
html += '<div class="group hour'+lastItem+'">';
for(var i=0; i<hourTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(hourTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displayMinute){
var lastItem = (!displaySecond) ? " lastItem" : "";
html += '<div class="group minute'+lastItem+'">';
for(var i=0; i<minuteTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(minuteTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
if(displaySecond){
html += '<div class="group second lastItem">';
for(var i=0; i<secondTextNumber; i++){
itemClass = " item"+(i+1);
lastClass = i==(secondTextNumber-1) ? " lastItem" : "";
html += '<div class="container'+itemClass+lastClass+'">';
if(style=="slide" || style=="crystal" || style=="metal"){
html += '<div class="cover"></div>';
};
html += '<div class="sexy_text"></div>';
html += '</div>';
};
if(displayLabel){
html += '<div class="sexy_label"></div>';
};
html += '</div>';
};
html += '</div>';
target.html(html);
var countdownObject = target.children(".jCountdown");
countdownObject.addClass(style);
countdownObject.addClass(color);
countdownObject.children(".group").css("margin-right",textGroupSpace+"px");
countdownObject.children(".group.lastItem").css("margin-right","0px");
countdownObject.children(".group").children(".container").css("margin-right",textSpace+"px");
countdownObject.children(".group").children(".container.lastItem").css("margin-right","0px");
if(reflection){
if(($.browser.msie && browserVersion<10)){
}else{
reflectionObject = countdownObject.clone();
reflectionObject.addClass("reflection");
if(displayLabel){
reflectionObject.addClass("displayLabel");
};
if(reflectionOpacity!=100){
reflectionObject.css("opacity",reflectionOpacity/100);
};
if(reflectionBlur!=0){
reflectionObject.addClass("blur"+reflectionBlur);
};
countdownObject = countdownObject.add(reflectionObject);
}
};
var countdownContainer = $('<div class="jCountdownContainer"></div>');
countdownContainer.append(countdownObject);
target.append(countdownContainer);
if(width!=0){
var countdownScaleObject = $('<div class="jCountdownScale"></div>');
countdownScaleObject.append(countdownObject);
countdownContainer.append(countdownScaleObject);
var countdownScaleObjectWidth = countdownScaleObject.width();
var countdownScaleObjectHeight = countdownScaleObject.height();
var scale = width/countdownScaleObjectWidth;
var left = -(1-scale)*countdownScaleObjectWidth/2;
var top = -(1-scale)*countdownScaleObjectHeight/2;
var scaleCss = "scale("+scale+")";
countdownContainer.width(countdownScaleObjectWidth*scale);
countdownContainer.height(countdownScaleObjectHeight*scale);
if($.browser.msie && browserVersion<=8){
countdownScaleObject.css("zoom", scale);
}else{
countdownScaleObject.css("transform", scaleCss).
css("-moz-transform", scaleCss).
css("-webkit-transform", scaleCss).
css("-o-transform", scaleCss).
css("-ms-transform", scaleCss);
countdownScaleObject.css("left",left).css("top",top);
};
};
var selector = "";
var index = 0;
var days = [];
var hours = [];
var minutes = [];
var seconds = [];
var itemClass = function(){};
switch(style){
case "flip":
itemClass = Flip;
break;
case "slide":
itemClass = Slide;
break;
case "crystal":
itemClass = Crystal;
break;
case "metal":
itemClass = Metal;
break;
default:
};
index = 1;
selector = ".group.day>.container.item";
while(countdownObject.find(selector+index).length){
days.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.hour>.container.item";
while(countdownObject.find(selector+index).length){
hours.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.minute>.container.item";
while(countdownObject.find(selector+index).length){
minutes.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
index = 1;
selector = ".group.second>.container.item";
while(countdownObject.find(selector+index).length){
seconds.push(new itemClass(countdownObject.find(selector+index)));
index++;
};
countdown.items(days, hours, minutes, seconds);
countdown.onFinish = onFinish;
countdown.time(timeText, timeZone);
};
var destroy = function(){
destroyCountdown();
target.children().remove();
};
var start = function(){
countdown.start();
};
var stop = function(){
countdown.stop();
};
if(arguments.length>0){
var target = this;
var countdown = getCountdown();
if(arguments.length==1 && typeof(arguments[0])=="object"){
//destroy the old countdown
if(countdown!=undefined){
destroy();
};
//init new countdown
init(arguments[0]);
}else if(typeof(arguments[0])=="string"){
//set setting & call method
if(countdown!=undefined){
switch(arguments[0]){
case "stop":
stop();
break;
case "start":
start();
break;
case "destroy":
destroy();
break;
default:
};
};
};
};
return this;
}
});
})(sexyJ);
| JavaScript |
sexyJ(function(e,i){function j(){var a=e("script:first"),b=a.css("color"),c=false;if(/^rgba/.test(b))c=true;else try{c=b!=a.css("color","rgba(0, 0, 0, 0.5)").css("color");a.css("color",b)}catch(d){}return c}function k(a,b,c){var d=[];a.c&&d.push("inset");typeof b.left!="undefined"&&d.push(parseInt(a.left+c*(b.left-a.left),10)+"px "+parseInt(a.top+c*(b.top-a.top),10)+"px");typeof b.blur!="undefined"&&d.push(parseInt(a.blur+c*(b.blur-a.blur),10)+"px");typeof b.a!="undefined"&&d.push(parseInt(a.a+c*
(b.a-a.a),10)+"px");if(typeof b.color!="undefined"){var g="rgb"+(e.support.rgba?"a":"")+"("+parseInt(a.color[0]+c*(b.color[0]-a.color[0]),10)+","+parseInt(a.color[1]+c*(b.color[1]-a.color[1]),10)+","+parseInt(a.color[2]+c*(b.color[2]-a.color[2]),10);if(e.support.rgba)g+=","+parseFloat(a.color[3]+c*(b.color[3]-a.color[3]));g+=")";d.push(g)}return d.join(" ")}function h(a){var b,c,d={};if(b=/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(a))c=[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],
16),1];else if(b=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(a))c=[parseInt(b[1],16)*17,parseInt(b[2],16)*17,parseInt(b[3],16)*17,1];else if(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),1];else if(b=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(a))c=[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10),parseFloat(b[4])];d=(b=/(-?[0-9]+)(?:px)?\s+(-?[0-9]+)(?:px)?(?:\s+(-?[0-9]+)(?:px)?)?(?:\s+(-?[0-9]+)(?:px)?)?/.exec(a))?
{left:parseInt(b[1],10),top:parseInt(b[2],10),blur:b[3]?parseInt(b[3],10):0,a:b[4]?parseInt(b[4],10):0}:{left:0,top:0,blur:0,a:0};d.c=/inset/.test(a);d.color=c;return d}e.extend(true,e,{support:{rgba:j()}});var f;e.each(["boxShadow","MozBoxShadow","WebkitBoxShadow"],function(a,b){a=e("html").css(b);if(typeof a=="string"&&a!=""){f=b;return false}});if(f)e.fx.step.boxShadow=function(a){if(!a.init){a.b=h(e(a.elem).get(0).style[f]||e(a.elem).css(f));a.end=e.extend({},a.b,h(a.end));if(a.b.color==i)a.b.color=
a.end.color||[0,0,0];a.init=true}a.elem.style[f]=k(a.b,a.end,a.pos)}});
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(sexyJ); | JavaScript |
/*
* --------------------------------------------------------------------
* jQuery-Plugin - selectToUISlider - creates a UI slider component from a select element(s)
* by Scott Jehl, scott@filamentgroup.com
* http://www.filamentgroup.com
* reference article: http://www.filamentgroup.com/lab/update_jquery_ui_16_slider_from_a_select_element/
* demo page: http://www.filamentgroup.com/examples/slider_v2/index.html
*
* Copyright (c) 2008 Filament Group, Inc
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Usage Notes: please refer to our article above for documentation
*
* --------------------------------------------------------------------
*/
(function(jQuery) {
jQuery.fn.selectToUISlider = function(settings){
var selects = jQuery(this);
//accessible slider options
var options = jQuery.extend({
labels: 3, //number of visible labels
tooltip: true, //show tooltips, boolean
tooltipSrc: 'text',//accepts 'value' as well
labelSrc: 'value',//accepts 'value' as well ,
sliderOptions: null
}, settings);
//handle ID attrs - selects each need IDs for handles to find them
var handleIds = (function(){
var tempArr = [];
selects.each(function(){
tempArr.push('handle_'+jQuery(this).attr('id'));
});
return tempArr;
})();
//array of all option elements in select element (ignores optgroups)
var selectOptions = (function(){
var opts = [];
selects.eq(0).find('option').each(function(){
opts.push({
value: jQuery(this).attr('value'),
text: jQuery(this).text()
});
});
return opts;
})();
//array of opt groups if present
var groups = (function(){
if(selects.eq(0).find('optgroup').size()>0){
var groupedData = [];
selects.eq(0).find('optgroup').each(function(i){
groupedData[i] = {};
groupedData[i].label = jQuery(this).attr('label');
groupedData[i].options = [];
jQuery(this).find('option').each(function(){
groupedData[i].options.push({text: jQuery(this).text(), value: jQuery(this).attr('value')});
});
});
return groupedData;
}
else return null;
})();
//check if obj is array
function isArray(obj) {
return obj.constructor == Array;
}
//return tooltip text from option index
function ttText(optIndex){
return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
}
//plugin-generated slider options (can be overridden)
var sliderOptions = {
step: 1,
min: 0,
orientation: 'horizontal',
max: selectOptions.length-1,
range: selects.length > 1,//multiple select elements = true
slide: function(e, ui) {//slide function
var thisHandle = jQuery(ui.handle);
//handle feedback
var textval = ttText(ui.value);
thisHandle
.attr('aria-valuetext', textval)
.attr('aria-valuenow', ui.value)
.find('.ui-slider-tooltip .ttContent')
.text( textval );
//control original select menu
var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
currSelect.find('option').eq(ui.value).attr('selected', 'selected');
},
values: (function(){
var values = [];
selects.each(function(){
values.push( jQuery(this).get(0).selectedIndex );
});
return values;
})()
};
//slider options from settings
options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;
//select element change event
selects.bind('change keyup click', function(){
var thisIndex = jQuery(this).get(0).selectedIndex;
var thisHandle = jQuery('#handle_'+ jQuery(this).attr('id'));
var handleIndex = thisHandle.data('handleNum');
thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
});
//create slider component div
var sliderComponent = jQuery('<div></div>');
//CREATE HANDLES
selects.each(function(i){
var hidett = '';
//associate label for ARIA
var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') +']');
//labelled by aria doesn't seem to work on slider handle. Using title attr as backup
var labelText = (thisLabel.size()>0) ? 'Slider control for '+ thisLabel.text()+'' : '';
var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_'+handleIds[i]).attr('id');
if( options.tooltip == false ){hidett = ' style="display: none;"';}
jQuery('<a '+
'href="#" tabindex="0" '+
'id="'+handleIds[i]+'" '+
'class="ui-slider-handle" '+
'role="slider" '+
'aria-labelledby="'+thisLabelId+'" '+
'aria-valuemin="'+options.sliderOptions.min+'" '+
'aria-valuemax="'+options.sliderOptions.max+'" '+
'aria-valuenow="'+options.sliderOptions.values[i]+'" '+
'aria-valuetext="'+ttText(options.sliderOptions.values[i])+'" '+
'><span class="screenReaderContext">'+labelText+'</span>'+
'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"'+ hidett +'><span class="ttContent"></span>'+
'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>'+
'</span></a>')
.data('handleNum',i)
.appendTo(sliderComponent);
});
//CREATE SCALE AND TICS
//write dl if there are optgroups
if(groups) {
var inc = 0;
var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
jQuery(groups).each(function(h){
scale.append('<dt style="width: '+ (100/groups.length).toFixed(2) +'%' +'; left:'+ (h/(groups.length-1) * 100).toFixed(2) +'%' +'"><span>'+this.label+'</span></dt>');//class name becomes camelCased label
var groupOpts = this.options;
jQuery(this.options).each(function(i){
var style = (inc == selectOptions.length-1 || inc == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
scale.append('<dd style="left:'+ leftVal(inc) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></dd>');
inc++;
});
});
}
//write ol
else {
var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
jQuery(selectOptions).each(function(i){
var style = (i == selectOptions.length-1 || i == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? this.text : this.value;
scale.append('<li style="left:'+ leftVal(i) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></li>');
});
}
function leftVal(i){
return (i/(selectOptions.length-1) * 100).toFixed(2) +'%';
}
//show and hide labels depending on labels pref
//show the last one if there are more than 1 specified
if(options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');
//set increment
var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
//show em based on inc
for(var j=0; j<selectOptions.length; j+=increm){
if((selectOptions.length - j) > increm){//don't show if it's too close to the end label
sliderComponent.find('.ui-slider-scale li:eq('+ j +') span.ui-slider-label, .ui-slider-scale dd:eq('+ j +') span.ui-slider-label').addClass('ui-slider-label-show');
}
}
//style the dt's
sliderComponent.find('.ui-slider-scale dt').each(function(i){
jQuery(this).css({
'left': ((100 /( groups.length))*i).toFixed(2) + '%'
});
});
//inject and return
sliderComponent
.insertAfter(jQuery(this).eq(this.length-1))
.slider(options.sliderOptions)
.attr('role','application')
.find('.ui-slider-label')
.each(function(){
jQuery(this).css('marginLeft', -jQuery(this).width()/2);
});
//update tooltip arrow inner color
sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function(){
var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
jQuery(this).css('border-top', bWidth+' solid '+bColor);
});
var values = sliderComponent.slider('values');
if(isArray(values)){
jQuery(values).each(function(i){
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text( ttText(this) );
});
}
else {
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text( ttText(values) );
}
return this;
}
})(sexyJ);
| JavaScript |
(function($) {
$(window).load(function() {
function sp_make_li_h() {
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
};
sp_make_li_h();
function sp_make_ul_h() {
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
};
sp_make_ul_h();
});
$(document).ready(function() {
var sexyCountry = '',
sexyCountryCode = '',
sexyCity = '',
sexyRegion = '';
var offset_padding = 2;
function sp_make_li_h_() {
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
};
function sp_make_ul_h_() {
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
};
setTimeout(function() {
sp_make_li_h_();
sp_make_ul_h_();
},1000);
function check_pro_version($elem) {
return true;
$elem_1 = $elem.find('.powered_by');
$elem_2 = $elem.find('.powered_by a');
var sexy_font_size_1 = parseInt($elem_1.css('font-size'));
var sexy_top_1 = parseInt($elem_1.css('top'));
var sexy_left_1 = parseInt($elem_1.css('left'));
var sexy_bottom_1 = parseInt($elem_1.css('bottom'));
var sexy_right_1 = parseInt($elem_1.css('right'));
var sexy_text_indent_1 = parseInt($elem_1.css('text-indent'));
var sexy_margin_top_1 = parseInt($elem_1.css('margin-top'));
var sexy_margin_bottom_1 = parseInt($elem_1.css('margin-bottom'));
var sexy_margin_left_1 = parseInt($elem_1.css('margin-left'));
var sexy_margin_right_1 = parseInt($elem_1.css('margin-right'));
var sexy_display_1 = $elem_1.css('display');
var sexy_position_1 = $elem_1.css('position');
var sexy_width_1 = parseInt($elem_1.css('width'));
var sexy_height_1 = parseInt($elem_1.css('height'));
var sexy_visibility_1 = $elem_1.css('visibility');
var sexy_overflow_1 = $elem_1.css('overflow');
var sexy_zindex_1 = parseInt($elem_1.css('z-index'));
var sexy_font_size_2 = parseInt($elem_2.css('font-size'));
var sexy_top_2 = parseInt($elem_2.css('top'));
var sexy_left_2 = parseInt($elem_2.css('left'));
var sexy_bottom_2 = parseInt($elem_2.css('bottom'));
var sexy_right_2 = parseInt($elem_2.css('right'));
var sexy_text_indent_2 = parseInt($elem_2.css('text-indent'));
var sexy_margin_top_2 = parseInt($elem_2.css('margin-top'));
var sexy_margin_right_2 = parseInt($elem_2.css('margin-right'));
var sexy_margin_bottom_2 = parseInt($elem_2.css('margin-bottom'));
var sexy_margin_left_2 = parseInt($elem_2.css('margin-left'));
var sexy_display_2 = $elem_2.css('display');
var sexy_position_2 = $elem_2.css('position');
var sexy_width_2 = parseInt($elem_2.css('width'));
var sexy_height_2 = parseInt($elem_2.css('height'));
var sexy_visibility_2 = $elem_2.css('visibility');
var sexy_overflow_2 = $elem_2.css('overflow');
var sexy_zindex_2 = parseInt($elem_2.css('z-index'));
var txt1 = $.trim($elem_1.html().replace(/<[^>]+>.*?<\/[^>]+>/gi, ''));
var txt2 = $.trim($elem_2.html().replace(/<[^>]+>.*?<\/[^>]+>/gi, ''));
var txt1_l = parseInt(txt1.length);
var txt2_l = parseInt(txt2.length);
var a_href = $elem_2.attr("href").replace('http://','');
a_href = a_href.replace('www.','');
a_href = $.trim(a_href.replace('www',''));
a_href_l = parseInt(a_href.length);
if(
sexy_font_size_1 == '13' && sexy_top_1 == '0' && sexy_left_1 == '0' && sexy_bottom_1 == '0' && sexy_right_1 == '0' && sexy_text_indent_1 == '0' && sexy_margin_top_1 == '-1' && sexy_margin_right_1 == '8' && sexy_margin_bottom_1 == '13' && sexy_margin_left_1 == '0' &&
sexy_display_1 == 'block' && sexy_position_1 == 'relative' && sexy_width_1 > '20' && sexy_height_1 > '10' && sexy_visibility_1 == 'visible' && sexy_overflow_1 == 'visible' && sexy_zindex_1 == '10' &&
sexy_font_size_2 == '13' && sexy_top_2 == '0' && sexy_left_2 == '0' && sexy_bottom_2 == '0' && sexy_right_2 == '0' && sexy_text_indent_2 == '0' && sexy_margin_top_2 == '0' && sexy_margin_right_2 == '0' && sexy_margin_bottom_2 == '0' && sexy_margin_left_2 == '0' &&
sexy_display_2 != 'none' && sexy_position_2 == 'relative' && sexy_width_2 > '20' && sexy_height_2 > '10' && sexy_visibility_2 == 'visible' && sexy_overflow_2 == 'visible' && sexy_zindex_2 == '10' &&
txt1 != '' && txt2 == 'Sexy Polling' && txt1_l > 1 && txt2_l == '12' && a_href_l == '30' && a_href == '2glux.com/projects/sexypolling'
)
return true;
return false;
};
$.ajax
({
url: sexyPath + 'components/com_sexypolling/geoip.php?ip=' + sexyIp,
type: "get",
dataType: "json",
success: function(data)
{
if(data != null) {
sexyCountry = data.countryName;
sexyCountryCode = data.countryCode;
sexyCity = data.cityName;
sexyRegion = data.regionName;
}
},
error: function()
{
}
});
setTimeout(function() {
$(".polling_container_wrapper").each(function() {
var w = $(this).width();
$(this).css("width",w);
var curr_h = $(this).find('.answer_wrapper').height();
$(this).find('.answer_wrapper').attr("h",curr_h);
});
},100);
var estimated_seconds = new Array();
function create_seconds_timers() {
var onlyVotedIds = new Array();
for(t in votedIds) {
var poll_id = votedIds[t][0];
estimated_seconds[poll_id] = parseInt(votedIds[t][2] * 3600);
};
setInterval(function() {
for(t in estimated_seconds) {
if(estimated_seconds[t] > 0)
estimated_seconds[t] -= 1;
};
},1000);
};
create_seconds_timers();
var estimated_seconds_start_poll = new Array();
function create_start_poll_seconds_timers() {
//check start dates
var s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var poll_id = startDisabledIds[i][0];
estimated_seconds_start_poll[poll_id] = parseInt(startDisabledIds[i][3] * 3600);
};
};
setInterval(function() {
for(tt in estimated_seconds_start_poll) {
if(estimated_seconds_start_poll[tt] > 0)
estimated_seconds_start_poll[tt] -= 1;
};
},1000);
};
create_start_poll_seconds_timers();
//alert box ////////////////////////////////////////////////////////////////////////////////////////
//function to create shadow
function create_shadow() {
var $shadow = '<div id="sexy_shadow"></div>';
$('body').css('position','relative').append($shadow);
$("#sexy_shadow")
.css( {
'position' : 'absolute',
'top' : '0',
'right' : '0',
'bottom' : '0',
'left' : '0',
'z-index' : '10000',
'opacity' : '0',
'backgroundColor' : '#000'
})
.fadeTo(200,'0.7');
};
function make_alert(txt,type) {
//create shadow
create_shadow();
//make alert
var $alert_body = '<div id="sexy_alert_wrapper"><div id="sexy_alert_body" class="' + type + '">' + txt + '</div><input type="button" id="close_sexy_alert" value="' + sexyPolling_words[21] + '" /></div>';
$('body').append($alert_body);
var scollTop = $(window).scrollTop();
var w_width = $(window).width();
var w_height = $(window).height();
var s_height = $("#sexy_alert_wrapper").height();
var alert_left = (w_width - 420) / 2;
var alert_top = (w_height - s_height) / 2;
$("#sexy_alert_wrapper")
.css( {
'top' : -1 * (s_height + 55 * 1) + scollTop * 1,
'left' : alert_left
})
.stop()
.animate({
'top' : alert_top + scollTop * 1
},450,'easeOutBack',function() {
//$(this).css('position','fixed');
});
};
function remove_alert_box() {
$("#sexy_shadow").stop().fadeTo(200,0,function() {$(this).remove();});
$("#sexy_alert_wrapper").stop().fadeTo(200,0,function() {$(this).remove();});
};
function move_alert_box() {
var scollTop = $(window).scrollTop();
var w_width = $(window).width();
var w_height = $(window).height();
var s_height = $("#sexy_alert_wrapper").height();
var alert_left = (w_width - 420) / 2;
var alert_top = (w_height - s_height) / 2;
$("#sexy_alert_wrapper")
.stop()
.animate({
'top' : alert_top + scollTop * 1,
'left' : alert_left
},450,'easeOutBack',function() {
//$(this).css('position','fixed');
});
};
$('#close_sexy_alert').live('click', function() {
remove_alert_box();
});
$(window).resize(function() {
move_alert_box();
});
$(window).scroll(function() {
move_alert_box();
});
setTimeout(function() {
$(".polling_bottom_wrapper1").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".polling_loading").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".answer_input").each(function() {
var w = $(this).width();
$(this).attr("w",w);
});
$(".polling_ul").each(function() {
var h = $(this).height();
$(this).attr("h",h);
});
$(".polling_li").each(function() {
var h = $(this).height();
$(this).attr("h_start",h);
});
$(".answer_navigation").each(function() {
var b = parseInt($(this).css("borderWidth"));
$(this).attr("b",b);
});
},50);
function create_timer(seconds_diff, show_date) {
var newdate = new Date();
newdate.setSeconds(newdate.getSeconds() + seconds_diff);
var dd = newdate.getDate();
var mm = newdate.getMonth()+1;
var hh = newdate.getHours();
var ii = newdate.getMinutes();
var ss = newdate.getSeconds();
var yyyy = newdate.getFullYear();
if(dd<10) dd='0'+dd;
if(mm<10) mm='0'+mm;
if(hh<10) hh='0'+hh;
if(ii<10) ii='0'+ii;
if(ss<10) ss='0'+ss;
var time_text = yyyy+'/'+mm+'/'+dd + ' ' + hh + ':' + ii + ':' + ss;
var timezone = new Date().getTimezoneOffset();
$("#sexy_timer").jCountdown({
timeText:time_text,
timeZone:0,
style:"slide",
color:"black",
width:350,
textGroupSpace:15,
textSpace:0,
reflection:true,
reflectionOpacity:20,
reflectionBlur:1,
dayTextNumber:2,
displayDay:show_date,
displayHour:true,
displayMinute:true,
displaySecond:true,
displayLabel:true,
onFinish:function(){
remove_alert_box();
}
});
};
$('.polling_submit').click(function() {
$elem = $(this).parents('.polling_container');
if(!check_pro_version($elem)) {
make_alert('To hide a backlink please purchase a Sexy Polling PRO version','sexy_error');
return false;
}
if($(this).hasClass('voted_button')) {
make_alert(sexyPolling_words[9],'sexy_error');
return;
}
var t_id = $(this).attr("id");
var polling_id = $(this).parent('span').parent('div').find('.poll_answer').attr('name');
if(votingPermissions[polling_id] != 'allow_voting') {
make_alert(votingPermissions[polling_id],'sexy_error');
return false;
};
//check if already voted
var onlyVotedIds = new Array();
var estimated_seconds_item = estimated_seconds[polling_id];
for(t in votedIds) {
onlyVotedIds.push(votedIds[t][0]);
if(votedIds[t][0] == polling_id)
var estimated_ours = votedIds[t][2];
};
if(estimated_seconds_item > 0 || estimated_ours == 'never') {
if($.inArray(polling_id,onlyVotedIds) != -1) {
if(estimated_ours == 'never') {
make_alert(sexyPolling_words[9],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(sexyPolling_words[9] + '<div id="estimated_time_message">' + sexyPolling_words[20] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_item, show_date);
return false;
}
}
};
//check start dates
var estimated_seconds_start_poll_item = estimated_seconds_start_poll[polling_id];
s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + startDisabledIds[i][2] + "_" + startDisabledIds[i][0];
if(c_id == t_id) {
var estimated_ours = startDisabledIds[i][3];
if(estimated_seconds_start_poll_item > 0 || estimated_ours == 'never') {
if(estimated_ours == 'never') {
make_alert(startDisabledIds[i][1],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(startDisabledIds[i][1] + '<div id="estimated_time_message">' + sexyPolling_words[22] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_start_poll_item, show_date);
return false;
}
}
}
}
};
//check end dates
e_length = endDisabledIds.length;
for(var i = 0;i <= e_length; i++) {
if(typeof endDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + endDisabledIds[i][2] + "_" + endDisabledIds[i][0];
if(c_id == t_id) {
make_alert(endDisabledIds[i][1],'sexy_normal');
return false;
}
}
};
var polling_checked_value = $(this).parent('span').parent('div').find('.poll_answer:checked').val();
if(polling_checked_value == undefined) {
make_alert(sexyPolling_words[8],'sexy_normal');
return false;
};
var $t = $(this);
vote_polling($t);
});
$('.polling_result').click(function() {
$elem = $(this).parents('.polling_container');
if(!check_pro_version($elem)) {
make_alert('To hide a backlink please purchase a Sexy Polling PRO version','sexy_error');
return false;
}
var $t = $(this);
show_polling($t);
});
$('.polling_select2,.polling_select1').change(function() {
var $t = $(this).parents('.polling_container');
show_polling_by_date($t);
});
function show_polling($t) {
var polling_id = $t.parent('span').parent('div').find('.poll_answer').attr('name');
var module_id = $t.parent('span').parent('div').parent('div').attr('roll');
$container = $t.parent('span').parent('div');
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
//function to remove user added input boxes
$container.find('.doNotUncheck').parent('div').parent('div').parent('li').remove();
//hide all radio buttons
$t.parent('span').parent('div').find('.answer_input').animate({
width:0,
opacity:0
},1000);
//animate answers
$t.parent('span').parent('div').find('.answer_name label').animate({
marginLeft:0
},1000);
//show navigation bar
//TODO: when animating border, there is jquery issue with animation. Find the way to fix that!
var b = $t.parent('span').parent('div').find('.answer_navigation').attr("b");
$t.parent('span').parent('div').find('.answer_navigation').css("borderWidth","0").show().animate({
height:animation_styles[module_id+"_"+polling_id][9],
borderWidth: b,
opacity:1
},1000);
//animate loading
var l_h = $t.parent('span').parent('div').find('.polling_loading').height();
$t.parent('span').parent('div').find('.polling_loading').css({display:'block',opacity:0,height:0});
$t.parent('span').parent('div').find('.polling_loading').animate({
opacity:0.85,
height: l_h
},1000);
//send request
var h = $container.find('.answer_votes_data').height();
var min_date = $container.find('.polling_select1').val();
var max_date = $container.find('.polling_select2').val();
//total time = 1000;
setTimeout(function() {
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id + '&mode=view_by_date&min_date=' + min_date + '&max_date=' + max_date + '&dateformat=' + dateFormat[polling_id] + '&module_id=' + module_id+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
$container = $("#mod_" + data[0].module_id + "_" + data[0].poll_id);
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
data_length = data.length;
max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = parseFloat(this.percent_formated);
response_votes = this.votes;
order = this.order;
order_start = this.order_start;
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
if(max_percent == 'none')
max_percent = percent;
answers_array.push(parseInt(answer_id));
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title',sexyPolling_words[0] + ': ' + response_votes);
//start animating navigation bar
$nav_width = $container.find(".polling_li").width();
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
$current_width_tobeset = $container.find('.scale_icon').hasClass('opened') ? $current_width_rel : $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
//set the value
$container.find('#answer_votes_data_count_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_count_val_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_percent_' + answer_id).html(percent_formated);
$container.find('#answer_votes_data_percent_val_' + answer_id).html(percent_formated);
//show answer data
$container.find('.answer_votes_data').css({'display':'block','height':0}).animate({height:h},1000);
//set to absolute
if(i == data_length - 1) {
animate_poll_items($container,answers_array,polling_id,module_id,total_votes,min_date,max_date,orders_array,orders_array_start);
}
});
},
error: function()
{
}
});
},1000);
};
//function to animate elements
function animate_poll_items($container,answers_array,polling_id,module_id,total_votes,min_date,max_date,orders_array,orders_array_start) {
var s_timeout = 2700;
if(
$container.find('.polling_info').attr("rell") == 'noanimate' &&
$container.find('.sexyback_icon').attr("rell") == 'noanimate' &&
$container.find('.timeline_icon').attr("rell") == 'noanimate' &&
$container.find('.scale_icon').attr("rell") == 'noanimate' &&
$container.find('.add_answer_icon').attr("rell") == 'noanimate'
)
s_timeout = 1200;
setTimeout(function(){
var offset_0_ = $container.find('.polling_ul').offset();
offset_0 = offset_0_.top;
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
$container.find('.polling_ul').css('height',$container.find('.polling_ul').height());
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
});
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},s_timeout,function() {
});
//show total votes, min and max dates
$container.find('.total_votes').html(total_votes);
$container.find('.total_votes_val').html(total_votes);
$container.find('.first_vote').html(min_date);
$container.find('.last_vote').html(max_date);
//hide submit button and loading
$container.find('.polling_bottom_wrapper1')
.stop(true,true).animate({
height:0
},
1000,
function(){
$container.find('.polling_bottom_wrapper1').hide();
$container.find('.polling_loading').hide();
});
setTimeout(function() {
//show polling info
$container.find('.polling_info').css({'display':'block'});
var h = $container.find('.polling_info').height();
$container.find('.polling_info').css({'display':'none'});
$container.find('.polling_info')
.css({'height': 0,'display':'block'})
.animate({height:h},1000);
//show timeline
$container.find('.timeline_icon').animate({height:32},1000);
//show add answer
$container.find('.add_answer_icon').animate({height:32},1000);
//show add answer
$container.find('.sexyback_icon').animate({height:32},1000);
//show add answer
$container.find('.scale_icon').animate({height:32},1000);
},1700);
if(autoOpenTimeline[polling_id] == 1) {
setTimeout(function() {
$container.find('.timeline_icon').trigger("click");
},s_timeout);
}
}
//global variable, to store digit animations
$digit_int = new Array();
$digit_int_percent = new Array();
$digit_int_total = '';
function show_polling_by_date($t,use_current_date) {
use_current_date = typeof use_current_date !== 'undefined' ? use_current_date : 'no';
var polling_id = $t.find('.poll_answer').attr('name');
var module_id = $t.parent('div').attr('roll');
var min_date = $t.find('.polling_select1').val();
var max_date = $t.find('.polling_select2').val();
$container = $t;
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
//clear all intervals
for(i_v in $digit_int) {
clearInterval($digit_int[i_v]);
}
//clear all intervals
for(i_v in $digit_int_percent) {
clearInterval($digit_int_percent[i_v]);
}
clearInterval($digit_int_total);
setTimeout(function() {
$nav_width = $container.find(".polling_li").width();
//send request
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id + '&mode=view_by_date&min_date=' + min_date + '&max_date=' + max_date + '&dateformat=' + dateFormat[polling_id] + '&curr_date=' + use_current_date+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
//count of json objects
data_length = data.length;
//assign variables
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
$curr_count = new Array();
$new_count = new Array();
$step_sign = new Array();
$steps = new Array();
$interval_value = new Array();
$curr_count_ = new Array();
$curr_step = new Array();
$curr_percent = new Array();
$new_percent = new Array();
$step_sign_percent = new Array();
$steps_percent = new Array();
$interval_value_percent = new Array();
$curr_percent_ = new Array();
$curr_step_percent = new Array();
var max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = parseFloat(this.percent_formated);
response_votes = parseInt(this.votes);
order = this.order;
order_start = this.order_start;
if(max_percent == 'none')
max_percent = percent;
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
answers_array.push(answer_id);
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title','Votes: ' + response_votes);
//start animating navigation bar
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
if($container.find('.scale_icon').hasClass('opened'))
new_w = $current_width_rel;
else
new_w = $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).stop(true,false).animate({
width: new_w
},1000,sexyAnimationTypeBar[polling_id]);
//ie box shadow animation
if($container.find('#answer_navigation_' + answer_id).next(".ie-shadow").width() != $current_width + 4*1)
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").stop(true,false).animate({
width: new_w
},1000,sexyAnimationTypeBar[polling_id]);
//digit animation //remember min_count_of_votes / $steps_count_percent must have influance on tofixed(it's value) ...
//animate percents
$curr_percent[answer_id] = parseFloat($container.find('#answer_votes_data_percent_' + answer_id).html());
$new_percent[answer_id] = percent_formated;
$steps_percent[answer_id] = Math.abs($curr_percent[answer_id] - $new_percent[answer_id]);
$steps_count_percent = 20;
$step_item_percent = $steps_percent[answer_id] / $steps_count_percent;
//get sign
$step_sign_percent[answer_id] = ($new_percent[answer_id] > $curr_percent[answer_id]) ? 1 * $step_item_percent : (($new_percent[answer_id] < $curr_percent[answer_id]) ? -1 * $step_item_percent : 0);
$interval_value_percent[answer_id] = parseFloat(1000 / $steps_count_percent);
//animate total count
$curr_total = parseInt($t.find('.total_votes').html());
$new_total = total_votes;
$steps_total = Math.abs($curr_total - $new_total);
$steps_count_total = 20;
$step_item_total = $steps_total / $steps_count_total;
//get sign
$step_sign_total = ($new_total > $curr_total) ? 1 * $step_item_total : (($new_total < $curr_total) ? -1 * $step_item_total : 0);
$interval_value_total = parseFloat(1000 / $steps_count_total);
//animate answer votes count
$curr_count[answer_id] = parseInt($container.find('#answer_votes_data_count_' + answer_id).html());
$new_count[answer_id] = response_votes;
$steps[answer_id] = Math.abs($curr_count[answer_id] - $new_count[answer_id]);
$steps_count = 15;
$step_item = $steps[answer_id] / $steps_count;
//get sign
$step_sign[answer_id] = ($new_count[answer_id] > $curr_count[answer_id]) ? 1 * $step_item : (($new_count[answer_id] < $curr_count[answer_id]) ? -1 * $step_item : 0);
$interval_value[answer_id] = parseFloat(1000 / $steps_count);
if(i == data_length - 1) {
//show total votes, min and max dates
$t.find('.first_vote').html(min_date);
$t.find('.last_vote').html(max_date);
function animate_total() {
if($step_sign_total != 0) {
$digit_int_total = setInterval(function(){
$curr_total_ = parseFloat($t.find('.total_votes_val').html());
$curr_total_ = $curr_total_ + 1 * $step_sign_total;
$t.find('.total_votes').html($curr_total_.toFixed(1));
$t.find('.total_votes_val').html($curr_total_);
if($step_sign_total > 0) {
if($curr_total_ >= $new_total) {
clearInterval($digit_int_total);
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
}
else {
if($curr_total_ <= $new_total) {
clearInterval($digit_int_total);
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
}
},$interval_value_total);
}
else {
$t.find('.total_votes').html($new_total);
$t.find('.total_votes_val').html($new_total);
}
};
animate_total();
var animate_percent = function(ans_id) {
if($step_sign_percent[ans_id] !== 0) {
$digit_int_percent[ans_id] = setInterval(function(){
$curr_percent_[ans_id] = parseFloat($container.find('#answer_votes_data_percent_val_' + ans_id).html());
$curr_percent_[ans_id] = $curr_percent_[ans_id] + 1 * $step_sign_percent[ans_id];
$container.find('#answer_votes_data_percent_val_' + ans_id).html($curr_percent_[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($curr_percent_[ans_id].toFixed(2));
if($step_sign_percent[ans_id] > 0) {
if($curr_percent_[ans_id] >= $new_percent[ans_id]) {
clearInterval($digit_int_percent[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
}
else {
if($curr_percent_[ans_id] <= $new_percent[ans_id]) {
clearInterval($digit_int_percent[ans_id]);
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
}
},$interval_value_percent[ans_id]);
}
else {
$container.find('#answer_votes_data_percent_' + ans_id).html($new_percent[ans_id]);
$container.find('#answer_votes_data_percent_val_' + ans_id).html($new_percent[ans_id]);
}
};
var animate_digit = function(ans_id) {
if($step_sign[ans_id] != 0) {
$digit_int[ans_id] = setInterval(function(){
$curr_count_[ans_id] = parseFloat($container.find('#answer_votes_data_count_val_' + ans_id).html());
$curr_count_[ans_id] = $curr_count_[ans_id] + 1 * $step_sign[ans_id];
$container.find('#answer_votes_data_count_' + ans_id).html($curr_count_[ans_id].toFixed(1));
$container.find('#answer_votes_data_count_val_' + ans_id).html($curr_count_[ans_id]);
if($step_sign[ans_id] > 0) {
if($curr_count_[ans_id] >= $new_count[ans_id]) {
clearInterval($digit_int[ans_id]);
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
}
else {
if($curr_count_[ans_id] <= $new_count[ans_id]) {
clearInterval($digit_int[ans_id]);
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
}
},$interval_value[ans_id]);
}
else {
$container.find('#answer_votes_data_count_' + ans_id).html($new_count[ans_id]);
$container.find('#answer_votes_data_count_val_' + ans_id).html($new_count[ans_id]);
}
};
for(var b = 0; b < answers_array.length; b++) {
animate_digit(answers_array[b]);
animate_percent(answers_array[b]);
}
};
//set to absolute
if(i == data_length - 1) {
var offset_0_ = $t.find('.polling_ul').offset();
offset_0 = offset_0_.top;
setTimeout(function(){
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block'})
.stop(false,false)
.animate( {
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],
function() {
$(this).animate( {
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
})
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},1);
}
});
},
error: function()
{
}
})
},1);
};
function vote_polling($t) {
var polling_id = $t.parent('span').parent('div').find('.poll_answer').attr('name');
var module_id = $t.parent('span').parent('div').parent('div').attr('roll');
$container = $t.parent('span').parent('div');
var sexypolling_token = $container.find('.sexypolling_token').attr("name");
var voting_period = voting_periods[module_id + '_' + polling_id];
//close answer
$container.find('.answer_wrapper')
.css({'overflow':'hidden'})
.animate({
height:0
},600);
$container.find('.add_answer_icon').removeClass('opened').addClass('voted_button');
$container.find('.polling_submit').addClass('voted_button');
//recalculate ul height
$ul_height = $container.children("ul").height();
$container.children("ul").attr("h",$ul_height);
//if we have added answers, add them to post
var additionalAnswers = '';
$container.find('.doNotUncheck').each(function(i) {
var htm = $(this).parents('li').find('label').html();
htm = htm.replace(/\?\?/g,'sexydoublequestionmark');
additionalAnswers += '&answers[]=' + htm;
});
//hide all radio buttons
$container.find('.answer_input').animate({
width:0,
opacity:0
},1000);
//animate answers
$container.find('.answer_name label').animate({
marginLeft:0
},1000);
//show navigation bar
var b = $container.find('.answer_navigation').attr("b");
$container.find('.answer_navigation').css("borderWidth","0").show().animate({
height:animation_styles[module_id+"_"+polling_id][9],
borderWidth: b,
opacity:1
},1000);
//animate loading
var l_h = $t.parent('span').parent('div').find('.polling_loading').height();
$t.parent('span').parent('div').find('.polling_loading').attr("h",l_h).css({display:'block',opacity:0,height:0});
$t.parent('span').parent('div').find('.polling_loading').animate({
opacity:0.85,
height: l_h
},1000);
//send request
$nav_width = $container.find(".polling_li").width();
var h = $container.find('.answer_votes_data').height();
var ch_data = '';
$t.parent('span').parent('div').find('.poll_answer:checked').not('.doNotUncheck').each(function() {
ch_data += '&answer_id[]=' + $(this).val();
});
var min_date = $container.find('.polling_select1').val();
var max_date = $container.find('.polling_select2').val();
setTimeout(function() {
$.ajax
({
url: sexyPath + 'components/com_sexypolling/vote.php',
type: "post",
data: 'polling_id=' + polling_id +ch_data + '&dateformat=' + dateFormat[polling_id] + additionalAnswers + '&min_date=' + min_date + '&max_date=' + max_date + '&country_name=' + sexyCountry + '&country_code=' + sexyCountryCode + '&city_name=' + sexyCity + '®ion_name=' + sexyRegion + '&voting_period='+voting_period+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
if((data[0].invalid) == 'invalid_token')
make_alert('Invalid Token','sexy_error');
$container.find('.doNotUncheck').each(function(i) {
if(typeof data[0].addedanswers !== 'undefined') {
$(this).parents('li').attr("id",'answer_' + data[0].addedanswers[i]);
$(this).parents('li').find('.answer_navigation').attr("id",'answer_navigation_' + data[0].addedanswers[i]);
$(this).parents('li').find('.answer_votes_data').attr("id",'answer_votes_data_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_count_0').attr("id",'answer_votes_data_count_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_count_val_0').attr("id",'answer_votes_data_count_val_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_percent_0').attr("id",'answer_votes_data_percent_' + data[0].addedanswers[i]);
$(this).parents('li').find('#answer_votes_data_percent_val_0').attr("id",'answer_votes_data_percent_val_' + data[0].addedanswers[i]);
}
});
$container.find('.doNotUncheck').removeClass('doNotUncheck');
answers_array = new Array();
orders_array = new Array();
orders_array_start = new Array();
max_percent = 'none';
$.each(data, function(i) {
answer_id = this.answer_id;
percent = this.percent;
percent_formated = this.percent_formated;
response_votes = this.votes;
order = this.order;
order_start = this.order_start;
if(max_percent == 'none')
max_percent = percent;
answers_array.push(answer_id);
orders_array.push(order);
orders_array_start.push(order_start);
//sets the title of navigations
$container.find('#answer_navigation_' + answer_id).attr('title','Votes: ' + response_votes);
//start animating navigation bar
$current_width_rel = parseInt($nav_width * percent / 100 );
$current_width_rel = $current_width_rel == 0 ? '1' : $current_width_rel;
$current_width = parseInt($nav_width * percent / max_percent );
$current_width = ($current_width == 0 || isNaN($current_width)) ? '1' : $current_width;
$current_width_tobeset = $container.find('.scale_icon').hasClass('opened') ? $current_width_rel : $current_width;
$container.find('#answer_navigation_' + answer_id).attr({"rel_width":$current_width_rel,"ab_width":$current_width}).animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
$container.find('#answer_navigation_' + answer_id).next(".ie-shadow").animate({
width: $current_width_tobeset
},1000,sexyAnimationTypeBar[polling_id]);
//set the value
$container.find('#answer_votes_data_count_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_count_val_' + answer_id).html(response_votes);
$container.find('#answer_votes_data_percent_' + answer_id).html(percent_formated);
$container.find('#answer_votes_data_percent_val_' + answer_id).html(percent_formated);
//show answer data
$container.find('.answer_votes_data').css({'display':'block','height':0}).animate({height:h},1000);
var s_timeout = 2700;
if(
$container.find('.polling_info').attr("rell") == 'noanimate' &&
$container.find('.sexyback_icon').attr("rell") == 'noanimate' &&
$container.find('.timeline_icon').attr("rell") == 'noanimate' &&
$container.find('.scale_icon').attr("rell") == 'noanimate' &&
$container.find('.add_answer_icon').attr("rell") == 'noanimate'
)
s_timeout = 1200;
//set to absolute
if(i == 0) {
var offset_0_ = $container.find('.polling_ul').offset();
offset_0 = offset_0_.top;
setTimeout(function(){
//calculates offsets
var offsets_array = new Array();
for(var b = 0; b < answers_array.length; b++) {
var offset_1_ = $container.find("#answer_" + answers_array[b]).offset();
var offset_1 = offset_1_.top;
var total_offset = offset_1 * 1 - offset_0;
offsets_array.push(total_offset);
};
//animate items
curr_top = 0;
curr_height = 0;
curr_z_index = 1000;
$container.find('.polling_ul').css('height',$container.find('.polling_ul').height());
for(var b = 0; b < answers_array.length; b++) {
var li_item_height = $container.find("#answer_" + answers_array[b]).height() + offset_padding;
curr_height = curr_height * 1 + li_item_height;
$container.find("#answer_" + answers_array[b]).css({position:'absolute',top:offsets_array[b],'z-index':curr_z_index});
$container.find("#answer_" + answers_array[b]).stop(true,false).animate({
top: curr_top
},1200,sexyAnimationTypeContainerMove[polling_id]);
$container.find("#answer_" + answers_array[b] + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
});
});
$container.find("#answer_" + answers_array[b]).attr('order',orders_array[b]);
$container.find("#answer_" + answers_array[b]).attr('order_start',orders_array_start[b]);
curr_top = curr_top + li_item_height;
curr_z_index = curr_z_index - 1;
};
$container.find('.polling_ul').css('height',curr_height);
},s_timeout);
//show total votes, min and max dates
total_votes = this.total_votes;
min_date = this.min_date;
max_date = this.max_date;
$container.find('.total_votes').html(total_votes);
$container.find('.total_votes_val').html(total_votes);
$container.find('.first_vote').html(min_date);
$container.find('.last_vote').html(max_date);
//hide submit button and loading
$container.find('.polling_bottom_wrapper1')
.animate({
height:0
},
1000,
function(){
$container.find('.polling_bottom_wrapper1').hide();
$container.find('.polling_loading').hide();
});
setTimeout(function() {
//show polling info
$container.find('.polling_info').css({'display':'block'});
var h = $container.find('.polling_info').height();
$container.find('.polling_info').css({'display':'none'});
$container.find('.polling_info')
.css({'height': 0,'display':'block'})
.animate({height:h},1000);
//show timeline
$container.find('.timeline_icon').animate({height:32},1000);
//show add answer
$container.find('.add_answer_icon').animate({height:32},1000);
//show add answer
$container.find('.sexyback_icon').animate({height:32},1000);
//show add answer
$container.find('.scale_icon').animate({height:32},1000);
},1700);
if(autoOpenTimeline[polling_id] == 1) {
setTimeout(function() {
$container.find('.timeline_icon').trigger("click");
},s_timeout);
};
};
});
},
error: function()
{
}
})
},1000);
};
$('.timeline_icon').click(function() {
var $c = $(this).parent('div').children('.timeline_select_wrapper');
var curr_h = 90;
var new_class = $c.hasClass('opened') ? 'closed' : 'opened';
if(new_class == 'opened') {
$(this).addClass('opened');
$c.removeClass('closed');
$c.addClass('opened');
$(this).attr('title',sexyPolling_words[5]);
}
else {
$(this).removeClass('opened');
$c.removeClass('opened');
$c.addClass('closed');
$(this).attr('title',sexyPolling_words[4]);
}
//open timeline
$(this).parent('div').children('.timeline_select_wrapper.opened')
.css({'overflow':'hidden','height':0})
.stop(true,true)
.animate({
height:curr_h
},
1000,
function(){
$(this).css({'overflow':'visible'})
});
//close timeline
$(this).parent('div').children('.timeline_select_wrapper.closed')
.css({'overflow':'hidden'})
.stop(true,true)
.animate({
height:0
},1000,function() {
$(this).css({'overflow':'hidden'});
});
});
function make_relative($t) {
var module_id = $t.parent('div').parent('div').parent('div').attr('roll');
var polling_id = $t.parent('div').parent('div').parent('div').find(".poll_answer").attr('name');
$t.parent('div').parent('div').find('.answer_navigation').each(function() {
var rel_width = $(this).attr("rel_width");
$(this).stop(true,false).animate({
width: rel_width
},1000,sexyAnimationTypeBar[polling_id]);
});
};
function make_absolute($t) {
var module_id = $t.parent('div').parent('div').parent('div').attr('roll');
var polling_id = $t.parent('div').parent('div').parent('div').find(".poll_answer").attr('name');
$t.parent('div').parent('div').find('.answer_navigation').each(function() {
var ab_width = $(this).attr("ab_width");
$(this).stop(true,false).animate({
width: ab_width
},1000,sexyAnimationTypeBar[polling_id]);
});
};
function animate_back($t) {
$container = $t.parents('.polling_container');
//show results button
$container.find('.polling_result').removeClass('hide_sexy_button');
//uncheck all inpust
$container.find('.poll_answer').attr("checked",false);
$container.find('.twoglux_styled_element').removeClass("twoglux_checked");
$container.find('.checkbox_part1').css("height",0);
$container.find('.checkbox_part2').css("height",0);
$container.find('.radio_part1').css("opacity",0);
//hide polling info
$container.find('.polling_info')
.stop()
.stop(true,true).animate({height:0},1000,
function() {
//$(this).css({'display':'none'});
$(this).removeAttr("style");
});
//hide timeline
$container.find('.timeline_select_wrapper')
.stop()
.stop(true,true).animate({height:0},1000,
function() {
$(this).css({'overflow':'hidden'});
});
$('.timeline_icon').removeClass('opened');
$('.timeline_select_wrapper').removeClass('opened');
//hide loading
var l_h = $container.find('.polling_loading').attr("h");
$container.find('.polling_loading').css({'display':'none'});
//show bottons
var h = $container.find('.polling_bottom_wrapper1').attr("h");
$container.find('.polling_bottom_wrapper1')
.css({'display':'block'})
.stop()
.stop(true,true).animate({height:h},1000,function() {
$(this).css('height','auto');
});
var answer_w = $container.find('.answer_input').attr("w");
var ratio_h = $container.find('.answer_result').height();
var ul_h = $container.find('.polling_ul').attr("h");
//hide timeline
$container.find('.timeline_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.add_answer_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.sexyback_icon').stop(true,true).animate({height:0},1000);
//hide add answer
$container.find('.scale_icon').stop(true,true).animate({height:0},1000);
$container.find('.answer_votes_data').stop(true,true).animate({height:0},1000,function(){$(this).removeAttr("style");});
$container.find('.answer_input').stop(true,true).animate({width:answer_w,opacity:1},1000);
$container.find('.answer_name label').stop(true,true).animate({marginLeft:answer_w},1000);
$container.find('.answer_navigation').stop(true,true).animate({height:0,borderWidth:0},1000,function() {$(this).hide();});
var total_h = 0;
$container.find('.polling_li').each(function(k) {
var h = $(this).attr("h_start")*1;
$(this).stop(true,true).animate({"top" :total_h},1000,function() {
$(this).removeAttr("style");
});
total_h = total_h + h*1;
});
$container.find('.polling_ul').stop(true,true).animate({height:ul_h},1000,function(){$(this).removeAttr("style");});
};
$('.scale_icon').click(function() {
if($(this).hasClass('opened') ) {
$(this).removeClass('opened');
$(this).attr("title",sexyPolling_words[16]);
make_absolute($(this));
}
else {
$(this).addClass('opened');
$(this).attr("title",sexyPolling_words[15]);
make_relative($(this));
}
});
$('.sexyback_icon').click(function() {
animate_back($(this));
});
$('.add_answer_icon').click(function() {
if($(this).hasClass('voted_button')) {
make_alert(sexyPolling_words[9],'sexy_error');
return;
}
if($(this).hasClass('disabled'))
return;
var $c = $(this).parents('.polling_container').find('.answer_wrapper');
var curr_h = $(this).parents('.polling_container').find('.answer_wrapper').attr("h");
//open answer
$(this).parents('.polling_container').find('.answer_wrapper.closed')
.css({'overflow':'hidden','height':0})
.animate({
height:curr_h
},
600,
function(){
$(this).css({'overflow':'visible'});
});
//close answer
$(this).parents('.polling_container').find('.answer_wrapper.opened')
.css({'overflow':'hidden'})
.animate({
height:0
},600);
var new_class = $c.hasClass('opened') ? 'closed' : 'opened';
if(new_class == 'opened') {
$(this).addClass('opened');
$c.removeClass('closed');
$c.addClass('opened');
}
else {
$(this).removeClass('opened');
$c.removeClass('opened');
$c.addClass('closed');
}
});
//add new answer
$('.add_ans_name').focus(function() {
var polling_id = $(this).parents('.polling_container').find('.poll_answer').attr('name');
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
if($(this).val() == sexyPolling_words[11]) {
$(this).val('');
$(this).css('color',animation_styles[module_id+"_"+polling_id][11]);
$(this).parent('div').children('.add_ans_submit').show();
var s_w = $(this).parent('div').children('.add_ans_submit').width();
s_w += 14;
$(this).parent('.add_answer').css('paddingRight',s_w);
}
});
$('.add_ans_name').blur(function() {
var polling_id = $(this).parents('.polling_container').find('.poll_answer').attr('name');
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
if($.trim($(this).val()) == '') {
$(this).val(sexyPolling_words[11]);
$(this).css('color',animation_styles[module_id+"_"+polling_id][10]);
$(this).parent('div').children('.add_ans_submit').hide();
$(this).parent('.add_answer').css('paddingRight',0);
}
else {
$(this).val($.trim($(this).val()));
}
});
$(".add_ans_name").keydown(function(e) {
if(e.keyCode == 13) {
var dis = $(this).parent('div').children('.add_ans_submit').css("display");
if(dis == 'block' || dis == 'inline-block') {
$(this).parent('div').children('.add_ans_submit').trigger('click');
$(this).blur();
}
}
});
//add new answer functions
$('.add_ans_submit').click(function() {
var sexypolling_token = $(this).parents('.polling_container_wrapper').find('.sexypolling_token').attr("name");
var answers_count = parseInt($(this).parents('.polling_container_wrapper').find('.answer_input').length);
if(answers_count >= 5) {
make_alert('This poll can not have more than 5 answers','sexy_error');
return false;
}
//check count allowed options
if(!check_allowed_answers_count($(this).parents('.polling_container_wrapper')))
return false;
$this = $(this);
$ans_name = $.trim($this.parent('div').children('.add_ans_name').val());
$ans_name = $ans_name.replace(/\\/g, "");
if($ans_name == '')
return false;
$poll_id = $this.parent('div').children('.poll_id').val();
var module_id = $(this).parents('.polling_container_wrapper').attr('roll');
var voting_period = voting_periods[module_id + '_' + $poll_id];
//check if already voted
var onlyVotedIds = new Array();
var estimated_seconds_item = estimated_seconds[$poll_id];
for(t in votedIds) {
onlyVotedIds.push(votedIds[t][0]);
if(votedIds[t][0] == $poll_id)
var estimated_ours = votedIds[t][2];
};
if(estimated_seconds_item > 0 || estimated_ours == 'never') {
if($.inArray($poll_id,onlyVotedIds) != -1) {
if(estimated_ours == 'never') {
make_alert(sexyPolling_words[9],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(sexyPolling_words[9] + '<div id="estimated_time_message">' + sexyPolling_words[20] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_item, show_date);
return false;
}
}
};
//check start dates
var t_id = $this.parents('.polling_container').find('.polling_submit').attr("id");
var estimated_seconds_start_poll_item = estimated_seconds_start_poll[$poll_id];
s_length = startDisabledIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof startDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + startDisabledIds[i][2] + "_" + startDisabledIds[i][0];
if(c_id == t_id) {
var estimated_ours = startDisabledIds[i][3];
if(estimated_seconds_start_poll_item > 0 || estimated_ours == 'never') {
if(estimated_ours == 'never') {
make_alert(startDisabledIds[i][1],'sexy_error');
return false;
}
else {
var estimated_days = parseInt(estimated_ours / 24);
var show_date = estimated_days == 0 ? false : true;
var timer_htm = '<div id="sexy_timer"></div>';
make_alert(startDisabledIds[i][1] + '<div id="estimated_time_message">' + sexyPolling_words[22] + '</div>' + timer_htm,'sexy_error');
create_timer(estimated_seconds_start_poll_item, show_date);
return false;
}
}
}
}
};
//check end dates
e_length = endDisabledIds.length;
for(var i = 0;i <= e_length; i++) {
if(typeof endDisabledIds[i] !== 'undefined') {
var c_id = "poll_" + endDisabledIds[i][2] + "_" + endDisabledIds[i][0];
if(c_id == t_id) {
make_alert(endDisabledIds[i][1],'sexy_normal');
return false;
}
}
};
//check if opened
var cOpened = false;
var position = $this.parents('.polling_container').find('.polling_li').css('position');
if (position == 'absolute') {
cOpened = true;
};
var buttonType = multipleAnswersInfoArray[$poll_id] == 1 ? 'checkbox' : 'radio';
//if we have checkboxes and sexy poll is closed, then we do not write answer to database, untill user do not vote vor it
var writeInto = (buttonType == 'checkbox' && !cOpened) ? 0 : 1;
var added_answer = $ans_name.replace(/\?\?/g,'sexydoublequestionmark');
$this.parent('div').children('.loading_small').fadeIn(400);
$this.fadeOut(400);
$.ajax
({
url: sexyPath + 'components/com_sexypolling/addanswer.php',
type: "post",
data: 'polling_id=' + $poll_id + '&answer=' + added_answer + '&autopublish=' + sexyAutoPublish[$poll_id] + '&writeinto=' + writeInto + '&country_name=' + sexyCountry + '&country_code=' + sexyCountryCode + '&city_name=' + sexyCity + '®ion_name=' + sexyRegion + '&voting_period='+voting_period+'&'+sexypolling_token+'=1',
dataType: "json",
success: function(data)
{
if((data[0].invalid) == 'invalid_token')
make_alert('Invalid Token','sexy_error');
if(buttonType == 'radio' || (buttonType == 'checkbox' && cOpened)) {
$this.parents('.polling_container').find('.add_answer_icon').addClass('voted_button');
$this.parents('.polling_container').find('.polling_submit').addClass('voted_button');
}
$this.parent('div').children('.loading_small').fadeOut(400);
if(sexyAutoPublish[$poll_id] == 1) {
//disable icon clicking
$this.parents('.polling_container').find('.add_answer_icon').addClass('disabled');
setTimeout(function() {
/*we keep add answer box opened only if
* 1. we have checkboxes
* 2. poll box is closed
*/
if((buttonType == 'checkbox' && !cOpened)) {
//close add answer box
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
//reset padding
$this.parent('.add_answer').css('paddingRight',0);
}
else {
$this.parents('.polling_container').find('.add_answer_icon').removeClass('opened');
//close add answer box
$this.parents('.answer_wrapper')
.removeClass('opened')
.addClass('closed')
.css({'overflow':'hidden'})
.animate({
height:0
},600,function() {
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
//reset padding
$this.parent('.add_answer').css('paddingRight',0);
});
};
},1);
//add new answer
add_answer($this.parents('.polling_container'),data[0].answer,data[0].id);
}
else {
//show moderation message
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.attr("readonly","readonly")
.val(sexyPolling_words[13]);
make_alert(sexyPolling_words[13],'sexy_normal');
$this.parent('.add_answer').css('paddingRight',0);
$this.parents('.polling_container').find('.add_answer_icon').addClass('disabled');
setTimeout(function() {
//change icon background
$this.parents('.polling_container').find('.add_answer_icon').removeClass('opened');
//close add answer box
$this.parents('.answer_wrapper')
.removeClass('opened')
.addClass('closed')
.css({'overflow':'hidden'})
.animate({
height:0
},600,function() {
//reset values
$this.parent('div').children('.add_ans_name')
.css("color",animation_styles[module_id+"_"+$poll_id][10])
.removeAttr('readonly')
.val(sexyPolling_words[11]);
//remove icon disabled
$this.parents('.polling_container').find('.add_answer_icon').removeClass('disabled');
});
},3000)
}
}
});
//function to add new answer to the answers list
function add_answer($c,$answer,$id) {
//check if opened
var cOpened = false;
var position = $c.find('.polling_li').css('position');
if (position == 'absolute') {
cOpened = true;
};
var polling_id = $c.find('.poll_answer').attr('name');
var module_id = $c.parent('div').attr('roll');
var h = $c.find('.answer_votes_data').height();
var buttonType = multipleAnswersInfoArray[polling_id] == 1 ? 'checkbox' : 'radio';
var color = 'blue';
if(buttonType == 'radio')
var inner_img_html = '<div class="radio_part1 ' + color + '_radio_part1 unselectable" style="opacity: 1;" > </div>';
else
var inner_img_html = '<div class="checkbox_part1 ' + color + '_checkbox_part1 unselectable" style="height: 9px;" > </div><div class="checkbox_part2 ' + color + '_checkbox_part2 unselectable" style="height: 12px;"> </div>';
//create new element html
if(cOpened) {
var t_votes = $c.find('.total_votes_val').html();
var t_votes_new = ++t_votes;
$c.find('.total_votes_val').html(t_votes_new);
$c.find('.total_votes').html(t_votes_new);
var new_percent = parseFloat(100 / t_votes).toFixed(1);
$new_li = '<li id="answer_' + $id + '" class="polling_li"><div class="animation_block"></div><div class="answer_name"><label style="margin-left:0" uniq_index="' + $id + '" class="twoglux_label">' + $answer + '</label></div><div class="answer_input" style="width: 0px; opacity: 0; "><div class="twoglux_styled_input_wrapper" ><input name="' + polling_id + '" id="' + $id + '" type="' + buttonType + '" checked="checked" class="poll_answer ' + $id + ' twoglux_styled" style="display:none" value="' + $id + '" /><a id="twoglux_styled_elem_' + $id + '_' + added_length + '" class="twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + buttonType + ' unselectable name_' + polling_id + ' twoglux_checked">' + inner_img_html + '</a></div></div><div class="sexy_clear"></div><div class="answer_result"><div class="answer_navigation polling_bar_' + newAnswerBarIndex + '" id="answer_navigation_' + $id + '" style=" opacity: 1; width: 1px;display:block;"><div class="grad"></div></div><div class="answer_votes_data" id="answer_votes_data_' + $id + '" style="height: ' + h + 'px;display:block; ">' + sexyPolling_words[0] + ': <span id="answer_votes_data_count_' + $id + '">1</span><span id="answer_votes_data_count_val_' + $id + '" style="display:none">1</span> (<span id="answer_votes_data_percent_' + $id + '">' + new_percent + '</span><span style="display:none" id="answer_votes_data_percent_val_' + $id + '">' + new_percent + '</span>%)</div><div class="sexy_clear"></div></div></li>';
//add html to DOM
$c.find("li").last().after($new_li);
//set height
$("#answer_navigation_" + $id).css('height',animation_styles[module_id+"_"+polling_id][9]);
$new_height = $("#answer_" + $id).height() + offset_padding;
$ul_height = $c.children("ul").height();
$("#answer_" + $id).css({"position":"absolute","top":$ul_height});
$c.children("ul").stop(true,false).animate( {
height: "+=" + $new_height
},600,function() {
show_polling_by_date($c,'yes');
});
}
else {
var user_class = buttonType == 'checkbox' ? 'doNotUncheck' : '';
var added_length = $c.find(".doNotUncheck").length;
$new_li = '<li id="answer_' + $id + '" class="polling_li"><div class="animation_block"></div><div class="answer_name"><label uniq_index="elem_' + $id + '_' + added_length + '" class="twoglux_label">' + $answer + '</label></div><div class="answer_input"><div class="twoglux_styled_input_wrapper" ><input name="' + polling_id + '" id="elem_' + $id + '_' + added_length + '" type="' + buttonType + '" checked="checked" class="poll_answer ' + $id + ' twoglux_styled" style="display:none" value="' + $id + '" /><a id="twoglux_styled_elem_' + $id + '_' + added_length + '" class="' + user_class + ' twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + buttonType + ' unselectable name_' + polling_id + ' twoglux_checked">' + inner_img_html + '</a></div></div><div class="sexy_clear"></div><div class="answer_result"><div class="answer_navigation polling_bar_' + newAnswerBarIndex + '" id="answer_navigation_' + $id + '"><div class="grad"></div></div><div class="answer_votes_data" id="answer_votes_data_' + $id + '">' + sexyPolling_words[0] + ': <span id="answer_votes_data_count_' + $id + '"></span><span id="answer_votes_data_count_val_' + $id + '" style="display:none">0</span> (<span id="answer_votes_data_percent_' + $id + '">0</span><span style="display:none" id="answer_votes_data_percent_val_' + $id + '">0</span>%)</div><div class="sexy_clear"></div></div></li>';
//add html to DOM
$c.find("li").last().after($new_li);
$ul_height = $c.children("ul").height();
$c.children("ul").attr("h",$ul_height);
};
if(cOpened)
$("#answer_" + $id + " .animation_block")
.css({'display':'block','opacity' : '0'})
.stop(true,false).animate({
opacity: 1,
boxShadow: animation_styles[module_id+"_"+polling_id][2],
borderTopColor: animation_styles[module_id+"_"+polling_id][1],
borderBottomColor: animation_styles[module_id+"_"+polling_id][1],
borderLeftColor: animation_styles[module_id+"_"+polling_id][1],
borderRightColor: animation_styles[module_id+"_"+polling_id][1],
backgroundColor: animation_styles[module_id+"_"+polling_id][0],
borderTopLeftRadius: animation_styles[module_id+"_"+polling_id][3],
borderTopRightRadius: animation_styles[module_id+"_"+polling_id][4],
borderBottomLeftRadius: animation_styles[module_id+"_"+polling_id][5],
borderBottomRightRadius: animation_styles[module_id+"_"+polling_id][6]
},1200,sexyAnimationTypeContainer[polling_id],function(){
$(this).animate({
opacity: 0,
boxShadow: animation_styles[module_id+"_"+polling_id][8] + '0 0 0 0 ' + animation_styles[module_id+"_"+polling_id][7],
borderTopColor: animation_styles[module_id+"_"+polling_id][7],
borderBottomColor: animation_styles[module_id+"_"+polling_id][7],
borderLeftColor: animation_styles[module_id+"_"+polling_id][7],
borderRightColor: animation_styles[module_id+"_"+polling_id][7],
backgroundColor: animation_styles[module_id+"_"+polling_id][7],
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0
},1200,sexyAnimationTypeContainer[polling_id],function() {
$(this).hide();
})
});
//show polling
if(!cOpened && buttonType == 'radio') {
var sub_object = $c.find(".polling_submit");
show_polling(sub_object);
}
}
});
//slider function
s_length = sexyPollingIds.length;
for(var i = 0;i <= s_length; i++) {
if(typeof sexyPollingIds[i] !== 'undefined') {
var select1 = sexyPollingIds[i][0];
var select2 = sexyPollingIds[i][1];
$("#" + select1 + ",#" + select2).selectToUISlider(
{
labels:0,
sliderOptions:
{
stop: function(e,ui)
{
show_polling_by_date($(this).parents('.polling_container'));
}
}
});
}
};
//autoanimate
v_length = votedIds.length;
for(var i = 0;i <= v_length; i++) {
if(typeof votedIds[i] !== 'undefined' && autoAnimate[votedIds[i][0]] == '1') {
var time = (i * 1 + 1) * 10;
var t = $("#res_" + votedIds[i][1] + "_" + votedIds[i][0]);
animate_poll(t,time);
}
};
function animate_poll(t,time) {
setTimeout(function() {
show_polling(t);
},time)
}
///////////////////////////////////////////////////////////////Sexy Checkboxes/////////////////////////////////////////////////////////////////////////////////
$('.twoglux_styled').each(function() {
var $this = $(this);
var type = $this.attr("type");
var color = $this.attr("data-color");
var name = $this.attr("name");
var id = $this.attr("id");
$this.wrap('<div class="twoglux_styled_input_wrapper" />');
if(type == 'radio')
var inner_img_html = '<div class="radio_part1 ' + color + '_radio_part1 unselectable" > </div>';
else
var inner_img_html = '<div class="checkbox_part1 ' + color + '_checkbox_part1 unselectable" > </div><div class="checkbox_part2 ' + color + '_checkbox_part2 unselectable"> </div>';
var twoglux_styled_html = '<a id="twoglux_styled_' + id + '" class="twoglux_styled_element twoglux_styled_' + color + ' twoglux_styled_' + type + ' unselectable name_' + name + '">' + inner_img_html + '</a>';
$this.after(twoglux_styled_html);
$this.hide();
});
$('.twoglux_styled_element').live('mouseenter', function() {
make_mouseenter($(this));
});
$('.twoglux_styled_element').live('mouseleave', function() {
make_mouseleave($(this))
});
function make_mouseenter($elem) {
if($elem.hasClass('twoglux_styled_radio'))
$elem.addClass('twoglux_styled_radio_hovered');
else
$elem.addClass('twoglux_styled_checkbox_hovered');
};
function make_mouseleave($elem) {
if($elem.hasClass('twoglux_styled_radio'))
$elem.removeClass('twoglux_styled_radio_hovered');
else
$elem.removeClass('twoglux_styled_checkbox_hovered');
};
var sexyanimatetime = 150;
var last_event = 'up';
var last_event_radio = 'up';
var body_mouse_up_enabled = false;
//////////////////////////////////////////////////////////////////////MOVE FUNCTIONS////////////////////////////////////////
function animate_checkbox1_down($elem) {
$elem.animate({height: 9},sexyanimatetime);
};
function animate_checkbox1_up($elem) {
//uncheck element
$elem.parent('a').removeClass('twoglux_checked');
$elem.parent('a').prev('input').attr("checked",false);
$elem.animate({height: 0},sexyanimatetime);
};
function animate_checkbox2_up($elem) {
$elem.animate({height: 12},sexyanimatetime);
//check element
$elem.parent('a').addClass('twoglux_checked');
$elem.parent('a').prev('input').attr("checked",true);
};
function animate_checkbox2_down($elem) {
$elem.animate({height: 0},sexyanimatetime);
};
//////////////////////////////////////////////////////////////////////MOUSEDOWN////////////////////////////////////////
$('.twoglux_styled_checkbox').live('mousedown',function() {
//check if checkbox checked
if($(this).hasClass('twoglux_checked'))
animate_checkbox2_down($(this).find('.checkbox_part2'));
else
animate_checkbox1_down($(this).find('.checkbox_part1'));
last_event = 'down';
body_mouse_up_enabled = true;
});
//////////////////////////////////////////////////////////////////////MOUSEUP//////////////////////////////////////////
$('.twoglux_styled_checkbox').live('mouseup',function() {
if(!($(this).hasClass('twoglux_checked'))) {
if(!check_allowed_answers_count($(this).parents('.polling_container'))) {
last_event = 'up';
body_mouse_up_enabled = false;
animate_checkbox1_up($(this).find('.checkbox_part1'));
return false;
}
}
if(last_event == 'down') {
//check if checkbox checked
if($(this).hasClass('twoglux_checked'))
animate_checkbox1_up($(this).find('.checkbox_part1'));
else
animate_checkbox2_up($(this).find('.checkbox_part2'));
}
last_event = 'up';
body_mouse_up_enabled = false;
});
function check_allowed_answers_count($c) {
var poll_id = $c.find('.poll_answer').attr('name');
var alloewd_answers = allowedNumberAnswers[poll_id];
if(alloewd_answers == 0)
return true;
var checked_options_count = $c.find('input[type="checkbox"]:checked').length;
if(parseInt(checked_options_count) == alloewd_answers) {
make_alert(sexyPolling_words[23] + ' <span class="max_allowed_checkox_limit">' + alloewd_answers + '</span>','sexy_normal');
return false;
}
return true;
}
//////////////////////////////////////////////////////////RADIOBUTTONS//////////////////////////////////////////////////////////////
$('.radio_part1').css('opacity','0');
$('.twoglux_styled_radio').live('mousedown',function() {
//check if checkbox checked
if(!($(this).hasClass('twoglux_checked'))) {
$(this).find('.radio_part1').fadeTo(sexyanimatetime, 0.5);
}
last_event_radio = 'down';
body_mouse_up_enabled = true;
});
$('.twoglux_styled_radio').live('mouseup',function() {
if(last_event_radio == 'down') {
//check if checkbox checked
if(!($(this).hasClass('twoglux_checked'))) {
$(this).addClass('twoglux_checked');
var name = $(this).prev('input').attr("name");
$('input[name="' + name + '"]').attr("checked",false);
$(this).prev('input').attr("checked",true);
$('.name_' + name).removeClass('twoglux_checked');
$(this).addClass('twoglux_checked');
$('.name_' + name).not($(this)).find('.radio_part1').fadeTo(sexyanimatetime, 0);
$(this).find('.radio_part1').fadeTo(sexyanimatetime, 1);
}
}
last_event_radio = 'up';
body_mouse_up_enabled = false;
});
//////////////////////////////////////////////////////////////OTHER////////////////////////////////////////////////////////////////////////////////
//fixing bug in firefox
$('.twoglux_styled_input_wrapper').bind("dragstart", function() {
return false;
});
$("body").live('mouseup',function() {
if(body_mouse_up_enabled) {
//checkbox
var $elems = $('.twoglux_styled_element').not('.twoglux_checked').find('.checkbox_part1');
animate_checkbox1_up($elems);
var $elems = $('.twoglux_styled_element.twoglux_checked').find('.checkbox_part2');
animate_checkbox2_up($elems);
var $elems = $('.twoglux_styled_element').not('.twoglux_checked').find('.radio_part1');
$elems.fadeTo(sexyanimatetime, 0);
}
});
//trigger events for label
$('.twoglux_label').live('mouseenter', function() {
var uniq_index = $(this).attr("uniq_index");
make_mouseenter($("#twoglux_styled_" + uniq_index));
});
$('.twoglux_label').live('mouseleave',function() {
var uniq_index = $(this).attr("uniq_index");
make_mouseleave($("#twoglux_styled_" + uniq_index));
});
$('.twoglux_label').live('mousedown',function() {
var uniq_index = $(this).attr("uniq_index");
$("#twoglux_styled_" + uniq_index).trigger("mousedown");
});
$('.twoglux_label').live('mouseup',function() {
var uniq_index = $(this).attr("uniq_index");
$("#twoglux_styled_" + uniq_index).trigger("mouseup");
});
//function to prevent uncheck user added input boxes
$('.doNotUncheck').live('mouseup',function() {
if(! $(this).hasClass('twoglux_checked') ) {
$(this).parent('div').parent('div').parent('li').remove();
};
});
})
})(sexyJ); | JavaScript |
/**
*
* Utilities
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($) {
EYE.extend({
getPosition : function(e, forceIt)
{
var x = 0;
var y = 0;
var es = e.style;
var restoreStyles = false;
if (forceIt && sexyJ.curCSS(e,'display') == 'none') {
var oldVisibility = es.visibility;
var oldPosition = es.position;
restoreStyles = true;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
}
var el = e;
if (el.getBoundingClientRect) { // IE
var box = el.getBoundingClientRect();
x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2;
y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2;
} else {
x = el.offsetLeft;
y = el.offsetTop;
el = el.offsetParent;
if (e != el) {
while (el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
}
if (sexyJ.browser.safari && sexyJ.curCSS(e, 'position') == 'absolute' ) {
x -= document.body.offsetLeft;
y -= document.body.offsetTop;
}
el = e.parentNode;
while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML')
{
if (sexyJ.curCSS(el, 'display') != 'inline') {
x -= el.scrollLeft;
y -= el.scrollTop;
}
el = el.parentNode;
}
}
if (restoreStyles == true) {
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {x:x, y:y};
},
getSize : function(e)
{
var w = parseInt(sexyJ.curCSS(e,'width'), 10);
var h = parseInt(sexyJ.curCSS(e,'height'), 10);
var wb = 0;
var hb = 0;
if (sexyJ.curCSS(e, 'display') != 'none') {
wb = e.offsetWidth;
hb = e.offsetHeight;
} else {
var es = e.style;
var oldVisibility = es.visibility;
var oldPosition = es.position;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
wb = e.offsetWidth;
hb = e.offsetHeight;
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {w:w, h:h, wb:wb, hb:hb};
},
getClient : function(e)
{
var h, w;
if (e) {
w = e.clientWidth;
h = e.clientHeight;
} else {
var de = document.documentElement;
w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
}
return {w:w,h:h};
},
getScroll : function (e)
{
var t=0, l=0, w=0, h=0, iw=0, ih=0;
if (e && e.nodeName.toLowerCase() != 'body') {
t = e.scrollTop;
l = e.scrollLeft;
w = e.scrollWidth;
h = e.scrollHeight;
} else {
if (document.documentElement) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
if (typeof pageYOffset != 'undefined') {
t = pageYOffset;
l = pageXOffset;
}
iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
}
return { t: t, l: l, w: w, h: h, iw: iw, ih: ih };
},
getMargins : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'marginTop') || '';
var r = sexyJ.curCSS(e,'marginRight') || '';
var b = sexyJ.curCSS(e,'marginBottom') || '';
var l = sexyJ.curCSS(e,'marginLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getPadding : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'paddingTop') || '';
var r = sexyJ.curCSS(e,'paddingRight') || '';
var b = sexyJ.curCSS(e,'paddingBottom') || '';
var l = sexyJ.curCSS(e,'paddingLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getBorder : function(e, toInteger)
{
var t = sexyJ.curCSS(e,'borderTopWidth') || '';
var r = sexyJ.curCSS(e,'borderRightWidth') || '';
var b = sexyJ.curCSS(e,'borderBottomWidth') || '';
var l = sexyJ.curCSS(e,'borderLeftWidth') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)||0
};
else
return {t: t, r: r, b: b, l: l};
},
traverseDOM : function(nodeEl, func)
{
func(nodeEl);
nodeEl = nodeEl.firstChild;
while(nodeEl){
EYE.traverseDOM(nodeEl, func);
nodeEl = nodeEl.nextSibling;
}
},
getInnerWidth : function(el, scroll) {
var offsetW = el.offsetWidth;
return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth;
},
getInnerHeight : function(el, scroll) {
var offsetH = el.offsetHeight;
return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight;
},
getExtraWidth : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingLeft'))||0)
+ (parseInt($.curCSS(el, 'paddingRight'))||0)
+ (parseInt($.curCSS(el, 'borderLeftWidth'))||0)
+ (parseInt($.curCSS(el, 'borderRightWidth'))||0);
return 0;
},
getExtraHeight : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingTop'))||0)
+ (parseInt($.curCSS(el, 'paddingBottom'))||0)
+ (parseInt($.curCSS(el, 'borderTopWidth'))||0)
+ (parseInt($.curCSS(el, 'borderBottomWidth'))||0);
return 0;
},
isChildOf: function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (!el || !el.nodeType || el.nodeType != 1) {
return false;
}
if (parentEl.contains && !$.browser.safari) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
centerEl : function(el, axis)
{
var clientScroll = EYE.getScroll();
var size = EYE.getSize(el);
if (!axis || axis == 'vertically')
$(el).css(
{
top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px'
}
);
if (!axis || axis == 'horizontally')
$(el).css(
{
left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px'
}
);
}
});
if (!$.easing.easeout) {
$.easing.easeout = function(p, n, firstNum, delta, duration) {
return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum;
};
}
})(sexyJ); | JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(sexyJ) | JavaScript |
(function($){
var initLayout = function() {
var hash = window.location.hash.replace('#', '');
var currentTab = $('ul.navigationTabs a')
.bind('click', showTab)
.filter('a[rel=' + hash + ']');
if (currentTab.size() == 0) {
currentTab = $('ul.navigationTabs a:first');
}
showTab.apply(currentTab.get(0));
$('#colorpickerHolder').ColorPicker({flat: true});
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerField1, #colorpickerField2, #colorpickerField3').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
$('#colorSelector').ColorPicker({
color: '#0000ff',
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
$('#colorSelector div').css('backgroundColor', '#' + hex);
}
});
};
var showTab = function(e) {
var tabIndex = $('ul.navigationTabs a')
.removeClass('active')
.index(this);
$(this)
.addClass('active')
.blur();
$('div.tab')
.hide()
.eq(tabIndex)
.show();
};
EYE.register(initLayout, 'init');
})(jQuery) | JavaScript |
/**
*
* Zoomimage
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($){
var EYE = window.EYE = function() {
var _registered = {
init: []
};
return {
init: function() {
$.each(_registered.init, function(nr, fn){
fn.call();
});
},
extend: function(prop) {
for (var i in prop) {
if (prop[i] != undefined) {
this[i] = prop[i];
}
}
},
register: function(fn, type) {
if (!_registered[type]) {
_registered[type] = [];
}
_registered[type].push(fn);
}
};
}();
$(EYE.init);
})(sexyJ);
| JavaScript |
$(document).ready(function(){
// for show details like tipsy
function social(){
$('ul.social li').find('.details').hide();
$('ul.social li').hover(function(){
$('ul.social li').find('.details').hide();
$(this).find('.details').stop(true, true).fadeIn(200);
},function(){
$(this).find('.details').stop(true, true).delay(500).fadeOut(200);
});
}
//for get content
var content,loading,element, href, e_class;
content = $('section');
loading = '<span class="loading hide"></span>';
content.html(loading);
content.find('span.loading').removeClass('hide');
$.get('home.html', function(data) {
content.html(data);
content.find('span.loading').addClass('hide');
$('article.home ul.cv li:nth-child(3n)').addClass('nth3');
social();
});
$('nav a').on("click", function(){
element = $(this);
href = element.attr('href');
e_class = element.attr('class').split("current").join("");
content.removeClass().addClass('content auto '+e_class);
$('nav a.current').removeClass('current');
element.addClass('current');
content.html(loading);
content.find('span.loading').removeClass('hide');
$.get(href, function(data) {
content.html(data);
content.find('span.loading').addClass('hide');
$('article.home ul.cv li:nth-child(3n)').addClass('nth3');
social();
});
return false;
});
}); | JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.