code
stringlengths
1
2.08M
language
stringclasses
1 value
// Copyright 2012 Google Inc. 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 Moog-like low pass audio filter. */ goog.provide('doodle.moog.LowPassFilter'); goog.require('doodle.moog.CompoundAudioNode'); /** * A dynamic low pass filter emulator. * @param {!AudioContext} audioContext Audio context to which this oscillator * will be bound. * @param {number} cutoffFrequency The cutoff frequency above which the * frequencies are attenuated. * @param {number} contour Amount of contour to apply to the filter envelope. * @param {number} attackTime Initial attack time in seconds. * @param {number} decayTime Initial decay time in seconds. * @param {number} sustainLevel Initial sustain level [0..1]. * @constructor * @implements {doodle.moog.CompoundAudioNode} */ doodle.moog.LowPassFilter = function( audioContext, cutoffFrequency, contour, attackTime, decayTime, sustainLevel) { /** * Audio context in which this filter operates. * @type {!AudioContext} * @private */ this.audioContext_ = audioContext; /** * The low pass filter Web Audio node. * @type {!BiquadFilterNode} * @private */ this.lowPassFilterNode_ = audioContext.createBiquadFilter(); this.lowPassFilterNode_.type = doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_; /** * Frequency above which sound should be progressively attenuated. * @type {number} * @private */ this.cutoffFrequency_ = cutoffFrequency; /** * The amount of 'contour' to add to the low pass filter ADS (attack, decay, * sustain) envelope. Contour is essentially a variable cutoff frequency * coefficient. See doodle.moog.EnvelopeGenerator for an explanation of how * ADS envelopes work. * @type {number} * @private */ this.contour_ = contour; /** * The duration of the attack phase in seconds. * @type {number} * @private */ this.attackTime_ = attackTime; /** * The duration of the decay phase in seconds. * @type {number} * @private */ this.decayTime_ = decayTime; /** * The sustain frequency coefficient. * @type {number} * @private */ this.sustainLevel_ = sustainLevel; this.resetContourEnvelope_(); }; /** * Biquad Filter type ID for a low pass filter (from the Web Audio spec). * @type {number} * @const * @private */ doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0; /** * Initiates the attack phase of the contour envelope (e.g., when a key is * pressed). */ doodle.moog.LowPassFilter.prototype.startAttack = function() { var now = this.audioContext_.currentTime; this.lowPassFilterNode_.frequency.cancelScheduledValues(now); this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_; this.lowPassFilterNode_.frequency.setValueAtTime(this.cutoffFrequency_, now); var contourFrequency = this.contour_ * this.cutoffFrequency_; this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime( contourFrequency, now + this.attackTime_); this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime( this.cutoffFrequency_ + this.sustainLevel_ * (contourFrequency - this.cutoffFrequency_), now + this.attackTime_ + this.decayTime_); }; /** * Sets the filter cutoff frequency. * @param {number} cutoffFrequency The cutoff frequency above which the * frequencies are attenuated. */ doodle.moog.LowPassFilter.prototype.setCutoffFrequency = function( cutoffFrequency) { this.cutoffFrequency_ = cutoffFrequency; this.resetContourEnvelope_(); }; /** * Sets the filter envelope contour. * @param {number} contour Amount of contour to apply to the filter envelope. */ doodle.moog.LowPassFilter.prototype.setContour = function(contour) { this.contour_ = contour; this.resetContourEnvelope_(); }; /** * Sets attack phase duration. * @param {number} time Duration of the attack phase in seconds. */ doodle.moog.LowPassFilter.prototype.setContourAttackTime = function(time) { this.attackTime_ = time; this.resetContourEnvelope_(); }; /** * Sets decay phase duration. * @param {number} time Duration of the decay phase in seconds. */ doodle.moog.LowPassFilter.prototype.setContourDecayTime = function(time) { this.decayTime_ = time; this.resetContourEnvelope_(); }; /** * Sets the sustain level. * @param {number} level The sustain level, a number in the range [0, 1]. */ doodle.moog.LowPassFilter.prototype.setContourSustainLevel = function(level) { this.sustainLevel_ = level; this.resetContourEnvelope_(); }; /** * Resets the contour envelope AudioParam using current LowPassFilter state. * @private */ doodle.moog.LowPassFilter.prototype.resetContourEnvelope_ = function() { this.lowPassFilterNode_.frequency.cancelScheduledValues(0); this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_; }; /** @inheritDoc */ doodle.moog.LowPassFilter.prototype.getSourceNode = function() { return this.lowPassFilterNode_; }; /** @inheritDoc */ doodle.moog.LowPassFilter.prototype.connect = function(destination) { this.lowPassFilterNode_.connect(destination); }; /** @inheritDoc */ doodle.moog.LowPassFilter.prototype.disconnect = function() { this.lowPassFilterNode_.disconnect(); };
JavaScript
// Copyright 2012 Google Inc. 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. goog.addDependency('../../../compound_audio_node.js', ['doodle.moog.CompoundAudioNode'], []); goog.addDependency('../../../envelope_generator.js', ['doodle.moog.EnvelopeGenerator'], []); goog.addDependency('../../../low_pass_filter.js', ['doodle.moog.LowPassFilter'], ['doodle.moog.CompoundAudioNode']); goog.addDependency('../../../master_mixer.js', ['doodle.moog.MasterMixer'], ['doodle.moog.MasterMixerInterface']); goog.addDependency('../../../master_mixer_interface.js', ['doodle.moog.MasterMixerInterface'], []); goog.addDependency('../../../moog.js', ['doodle.moog.Moog'], ['doodle.moog.LowPassFilter', 'doodle.moog.MasterMixer', 'doodle.moog.Oscillator', 'doodle.moog.OscillatorInterface', 'doodle.moog.Synthesizer', 'doodle.moog.WideBandPassFilter', 'goog.Disposable']); goog.addDependency('../../../oscillator.js', ['doodle.moog.Oscillator'], ['doodle.moog.EnvelopeGenerator', 'doodle.moog.OscillatorInterface']); goog.addDependency('../../../oscillator_interface.js', ['doodle.moog.OscillatorInterface', 'doodle.moog.OscillatorInterface.FillMode', 'doodle.moog.OscillatorInterface.Range', 'doodle.moog.OscillatorInterface.WaveForm'], []); goog.addDependency('../../../synthesizer.js', ['doodle.moog.Synthesizer'], ['doodle.moog.CompoundAudioNode', 'doodle.moog.OscillatorInterface', 'doodle.moog.SynthesizerInterface', 'goog.array', 'goog.userAgent']); goog.addDependency('../../../synthesizer_interface.js', ['doodle.moog.SynthesizerInterface'], []); goog.addDependency('../../../wide_band_pass_filter.js', ['doodle.moog.WideBandPassFilter'], ['doodle.moog.CompoundAudioNode']);
JavaScript
// Copyright 2012 Google Inc. 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 Voltage controlled oscillator emulators. */ goog.provide('doodle.moog.OscillatorInterface'); goog.provide('doodle.moog.OscillatorInterface.FillMode'); goog.provide('doodle.moog.OscillatorInterface.Range'); goog.provide('doodle.moog.OscillatorInterface.WaveForm'); /** * Oscillator interface to be implemented in WebAudio and FlashAudio. * @interface */ doodle.moog.OscillatorInterface = function() {}; /** * Different methods in which an oscillator can fill an audio buffer. * @enum {number} */ doodle.moog.OscillatorInterface.FillMode = { // Clobber any pre-existing data in the buffer. CLOBBER: 0, // Add signal to the buffer. ADD: 1, // Add signal to the buffer and then do an even mix down. MIX: 2 }; /** * Different 'ranges' (i.e., octaves in synth lingo) in which an oscillator can * generate a tone. 'LO' is a special Moog-ism that generates sub-audio clicks * and pops. * @enum {number} */ doodle.moog.OscillatorInterface.Range = { LO: 0.0625, R32: 2, R16: 4, R8: 8, R4: 16, R2: 32 }; /** * Different wave forms that can be generated by an oscillator, each of which * has a different overtone spectrum leading to a different base timbre. * @enum {number} */ doodle.moog.OscillatorInterface.WaveForm = { TRIANGLE: 0, SAWANGLE: 1, RAMP: 2, REVERSE_RAMP: 3, SQUARE: 4, FAT_PULSE: 5, PULSE: 6 }; /** * Sets the volume on this oscillator. * @param {number} volume Volume in the range of [0, 1]. */ doodle.moog.OscillatorInterface.prototype.setVolume = function(volume) {}; /** * Sets the wave form generated by this oscillator. * @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm The wave form to * use. */ doodle.moog.OscillatorInterface.prototype.setWaveForm = function(waveForm) {}; /** * Sets the pitch bend on this oscillator. * @param {number} pitchBend Pitch bend amount in the range of [-1, 1]. */ doodle.moog.OscillatorInterface.prototype.setPitchBend = function(pitchBend) {}; /** * Sets the octave/range of this oscillator. * @param {!doodle.moog.OscillatorInterface.Range} range The range of this * oscillator. */ doodle.moog.OscillatorInterface.prototype.setRange = function(range) {}; /** * Turns on keyboard pitch control. */ doodle.moog.OscillatorInterface.prototype.turnOnKeyboardPitchControl = function() {}; /** * Turns off keyboard pitch control. */ doodle.moog.OscillatorInterface.prototype.turnOffKeyboardPitchControl = function() {}; /** * Turns on frequency modulation. */ doodle.moog.OscillatorInterface.prototype.turnOnFrequencyModulation = function() {}; /** * Turns off frequency modulation. */ doodle.moog.OscillatorInterface.prototype.turnOffFrequencyModulation = function() {}; /** * Sets the modulation signal level. * @param {number} modulatorLevel If a modulator, how strong the modulator * control signal should be [0..1]. */ doodle.moog.OscillatorInterface.prototype.setModulatorLevel = function(modulatorLevel) {}; /** * Turns on glide. */ doodle.moog.OscillatorInterface.prototype.turnOnGlide = function() {}; /** * Turns off glide. */ doodle.moog.OscillatorInterface.prototype.turnOffGlide = function() {}; /** * Sets the duration of gliding. * @param {number} time The time to glide between notes in seconds. */ doodle.moog.OscillatorInterface.prototype.setGlideDuration = function(time) {}; /** * Sets the note this oscillator should generate. * @param {number} note Chromatic index of the note to be played relative to the * beginning of the keyboard. */ doodle.moog.OscillatorInterface.prototype.setActiveNote = function(note) {}; /** * Sets the attack time for this oscillator's envelope generator. * @param {number} attackTime The new attack time. */ doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorAttackTime = function(attackTime) {}; /** * Sets the decay time for this oscillator's envelope generator. * @param {number} decayTime The new decay time. */ doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorDecayTime = function(decayTime) {}; /** * Sets the sustain level for this oscillator's envelope generator. * @param {number} sustainLevel The new sustain level. */ doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorSustainLevel = function(sustainLevel) {};
JavaScript
// Copyright 2012 Google Inc. 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 moog-like audio synthesizer built on top of the HTML5 Web * Audio API. */ goog.provide('doodle.moog.Synthesizer'); goog.require('doodle.moog.CompoundAudioNode'); goog.require('doodle.moog.OscillatorInterface'); goog.require('doodle.moog.SynthesizerInterface'); goog.require('goog.array'); goog.require('goog.userAgent'); /** * A Moog-like synthesizer built on top of the HTML5 Web Audio API. * @param {!AudioContext} audioContext Audio context in which this synthesizer * will operate. * @param {!Array.<!doodle.moog.Oscillator>} oscillators The oscillators used * within this synthesizer. * @param {!doodle.moog.LowPassFilter} lowPassFilter The low pass filter used * within this synthesizer. * @param {number} volume How much the gain should be adjusted. * @implements {doodle.moog.CompoundAudioNode} * @implements {doodle.moog.SynthesizerInterface} * @constructor */ doodle.moog.Synthesizer = function( audioContext, oscillators, lowPassFilter, volume) { /** * The audio context in which this synthesizer operates. * @type {!AudioContext} * @private */ this.audioContext_ = audioContext; /** * Oscillators used to generate synthesizer sounds. * @type {!Array.<!doodle.moog.Oscillator>} */ this.oscillators = oscillators; /** * Filter used to cut off high frequencies. * @type {!doodle.moog.LowPassFilter} */ this.lowPassFilter = lowPassFilter; /** * The volume Web Audio node. * @type {!AudioGainNode} * @private */ this.volumeNode_ = audioContext.createGainNode(); /** * Frequency analyser node. * @type {!RealtimeAnalyserNode} */ this.analyserNode = audioContext.createAnalyser(); this.analyserNode.smoothingTimeConstant = 0.5; /** * Volume/gain adjustment to apply to the output signal. * @type {number} * @private */ this.volume_; this.setVolume(volume); /** * Web Audio JavaScript node used by oscillators to generate sound. * Chrome 20+ won't connect a js node with no inputs for some reason. * @type {!JavaScriptAudioNode} * @private */ this.jsAudioNode_ = goog.userAgent.isVersion('20.0') ? audioContext.createJavaScriptNode( doodle.moog.Synthesizer.BUFFER_SIZE_, 1, 1) : audioContext.createJavaScriptNode( doodle.moog.Synthesizer.BUFFER_SIZE_, 0, 1); this.jsAudioNode_.onaudioprocess = goog.bind(this.fillAudioBuffer_, this); this.jsAudioNode_.connect(this.lowPassFilter.getSourceNode()); this.lowPassFilter.connect(this.volumeNode_); this.volumeNode_.connect(this.analyserNode); }; /** * How many samples to fill at a time in a JavaScript audio node callback. A * larger number here will decrease the chance of jitters/gaps at the expense of * control latency. * @type {number} * @const * @private */ doodle.moog.Synthesizer.BUFFER_SIZE_ = 1024; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setKeyDown = function(note) { goog.array.forEach(this.oscillators, function(oscillator) { oscillator.setActiveNote(note); oscillator.envelopeGenerator.startAttack(); }); this.lowPassFilter.startAttack(); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setKeyDownCallback = function(callback) { // No-op, since this is only required on non-WebAudio browsers. }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setKeyUp = function() { goog.array.forEach(this.oscillators, function(oscillator) { oscillator.envelopeGenerator.startRelease(); }); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpCutoffFrequency = function(cutoffFrequency) { this.lowPassFilter.setCutoffFrequency(cutoffFrequency); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContour = function(contour) { this.lowPassFilter.setContour(contour); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContourAttackTime = function(time) { this.lowPassFilter.setContourAttackTime(time); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContourDecayTime = function(time) { this.lowPassFilter.setContourDecayTime(time); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContourSustainLevel = function(level) { this.lowPassFilter.setContourSustainLevel(level); }; /** * Fills the passed audio buffer with tones generated by oscillators. * @param {!AudioProcessingEvent} e The audio process event object. * @private */ doodle.moog.Synthesizer.prototype.fillAudioBuffer_ = function(e) { // NOTE: We fill oscillator 2 first since it generates a modulation control // signal on which oscillators 0 and 1 depend. this.oscillators[2].fillAudioBuffer( e, null, doodle.moog.OscillatorInterface.FillMode.CLOBBER); this.oscillators[0].fillAudioBuffer( e, this.oscillators[2].modulatorSignal, doodle.moog.OscillatorInterface.FillMode.ADD); this.oscillators[1].fillAudioBuffer( e, this.oscillators[2].modulatorSignal, doodle.moog.OscillatorInterface.FillMode.MIX, this.oscillators.length); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setVolume = function(volume) { this.volume_ = volume; this.volumeNode_.gain.value = volume; }; /** @override */ doodle.moog.Synthesizer.prototype.getSourceNode = function() { return this.jsAudioNode_; }; /** @override */ doodle.moog.Synthesizer.prototype.connect = function(destination) { this.analyserNode.connect(destination); }; /** @override */ doodle.moog.Synthesizer.prototype.disconnect = function() { this.analyserNode.disconnect(); };
JavaScript
// Copyright 2012 Google Inc. 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 Attack, Decay, Sustain, Decay (ADSD) envelope generator. */ goog.provide('doodle.moog.EnvelopeGenerator'); /** * An ADSD envelope generator, used to control volume of a single synth note. * * See the Phase_ enum below for a description of how ADSD envelopes work. * * @param {number} sampleInterval How many seconds pass with each sample. * @param {number} attackTime Initial attack time in seconds. * @param {number} decayTime Initial decay time in seconds. * @param {number} sustainLevel Initial sustain level [0..1]. * @constructor */ doodle.moog.EnvelopeGenerator = function( sampleInterval, attackTime, decayTime, sustainLevel) { /** * How many seconds pass with each sample. * @type {number} * @private * @const */ this.SAMPLE_INTERVAL_ = sampleInterval; /** * The amount by which the tone associated with this envelope should be * scaled. A number in the range [0, 1]. * @type {number} * @private */ this.amplitudeCoefficient_ = 0; /** * The current phase of the envelope. * @type {!doodle.moog.EnvelopeGenerator.Phase_} * @private */ this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE; /** * The duration of the attack phase in seconds. * @type {number} * @private */ this.attackTime_ = attackTime; /** * How much the amplitude should be increased for each sample in the attack * phase. * * NOTE: This variable and other 'step' variables can be computed from other * EnvelopeGenerator state. We explicitly store these values though since * they are precisely the data needed in getNextAmplitudeCoefficient which is * typically executed in a sound buffer filling loop and therefore performance * critical. * @type {number} * @private */ this.attackStep_; /** * The duration of the decay phase in seconds. * @type {number} * @private */ this.decayTime_ = decayTime; /** * How much the amplitude should be decreased for each sample in the decay * phase. * @type {number} * @private */ this.decayStep_; /** * The sustain amplitude coefficient. * @type {number} * @private */ this.sustainLevel_ = sustainLevel; /** * How much the amplitude should be decreased for each sample in the release * phase. * @type {number} * @private */ this.releaseStep_; this.recomputePhaseSteps_(); }; /** * The different phases of an ADSD envelope. When playing a key on a synth, * these phases are always executed in the order they're defined in this enum. * * @enum {number} * @private */ doodle.moog.EnvelopeGenerator.Phase_ = { // A linear ramp up from no volume (just before a key is struck) to maximum // volume. ATTACK: 0, // A linear ramp down from maximum volume to the sustain volume level. DECAY: 1, // Once the attack and decay phases have completed, the volume at which the // note is held until the key is released. SUSTAIN: 2, // A linear ramp down from the sustain volume to no volume after a key is // released. Moog instruments uniquely reuse the decay time parameter for the // release time (hence the "ADSD" acronym instead of "ADSR"). RELEASE: 3, // Meta state indicating that the envelope is not currently active. INACTIVE: 4 }; /** * Initiates the attack phase of the envelope (e.g., when a key is pressed). */ doodle.moog.EnvelopeGenerator.prototype.startAttack = function() { this.recomputePhaseSteps_(); this.amplitudeCoefficient_ = 0; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.ATTACK; }; /** * Initiates the release phase of the envelope (e.g., when a key is lifted). */ doodle.moog.EnvelopeGenerator.prototype.startRelease = function() { if (this.phase_ == doodle.moog.EnvelopeGenerator.Phase_.RELEASE) { return; } else { // Compute release step based on the current amplitudeCoefficient_. if (this.decayTime_ <= 0) { this.releaseStep_ = 1; } else { this.releaseStep_ = this.amplitudeCoefficient_ * this.SAMPLE_INTERVAL_ / this.decayTime_; } } this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.RELEASE; }; /** * Gets the next amplitude coefficient that should be applied to the currently * playing note. This method must be called (and applied, natch) for each * sample filled for the duration of a note. * * @return {number} An amplitude coefficient in the range [0, 1] that should be * applied to the current sample. */ doodle.moog.EnvelopeGenerator.prototype.getNextAmplitudeCoefficient = function() { switch (this.phase_) { case doodle.moog.EnvelopeGenerator.Phase_.ATTACK: this.amplitudeCoefficient_ += this.attackStep_; if (this.amplitudeCoefficient_ >= 1) { this.amplitudeCoefficient_ = 1; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.DECAY; } break; case doodle.moog.EnvelopeGenerator.Phase_.DECAY: this.amplitudeCoefficient_ -= this.decayStep_; if (this.amplitudeCoefficient_ <= this.sustainLevel_) { this.amplitudeCoefficient_ = this.sustainLevel_; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN; } break; case doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN: // Just stay at the sustain level until a release is signaled. break; case doodle.moog.EnvelopeGenerator.Phase_.RELEASE: this.amplitudeCoefficient_ -= this.releaseStep_; if (this.amplitudeCoefficient_ <= 0) { this.amplitudeCoefficient_ = 0; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE; } break; case doodle.moog.EnvelopeGenerator.Phase_.INACTIVE: // Stay at 0, as set in the release transition (muted). break; } return this.amplitudeCoefficient_; }; /** * Sets attack phase duration. * @param {number} time Duration of the attack phase in seconds. */ doodle.moog.EnvelopeGenerator.prototype.setAttackTime = function(time) { this.attackTime_ = time; this.recomputePhaseSteps_(); }; /** * Sets decay phase duration. * @param {number} time Duration of the decay phase in seconds. */ doodle.moog.EnvelopeGenerator.prototype.setDecayTime = function(time) { this.decayTime_ = time; this.recomputePhaseSteps_(); }; /** * Sets the sustain level. * @param {number} level The sustain level, a number in the range [0, 1]. */ doodle.moog.EnvelopeGenerator.prototype.setSustainLevel = function(level) { this.sustainLevel_ = level; this.recomputePhaseSteps_(); }; /** * Updates phase step variables to reflect current EnvelopeGenerator state. * @private */ doodle.moog.EnvelopeGenerator.prototype.recomputePhaseSteps_ = function() { if (this.attackTime_ <= 0) { this.attackStep_ = 1; } else { this.attackStep_ = this.SAMPLE_INTERVAL_ / this.attackTime_; } if (this.decayTime_ <= 0) { this.decayStep_ = 1; this.releaseStep_ = 1; } else { this.decayStep_ = (1 - this.sustainLevel_) * this.SAMPLE_INTERVAL_ / this.decayTime_; this.releaseStep_ = this.sustainLevel_ * this.SAMPLE_INTERVAL_ / this.decayTime_; } };
JavaScript
// Copyright 2012 Google Inc. 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 Interface for compound Web Audio audio nodes. */ goog.provide('doodle.moog.CompoundAudioNode'); /** * Connection interface for compound Web Audio nodes. * @interface */ doodle.moog.CompoundAudioNode = function() {}; /** * Gets the source node for this compound node. * @return {!AudioNode} The input/source node for this compound node. */ doodle.moog.CompoundAudioNode.prototype.getSourceNode = function() {}; /** * Connects this compound node to a destination audio node. * @param {!AudioNode} destination The destination to connect this node to. */ doodle.moog.CompoundAudioNode.prototype.connect = function(destination) {}; /** * Disconnects this compound node from any destination audio node. */ doodle.moog.CompoundAudioNode.prototype.disconnect = function() { };
JavaScript
// Copyright 2012 Google Inc. 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 moog-like audio synthesizer built on top of the HTML5 Web * Audio API. */ goog.provide('doodle.moog.SynthesizerInterface'); /** * A Moog-like synthesizer built on top of the HTML5 Web Audio API. * @interface */ doodle.moog.SynthesizerInterface = function() {}; /** * Signals that a key on the synthesizer has been pressed. * @param {number} note Chromatic index of the note to be played relative to * the beginning of the keyboard. */ doodle.moog.SynthesizerInterface.prototype.setKeyDown = function(note) {}; /** * Binds a callback to a key down event. * @param {function(number)} callback The function called when a key is pressed. */ doodle.moog.SynthesizerInterface.prototype.setKeyDownCallback = function(callback) {}; /** * Signals that a key on the synthesizer has been released. Since the * synthesizer is monophonic, no note parameter is necessary. */ doodle.moog.SynthesizerInterface.prototype.setKeyUp = function() {}; /** * Increases/decreases the output gain. * @param {number} volume The output volume level. A number in the range * [0..1]. */ doodle.moog.SynthesizerInterface.prototype.setVolume = function(volume) {}; /** * Proxy to the synthesizer's low-pass filter setCutoffFrequency. * @param {number} cutoffFrequency The cutoff frequency above which the * frequencies are attenuated. */ doodle.moog.SynthesizerInterface.prototype.setLpCutoffFrequency = function(cutoffFrequency) {}; /** * Proxy to the synthesizer's low-pass filter setContour. * @param {number} contour Amount of contour to apply to the filter envelope. */ doodle.moog.SynthesizerInterface.prototype.setLpContour = function(contour) {}; /** * Proxy to the synthesizer's low-pass filter setContourAttackTime. * @param {number} time Duration of the attack phase in seconds. */ doodle.moog.SynthesizerInterface.prototype.setLpContourAttackTime = function(time) {}; /** * Proxy to the synthesizer's low-pass filter setContourDecayTime. * @param {number} time Duration of the decay phase in seconds. */ doodle.moog.SynthesizerInterface.prototype.setLpContourDecayTime = function(time) {}; /** * Proxy to the synthesizer's low-pass filter setContourSustainLevel. * @param {number} level The sustain level, a number in the range [0, 1]. */ doodle.moog.SynthesizerInterface.prototype.setLpContourSustainLevel = function(level) {};
JavaScript
// Copyright 2012 Google Inc. 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 Voltage controlled oscillator emulators. */ goog.provide('doodle.moog.Oscillator'); goog.require('doodle.moog.EnvelopeGenerator'); goog.require('doodle.moog.OscillatorInterface'); /** * A voltage controlled oscillator emulator built on the HTML5 Audio API. This * is the root source of all sound in the Moog doodle. * * @param {!AudioContext} audioContext Audio context to which this oscillator * will be bound. * @param {number} volume Initial volume level [0..1]. * @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm Initial wave * form. * @param {!doodle.moog.OscillatorInterface.Range} range Initial pitch range. * @param {number} pitchBend Initial pitch bend [-1..1]. * @param {boolean} isAcceptingKeyboardPitch Whether keyboard control is on. * @param {boolean} isFrequencyModulationOn Whether this oscillator should * modulate its frequency using the modulator control signal. * @param {boolean} isModulator Whether this modulator should act as a modulator * control signal in addition to an audio signal. * @param {number} modulatorLevel If a modulator, how strong the modulator * control signal should be [0..1]. * @param {boolean} isGlideOn Whether glide is on. * @param {number} glideTime Glide time in seconds. * @param {number} attackTime Initial attack time in seconds. * @param {number} decayTime Initial decay time in seconds. * @param {number} sustainLevel Initial sustain level [0..1]. * @constructor * @implements {doodle.moog.OscillatorInterface} */ doodle.moog.Oscillator = function( audioContext, volume, waveForm, range, pitchBend, isAcceptingKeyboardPitch, isFrequencyModulationOn, isModulator, modulatorLevel, isGlideOn, glideTime, attackTime, decayTime, sustainLevel) { /** * How many seconds pass with each sample. * @type {number} * @private * @const */ this.SAMPLE_INTERVAL_ = 1 / audioContext.sampleRate; /** * How many seconds we have advanced in the current cycle. * @type {number} * @private */ this.phase_ = 0.0; /** * The amount of oscillator signal which is fed into the mixer. Mapped onto * the range [0.0, 1.0] where 0 means muted and 1.0 means full loudness. * @type {number} * @private */ this.volume_ = volume; /** * Shape of the wave this oscillator generates. * @type {!doodle.moog.OscillatorInterface.WaveForm} * @private */ this.waveForm_ = waveForm; /** * Octave/range in which the oscillator functions. * @type {!doodle.moog.OscillatorInterface.Range} * @private */ this.range_ = range; /** * Pitch bend to apply on top of the base frequency on the range [-1.0, 1.0]. * If isAcceptingKeyboardPitch_ is true, -1/1 are a major 6th down/up; 0 is no * pitch bend. If isAcceptingKeyboardPitch_ is false, -1/1 are 3 octaves * down/up; 0 is still no pitch bend. * @type {number} * @private */ this.pitchBend_ = pitchBend; /** * Whether the oscillator pitch is controlled by keyboard signals. If true, * the pitch follows the keyboard as one would expect on a piano-like * instrument. If false, pressing any key on the keyboard will result in the * same pitch (as set by range_ and pitchBend_). * @type {boolean} * @private */ this.isAcceptingKeyboardPitch_ = isAcceptingKeyboardPitch; /** * Whether this oscillator should modulate its frequency using the modulator * control signal. * @type {boolean} * @private */ this.isFrequencyModulationOn_ = isFrequencyModulationOn; /** * Whether this modulator should act as a modulator control signal in addition * to an audio signal. * @type {boolean} * @const * @private */ this.IS_MODULATOR_ = isModulator; /** * If this oscillator is also a modulator, how strong the modulator control * signal should be [0..1]. 0 fully attenuates the control signal; 1 fully * applies it. * @type {number} * @private */ this.modulatorLevel_ = modulatorLevel; /** * If this oscillator is also a modulator, a buffer for storing modulator * control signal samples. Null iff this oscillator does not act as a * modulator. * @type {Float32Array} */ this.modulatorSignal = null; /** * Whether glide (portamento sliding between notes) is enabled. * @type {boolean} * @private */ this.isGlideOn_ = isGlideOn; /** * Glide duration in seconds. * @type {number} * @private */ this.glideDuration_ = glideTime; /** * How much to advanced the frequency per sample while gliding. Null until * the first tone is played. * @type {?number} * @private */ this.glideDelta_ = null; /** * Current glide pitch. Null until the first tone is played. * @type {?number} * @private */ this.currentGlidePitch_ = null; /** * Target glide pitch. Null until the first tone is played. * @type {?number} * @private */ this.targetGlidePitch_ = null; /** * Chromatic index of the note to be played relative to the beginning of the * keyboard. * @type {number} * @private */ this.activeNote_ = 0; /** * Envelope generator that will shape the dynamics of this oscillator. * @type {!doodle.moog.EnvelopeGenerator} */ this.envelopeGenerator = new doodle.moog.EnvelopeGenerator( this.SAMPLE_INTERVAL_, attackTime, decayTime, sustainLevel); }; /** * The base frequency (in hertz) from which other notes' frequencies are * calculated. A low 'A'. * @type {number} * @const * @private */ doodle.moog.Oscillator.BASE_FREQUENCY_ = 55; /** * Frequency ratio of major sixth musical interval. * @type {number} * @const * @private */ doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_ = 5 / 3; /** * Frequency ratio of a three octave musical interval. * @type {number} * @const * @private */ doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_ = 8; /** * The chromatic distance between keyboard notes (as passed to * getInstantaneousFrequency_) and low A. * @type {number} * @const * @private */ doodle.moog.Oscillator.NOTE_OFFSET_ = -4; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setVolume = function(volume) { this.volume_ = volume; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setWaveForm = function(waveForm) { this.waveForm_ = waveForm; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setPitchBend = function(pitchBend) { this.pitchBend_ = pitchBend; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setRange = function(range) { this.range_ = range; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOnKeyboardPitchControl = function() { this.isAcceptingKeyboardPitch_ = true; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOffKeyboardPitchControl = function() { this.isAcceptingKeyboardPitch_ = false; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOnFrequencyModulation = function() { this.isFrequencyModulationOn_ = true; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOffFrequencyModulation = function() { this.isFrequencyModulationOn_ = false; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setModulatorLevel = function(modulatorLevel) { this.modulatorLevel_ = modulatorLevel; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOnGlide = function() { this.isGlideOn_ = true; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOffGlide = function() { this.isGlideOn_ = false; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setGlideDuration = function(time) { this.glideDuration_ = time; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setActiveNote = function(note) { this.activeNote_ = note; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setEnvelopeGeneratorAttackTime = function(attackTime) { this.envelopeGenerator.setAttackTime(attackTime); }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setEnvelopeGeneratorDecayTime = function(decayTime) { this.envelopeGenerator.setDecayTime(decayTime); }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setEnvelopeGeneratorSustainLevel = function(sustainLevel) { this.envelopeGenerator.setSustainLevel(sustainLevel); }; /** * Gets the instantaneous frequency that this oscillator ought to be generating. * @param {number} note Chromatic index of the note to be played relative to * the beginning of the keyboard. * @return {number} The instantaneous frequency. * @private */ doodle.moog.Oscillator.prototype.getInstantaneousFrequency_ = function(note) { if (!this.isAcceptingKeyboardPitch_) { note = 0; } return doodle.moog.Oscillator.BASE_FREQUENCY_ * this.range_ * Math.pow(2, (note + doodle.moog.Oscillator.NOTE_OFFSET_) / 12); }; /** * Gets the pitch bend that should be applied to this oscillator. * @return {number} The frequency ratio that should be applied to the base * pitch. * @private */ doodle.moog.Oscillator.prototype.getPitchBend_ = function() { var pitchBendScale = doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_; if (!this.isAcceptingKeyboardPitch_) { pitchBendScale = doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_; } var normalizedPitchBend = Math.abs(this.pitchBend_ * (pitchBendScale - 1)) + 1; return this.pitchBend_ >= 0 ? normalizedPitchBend : 1 / normalizedPitchBend; }; /** * Gets the frequency this oscillator ought to generate after undergoing * optional glide. * @param {number} target The target frequency to move towards. * @return {number} The frequency this oscillator should generate with glide. * @private */ doodle.moog.Oscillator.prototype.getGlideFrequency_ = function(target) { if (!this.isGlideOn_ || this.currentGlidePitch_ === null || this.glideDuration_ <= 0 || Math.abs(this.currentGlidePitch_ - target) <= Math.abs(this.glideDelta_)) { this.currentGlidePitch_ = this.targetGlidePitch_ = target; return target; } if (this.targetGlidePitch_ != target) { var glideDurationInSamples = this.glideDuration_ / this.SAMPLE_INTERVAL_; this.glideDelta_ = (target - this.currentGlidePitch_) / glideDurationInSamples; this.targetGlidePitch_ = target; } this.currentGlidePitch_ += this.glideDelta_; return this.currentGlidePitch_; }; /** * Gets the frequency this oscillator ought to generate after undergoing * optional frequency modulation. * @param {number} baseFrequency The base frequency to modulate. * @param {Float32Array} modulatorSignal Modulator signal buffer to apply to * this oscillator. If null, no modulation should be applied. * @param {number} index Sample index of the modulation signal to apply. * @return {number} The frequency this oscillator should generate with * modulation. * @private */ doodle.moog.Oscillator.prototype.getModulationFrequency_ = function( baseFrequency, modulatorSignal, index) { if (!modulatorSignal || !this.isFrequencyModulationOn_) { return baseFrequency; } // Linearly project modulation level [0..1] onto [0.5..2] (down/up an octave). // TODO: Re-evaluate this maximum frequency modulation range based on real // Moog behavior. return (modulatorSignal[index] * 0.75 + 1.25) * baseFrequency; }; /** * Advances the oscillator's phase of play. This helper function must be called * exactly once per sample. * @param {number} frequency The frequency being played. * @return {number} Progress made in the current cycle, projected on the range * [0, 1]. * @private */ doodle.moog.Oscillator.prototype.advancedPhase_ = function(frequency) { var cycleLengthInSeconds = 2 / frequency; if (this.phase_ > cycleLengthInSeconds) { this.phase_ -= cycleLengthInSeconds; } var progressInCycle = this.phase_ * frequency / 2; this.phase_ += this.SAMPLE_INTERVAL_; return progressInCycle; }; /** * Fills the passed audio buffer with the tone represented by this oscillator. * @param {!AudioProcessingEvent} e The audio process event object. * @param {Float32Array} modulatorSignal Modulator signal buffer to apply to * this oscillator. If null, no modulation will be applied. * @param {!doodle.moog.OscillatorInterface.FillMode} fillMode How the * oscillator should fill the passed audio buffer. * @param {number=} opt_mixDivisor Iff using FillMode.MIX, how much to mix down * the buffer. This should usually be the number of oscillators that have * added data to the buffer. */ doodle.moog.Oscillator.prototype.fillAudioBuffer = function( e, modulatorSignal, fillMode, opt_mixDivisor) { var buffer = e.outputBuffer; var left = buffer.getChannelData(1); var right = buffer.getChannelData(0); if (this.IS_MODULATOR_ && !this.modulatorSignal) { this.modulatorSignal = new Float32Array(buffer.length); } var targetFrequency = this.getInstantaneousFrequency_(this.activeNote_); var pitchBend = this.getPitchBend_(); var frequency = targetFrequency * pitchBend; var audioLevel, envelopeCoefficient, level, on, progressInCycle, ramp; for (var i = 0; i < buffer.length; ++i) { envelopeCoefficient = this.envelopeGenerator.getNextAmplitudeCoefficient(); progressInCycle = this.advancedPhase_( pitchBend * this.getModulationFrequency_( this.getGlideFrequency_(targetFrequency), modulatorSignal, i)); switch (this.waveForm_) { case doodle.moog.OscillatorInterface.WaveForm.TRIANGLE: level = 4 * ((progressInCycle > 0.5 ? 1 - progressInCycle : progressInCycle) - .25); break; case doodle.moog.OscillatorInterface.WaveForm.SAWANGLE: ramp = progressInCycle < 0.5; level = ramp ? (4 * progressInCycle - 1) : (-2 * progressInCycle + 1); break; case doodle.moog.OscillatorInterface.WaveForm.RAMP: level = 2 * (progressInCycle - 0.5); break; case doodle.moog.OscillatorInterface.WaveForm.REVERSE_RAMP: level = -2 * (progressInCycle - 0.5); break; case doodle.moog.OscillatorInterface.WaveForm.SQUARE: level = progressInCycle < 0.5 ? 1 : -1; break; case doodle.moog.OscillatorInterface.WaveForm.FAT_PULSE: level = progressInCycle < 1 / 3 ? 1 : -1; break; case doodle.moog.OscillatorInterface.WaveForm.PULSE: level = progressInCycle < 0.25 ? 1 : -1; break; } if (this.IS_MODULATOR_) { this.modulatorSignal[i] = level * this.modulatorLevel_; } audioLevel = level * this.volume_ * envelopeCoefficient; if (fillMode == doodle.moog.OscillatorInterface.FillMode.CLOBBER) { right[i] = audioLevel; } else if (fillMode == doodle.moog.OscillatorInterface.FillMode.ADD) { right[i] = right[i] + audioLevel; } else { // Otherwise FillMode.MIX. right[i] = (right[i] + audioLevel) / opt_mixDivisor; // In older versions of Chrome, Web Audio API always created two // channels even if you have requested monaural sound. However, this // is not the case in the newer (dev/canary) versions. This should // cover both. if (left) { left[i] = right[i]; } } } };
JavaScript
// Copyright 2012 Google Inc. 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 a wide band pass filter to protect headphones and * speakers from really low and high frequencies. */ goog.provide('doodle.moog.WideBandPassFilter'); goog.require('doodle.moog.CompoundAudioNode'); /** * A wide band pass filter designed to filter out low and high frequencies that * might damage poorly made speakers connected to poorly made sound cards. * @param {!AudioContext} audioContext Audio context to which this oscillator * will be bound. * @param {number} lowCutoffFrequency The cutoff frequency below which sound is * attenuated. * @param {number} highCutoffFrequency The cutoff frequency above which sound is * attenuated. * @constructor * @implements {doodle.moog.CompoundAudioNode} */ doodle.moog.WideBandPassFilter = function( audioContext, lowCutoffFrequency, highCutoffFrequency) { /** * The low pass filter Web Audio node. * @type {!BiquadFilterNode} * @private */ this.lowPassFilterNode_ = audioContext.createBiquadFilter(); this.lowPassFilterNode_.type = doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_; this.lowPassFilterNode_.frequency.value = highCutoffFrequency; /** * The high pass filter Web Audio node. * @type {!BiquadFilterNode} * @private */ this.highPassFilterNode_ = audioContext.createBiquadFilter(); this.highPassFilterNode_.type = doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_; this.highPassFilterNode_.frequency.value = lowCutoffFrequency; this.lowPassFilterNode_.connect(this.highPassFilterNode_); }; /** * Biquad Filter type ID for a low pass filter (from the Web Audio spec). * @type {number} * @const * @private */ doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0; /** * Biquad Filter type ID for a low pass filter (from the Web Audio spec). * @type {number} * @const * @private */ doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_ = 1; /** @inheritDoc */ doodle.moog.WideBandPassFilter.prototype.getSourceNode = function() { return this.lowPassFilterNode_; }; /** @inheritDoc */ doodle.moog.WideBandPassFilter.prototype.connect = function(destination) { this.highPassFilterNode_.connect(destination); }; /** @inheritDoc */ doodle.moog.WideBandPassFilter.prototype.disconnect = function() { this.highPassFilterNode_.disconnect(); };
JavaScript
// Copyright 2012 Google Inc. 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 Master mixer interface for all doodle Web Audio sources. */ goog.provide('doodle.moog.MasterMixerInterface'); /** * Master mixer for the multiple virtual synthesizers that may play back * simultaneously via the Sequencer. * @interface */ doodle.moog.MasterMixerInterface = function() {}; /** * Turns on the mixer. */ doodle.moog.MasterMixerInterface.prototype.turnOn = function() {}; /** * Turns off the mixer. */ doodle.moog.MasterMixerInterface.prototype.turnOff = function() {};
JavaScript
// Copyright 2012 Google Inc. 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 Main module for the Dr. Robert Moog Synthesizer doodle. */ goog.provide('doodle.moog.Moog'); goog.require('doodle.moog.LowPassFilter'); goog.require('doodle.moog.MasterMixer'); goog.require('doodle.moog.Oscillator'); goog.require('doodle.moog.OscillatorInterface'); goog.require('doodle.moog.Synthesizer'); goog.require('doodle.moog.WideBandPassFilter'); goog.require('goog.Disposable'); /** * The Moog doodle manager. * @constructor * @extends {goog.Disposable} */ doodle.moog.Moog = function() { goog.base(this); /** * The set of available synthesizers. * @type {!Array.<!doodle.moog.SynthesizerInterface>} * @private */ this.synthesizers_ = []; /** * A reference to a master mixer instance. * @type {!doodle.moog.MasterMixerInterface} * @private */ this.masterMixer_; /** * @private */ this.isWebAudioEnabled_ = typeof webkitAudioContext === 'function'; if (this.isWebAudioEnabled_) { this.initializeWebAudio_(); } }; goog.inherits(doodle.moog.Moog, goog.Disposable); /** @inheritDoc */ doodle.moog.Moog.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); this.turnOffAudio(); }; /** * Initializes the Moog doodle on WebAudio-compatible browsers. * @private */ doodle.moog.Moog.prototype.initializeWebAudio_ = function() { try { // Audio context creation can throw an error if the user is missing sound // drivers, etc. var audioContext = new webkitAudioContext(); } catch(e7) { // Abort the initialization sequence like we do with flash. return; } var oscillators = [ new doodle.moog.Oscillator( audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE, doodle.moog.OscillatorInterface.Range.R16, 0, true, false, false, 0, true, 0.05, 0, 0.4, 1), new doodle.moog.Oscillator( audioContext, 0.82, doodle.moog.OscillatorInterface.WaveForm.SQUARE, doodle.moog.OscillatorInterface.Range.R4, 0, true, false, false, 0, true, 0.05, 0, 0.4, 1), new doodle.moog.Oscillator( audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE, doodle.moog.OscillatorInterface.Range.R32, 0, true, false, true, 0.6, true, 0.05, 0, 0.4, 1) ]; var lowPassFilter = new doodle.moog.LowPassFilter( audioContext, 2100, 7, 0, .8, 0); this.synthesizers_.push(new doodle.moog.Synthesizer( audioContext, oscillators, lowPassFilter, 0.82)); var wideBandPassFilter = new doodle.moog.WideBandPassFilter( audioContext, 20, 20000); this.masterMixer_ = new doodle.moog.MasterMixer( audioContext, this.synthesizers_, wideBandPassFilter); }; /** * Turns on the audio pipeline. */ doodle.moog.Moog.prototype.turnOnAudio = function() { if (this.masterMixer_) { this.masterMixer_.turnOn(); } }; /** * Turns off the audio pipeline. */ doodle.moog.Moog.prototype.turnOffAudio = function() { if (this.masterMixer_) { this.masterMixer_.turnOff(); } };
JavaScript
// Copyright 2012 Google Inc. 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 Master mixer for all doodle Web Audio sources. */ goog.provide('doodle.moog.MasterMixer'); goog.require('doodle.moog.MasterMixerInterface'); /** * Master mixer for the multiple virtual synthesizers that may play back * simultaneously via the Sequencer. * @param {!AudioContext} audioContext Audio context in which this mixer will * operate. * @param {!Array.<!doodle.moog.SynthesizerInterface>} synthesizers The * synthesizers that feed into this mixer. * @param {!doodle.moog.WideBandPassFilter} wideBandPassFilter The wide band * pass filter used within this mixer. * @constructor * @implements {doodle.moog.MasterMixerInterface} */ doodle.moog.MasterMixer = function( audioContext, synthesizers, wideBandPassFilter) { /** * The audio context in which this mixer operates. * @type {!AudioContext} * @private */ this.audioContext_ = audioContext; /** * The synthesizers this mixer mixes. * @type {!Array.<!doodle.moog.Synthesizer>} * @private */ this.synthesizers_ = synthesizers; /** * Filter used to cut out really low/high frequencies. * @type {!doodle.moog.WideBandPassFilter} * @private */ this.wideBandPassFilter_ = wideBandPassFilter; for (var i = 0; i < synthesizers.length; i++) { synthesizers[i].connect(wideBandPassFilter.getSourceNode()); } }; /** @inheritDoc */ doodle.moog.MasterMixer.prototype.turnOn = function() { window.setTimeout(goog.bind(function() { // NOTE: The audio pipeline is connected in a setTimeout to avoid a Chrome // bug in which the audio will occasionally fail to initialize/play. this.wideBandPassFilter_.connect(this.audioContext_.destination); }, this), 0); }; /** @inheritDoc */ doodle.moog.MasterMixer.prototype.turnOff = function() { this.wideBandPassFilter_.disconnect(); };
JavaScript
$(document).ready(function() { $('#home-slide').cycle('fade'); });
JavaScript
/******* *** Anchor Slider by Cedric Dugas *** *** Http://www.position-absolute.com *** Never have an anchor jumping your content, slide it. Don't forget to put an id to your anchor ! You can use and modify this script for any project you want, but please leave this comment as credit. *****/ $(document).ready(function() { $("a.anchorLink").anchorAnimate() }); jQuery.fn.anchorAnimate = function(settings) { settings = jQuery.extend({ speed : 1100 }, settings); return this.each(function(){ var caller = this $(caller).click(function (event) { event.preventDefault() var locationHref = window.location.href var elementClick = $(caller).attr("href") var destination = $(elementClick).offset().top; $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() { window.location.hash = elementClick }); return false; }) }) }
JavaScript
$(document).ready(function() { $('#home-slide').cycle('fade'); });
JavaScript
/******* *** Anchor Slider by Cedric Dugas *** *** Http://www.position-absolute.com *** Never have an anchor jumping your content, slide it. Don't forget to put an id to your anchor ! You can use and modify this script for any project you want, but please leave this comment as credit. *****/ $(document).ready(function() { $("a.anchorLink").anchorAnimate() }); jQuery.fn.anchorAnimate = function(settings) { settings = jQuery.extend({ speed : 1100 }, settings); return this.each(function(){ var caller = this $(caller).click(function (event) { event.preventDefault() var locationHref = window.location.href var elementClick = $(caller).attr("href") var destination = $(elementClick).offset().top; $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() { window.location.hash = elementClick }); return false; }) }) }
JavaScript
$(document).ready(function() { $('#home-slide').cycle('fade'); });
JavaScript
/******* *** Anchor Slider by Cedric Dugas *** *** Http://www.position-absolute.com *** Never have an anchor jumping your content, slide it. Don't forget to put an id to your anchor ! You can use and modify this script for any project you want, but please leave this comment as credit. *****/ $(document).ready(function() { $("a.anchorLink").anchorAnimate() }); jQuery.fn.anchorAnimate = function(settings) { settings = jQuery.extend({ speed : 1100 }, settings); return this.each(function(){ var caller = this $(caller).click(function (event) { event.preventDefault() var locationHref = window.location.href var elementClick = $(caller).attr("href") var destination = $(elementClick).offset().top; $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() { window.location.hash = elementClick }); return false; }) }) }
JavaScript
function getVal(id) { return $("#" + id).val(); } function getAttr(id, attr) { return $("#" + id).attr(attr) } /**//************************************************************************ | 函数名称: setCookie | | 函数功能: 设置cookie函数 | | 入口参数: name:cookie名称;value:cookie值 | | 维护记录: Spark(创建) | *************************************************************************/ function setCookie(name, value) { var argv = setCookie.arguments; var argc = setCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; if (expires != null) { var LargeExpDate = new Date(); LargeExpDate.setTime(LargeExpDate.getTime() + (expires * 1000 * 3600 * 24)); } document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + LargeExpDate .toGMTString())); } /**//************************************************************************ | 函数名称: getCookie | | 函数功能: 读取cookie函数 | | 入口参数: Name:cookie名称 | | 维护记录: Spark(创建) | *************************************************************************/ function getCookie(Name) { var search = Name + "=" if (document.cookie.length > 0) { offset = document.cookie.indexOf(search) if (offset != -1) { offset += search.length end = document.cookie.indexOf(";", offset) if (end == -1) end = document.cookie.length return unescape(document.cookie.substring(offset, end)) } else return "" } } /**//************************************************************************ | 函数名称: deleteCookie | | 函数功能: 删除cookie函数 | | 入口参数: Name:cookie名称 | | 维护记录: Spark(创建) | *************************************************************************/ function deleteCookie(name) { var expdate = new Date(); expdate.setTime(expdate.getTime() - (86400 * 1000 * 1)); setCookie(name, "", expdate); }
JavaScript
/** * */
JavaScript
/** * */ colors = Array("#ffb","#fbf","#bff","#6ff","#ff6","#f6f","#6ff"); color = 0; $(document).ready(function() { $(".component").hover(function() { $("#"+$(this).children(".position").text()).addClass("myhover"); //$("#"+$(this).attr("value")).css("color","#fff"); },function() { $("#"+$(this).children(".position").text()).removeClass("myhover"); }); $(".component").click(function() { if($(this).hasClass("mystayhover")) { $(this).removeClass("mystayhover"); text = $(this).children(".position").text(); rem = true; $(".mystayhover").each(function() { if($(this).children(".position").text() == text) rem = false; }); if(rem) $("#"+$(this).children(".position").text()).removeClass("mystayhover"); }else { $(this).addClass("mystayhover"); $("#"+$(this).children(".position").text()).addClass("mystayhover"); } }); $(".box").hover(function() { id = $(this).attr("id"); $(".position").each(function() { if($(this).text() == id) { $(this).parent().addClass("myhover"); } }); },function() { $(".position").each(function() { if($(this).text() == id) { $(this).parent().removeClass("myhover"); } }); }); $(".box").click(function() { if($(this).hasClass("mystayhover")) { $(this).removeClass("mystayhover"); id = $(this).attr("id"); $(".position").each(function() { if($(this).text() == id) { $(this).parent().removeClass("mystayhover"); } }); }else { $(this).addClass("mystayhover"); id = $(this).attr("id"); $(".position").each(function() { if($(this).text() == id) { $(this).parent().addClass("mystayhover"); } }); } }); registNumOpera(); $(".box").dblclick(function() { self.location = "./addcomp.php?position=" + $(this).text(); }); }); function registNumOpera() { // TODO 添加数量增减支持 $(".comPlus").click(function() { self = $(this); $.post("function.php",{ id:$(this).parent().parent().attr("value"), func:"addNum" },function(data) { self.parent().html(data + "<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" />"); registNumOpera(); }); }); $(".comMinus").click(function() { self = $(this); $.post("function.php",{ id:$(this).parent().parent().attr("value"), func:"minNum" },function(data) { if(data == 0) { self.parent().parent().remove(); } else { self.parent().html(data + "<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" />"); registNumOpera(); } }); }); }
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. /* prop = { header, // String property, // String events, // type, // checkbox, select, input.type, button extra // depend on type } */ function List(config) { this.config = config; this.props = config.props; this.main = config.main; this.selectedLine = -2; this.lines = []; if (!config.getItems) { config.getItems = function() { return config.items; } } if (!config.getItemProp) { config.getItemProp = function(id, prop) { return config.getItem(id)[prop]; } } if (!config.setItemProp) { config.setItemProp = function(id, prop, value) { config.getItem(id)[prop] = value; } } if (!config.getItem) { config.getItem = function(id) { return config.getItems()[id]; } } if (!config.move) { config.move = function(a, b) { if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) { var list = config.getItems(); var tmp = list[a]; // remove a list.splice(a, 1); // insert b list.splice(b, 0, tmp); } } }; if (!config.insert) { config.insert = function(id, newItem) { config.getItems().splice(id, 0, newItem); } } if (!config.remove) { config.remove = function(a) { config.move(a, config.count() - 1); config.getItems().pop(); } } if (!config.validate) { config.validate = function() {return true;}; } if (!config.count) { config.count = function() { return config.getItems().length; } } if (!config.patch) { config.patch = function(id, newVal) { for (var name in newVal) { config.setItemProp(id, name, newVal[name]); } } } if (!config.defaultValue) { config.defaultValue = {}; } config.main.addClass('list'); } List.ids = { noline: -1, }; List.types = {}; List.prototype = { init: function() { with (this) { if (this.inited) { return; } this.inited = true; this.headergroup = $('<div class="headers"></div>'); for (var i = 0; i < props.length; ++i) { var header = $('<div class="header"></div>'). attr('property', props[i].property).html(props[i].header); headergroup.append(header); } this.scrolls = $('<div>').addClass('listscroll'); this.contents = $('<div class="listitems"></div>').appendTo(scrolls); scrolls.scroll(function() { headergroup.css('left', -(scrolls.scrollLeft()) + 'px'); }); contents.click(function(e) { if (e.target == contents[0]) { selectLine(List.ids.noline); } }); $(main).append(headergroup).append(scrolls); var height = this.main.height() - this.headergroup.outerHeight(); this.scrolls.height(height); load(); selectLine(List.ids.noline); } }, editNewLine: function() { this.startEdit(this.lines[this.lines.length - 1]); }, updatePropDisplay : function(line, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var id = Number(line.attr('row')); if (id == this.config.count()) { var value = this.config.defaultValue[name]; if (value) { ctrl.value = value; } obj.trigger('createNew'); } else { ctrl.value = this.config.getItemProp(id, name); obj.trigger('update'); } }, updateLine: function(line) { for (var i = 0; i < this.props.length; ++i) { this.updatePropDisplay(line, this.props[i]); } if (Number(line.attr('row')) < this.config.count()) { line.trigger('update'); } else { line.addClass('newline'); } }, createLine: function() { with (this) { var line = $('<div></div>').addClass('itemline'); var inner = $('<div>'); line.append(inner); // create input boxes for (var i = 0; i < props.length; ++i) { var prop = props[i]; var ctrl = $('<div></div>').attr('property', prop.property) .addClass('listvalue').attr('tabindex', -1); var valueobj = new List.types[prop.type](ctrl, prop); var data = {list: this, line: line, prop: prop}; for (var e in prop.events) { ctrl.bind(e, data, prop.events[e]); } ctrl.bind('change', function(e) { validate(line); return true; }); ctrl.bind('keyup', function(e) { if (e.keyCode == 27) { cancelEdit(line); } }); ctrl.trigger('create'); inner.append(ctrl); } // Event listeners line.click(function(e) { startEdit(line); }); line.focusin(function(e) { startEdit(line); }); line.focusout(function(e) { finishEdit(line); }); for (var e in this.config.lineEvents) { line.bind(e, {list: this, line: line}, this.config.lineEvents[e]); } var list = this; line.bind('updating', function() { $(list).trigger('updating'); }); line.bind('updated', function() { $(list).trigger('updated'); }); this.bindId(line, this.lines.length); this.lines.push(line); line.appendTo(this.contents); return line; } }, refresh: function(lines) { var all = false; if (lines === undefined) { all = true; lines = []; } for (var i = this.lines.length; i <= this.config.count(); ++i) { var line = this.createLine(); lines.push(i); } while (this.lines.length > this.config.count() + 1) { this.lines.pop().remove(); } $('.newline', this.contents).removeClass('newline'); this.lines[this.lines.length - 1].addClass('newline'); if (all) { for (var i = 0; i < this.lines.length; ++i) { this.updateLine(this.lines[i]); } } else { for (var i = 0; i < lines.length; ++i) { this.updateLine(this.lines[lines[i]]); } } }, load: function() { this.contents.empty(); this.lines = []; this.refresh(); }, bindId: function(line, id) { line.attr('row', id); }, getLineNewValue: function(line) { var ret = {}; for (var i = 0; i < this.props.length; ++i) { this.getPropValue(line, ret, this.props[i]); } return ret; }, getPropValue: function(line, item, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var value = ctrl.value; if (value !== undefined) { item[name] = value; } return value; }, startEdit: function(line) { if (line.hasClass('editing')) { return; } line.addClass('editing'); this.showLine(line); this.selectLine(line); var list = this; setTimeout(function() { if (!line[0].contains(document.activeElement)) { $('.valinput', line).first().focus(); } list.validate(line); }, 50); }, finishEdit: function(line) { var list = this; function doFinishEdit() { with(list) { if (line[0].contains(document.activeElement)) { return; } var valid = isValid(line); if (valid) { var id = Number(line.attr('row')); var newval = getLineNewValue(line); if (line.hasClass('newline')) { $(list).trigger('updating'); if(!config.insert(id, newval)) { line.removeClass('newline'); list.selectLine(line); $(list).trigger('add', id); addNewLine(); } } else { line.trigger('updating'); config.patch(id, newval); } line.trigger('updated'); } cancelEdit(line); } }; setTimeout(doFinishEdit, 50); }, cancelEdit: function(line) { line.removeClass('editing'); line.removeClass('error'); var id = Number(line.attr('row')); if (id == this.config.count() && this.selectedLine == id) { this.selectedLine = List.ids.noline; } this.updateLine(line); }, addNewLine: function() { with(this) { var line = $('.newline', contents); if (!line.length) { line = createLine().addClass('newline'); } return line; } }, isValid: function(line) { var id = Number(line.attr('row')); var obj = this.getLineNewValue(line); return valid = this.config.validate(id, obj); }, validate: function(line) { if (this.isValid(line)) { line.removeClass('error'); } else { line.addClass('error'); } }, move: function(a, b, keepSelect) { var len = this.config.count(); if (a == b || a < 0 || b < 0 || a >= len || b >= len) { return; } this.config.move(a, b); for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) { this.updateLine(this.getLine(i)); } if (keepSelect) { if (this.selectedLine == a) { this.selectLine(b); } else if (this.selectedLine == b) { this.selectLine(a); } } }, getLine: function(id) { if (id < 0 || id >= this.lines.length) { return null; } return this.lines[id]; }, remove: function(id) { id = Number(id); if (id < 0 || id >= this.config.count()) { return; } $(this).trigger('updating'); var len = this.lines.length; this.getLine(id).trigger('removing'); if (this.config.remove(id)) { return; } this.getLine(len - 1).remove(); this.lines.pop(); for (var i = id; i < len - 1; ++i) { this.updateLine(this.getLine(i)); } if (id >= len - 2) { this.selectLine(id); } else { this.selectLine(List.ids.noline); } $(this).trigger('updated'); }, selectLine: function(id) { var line = id; if (typeof id == "number") { line = this.getLine(id); } else { id = Number(line.attr('row')); } // Can't select the new line. if (line && line.hasClass('newline')) { line = null; id = List.ids.noline; } if (this.selectedLine == id) { return; } var oldline = this.getLine(this.selectedLine); if (oldline) { this.cancelEdit(oldline); oldline.removeClass('selected'); oldline.trigger('deselect'); this.selectedLine = List.ids.noline; } this.selectedLine = id; if (line != null) { line.addClass('selected'); line.trigger('select'); this.showLine(line); } $(this).trigger('select'); }, showLine: function(line) { var showtop = this.scrolls.scrollTop(); var showbottom = showtop + this.scrolls.height(); var top = line.offset().top - this.contents.offset().top; // Include the scroll bar var bottom = top + line.height() + 20; if (top < showtop) { // show at top this.scrolls.scrollTop(top); } else if (bottom > showbottom) { // show at bottom this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height())); } } };
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var baseDir = '/setting/'; var rules = []; var scripts = []; var issues = []; var dirty = false; function stringHash(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { ch = str.charCodeAt(i); hash = ((hash << 5) - hash) + ch; hash = hash & hash; // Convert to 32bit integer } return hash; } function setScriptAutoComplete(e) { var last = /[^\s]*$/; var obj = $('input', e.target); $(obj).bind("keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function(request, response) { // delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( scriptItems, last.exec(request.term)[0])); }, focus: function() { // prevent value inserted on focus return false; }, select: function(event, ui) { this.value = this.value.replace(last, ui.item.value); return false; } }); } var ruleProps = [ { header: "Identifier", property: "identifier", type: "input" }, { header: "Name", property: "title", type: "input" }, { header: "Mode", property: "type", type: "select", option: "static", options: [ {value: "wild", text: "WildChar"}, {value: "regex", text: "RegEx"}, {value: "clsid", text: "CLSID"} ] }, { header: "Pattern", property: "value", type: "input" }, { header: "Keyword", property: "keyword", type: "input" }, { header: "testURL", property: "testUrl", type: "input" }, { header: "UserAgent", property: "userAgent", type: "select", option: "static", options: [ {value: "", text: "Chrome"}, {value: "ie9", text: "MSIE9"}, {value: "ie8", text: "MSIE8"}, {value: "ie7", text: "MSIE7"}, {value: "ff7win", text: "Firefox 7 Windows"}, {value: "ff7mac", text: "Firefox 7 Mac"}, {value: "ip5", text: "iPhone"}, {value: "ipad5", text: "iPad"} ] }, { header: "Helper Script", property: "script", type: "input", events: { create: setScriptAutoComplete } }]; var currentScript = -1; function showScript(id) { var url = baseDir + scripts[id].url; currentScript = id; $(scriptEditor).val(''); $.ajax(url, { success: function(value) { origScript = value; $(scriptEditor).val(value); } }); $('#scriptDialog').dialog('open'); } function saveToFile(file, value) { $.ajax(baseDir + 'upload.php', { type: "POST", data: { file: file, data: value } }); } var checksumComputing = 0; function computeScriptChecksum(id) { scripts[id].checksum = "computing"; ++checksumComputing; scriptList.updateLine(scriptList.lines[id]); $.ajax(baseDir + scripts[id].url, { complete: function() { --checksumComputing; }, dataType: "text", success: function(value, status, xhr) { scripts[id].checksum = stringHash(value); scriptList.updateLine(scriptList.lines[id]); } }); } var origScript; function saveScript(id) { var value = $('#scriptEditor').val(); if (value == origScript) { return; } var file = scripts[id].url; ++scripts[id].version; scriptList.updateLine(scriptList.getLine(id)); saveToFile(file, value); dirty = true; } var scriptProps = [{ property: "identifier", header: "Identifier", type: "input" }, { property: "url", header: "URL", type: "input" }, { property: "version", header: "Version", type: "input" }, { property: "context", header: "Context", type: "select", option: "static", options: [ {value: "page", text: "Page"}, {value: "extension", text: "Extension"} ] }, { property: "show", header: "Show", type: "button", events: { create: function(e) { $('button', this).text('Show'); }, command: function(e) { showScript(Number(e.data.line.attr('row')), true); } } }, { property: "checksum", header: "checksum", type: "input", events: { "create": function(e) { $(this).addClass('readonly'); } } }, { property: "compute", header: "Checksum", type: "button", events: { create: function(e) { $('button', this).text('Recompute'); }, command: function(e) { computeScriptChecksum(Number(e.data.line.attr('row'))); } } }]; var issueProps = [{ header: "Identifier", property: "identifier", type: "input" }, { header: "Mode", property: "type", type: "select", option: "static", options: [ {value: "wild", text: "WildChar"}, {value: "regex", text: "RegEx"}, {value: "clsid", text: "CLSID"} ] }, { header: "Pattern", property: "value", type: "input" }, { header: "Description", property: "description", type: "input" }, { header: "IssueId", property: "issueId", type: "input" }, { header: "url", property: "url", type: "input" }]; // The JSON formatter is from http://joncom.be/code/javascript-json-formatter/ function FormatJSON(oData, sIndent) { function RealTypeOf(v) { if (typeof(v) == "object") { if (v === null) return "null"; if (v.constructor == Array) return "array"; if (v.constructor == Date) return "date"; if (v.constructor == RegExp) return "regex"; return "object"; } return typeof(v); } if (arguments.length < 2) { var sIndent = ""; } var sIndentStyle = " "; var sDataType = RealTypeOf(oData); // open object if (sDataType == "array") { if (oData.length == 0) { return "[]"; } var sHTML = "["; } else { var iCount = 0; $.each(oData, function() { iCount++; return; }); if (iCount == 0) { // object is empty return "{}"; } var sHTML = "{"; } // loop through items var iCount = 0; $.each(oData, function(sKey, vValue) { if (iCount > 0) { sHTML += ","; } if (sDataType == "array") { sHTML += ("\n" + sIndent + sIndentStyle); } else { sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": "); } // display relevant data type switch (RealTypeOf(vValue)) { case "array": case "object": sHTML += FormatJSON(vValue, (sIndent + sIndentStyle)); break; case "boolean": case "number": sHTML += vValue.toString(); break; case "null": sHTML += "null"; break; case "string": sHTML += ("\"" + vValue + "\""); break; default: sHTML += JSON.stringify(vValue); } // loop iCount++; }); // close object if (sDataType == "array") { sHTML += ("\n" + sIndent + "]"); } else { sHTML += ("\n" + sIndent + "}"); } // return return sHTML; } function loadRules(value) { rules = []; for (var i in value) { rules.push(value[i]); } ruleList.refresh(); freezeIdentifier(ruleList); } function loadIssues(value) { issues = []; for (var i in value) { issues.push(value[i]); } issueList.refresh(); freezeIdentifier(issueList); } function loadScripts(value) { scripts = []; for (var i in value) { scripts.push(value[i]); } scriptList.refresh(); freezeIdentifier(scriptList); updateScriptItems(); } function serialize(list) { var obj = {}; for (var i = 0; i < list.length; ++i) { obj[list[i].identifier] = list[i]; } return FormatJSON(obj); } function save() { saveToFile('setting.json', serialize(rules)); saveToFile('scripts.json', serialize(scripts)); saveToFile('issues.json', serialize(issues)); dirty= false; freezeIdentifier(ruleList); freezeIdentifier(scriptList); } function reload() { $.ajax(baseDir + 'setting.json', { success: loadRules }); $.ajax(baseDir + 'scripts.json', { success: loadScripts }); $.ajax(baseDir + 'issues.json', { success: loadIssues }); dirty = false; } function freezeIdentifier(list) { $('.itemline:not(.newline) div[property=identifier]', list.contents) .addClass('readonly'); } var scriptList, ruleList, issueList; var scriptItems = []; function updateScriptItems() { scriptItems = []; for (var i = 0; i < scripts.length; ++i) { scriptItems.push(scripts[i].identifier); } } $(document).ready(function() { window.onbeforeunload=function() { if (dirty) { return 'Page not saved. Continue?'; } } $('#addRule').click(function() { ruleList.editNewLine(); }).button(); $('#deleteRule').click(function() { ruleList.remove(ruleList.selectedLine); }).button(); $('#addScript').click(function() { scriptList.editNewLine(); }).button(); $('#deleteScript').click(function() { scriptList.remove(scriptList.selectedLine); }).button(); $('#compute_checkSum').click(function() { for (var i = 0; i < scripts.length; ++i) { computeScriptChecksum(i); } }).button(); $('#addIssue').click(function() { issueList.editNewLine(); }).button(); $('#deleteIssue').click(function() { issueList.remove(issueList.selectedLine); }).button(); $('.doSave').each(function() { $(this).click(save).button(); }); $('#tabs').tabs(); $('#scriptDialog').dialog({ modal: true, autoOpen: false, height: 500, width: 700, buttons: { "Save": function() { saveScript(currentScript); $(this).dialog('close'); }, "Cancel": function() { $(this).dialog('close'); } } }); $.ajaxSetup({ cache: false }); scriptList = new List({ props: scriptProps, main: $('#scriptTable'), getItems: function() {return scripts;} }); $(scriptList).bind('updated', function() { dirty = true; updateScriptItems(); }); scriptList.init(); ruleList = new List({ props: ruleProps, main: $('#ruleTable'), getItems: function() {return rules;} }); ruleList.init(); $(ruleList).bind('updated', function() { dirty = true; }); issueList = new List({ props: issueProps, main: $('#issueTable'), getItems: function() {return issues;} }); issueList.init(); $(issueList).bind('updated', function() { dirty = true; }); reload(); });
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. List.types.input = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input></input>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); this.input.focus(function(e) { input.select(); }); this.input.keypress(function(e) { p.trigger('change'); }); this.input.keyup(function(e) { p.trigger('change'); }); this.input.change(function(e) { p.trigger('change'); }); p.append(this.input).append(this.label); }; List.types.input.prototype.__defineSetter__('value', function(val) { this.input.val(val); this.label.text(val); }); List.types.input.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<select></select>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); if (prop.option == 'static') { this.loadOptions(prop.options); } var select = this; this.input.change(function(e) { if (p.hasClass('readonly')) { select.value = select.lastval; } else { p.trigger('change'); } }); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); p.append(this.input).append(this.label); }; List.types.select.prototype.loadOptions = function(options) { this.options = options; this.mapping = {}; this.input.html(""); for (var i = 0; i < options.length; ++i) { this.mapping[options[i].value] = options[i].text; var o = $('<option></option>').val(options[i].value).text(options[i].text) this.input.append(o); } } List.types.select.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input.val(val); this.label.text(this.mapping[val]); }); List.types.checkbox = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input type="checkbox">').addClass('valcheck'); var box = this; this.input.change(function(e) { if (p.hasClass('readonly')) { box.value = box.lastval; } else { p.trigger('change'); } }); p.append(this.input); }; List.types.checkbox.prototype.__defineGetter__('value', function() { return this.input[0].checked; }); List.types.checkbox.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input[0].checked = val; }); List.types.button = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<button>'); if (prop.caption) { input.text(prop.caption); } input.click(function(e) { p.trigger('command'); return false; }); p.append(this.input); }; List.types.button.prototype.__defineGetter__('value', function() { return undefined; });
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var tabStatus = {}; var version; var default_id = "lgllffgicojgllpmdbemgglaponefajn"; var debug = chrome.i18n.getMessage("@@extension_id") != default_id; var firstRun = false; var firstUpgrade = false; var blackList = [ /^https?:\/\/[^\/]*\.taobao\.com\/.*/i, /^https?:\/\/[^\/]*\.alipay\.com\/.*/i ]; var MAX_LOG = 400; (function getVersion() { $.ajax('manifest.json', { success: function (v){ v = JSON.parse(v); version = v.version; trackVersion(version); } }); })(); function startListener() { chrome.extension.onConnect.addListener(function(port) { if (!port.sender.tab) { console.error('Not connect from tab'); return; } initPort(port); }); chrome.extension.onRequest.addListener( function(request, sender, sendResponse) { if (!sender.tab) { console.error('Request from non-tab'); } else if (request.command == 'Configuration') { var config = setting.getPageConfig(request.href); sendResponse(config); if (request.top) { resetTabStatus(sender.tab.id); var dummy = {href: request.href, clsid: 'NULL'}; if (!config.pageRule && setting.getFirstMatchedRule( dummy, setting.defaultRules)) { detectControl(dummy, sender.tab.id, 0); } } //notifyUser(request, sender, config); } else { sendResponse({}); } } ); } var greenIcon = chrome.extension.getURL('icon16.png'); var grayIcon = chrome.extension.getURL('icon16-gray.png'); var errorIcon = chrome.extension.getURL('icon16-error.png'); var responseCommands = {}; function resetTabStatus(tabId) { tabStatus[tabId] = { count: 0, actived: 0, error: 0, issueId: null, logs: {"0":[]}, objs: {"0":[]}, frames: 1, tracking: false }; } function initPort(port) { var tabId = port.sender.tab.id; if (!(tabId in tabStatus)) { resetTabStatus(tabId); } var status = tabStatus[tabId]; var frameId = tabStatus[tabId].frames++; status.logs[frameId] = []; status.objs[frameId] = []; port.onMessage.addListener(function(request) { var resp = responseCommands[request.command]; if (resp) { delete request.command; resp(request, tabId, frameId); } else { console.error("Unknown command " + request.command); } }); port.onDisconnect.addListener(function() { for (var i = 0; i < status.objs[frameId].length; ++i) { countTabObject(status, status.objs[frameId][i], -1); } showTabStatus(tabId); if (status.tracking) { if (status.count == 0) { // Open the log page. window.open('log.html?tabid=' + tabId); status.tracking = false; } } else { // Clean up. status.logs[frameId] = []; status.objs[frameId] = []; } }); } chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) { if (tabStatus[tabId]) { tabStatus[tabId].removed = true; var TIMEOUT = 1000 * 60 * 5; // clean up after 5 mins. window.setTimeout(function() { delete tabStatus[tabId]; }, TIMEOUT); } }); function countTabObject(status, info, delta) { for (var i = 0; i < blackList.length; ++i) { if (info.href.match(blackList[i])) { return; } } if (info.actived) { status.actived += delta; if (delta > 0) { trackUse(info.rule); } } else if (delta > 0) { trackNotUse(info.href); } status.count += delta; var issue = setting.getMatchedIssue(info); if (issue) { status.error += delta; status.issueId = issue.identifier; if (delta > 0) { trackIssue(issue); } } } function showTabStatus(tabId) { if (tabStatus[tabId].removed) { return; } var status = tabStatus[tabId]; var title = ""; if (status.count == 0) { chrome.pageAction.hide(tabId); return; } else { chrome.pageAction.show(tabId); } chrome.pageAction.setPopup({ tabId: tabId, popup: 'popup.html?tabid=' + tabId }); if (status.count == 0) { // Do nothing.. } else if (status.error != 0) { chrome.pageAction.setIcon({ tabId: tabId, path: errorIcon }); title = $$('status_error'); } else if (status.count != status.actived) { // Disabled.. chrome.pageAction.setIcon({ tabId: tabId, path: grayIcon }); title = $$('status_disabled'); } else { // OK chrome.pageAction.setIcon({ tabId: tabId, path: greenIcon }); title = $$('status_ok'); } chrome.pageAction.setTitle({ tabId: tabId, title: title }); } function detectControl(request, tabId, frameId) { var status = tabStatus[tabId]; if (frameId != 0 && status.objs[0].length) { // Remove the item to identify the page. countTabObject(status, status.objs[0][0], -1); status.objs[0] = []; } status.objs[frameId].push(request); countTabObject(status, request, 1); showTabStatus(tabId); } responseCommands.DetectControl = detectControl; responseCommands.Log = function(request, tabId, frameId) { var logs = tabStatus[tabId].logs[frameId]; if (logs.length < MAX_LOG) { logs.push(request.message); } else if (logs.length == MAX_LOG) { logs.push('More logs clipped'); } } function generateLogFile(tabId) { var status = tabStatus[tabId]; if (!status) { return ''; } var ret = ''; ret += 'UserAgent: ' + navigator.userAgent + '\n'; ret += 'Extension version: ' + version + '\n'; ret += '\n'; for (var i = 0; i < status.frames; ++i) { if (i) { ret += '\n\n'; } ret += '------------ Frame ' + (i + 1) + ' ------------------\n'; ret += 'Objects:\n'; for (var j = 0; j < status.objs[i].length; ++j) { ret += JSON.stringify(status.objs[i][j]) + '\n'; } ret += '\n'; ret += 'Log:\n'; for (var j = 0; j < status.logs[i].length; ++j) { ret += status.logs[i][j] + '\n'; } } return ret; }
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. // Permission for experimental not given. var handler = chrome.webRequest; function onBeforeSendHeaders(details) { var rule = setting.getFirstMatchedRule( {href: details.url}, setting.cache.userAgent); if (!rule || !(rule.userAgent in agents)) { return {}; } for (var i = 0; i < details.requestHeaders.length; ++i) { if (details.requestHeaders[i].name == 'User-Agent') { details.requestHeaders[i].value = agents[rule.userAgent]; break; } } return {requestHeaders: details.requestHeaders}; } function registerRequestListener() { if (!handler) { return; } var filters = { urls: ["<all_urls>"], types: ["main_frame", "sub_frame", "xmlhttprequest"] }; try{ handler.onBeforeSendHeaders.addListener( onBeforeSendHeaders, filters, ["requestHeaders", "blocking"]); } catch (e) { console.log('Your browser doesn\'t support webRequest'); } }
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. /* Rule: { identifier: an unique identifier title: description type: Can be "wild", "regex", "clsid" value: pattern, correspond to type userAgent: the useragent value. See var "agents" for options. script: script to inject. Separated by spaces } Order: { status: enabled / disabled / custom position: default / custom identifier: identifier of rule } Issue: { type: Can be "wild", "regex", "clsid" value: pattern, correspond to type description: The description of this issue issueId: Issue ID on issue tracking page url: optional, support page for issue tracking. Use code.google.com if omitted. } ServerSide: ActiveXConfig: { version: version rules: object of user-defined rules, propertied by identifiers defaultRules: ojbect of default rules scripts: mapping of workaround scripts, by identifiers. metadatas localScripts: metadatas of local scripts. order: the order of rules cache: to accerlerate processing issues: The bugs/unsuppoted sites that we have accepted. misc:{ lastUpdate: last timestamp of updating logEnabled: log tracking: Allow GaS tracking. verbose: verbose level of logging } } PageSide: ActiveXConfig: { pageSide: Flag of pageside. pageScript: Helper script to execute on context of page extScript: Helper script to execute on context of extension pageRule: If page is matched. clsidRules: If page is not matched or disabled. valid CLSID rules logEnabled: log verbose: verbose level of logging } */ // Update per 5 hours. var DEFAULT_INTERVAL = 1000 * 3600 * 5; function ActiveXConfig(input) { var settings; if (input === undefined) { var defaultSetting = { version: 3, rules: {}, defaultRules: {}, scripts: {}, localScripts: {}, order: [], notify: [], issues: [], misc: { lastUpdate: 0, logEnabled: false, tracking: true, verbose: 3 } }; input = defaultSetting; } if (input.version == '3') { settings = input; settings.__proto__ = ActiveXConfig.prototype; } else { settings = ActiveXConfig.convertVersion(input); } settings.updateCache(); return settings; } var settingKey = 'setting'; var scriptPrefix = 'script_'; clsidPattern = /[^0-9A-F][0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}[^0-9A-F]/; var agents = { ie9: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)", ie8: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0)", ie7: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64;)", ff7win: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1", ip5: "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3", ipad5: "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3" }; function stringHash(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { ch = str.charCodeAt(i); hash = ((hash << 5) - hash) + ch; hash = hash & hash; // Convert to 32bit integer } return hash; } function getUserAgent(key) { // This script is always run under sandbox, so useragent should be always // correct. if (key == '' || !(key in agents)) { return ""; } var current = navigator.userAgent; var wow64 = current.indexOf('WOW64') >= 0; var value = agents[key]; if (!wow64) { value = value.replace(' WOW64;', ''); } return value; } ActiveXConfig.convertVersion = function(setting) { if (setting.version == 3) { return setting; } else if (setting.version == 2) { function parsePattern(pattern) { pattern = pattern.trim(); var title = pattern.match(/###(.*)/); if (title != null) { return { pattern: pattern.match(/(.*)###/)[1].trim(), title: title[1].trim() } } else { return { pattern: pattern, title: "Rule" } } } var ret = new ActiveXConfig(); if (setting.logEnabled) { ret.misc.logEnabled = true; } var urls = setting.url_plain.split('\n'); for (var i = 0; i < urls.length; ++i) { var rule = ret.createRule(); var pattern = parsePattern(urls[i]); rule.title = pattern.title; var url = pattern.pattern; if (url.substr(0, 2) == 'r/') { rule.type = 'regex'; rule.value = url.substr(2); } else { rule.type == 'wild'; rule.value = url; } ret.addCustomRule(rule, 'convert'); } var clsids = setting.trust_clsids.split('\n'); for (var i = 0; i < clsids.length; ++i) { var rule = ret.createRule(); rule.type = 'clsid'; var pattern = parsePattern(clsids[i]); rule.title = pattern.title; rule.value = pattern.pattern; ret.addCustomRule(rule, 'convert'); } firstUpgrade = true; return ret; } } ActiveXConfig.prototype = { // Only used for user-scripts shouldEnable: function(object) { if (this.pageRule) { return this.pageRule; } var clsidRule = this.getFirstMatchedRule(object, this.clsidRules); if (clsidRule) { return clsidRule; } else { return null; } }, createRule: function() { return { title: "Rule", type: "wild", value: "", userAgent: "", scriptItems: "", }; }, addCustomRule: function(newItem, auto) { if (!this.validateRule(newItem)) { return; } var identifier = this.createIdentifier(); newItem.identifier = identifier; this.rules[identifier] = newItem; this.order.push({ status: 'custom', position: 'custom', identifier: identifier }); this.update() trackAddCustomRule(newItem, auto); }, updateDefaultRules: function(newRules) { var deleteAll = false, ruleToDelete = {}; if (typeof this.defaultRules != 'object') { // There might be some errors! // Clear all defaultRules console.log('Corrupted default rules, reload all'); deleteAll = true; this.defaultRules = {}; } else { for (var i in this.defaultRules) { if (!(i in newRules)) { console.log('Remove rule ' + i); ruleToDelete[i] = true; delete this.defaultRules[i]; } } } var newOrder = []; for (var i = 0; i < this.order.length; ++i) { if (this.order[i].position == 'custom' || (!deleteAll && !ruleToDelete[this.order[i].identifier])) { newOrder.push(this.order[i]); } } this.order = newOrder; var position = 0; for (var i in newRules) { if (!(i in this.defaultRules)) { this.addDefaultRule(newRules[i], position++); } this.defaultRules[i] = newRules[i]; } }, updateConfig: function(session) { session.startUpdate(); console.log('Start updating'); var updated = { issues: false, setting: false, scripts: false }; var setting = this; session.updateFile({ url: 'setting.json', dataType: "json", success: function(nv, status, xhr) { console.log('Update default rules'); updated.setting = true; setting.updateDefaultRules(nv); if (updated.setting && updated.scripts) { setting.updateAllScripts(session); } setting.update(); } }); session.updateFile({ url: 'scripts.json', dataType: "json", success: function(nv, status, xhr) { updated.scripts = true; console.log('Update scripts'); setting.scripts = nv; if (updated.setting && updated.scripts) { setting.updateAllScripts(session); } setting.update(); } }); session.updateFile({ url: 'issues.json', dataType: "json", success: function(nv, status, xhr) { console.log('Update issues'); setting.issues = nv; setting.update(); } }); }, getPageConfig: function(href) { var ret = {}; ret.pageSide = true; ret.version = this.version; ret.verbose = this.misc.verbose; ret.logEnabled = this.misc.logEnabled; ret.pageRule = this.getFirstMatchedRule({href:href}); if (!ret.pageRule) { ret.clsidRules = this.cache.clsidRules; } else { var script = this.getScripts(ret.pageRule.script); ret.pageScript = script.page; ret.extScript = script.extension; } return ret; }, getFirstMatchedRule: function(object, rules) { var useCache = false; if (!rules) { rules = this.cache.validRules; useCache = true; } if (Array.isArray(rules)) { for (var i = 0; i < rules.length; ++i) { if (this.isRuleMatched(rules[i], object, useCache ? i : -1)) { return rules[i]; } } } else { for (var i in rules) { if (this.isRuleMatched(rules[i], object)) { return rules[i]; } } } return null; }, getMatchedIssue: function(filter) { return this.getFirstMatchedRule(filter, this.issues); }, activeRule: function(rule) { for (var i = 0; i < this.order.length; ++i) { if (this.order[i].identifier == rule.identifier) { if (this.order[i].status == 'disabled') { this.order[i].status = 'enabled'; trackAutoEnable(rule.identifier); } break; } } this.update(); }, validateRule: function(rule) { var ret = true; try { if (rule.type == 'wild') { ret &= this.convertUrlWildCharToRegex(rule.value) != null; } else if (rule.type == 'regex') { ret &= rule.value != ''; var r = new RegExp(rule.value, 'i'); } else if (rule.type == 'clsid') { var v = rule.value.toUpperCase(); if (!clsidPattern.test(v) || v.length > 55) ret = false; } } catch (e) { ret = false; } return ret; }, isRuleMatched: function(rule, object, id) { if (rule.type == "wild" || rule.type == "regex" ) { var regex; if (id >= 0) { regex = this.cache.regex[id]; } else if (rule.type == 'wild') { regex = this.convertUrlWildCharToRegex(rule.value); } else if (rule.type == 'regex') { regex = new RegExp('^' + rule.value + '$', 'i'); } if (object.href && regex.test(object.href)) { return true; } } else if (rule.type == "clsid") { if (object.clsid) { var v1 = clsidPattern.exec(rule.value.toUpperCase()); var v2 = clsidPattern.exec(object.clsid.toUpperCase()); if (v1 && v2 && v1[0] == v2[0]) { return true; } } } return false; }, getScripts: function(script) { var ret = { page: "", extension: "" }; if (!script) { return ret; } var items = script.split(' '); for (var i = 0; i < items.length; ++i) { if (items[i] == '' || !this.scripts[items[i]]) { continue; } var name = items[i]; var val = '// '; val += items[i] + '\n'; val += this.getScriptContent(name); val += '\n\n'; ret[this.scripts[name].context] += val; } return ret; }, getScriptContent: function(scriptid) { this.updateScript(scriptid, false); var local = this.localScripts[scriptid]; if (!local) { // The script not found. return ""; } var id = scriptPrefix + scriptid; return localStorage[id]; }, updateAllScripts: function(session) { console.log('updateAllScripts'); var scripts = {}; for (var i = 0; i < this.order.length; ++i) { if (this.order[i].status == 'disabled') { continue; } var rule = this.getItem(this.order[i]); var script = rule.script; if (!script) { continue; } var items = script.split(' '); for (var j = 0; j < items.length; ++j) { scripts[items[j]] = true; } } for (var i in scripts) { this.updateScript(i, true, session); } }, updateScript: function(id, async, session) { var remote = this.scripts[id]; var local = this.localScripts[id]; if (!remote || remote.updating) { return; } if (local && local.checksum == remote.checksum) { return; } remote.updating = true; var setting = this; var config = { url: remote.url + "?hash=" + remote.checksum, async: async, complete: function() { delete remote.updating; }, error: function() { console.log('Update script ' + remote.identifier + ' failed'); }, context: this, success: function(nv, status, xhr) { delete remote.updating; var hash = stringHash(nv); if (hash == remote.checksum) { localStorage[scriptPrefix + id] = nv; setting.localScripts[id] = remote; setting.save(); console.log('script updated ', id); } else { var message = 'Hashcode mismatch!!'; message += ' script: ' + remote.identifier; messsge += ' actual: ' + hash; message += ' expected: ' + remote.checksum; console.log(message); } }, // Don't evaluate this. dataType: "text" }; if (!UpdateSession && !session) { // Should run update from background throw "Not valid session"; } if (session) { session.updateFile(config); } else { UpdateSession.updateFile(config); } }, convertUrlWildCharToRegex: function(wild) { try { function escapeRegex(str, star) { if (!star) star = '*'; var escapeChars = /([\.\\\/\?\{\}\+\[\]])/g; return str.replace(escapeChars, "\\$1").replace('*', star); } wild = wild.toLowerCase(); if (wild == "<all_urls>") { wild = "*://*/*"; } var pattern = /^(.*?):\/\/(\*?[^\/\*]*)\/(.*)$/i; // pattern: [all, scheme, host, page] var parts = pattern.exec(wild); if (parts == null) { return null; } var scheme = parts[1]; var host = parts[2]; var page = parts[3]; var regex = '^' + escapeRegex(scheme, '[^:]*') + ':\\/\\/'; regex += escapeRegex(host, '[^\\/]*') + '/'; regex += escapeRegex(page, '.*'); return new RegExp(regex, 'i'); } catch (e) { return null; } }, update: function() { if (this.pageSide) { return; } this.updateCache(); if (this.cache.listener) { this.cache.listener.trigger('update'); } this.save(); }, // Please remember to call update() after all works are done. addDefaultRule: function(rule, position) { console.log("Add new default rule: ", rule); var custom = null; if (rule.type == 'clsid') { for (var i in this.rules) { var info = {href: "not-a-URL-/", clsid: rule.value}; if (this.isRuleMatched(this.rules[i], info, -1)) { custom = this.rules[i]; break; } } } else if (rule.keyword && rule.testUrl) { // Try to find matching custom rule for (var i in this.rules) { if (this.isRuleMatched(this.rules[i], {href: rule.testUrl}, -1)) { if (this.rules[i].value.toLowerCase().indexOf(rule.keyword) != -1) { custom = this.rules[i]; break; } } } } var newStatus = 'disabled'; if (custom) { console.log('Convert custom rule', custom, ' to default', rule); // Found a custom rule which is similiar to this default rule. newStatus = 'enabled'; // Remove old one delete this.rules[custom.identifier]; for (var i = 0; i < this.order.length; ++i) { if (this.order[i].identifier == custom.identifier) { this.order.splice(i, 1); break; } } } this.order.splice(position, 0, { position: 'default', status: newStatus, identifier: rule.identifier }); this.defaultRules[rule.identifier] = rule; }, updateCache: function() { if (this.pageSide) { return; } this.cache = { validRules: [], regex: [], clsidRules: [], userAgentRules: [], listener: (this.cache || {}).listener } for (var i = 0; i < this.order.length; ++i) { if (this.order[i].status == 'custom' || this.order[i].status == 'enabled') { var rule = this.getItem(this.order[i]); var cacheId = this.cache.validRules.push(rule) - 1; if (rule.type == 'clsid') { this.cache.clsidRules.push(rule); } else if (rule.type == 'wild') { this.cache.regex[cacheId] = this.convertUrlWildCharToRegex(rule.value); } else if (rule.type == 'regex') { this.cache.regex[cacheId] = new RegExp('^' + rule.value + '$', 'i'); } if (rule.userAgent != '') { this.cache.userAgentRules.push(rule); } } } }, save: function() { if (location.protocol == "chrome-extension:") { // Don't include cache in localStorage. var cache = this.cache; delete this.cache; localStorage[settingKey] = JSON.stringify(this); this.cache = cache; } }, createIdentifier: function() { var base = 'custom_' + Date.now() + "_" + this.order.length + "_"; var ret; do { ret = base + Math.round(Math.random() * 65536); } while (this.getItem(ret)); return ret; }, getItem: function(item) { var identifier = item; if (typeof identifier != 'string') { identifier = item.identifier; } if (identifier in this.rules) { return this.rules[identifier]; } else { return this.defaultRules[identifier]; } } }; function loadLocalSetting() { var setting = undefined; if (localStorage[settingKey]) { try{ setting = JSON.parse(localStorage[settingKey]); } catch (e){ setting = undefined; } } if (!setting) { firstRun = true; } return new ActiveXConfig(setting); } function clearSetting() { localStorage.removeItem(settingKey); setting = loadLocalSetting(); }
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. // Updater events: // error // updating // complete // success // itemupdated // progress // properties: // status // lastUpdate // Can be used for debugging. var defaultServer = "http://settings.np-activex.googlecode.com/hg/"; var server=localStorage.updateServer || defaultServer; function ObjectWithEvent() { this._events = {}; }; ObjectWithEvent.prototype = { bind: function(name, func) { if (!Array.isArray(this._events[name])) { this._events[name] = []; } this._events[name].push(func); }, unbind: function(name, func) { if (!Array.isArray(this._events[name])) { return; } for (var i = 0; i < this._events[name].length; ++i) { if (this._events[name][i] == func) { this._events[name].splice(i, 1); break; } } }, trigger: function(name, argument) { if (this._events[name]) { var handlers = this._events[name]; for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(this, argument); } } } }; function UpdateSession() { ObjectWithEvent.call(this); this.jqXHRs = []; this.reset(); } UpdateSession.prototype = { __proto__: ObjectWithEvent.prototype, updateProgress: function() { with(this) { if (finished == total) { if (error == 0) { this.trigger('success'); } this.trigger('complete'); } else { this.trigger('progress'); } } }, updateFile: function(request) { ++this.total; var session = this; var jqXHR = UpdateSession.updateFile(request) .fail(function(xhr, msg, thrown) { ++session.error; session.trigger('error', [xhr, msg, thrown]); session.updateProgress(); }).always(function() { ++session.finished; session.updateProgress(); }); this.jqXHRs.push(jqXHR); }, reset: function() { this.finished = this.total = this.error = 0; if (this.updateToken) { clearTimeout(this.updateToken); this.updateToken = undefined; } for (var i = 0; i < this.jqXHRs.length; ++i) { //this.jqXHRs[i].abort(); } this.jqXHRs = []; }, startUpdate: function() { this.reset(); this.trigger('updating'); } }; UpdateSession.prototype.__defineGetter__('status', function() { if (this.finished == this.total) { return "stop"; } else { return "updating"; } }); UpdateSession.setUpdateInterval= function(callback, session, interval) { session.bind('complete', function() { session.updateToken = setTimeout(callback, interval); }); callback(); }; UpdateSession.updateFile = function(request) { if (request.url.match(/^.*:\/\//) == null) { request.url = server + request.url; } trackUpdateFile(request.url); return $.ajax(request); };
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var FLASH_CLSID = '{d27cdb6e-ae6d-11cf-96b8-444553540000}'; var typeId = "application/x-itst-activex"; function executeScript(script) { var scriptobj = document.createElement("script"); scriptobj.innerHTML = script; var element = document.head || document.body || document.documentElement || document; element.insertBefore(scriptobj, element.firstChild); element.removeChild(scriptobj); } function checkParents(obj) { var parent = obj; var level = 0; while (parent && parent.nodeType == 1) { if (getComputedStyle(parent).display == 'none') { var desp = obj.id + ' at level ' + level; if (scriptConfig.none2block) { parent.style.display = 'block'; parent.style.height = '0px'; parent.style.width = '0px'; log('Remove display:none for ' + desp); } else { log('Warning: Detected display:none for ' + desp); } } parent = parent.parentNode; ++level; } } function getLinkDest(url) { if (typeof url != 'string') { return url; } url = url.trim(); if (/^https?:\/\/.*/.exec(url)) { return url; } if (url[0] == '/') { if (url[1] == '/') { return location.protocol + url; } else { return location.origin + url; } } return location.href.replace(/\/[^\/]*$/, '/' + url); } var hostElement = null; function enableobj(obj) { // We can't use classid directly because it confuses the browser. obj.setAttribute("clsid", getClsid(obj)); obj.removeAttribute("classid"); checkParents(obj); var newObj = obj.cloneNode(true); newObj.type = typeId; // Remove all script nodes. They're executed. var scripts = newObj.getElementsByTagName('script'); for (var i = 0; i < scripts.length; ++i) { scripts[i].parentNode.removeChild(scripts[i]); } // Set codebase to full path. var codebase = newObj.getAttribute('codebase'); if (codebase && codebase != '') { newObj.setAttribute('codebase', getLinkDest(codebase)); } newObj.activex_process = true; obj.parentNode.insertBefore(newObj, obj); obj.parentNode.removeChild(obj); obj = newObj; if (obj.id) { var command = ''; if (obj.form && scriptConfig.formid) { var form = obj.form.name; command += "document.all." + form + "." + obj.id; command + " = document.all." + obj.id + ';\n'; log('Set form[obj.id]: form: ' + form + ', object: ' + obj.id) } // Allow access by document.obj.id if (obj.id && scriptConfig.documentid) { command += "delete document." + obj.id + ";\n"; command += "document." + obj.id + '=' + obj.id + ';\n'; } if (command) { executeScript(command); } } log("Enabled object, id: " + obj.id + " clsid: " + getClsid(obj)); return obj; } function getClsid(obj) { if (obj.hasAttribute("clsid")) return obj.getAttribute("clsid"); var clsid = obj.getAttribute("classid"); var compos = clsid.indexOf(":"); if (clsid.substring(0, compos).toLowerCase() != "clsid") return; clsid = clsid.substring(compos + 1); return "{" + clsid + "}"; } function notify(data) { connect(); data.command = 'DetectControl'; port.postMessage(data); } function process(obj) { if (obj.activex_process) return; if (onBeforeLoading.caller == enableobj || onBeforeLoading.caller == process || onBeforeLoading.caller == checkParents) { log("Nested onBeforeLoading " + obj.id); return; } if (obj.type == typeId) { if (!config || !config.pageRule) { // hack??? Deactive this object. log("Deactive unexpected object " + obj.outerHTML); return true; } log("Found objects created by client scripts"); notify({ href: location.href, clsid: clsid, actived: true, rule: config.pageRule.identifier }); obj.activex_process = true; return; } if (obj.type != "" || !obj.hasAttribute("classid")) return; if (getClsid(obj).toLowerCase() == FLASH_CLSID) { return; } if (config == null) { // Delay the process of this object. // Hope config will be load soon. log('Pending object ', obj.id); pendingObjects.push(obj); return; } obj.activex_process = true; connect(); var clsid = getClsid(obj); var rule = config.shouldEnable({href: location.href, clsid:clsid}); if (rule) { obj = enableobj(obj); notify({ href: location.href, clsid: clsid, actived: true, rule: rule.identifier }); } else { notify({href: location.href, clsid: clsid, actived: false}); } } function replaceDocument() { var s = document.querySelectorAll('object[classid]'); log("found " + s.length + " object(s) on page"); for (var i = 0; i < s.length; ++i) { process(s[i]); } }; function onBeforeLoading(event) { var obj = event.target; if (obj.nodeName == "OBJECT") { log("BeforeLoading " + obj.id); if (process(obj)) { event.preventDefault(); } } } function onError(event) { var message = 'Error: '; message += event.message; message += ' at '; message += event.filename; message += ':'; message += event.lineno; log(message); } function setUserAgent() { if (!config.pageRule) { return; } var agent = getUserAgent(config.pageRule.userAgent); if (agent && agent != '') { log("Set userAgent: " + config.pageRule.userAgent); var js = "(function(agent) {"; js += "delete navigator.userAgent;"; js += "navigator.userAgent = agent;"; js += "delete navigator.appVersion;"; js += "navigator.appVersion = agent.substr(agent.indexOf('/') + 1);"; js += "if (agent.indexOf('MSIE') >= 0) {"; js += "delete navigator.appName;"; js += 'navigator.appName = "Microsoft Internet Explorer";}})("'; js += agent; js += '")'; executeScript(js); } }
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var controlLogFName="__npactivex_log"; var controlLogEvent="__npactivex_log_event__"; var config = null; var port = null; var logs = []; var scriptConfig = { none2block: false, formid: false, documentid: false }; function onControlLog(event) { var message = event.data; log(message); } window.addEventListener(controlLogEvent, onControlLog, false); function connect() { if (port) { return; } port = chrome.extension.connect(); for (var i = 0; i < logs.length; ++i) { port.postMessage({command: 'Log', message: logs[i]}); } if (port && config) { logs = undefined; } } function log(message) { var time = (new Date()).toLocaleTimeString(); message = time + ' ' + message; if (config && config.logEnabled) { console.log(message); } if (port) { port.postMessage({command: 'Log', message: message}); } if (!config || !port) { logs.push(message); } } log('PageURL: ' + location.href); var pendingObjects = []; function init(response) { config = new ActiveXConfig(response); if (config.logEnabled) { for (var i = 0; i < logs.length; ++i) { console.log(logs[i]); } } eval(config.extScript); executeScript(config.pageScript); setUserAgent(); log('Page rule:' + JSON.stringify(config.pageRule)); for (var i = 0; i < pendingObjects.length; ++i) { pendingObjects[i].activex_process = false; process(pendingObjects[i]); cacheConfig(); } delete pendingObjects; } function cacheConfig() { sessionStorage.activex_config_cache = JSON.stringify(config); } function loadConfig(response) { if (config) { config = new ActiveXConfig(response); var cache = sessionStorage.activex_config_cache; if (cache) { cacheConfig(); } } else { init(response); } if (config.pageRule) { cacheConfig(); } } function loadSessionConfig() { var cache = sessionStorage.activex_config_cache; if (cache) { log('Loading config from session cache'); init(JSON.parse(cache)); } } loadSessionConfig(); chrome.extension.sendRequest( {command:"Configuration", href:location.href, top: self == top}, loadConfig); window.addEventListener("beforeload", onBeforeLoading, true); window.addEventListener('error', onError, true);
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. /* prop = { header, // String property, // String events, // type, // checkbox, select, input.type, button extra // depend on type } */ function List(config) { this.config = config; this.props = config.props; this.main = config.main; this.selectedLine = -2; this.lines = []; if (!config.getItems) { config.getItems = function() { return config.items; } } if (!config.getItemProp) { config.getItemProp = function(id, prop) { return config.getItem(id)[prop]; } } if (!config.setItemProp) { config.setItemProp = function(id, prop, value) { config.getItem(id)[prop] = value; } } if (!config.getItem) { config.getItem = function(id) { return config.getItems()[id]; } } if (!config.move) { config.move = function(a, b) { if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) { var list = config.getItems(); var tmp = list[a]; // remove a list.splice(a, 1); // insert b list.splice(b, 0, tmp); } } }; if (!config.insert) { config.insert = function(id, newItem) { config.getItems().splice(id, 0, newItem); } } if (!config.remove) { config.remove = function(a) { config.move(a, config.count() - 1); config.getItems().pop(); } } if (!config.validate) { config.validate = function() {return true;}; } if (!config.count) { config.count = function() { return config.getItems().length; } } if (!config.patch) { config.patch = function(id, newVal) { for (var name in newVal) { config.setItemProp(id, name, newVal[name]); } } } if (!config.defaultValue) { config.defaultValue = {}; } config.main.addClass('list'); } List.ids = { noline: -1, }; List.types = {}; List.prototype = { init: function() { with (this) { if (this.inited) { return; } this.inited = true; this.headergroup = $('<div class="headers"></div>'); for (var i = 0; i < props.length; ++i) { var header = $('<div class="header"></div>'). attr('property', props[i].property).html(props[i].header); headergroup.append(header); } this.scrolls = $('<div>').addClass('listscroll'); this.contents = $('<div class="listitems"></div>').appendTo(scrolls); scrolls.scroll(function() { headergroup.css('left', -(scrolls.scrollLeft()) + 'px'); }); contents.click(function(e) { if (e.target == contents[0]) { selectLine(List.ids.noline); } }); $(main).append(headergroup).append(scrolls); var height = this.main.height() - this.headergroup.outerHeight(); this.scrolls.height(height); load(); selectLine(List.ids.noline); } }, editNewLine: function() { this.startEdit(this.lines[this.lines.length - 1]); }, updatePropDisplay : function(line, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var id = Number(line.attr('row')); if (id == this.config.count()) { var value = this.config.defaultValue[name]; if (value) { ctrl.value = value; } obj.trigger('createNew'); } else { ctrl.value = this.config.getItemProp(id, name); obj.trigger('update'); } }, updateLine: function(line) { for (var i = 0; i < this.props.length; ++i) { this.updatePropDisplay(line, this.props[i]); } if (Number(line.attr('row')) < this.config.count()) { line.trigger('update'); } else { line.addClass('newline'); } }, createLine: function() { with (this) { var line = $('<div></div>').addClass('itemline'); var inner = $('<div>'); line.append(inner); // create input boxes for (var i = 0; i < props.length; ++i) { var prop = props[i]; var ctrl = $('<div></div>').attr('property', prop.property) .addClass('listvalue').attr('tabindex', -1); var valueobj = new List.types[prop.type](ctrl, prop); var data = {list: this, line: line, prop: prop}; for (var e in prop.events) { ctrl.bind(e, data, prop.events[e]); } ctrl.bind('change', function(e) { validate(line); return true; }); ctrl.bind('keyup', function(e) { if (e.keyCode == 27) { cancelEdit(line); } }); ctrl.trigger('create'); inner.append(ctrl); } // Event listeners line.click(function(e) { startEdit(line); }); line.focusin(function(e) { startEdit(line); }); line.focusout(function(e) { finishEdit(line); }); for (var e in this.config.lineEvents) { line.bind(e, {list: this, line: line}, this.config.lineEvents[e]); } var list = this; line.bind('updating', function() { $(list).trigger('updating'); }); line.bind('updated', function() { $(list).trigger('updated'); }); this.bindId(line, this.lines.length); this.lines.push(line); line.appendTo(this.contents); return line; } }, refresh: function(lines) { var all = false; if (lines === undefined) { all = true; lines = []; } for (var i = this.lines.length; i <= this.config.count(); ++i) { var line = this.createLine(); lines.push(i); } while (this.lines.length > this.config.count() + 1) { this.lines.pop().remove(); } $('.newline', this.contents).removeClass('newline'); this.lines[this.lines.length - 1].addClass('newline'); if (all) { for (var i = 0; i < this.lines.length; ++i) { this.updateLine(this.lines[i]); } } else { for (var i = 0; i < lines.length; ++i) { this.updateLine(this.lines[lines[i]]); } } }, load: function() { this.contents.empty(); this.lines = []; this.refresh(); }, bindId: function(line, id) { line.attr('row', id); }, getLineNewValue: function(line) { var ret = {}; for (var i = 0; i < this.props.length; ++i) { this.getPropValue(line, ret, this.props[i]); } return ret; }, getPropValue: function(line, item, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var value = ctrl.value; if (value !== undefined) { item[name] = value; } return value; }, startEdit: function(line) { if (line.hasClass('editing')) { return; } line.addClass('editing'); this.showLine(line); this.selectLine(line); var list = this; setTimeout(function() { if (!line[0].contains(document.activeElement)) { $('.valinput', line).first().focus(); } list.validate(line); }, 50); }, finishEdit: function(line) { var list = this; function doFinishEdit() { with(list) { if (line[0].contains(document.activeElement)) { return; } var valid = isValid(line); if (valid) { var id = Number(line.attr('row')); var newval = getLineNewValue(line); if (line.hasClass('newline')) { $(list).trigger('updating'); if(!config.insert(id, newval)) { line.removeClass('newline'); list.selectLine(line); $(list).trigger('add', id); addNewLine(); } } else { line.trigger('updating'); config.patch(id, newval); } line.trigger('updated'); } cancelEdit(line); } }; setTimeout(doFinishEdit, 50); }, cancelEdit: function(line) { line.removeClass('editing'); line.removeClass('error'); var id = Number(line.attr('row')); if (id == this.config.count() && this.selectedLine == id) { this.selectedLine = List.ids.noline; } this.updateLine(line); }, addNewLine: function() { with(this) { var line = $('.newline', contents); if (!line.length) { line = createLine().addClass('newline'); } return line; } }, isValid: function(line) { var id = Number(line.attr('row')); var obj = this.getLineNewValue(line); return valid = this.config.validate(id, obj); }, validate: function(line) { if (this.isValid(line)) { line.removeClass('error'); } else { line.addClass('error'); } }, move: function(a, b, keepSelect) { var len = this.config.count(); if (a == b || a < 0 || b < 0 || a >= len || b >= len) { return; } this.config.move(a, b); for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) { this.updateLine(this.getLine(i)); } if (keepSelect) { if (this.selectedLine == a) { this.selectLine(b); } else if (this.selectedLine == b) { this.selectLine(a); } } }, getLine: function(id) { if (id < 0 || id >= this.lines.length) { return null; } return this.lines[id]; }, remove: function(id) { id = Number(id); if (id < 0 || id >= this.config.count()) { return; } $(this).trigger('updating'); var len = this.lines.length; this.getLine(id).trigger('removing'); if (this.config.remove(id)) { return; } this.getLine(len - 1).remove(); this.lines.pop(); for (var i = id; i < len - 1; ++i) { this.updateLine(this.getLine(i)); } if (id >= len - 2) { this.selectLine(id); } else { this.selectLine(List.ids.noline); } $(this).trigger('updated'); }, selectLine: function(id) { var line = id; if (typeof id == "number") { line = this.getLine(id); } else { id = Number(line.attr('row')); } // Can't select the new line. if (line && line.hasClass('newline')) { line = null; id = List.ids.noline; } if (this.selectedLine == id) { return; } var oldline = this.getLine(this.selectedLine); if (oldline) { this.cancelEdit(oldline); oldline.removeClass('selected'); oldline.trigger('deselect'); this.selectedLine = List.ids.noline; } this.selectedLine = id; if (line != null) { line.addClass('selected'); line.trigger('select'); this.showLine(line); } $(this).trigger('select'); }, showLine: function(line) { var showtop = this.scrolls.scrollTop(); var showbottom = showtop + this.scrolls.height(); var top = line.offset().top - this.contents.offset().top; // Include the scroll bar var bottom = top + line.height() + 20; if (top < showtop) { // show at top this.scrolls.scrollTop(top); } else if (bottom > showbottom) { // show at bottom this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height())); } } };
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. replaceDocument(); window.addEventListener('load', replaceDocument, false);
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var USE_RECORD_GAP = 3 * 60 * 1000; // 3 minutes var background = chrome.extension.getBackgroundPage(); var _gaq = background._gaq || _gaq || []; if (window == background) { _gaq.push(['_setAccount', 'UA-28870762-4']); } _gaq.push(['_trackPageview', location.href]); function initGAS() { var setting = setting || background.setting || {}; if (!debug && setting.misc.tracking) { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); } else if (!debug) { // dummy it. Non-debug && non-track _gaq.push = function() {}; } } var useHistory = {}; var issueHistory = {}; function trackCheckSpan(history, item) { var last = history[item]; if (last && Date.now() - last < USE_RECORD_GAP) { return false; } history[item] = Date.now(); return true; } function trackIssue(issue) { if (!trackCheckSpan(issueHistory, issue.identifier)) { return; } _gaq.push(['_trackEvent', 'usage', 'error', '' + issue.identifier]); } function trackVersion(version) { _gaq.push(['_trackEvent', 'option', 'version', version]); } function serializeRule(rule) { return rule.type[0] + ' ' + rule.value; } function trackUse(identifier) { if (!trackCheckSpan(useHistory, identifier)) { return; } if (identifier.substr(0, 7) == 'custom_') { var setting = setting || background.setting || {}; var rule = setting.getItem(identifier); _gaq.push(['_trackEvent', 'usage', 'use-custom', serializeRule(rule)]); } else { _gaq.push(['_trackEvent', 'usage', 'use', identifier]); } } var urlHistory = {} function trackNotUse(url) { if (!trackCheckSpan(urlHistory, url)) { return; } _gaq.push(['_trackEvent', 'usage', 'notuse', url]); } function trackDisable(identifier) { _gaq.push(['_trackEvent', 'option', 'disable', identifier]); } function trackAutoEnable(identifier) { _gaq.push(['_trackEvent', 'option', 'autoenable', identifier]); } function trackEnable(identifier) { _gaq.push(['_trackEvent', 'option', 'enable', identifier]); } function trackAddCustomRule(rule, auto) { var cmd = 'add'; if (auto) { cmd = 'add-' + auto; } _gaq.push(['_trackEvent', 'option', cmd, serializeRule(rule)]); } function trackManualUpdate() { _gaq.push(['_trackEvent', 'update', 'manual']); } function trackUpdateFile(url) { _gaq.push(['_trackEvent', 'update', 'file', url]); }
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1')); if (isNaN(tabId)) { alert('Invalid tab id'); } var backgroundPage = chrome.extension.getBackgroundPage(); var tabInfo = backgroundPage.tabStatus[tabId]; var setting = backgroundPage.setting; if (!tabInfo) { alert('Cannot get tab tabInfo'); } $(document).ready(function() { $('.status').hide(); $('#submitissue').hide(); if (tabInfo.count == 0) { // Shouldn't have this popup } else if (tabInfo.error != 0) { $('#status_error').show(); } else if (tabInfo.count != tabInfo.actived) { $('#status_disabled').show(); } else { $('#status_ok').show(); $('#submitissue').show(); } }); $(document).ready(function() { $('#issue_view').hide(); if (tabInfo.error != 0) { var errorid = tabInfo.issueId; var issue = setting.issues[errorid]; $('#issue_content').text(issue.description); var url = issue.url; if (!url) { var issueUrl = "http://code.google.com/p/np-activex/issues/detail?id="; url = issueUrl + issue.issueId; } $('#issue_track').click(function() { chrome.tabs.create({url:url}); window.close(); }); $('#issue_view').show(); } }); function refresh() { alert($$('refresh_needed')); window.close(); } function showEnableBtns() { var list = $('#enable_btns'); list.hide(); if (tabInfo.count > tabInfo.actived) { list.show(); var info = {actived: true}; for (var i = 0; i < tabInfo.frames && info.actived; ++i) { for (var j = 0; j < tabInfo.objs[i].length && info.actived; ++j) { info = tabInfo.objs[i][j]; } } if (info.actived) { return; } var rule = setting.getFirstMatchedRule(info, setting.defaultRules); if (rule) { var button = $('<button>').addClass('defaultRule'); button.text($$('enable_default_rule', rule.title)); button.click(function() { setting.activeRule(rule); refresh(); }); list.append(button); } else { var site = info.href.replace(/[^:]*:\/\/([^\/]*).*/, '$1'); var sitepattern = info.href.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*'); var btn1 = $('<button>').addClass('customRule'). text($$('add_rule_site', site)).click(function() { var rule = setting.createRule(); rule.type = 'wild'; rule.value = sitepattern; setting.addCustomRule(rule, 'popup'); refresh(); }); var clsid = info.clsid; var btn2 = $('<button>').addClass('customRule'). text($$('add_rule_clsid')).click(function() { var rule = setting.createRule(); rule.type = 'clsid'; rule.value = clsid; setting.addCustomRule(rule, 'popup'); refresh(); }); list.append(btn1).append(btn2); } } } $(document).ready(function() { $('#submitissue').click(function() { tabInfo.tracking = true; alert($$('issue_submitting_desp')); window.close(); }); }); $(document).ready(showEnableBtns); $(window).load(function() { $('#share').load('share.html'); });
JavaScript
// Copyright (c) 2010 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var $$ = chrome.i18n.getMessage; function loadI18n() { document.title = chrome.i18n.getMessage("option_title") var spans = document.querySelectorAll('[i18n]'); for (var i = 0; i < spans.length; ++i) { var obj = spans[i]; v = $$(obj.getAttribute("i18n")); if (v == "") v = obj.getAttribute('i18n'); if (obj.tagName == 'INPUT') { obj.value = v; } else { obj.innerText = v; } } } window.addEventListener("load", loadI18n, false);
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var background = chrome.extension.getBackgroundPage(); var setting = background.setting; var updateSession = background.updateSession; function toggleRule(e) { var line = e.data.line; var index = line.attr('row'); var item = setting.order[index]; if (item.position == 'default') { if (item.status == 'enabled') { item.status = 'disabled'; trackDisable(item.identifier); } else if (item.status == 'disabled') { item.status = 'enabled'; trackEnable(item.identifier); } } line.blur(); e.data.list.finishEdit(line); e.data.list.updateLine(line); save(); } var settingProps = [ { header: "", property: "status", type: 'button', caption: "", events: { command: toggleRule, update: setStatus, createNew: setStatusNew } }, { header: $$("title"), property: "title", type: "input" }, { header: $$("mode"), property: "type", type: "select", option: "static", options: [ {value: "wild", text: $$("WildChar")}, {value: "regex", text: $$("RegEx")}, {value: "clsid", text: $$("CLSID")} ] }, { header: $$("pattern"), property: "value", type: "input" }, { header: $$("user_agent"), property: "userAgent", type: "select", option: "static", options: [ {value: "", text: "Chrome"}, {value: "ie9", text: "MSIE9"}, {value: "ie8", text: "MSIE8"}, {value: "ie7", text: "MSIE7"}, {value: "ff7win", text: "Firefox 7"}, {value: "ip5", text: "iPhone"}, {value: "ipad5", text: "iPad"} ] }, { header: $$("helper_script"), property: "script", type: "input" } ]; var table; var dirty = false; function save() { dirty = true; } function doSave() { if (dirty) { dirty = false; setting.update(); } } function setReadonly(e) { var line = e.data.line; var id = line.attr('row'); if (id < 0) { return; } var order = setting.order[id]; var divs = $('.listvalue', line); if (order.position != 'custom') { divs.addClass('readonly'); } else { divs.removeClass('readonly'); } } $(window).blur(doSave); function refresh() { table.refresh(); } // Main setting $(document).ready(function() { table = new List({ props: settingProps, main: $('#tbSetting'), lineEvents: { update: setReadonly }, getItems: function() { return setting.order; }, getItemProp: function(i, prop) { if (prop in setting.order[i]) { return setting.order[i][prop]; } return setting.getItem(setting.order[i])[prop]; }, setItemProp: function(i, prop, value) { if (prop in setting.order[i]) { setting.order[i][prop] = value; } else { setting.getItem(setting.order[i])[prop] = value; } }, defaultValue: setting.createRule(), count: function() { return setting.order.length; }, insert: function(id, newItem) { setting.addCustomRule(newItem); this.move(setting.order.length - 1, id); }, remove: function(id) { if (setting.order[id].position != 'custom') { return true; } var identifier = setting.order[id].identifier; delete setting.rules[identifier]; setting.order.splice(id, 1); }, validate: function(id, rule) { return setting.validateRule(rule); } }); $(table).bind('updated', save); $('#addRule').bind('click', function() { table.editNewLine(); }); $(table).bind('select', function() { var line = table.selectedLine; if (line < 0) { $('#moveUp').attr('disabled', 'disabled'); $('#moveDown').attr('disabled', 'disabled'); $('#deleteRule').attr('disabled', 'disabled'); } else { if (line != 0) { $('#moveUp').removeAttr('disabled'); } else { $('#moveUp').attr('disabled', 'disabled'); } if (line != setting.order.length - 1) { $('#moveDown').removeAttr('disabled'); } else { $('#moveDown').attr('disabled', 'disabled'); } if (setting.order[line].position != 'custom') { $('#deleteRule').attr('disabled', 'disabled'); } else { $('#deleteRule').removeAttr('disabled'); } } }); $('#moveUp').click(function() { var line = table.selectedLine; table.move(line, line - 1, true); }); $('#moveDown').click(function() { var line = table.selectedLine; table.move(line, line + 1, true); }); $('#deleteRule').click(function() { var line = table.selectedLine; table.remove(line); }); table.init(); updateSession.bind('update', refresh); updateSession.bind('updating', showUpdatingState); updateSession.bind('progress', showUpdatingState); updateSession.bind('complete', showUpdatingState); }); window.onbeforeunload = function() { updateSession.unbind('update', refresh); updateSession.unbind('updating', showUpdatingState); updateSession.unbind('progress', showUpdatingState); updateSession.unbind('complete', showUpdatingState); } function setStatusNew(e) { with (e.data) { s = 'Custom'; color = '#33f'; $('button', line).text(s).css('background-color', color); } } function setStatus(e) { with (e.data) { var id = line.attr('row'); var order = setting.order[id]; var rule = setting.getItem(order); var s, color; if (order.status == 'enabled') { s = $$('Enabled'); color = '#0A0'; } else if (order.status == 'disabled') { s = $$('Disabled'); color = 'indianred'; } else { s = $$('Custom'); color = '#33f'; } $('button', line).text(s).css('background-color', color); } } function showTime(time) { var never = 'Never' if (time == 0) { return never; } var delta = Date.now() - time; if (delta < 0) { return never; } function getDelta(delta) { var sec = delta / 1000; if (sec < 60) { return [sec, 'second']; } var minute = sec / 60; if (minute < 60) { return [minute, 'minute']; } var hour = minute / 60; if (hour < 60) { return [hour, 'hour']; } var day = hour / 24; return [day, 'day']; } var disp = getDelta(delta); var v1 = Math.floor(disp[0]); return v1 + ' ' + disp[1] + (v1 != 1 ? 's' : '') + " ago"; } function showUpdatingState(e) { if (updateSession.status == 'stop') { $('#lastUpdate').text(showTime(setting.misc.lastUpdate)); } else { $('#lastUpdate').text($$("update_progress") + updateSession.finish + '/' + updateSession.total); } } $(document).ready(function() { showUpdatingState({}); $('#doUpdate').click(function() { setting.updateConfig(updateSession); trackManualUpdate(); }); $('#log_enable').change(function(e) { setting.misc.logEnabled = e.target.checked; save(); })[0].checked = setting.misc.logEnabled; $('#tracking').change(function(e) { setting.misc.tracking = e.target.checked; save(); })[0].checked = setting.misc.tracking; }); $(document).ready(function() { var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl='; help = help + $$('wikicode'); $('.help').each(function() { this.href = help; }); }); $(window).load(function() { $('#share').load('share.html'); if (background.firstUpgrade) { background.firstUpgrade = false; alert($$("upgrade_show")); } $('#follow').html('<iframe width="136" height="24" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0" scrolling="no" border="0" src="http://widget.weibo.com/relationship/followbutton.php?language=zh_cn&width=136&height=24&uid=2356524070&style=2&btn=red&dpc=1"></iframe>'); });
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. List.types.input = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input></input>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); this.input.focus(function(e) { input.select(); }); this.input.keypress(function(e) { p.trigger('change'); }); this.input.keyup(function(e) { p.trigger('change'); }); this.input.change(function(e) { p.trigger('change'); }); p.append(this.input).append(this.label); }; List.types.input.prototype.__defineSetter__('value', function(val) { this.input.val(val); this.label.text(val); }); List.types.input.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<select></select>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); if (prop.option == 'static') { this.loadOptions(prop.options); } var select = this; this.input.change(function(e) { if (p.hasClass('readonly')) { select.value = select.lastval; } else { p.trigger('change'); } }); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); p.append(this.input).append(this.label); }; List.types.select.prototype.loadOptions = function(options) { this.options = options; this.mapping = {}; this.input.html(""); for (var i = 0; i < options.length; ++i) { this.mapping[options[i].value] = options[i].text; var o = $('<option></option>').val(options[i].value).text(options[i].text) this.input.append(o); } } List.types.select.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input.val(val); this.label.text(this.mapping[val]); }); List.types.checkbox = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input type="checkbox">').addClass('valcheck'); var box = this; this.input.change(function(e) { if (p.hasClass('readonly')) { box.value = box.lastval; } else { p.trigger('change'); } }); p.append(this.input); }; List.types.checkbox.prototype.__defineGetter__('value', function() { return this.input[0].checked; }); List.types.checkbox.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input[0].checked = val; }); List.types.button = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<button>'); if (prop.caption) { input.text(prop.caption); } input.click(function(e) { p.trigger('command'); return false; }); p.append(this.input); }; List.types.button.prototype.__defineGetter__('value', function() { return undefined; });
JavaScript
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1')); if (isNaN(tabId)) { alert('Invalid tab id'); } var backgroundPage = chrome.extension.getBackgroundPage(); $(document).ready(function() { var s = backgroundPage.generateLogFile(tabId); $("#text").val(s); });
JavaScript
$(document).ready(function() { $('#userRole').datagrid({ data :null }); $('#reloadList').linkbutton('disable'); $("#targetUser").combobox({ onSelect : function(record) { loadGridData(record.id); $('#reloadList').linkbutton('enable'); } }); }); function loadGridData(username) { if (username == undefined) return; // $.getJSON('listRole.htm?userId=' + username, function(resData) { // $('#userRole').datagrid({ // data : resData // }); // }); $.getJSON('listRole.htm?userId=' + username, function(resData) { $('#userRole').datagrid({ data : resData }); }) .done(function(data){ var rows = $('#userRole').datagrid('getRows'); for (var i = 0; i < rows.length; ++i) { if (rows[i]['permitted'] == true) $('#userRole').datagrid('checkRow', i); } }); } function reloadList(){ loadGridData($("#targetUser").combobox('getValue')); } function saveList(){ var roles = []; var rows = $('#userRole').datagrid('getSelections'); for(var i=0;i<rows.length;i++){ roles.push(rows[i].name); } var data = {}; data["roles"]=roles.join(':'); data["targetUser"]=$("#targetUser").combobox('getValue'); $.postJSON("UpdateRole.htm", data, function(result) { if (result.success) { showMessager("Info", result.message); loadGridData('Pending'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); }
JavaScript
var inData; $(document).ready( function() { toggleNotebooks(); var prjObjId = $("#prjObjId").val(); var oppId=$("#opportunityId").val(); $.getJSON('getCompleteOpportunity.htm?prjObjId=' + prjObjId + "&oppId=" + oppId, function(data) { inData = $.extend({}, data.opportunity, data.review); createOppStatusTable(data.oppStatus); $("#projectName").text(inData.title); $("#oppCurrentStatus").text("Current State : - " +data.oppCurrentStatus); // inData = data; loadDetails(); }); }); function showPanel(opt) { $("#reviewAccordion").accordion('select', opt-1); $("#reviewAccordion").accordion('getSelected', true); } function createOppStatusTable(statusData) { var htmlTbl = "<table class='blueTable'>"; htmlTbl += '<tr><td>Assign Date</td><td>Role</td><td>User</td><td>Status</td><td>End Date</td><td>Outcome</td></tr>'; var colNames = [ "startDate", "role","userId", "status","endDate", "outcome" ]; $.each(statusData, function(ind, obj) { htmlTbl += "<tr>"; $.each(colNames, function(i, col) { if (obj.hasOwnProperty(col)) htmlTbl += "<td>" + obj[col] + "</td>"; else htmlTbl += "<td>&nbsp;</td>"; }); htmlTbl += "</tr>"; }); htmlTbl += "</table>"; $("#oppStatus").html(htmlTbl); } function loadDetails() { $.each(inData, function(key, value) { try { if (jQuery.type(inData[key]) === "object") { $("#" + key).html(inData[key].value); } else { $("#" + key).html(inData[key]); } } catch (e) { } }); showPanel(1); } function toggleNotebooks() { $(".notebook span:first-child").each(function(ind, obj) { $(obj).addClass("collapse"); $(obj).parent().parent().find("div").addClass("collapseNotebook"); }); $(".notebook span:first-child").click( function(obj) { if ($(obj.target).hasClass('expand')) { $(obj.target).removeClass('expand'); $(obj.target).addClass('collapse'); $(obj.target).parent().parent().find("div").eq(0) .removeClass("expandNotebook"); $(obj.target).parent().parent().find("div").eq(0).addClass( "collapseNotebook"); } else { $(obj.target).removeClass('collapse'); $(obj.target).addClass('expand'); $(obj.target).parent().parent().find("div").eq(0) .removeClass("collapseNotebook"); $(obj.target).parent().parent().find("div").eq(0).addClass( "expandNotebook"); } }); } function createNotebookRow(title, id) { var content = ""; if (inData.hasOwnProperty(id)) content = inData[id]; var row = "<tr><td class='notebook' colspan='2'><b><span>&nbsp;&nbsp;&nbsp;&nbsp;</span><span>" + title + "</span></b>" + createDiv(id, content) + "</td></tr>"; return row; } function createTextRow(title, id) { var content = ""; if (inData.hasOwnProperty(id)) content = inData[id]; var row = "<tr><td><b>" + title + "</b></td><td>" + createSpan(id, content) + "</td></tr>"; return row; } function createObjectRow(title, id) { var content = ""; if (inData.hasOwnProperty(id)) content = inData[id]; var row = "<tr><td><b>" + title + "</b></td><td>" + createSpan(id, content.value) + "</td></tr>"; return row; } function createDiv(divId, content) { content = (content === undefined ? "" : content); return "<div id='" + divId + "' >" + content + "</div>"; } function createSpan(spanId, spanData) { content = (content === undefined ? "" : content); return "<Span id='" + spanId + "' style='width: 400px; height: 20px'>" + spanData + "</Span>"; }
JavaScript
$(document).ready(function() { loadGridData(""); $('#dg').datagrid({ toolbar : toolbar, rownumbers : true, singleSelect : true }); }); function loadGridData(filter) { var userId = $("#userId").val(); if (userId == undefined) return; $.getJSON('listActionItems.htm?userId=' + userId + '&filter=' + filter, function(resData) { $('#dg').datagrid({ data : resData }); }); } var toolbar = [ { id : 'btnClaim', text : 'Claim', iconCls : 'icon-add', handler : claimOpportunity }, { id : 'btnApprove', text : 'Approve', iconCls : 'icon-ok', handler : approveOpportunity }, { id : 'btnReject', text : 'Reject', iconCls : 'icon-cancel', handler : rejectOpportunity }, '-', { id : 'btnMyClaims', text : 'My Claims', iconCls : 'icon-inbox-plus', handler : getClaimedByMe }, { id : 'btnAllOpportunity', text : 'All Opportunity', iconCls : 'icon-archives', handler : getAllOpportunity }, '-', { id : 'btnViewDetails', text : 'View Details', iconCls : 'icon-search', handler : viewOpportunityDetails } ]; function viewOpportunityDetails() { var row = $('#dg').datagrid('getSelected'); if (row == null) { showMessager("Info", "Please select an opportunity to view details"); return; } if(row.stepId == "6" || row.stepId == 6){ var win = window.open("ResourceDetails.htm?assId=" + row.id + "&opportunityId=" + row.opportunityId + "&prjObjId=" + row.prjObjId, "width=880,height=750,scrollbars=yes,location=no,menubar=no"); win.focus(); }else if(row.stepId == "5" || row.stepId == 5){ } else{ var win = window.open("ViewOpportunity.htm?assId=" + row.id + "&opportunityId=" + row.opportunityId + "&prjObjId=" + row.prjObjId, "width=880,height=750,scrollbars=yes,location=no,menubar=no"); win.focus(); } } function getOpportunityDetails() { var row = $('#dg').datagrid('getSelected'); if (row == null) { showMessager("Info", "Please select an opportunity to view details"); return; } var url = "getDetail.htm?opportunityId=" + row.opportunityId; $.ajax({ url : url }); } function gridReset() { loadGridData('Pending'); } function getClaimedByMe() { loadGridData('Claimed'); } function getAllOpportunity() { loadGridData('Pending'); } function claimOpportunity() { var row = $('#dg').datagrid('getSelected'); if (row == null) { showMessager("Error", "Please select an Opportunity to claim!"); return false; } if ((row.stepId == "2" || row.stepId == "3" || row.stepId == "4" || row.stepId == "5" || row.stepId == "6") && row.status == "Pending") { } else { showMessager("Error", "Only pending opportunity can be claimed!"); return false; } var data = { "opportunityId" : row.opportunityId, "id" : row.id, "userId" : $("#userId").val(), "action" : "claim", "pmuser" : "None" }; $.postJSON("OpportunityAction.htm", data, function(result) { if (result.success) { showMessager("Info", result.message); loadGridData('Pending'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function approveOpportunity() { var row = $('#dg').datagrid('getSelected'); if (row == null) { showMessager("Error", "Please select an Opportunity to approve!"); return false; } if (row.status != "Claimed") { showMessager("Error", "Only claimed opportunity can be approved!"); return false; } if (row.userId != $("#userId").val()) { showMessager("Error", "You can not approve any opportunity claimed by others !!!"); return false; } if (row.stepId == "4" || row.stepId == 4 ) { $('#prcApprovalWindow').dialog('open'); return false; } if (row.stepId == "2") { openApprovalWindow(); return false; } var data = { "opportunityId" : row.opportunityId, "id" : row.id, "userId" : $("#userId").val(), "action" : "approve", "pmuser" : "None" }; $.postJSON("OpportunityAction.htm", data, function(result) { if (result.success) { showMessager("Info", result.message); loadGridData('Pending'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function approvePRCOpportunity() { if (!$("#approvalForm").form('validate')) { showMessager("Alert", 'Required fields can not be left blank.'); return false; } var row = $('#dg').datagrid('getSelected'); var pmuser=$("#showPM").combobox('getValue'); if (row == null) { showMessager("Error", "Please select an Opportunity to approve!"); return false; } if (row.status != "Claimed") { showMessager("Error", "Only claimed opportunity can be approved!"); return false; } if (row.userId != $("#userId").val()) { showMessager("Error", "You can not approve any opportunity claimed by others !!!"); return false; } var data = { "opportunityId" : row.opportunityId, "id" : row.id, "userId" : $("#userId").val(), "action" : "approve", "pmuser" : pmuser }; $.postJSON("OpportunityAction.htm", data, function(result) { if (result.success) { showMessager("Info", result.message); loadGridData('Pending'); $('#prcApprovalWindow').dialog('close'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function rejectOpportunity() { var row = $('#dg').datagrid('getSelected'); if (row == null) { showMessager("Error", "Please select an Opportunity to reject!"); return false; } var data = { "opportunityId" : row.opportunityId, "id" : row.id, "userId" : $("#userId").val(), "action" : "reject", "pmuser" : "None" }; $.postJSON("OpportunityAction.htm", data, function(result) { if (result.success) { showMessager("Info", result.message); loadGridData('Pending'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } //function rejectOpportunity() { // var row = $('#dg').datagrid('getSelected'); // if (row == null) { // showMessager("Error", "Please select an Opportunity to reject!"); // return false; // } // if ((row.stepId == "3" || row.stepId == "4" || row.stepId == "6") && row.status == "Claimed") { // // } else if (row.stepId == "2" && row.status == "Claimed") { // showMessager("Error", "You cannot reject the Opportunity!"); // return false; // } else { // showMessager("Error", "Only claimed opportunity can be rejected!"); // return false; // } // // // var data = { // "opportunityId" : row.opportunityId, // "id" : row.id, // "userId" : $("#userId").val(), // "action" : "reject", // "pmuser" : "None" // }; // // $.postJSON("OpportunityAction.htm", data, function(result) { // if (result.success) { // showMessager("Info", result.message); // loadGridData('Pending'); // } else { // showMessager("Exception", result.message); // } // }, function(xhr, ajaxOptions, thrownError) { // showMessager("Exception", thrownError); // }); //} function openApprovalWindow() { var row = $('#dg').datagrid('getSelected'); if (row == null) { showMessager("Error", "Please select an Opportunity to approve!"); return false; } if (row.status != "Claimed") { showMessager("Error", "Only Claimed opportunity can be approved!"); return false; } if (row.userId != $("#userId").val()) { showMessager("Error", "You can not approve any opportunity claimed by others!"); return false; } var type = ""; if (row.role == "FC") type = "financial"; else if (row.role == "CA") type = "legal"; else if (row.role == "PMO") type = "strategic"; else if (row.role == "PMORM") type = "capability"; else if (row.role == "BD") type = "BD"; var url = "OppReview.htm?type=" + type + "&userId=" + $("#userId").val() + "&opportunityId=" + row.opportunityId + "&prjObjId=" + row.prjObjId + "&assignmentId=" + row.id; window.open(url, "popupWindow", "width=880,height=750,scrollbars=yes,location=no,menubar=no"); return false; }
JavaScript
$(document).ready(function() { loadGridData(""); $('#resourceGrid').datagrid({ rownumbers : true, singleSelect : true }); }); function loadGridData(filter) { var prjObjId = $("#prjObjId").val(); if (prjObjId == undefined) return; $.getJSON('getResourceDetails.htm?prjObjId=' + prjObjId, function(resData) { $('#resourceGrid').datagrid({ data : resData }); }); }
JavaScript
$(document).ready(function() { $("#contractValSel").click(addCost); $("#contractValClear").click(clearCost); var prjObjId = $("#prjObjId").val(); $.getJSON('getOpportunityViewData.htm?prjObjId=' + prjObjId, function(data) { setFormData("ff", data); //alert($("#hiddenAddNotes").val()); }); }); function clearCost() { $('#contractVal').validatebox('enableValidation'); var opt = document.getElementById('contractValBreakup'); opt.options.length = 0; } function addCost() { var conVal = $("#contractVal").val(); var cur = $("#contractValCur").combobox('getValue'); if (conVal == "") { showMessager('Invalid input', 'Please input currency value!'); return false; } else if (cur == "") { showMessager('Invalid input', 'Please select currency!'); return false; } var curOpt = conVal + " " + cur; var opt = document.getElementById('contractValBreakup'); opt.options[opt.options.length] = new Option(curOpt, curOpt); $("#contractVal").val(""); $('#contractVal').numberbox('setValue', ''); $('#contractVal').validatebox('disableValidation'); } function getFieldObject(id, value) { return { "id" : id, "value" : value }; } function saveOpportunity() { if (!$("#ff").form('validate')) { $.messager.show({ title : 'Alert', msg : 'Required fields can not be left blank.', showType : 'show' }); return false; } var data = getFormData("ff"); var costList = document.getElementById('contractValBreakup'); var costAry = new Array(); for ( var i = 0; i < costList.options.length; i++) { var d = costList.options[i].value; var dAry = d.split(" "); costAry.push({ "value" : dAry[0], "currency" : dAry[1] }); } if (costAry.length > 0) data["contractVal"] = costAry; data["userId"] = $("#userId").val(); data["projectType"] = { "id" : $("#projectType").val(), "value" : $("#projectType").val() }; data["market"] = { "id" : $("#market").val(), "value" : $("#market").val() }; data["portfolio"] = { "id" : $("#portfolio").val(), "value" : $("#portfolio").val() }; data["portfolioName"] = { "id" : $("#portfolioName").val(), "value" : $("#portfolioName").val() }; $.postJSON("saveOpportunity.htm", data, function(result) { if (result.success) { showMessager("Info", "Opportunity Saved"); window.close(); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function resetForm() { $("#ff").reset(); }
JavaScript
function saveReviewData() { if (!$("#ff").form('validate')) { showMessager("Alert", 'Required fields can not be left blank.'); return false; } var data = getFormData("ff"); data["userId"] = $("#userId").val(); data["opportunityId"] = $("#opportunityId").val(); data["prjObjId"] = $("#prjObjId").val(); data["assignmentId"] = $("#assignmentId").val(); $.postJSON("saveReviewData.htm?type=financial", data, function(result) { if (result.success) { showMessager("Info", result.message); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function approveReview() { if (!$("#ff").form('validate')) { $.messager.show({ title : 'Alert', msg : 'Required fields can not be left blank.', showType : 'show' }); return false; } approveReviewOpportunity($("#opportunityId").val(), $("#assignmentId") .val(), $("#userId").val(), true); } function showAddComments() { $("#addNotesContent").html($("#hiddenAddNotes").val()); $('#winAddNotes').window('open'); return false; } $(document).ready(function() { var prjObjId = $("#prjObjId").val(); $.getJSON('getViewData.htm?prjObjId=' + prjObjId, function(data) { if (data.hasOwnProperty("addNotes")) { $("#hiddenAddNotes").val(data.addNotes); data["addNotes"] = ""; } setFormData("ff", data); if ($("#hiddenAddNotes").val() == ""){ $("#btnShowAddComments").hide(); } //alert($("#hiddenAddNotes").val()); }); });
JavaScript
var timerId = null; $(document).ready(function() { loadCalendar(); drawChart(); updateProgress(); // setUserImg(); loadBullitenBoard(); }); function loadCalendar() { $('#calendar').fullCalendar({ header : { left : 'prev,next today', center : 'title', right : 'month,basicWeek,basicDay' }, editable : false, events : function(start, end, callback) { var events = getEventData(); callback(events); } }); } function getEventData() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var eventData = [ { title : 'All Day Event', start : new Date(y, m, 1) }, { title : 'Long Event', start : new Date(y, m, d - 5), end : new Date(y, m, d - 2) }, { id : 999, title : 'Repeating Event', start : new Date(y, m, d - 3, 16, 0), allDay : false }, { id : 999, title : 'Repeating Event', start : new Date(y, m, d + 4, 16, 0), allDay : false }, { title : 'Meeting', start : new Date(y, m, d, 10, 30), allDay : false }, { title : 'Lunch', start : new Date(y, m, d, 12, 0), end : new Date(y, m, d, 14, 0), allDay : false }, { title : 'Birthday Party', start : new Date(y, m, d + 1, 19, 0), end : new Date(y, m, d + 1, 22, 30), allDay : false }, { title : 'Click for Google', start : new Date(y, m, 28), end : new Date(y, m, 29), url : 'http://google.com/' } ]; return eventData; } function drawChart() { var data = ""; var order = [ 0, 1, 2 ], i = 0, xFormat = d3.time.format('%A'), rotateTimer, chart, t = 5000; $ .getJSON( 'resources/app/js/chartData.json', function(result) { data = result; if ($("#xchart-sine").length > 0) { if (data && data.length > 0) { chart = new xChart('bar', data[order[i]], '#xchart-sine', { axisPaddingTop : 5, paddingLeft : 30, dataFormatX : function(x) { return new Date(x); }, tickFormatX : function(x) { return d3.time.format('%a')(x); } }); rotateTimer = setTimeout(rotateChart, t); } else { $("#xchart-sine") .html( "<div Style='min-height: inherit;line-height:170px;text-align:center;'>Configure charts on dashboard using <i class='fa fa-cog'></i></div>"); } } }); function updateChart(i) { chart.setData(data[i]); } function rotateChart() { i += 1; i = (i >= order.length) ? 0 : i; updateChart(order[i]); rotateTimer = setTimeout(rotateChart, t); } $("#btnStopTimer").click(function() { if (rotateTimer) { clearTimeout(rotateTimer); rotateTimer = null; $(this).find("i").removeClass("fa-pause"); $(this).find("i").addClass("fa-play"); } else { rotateTimer = setTimeout(rotateChart, 1000); $(this).find("i").removeClass("fa-play"); $(this).find("i").addClass("fa-pause"); } }); $("#btnPrevChart").click(function() { i -= 1; i = (i <= -1) ? order.length-1 : i; updateChart(order[i]); }); $("#btnNextChart").click(function() { i += 1; i = (i >= order.length) ? 0 : i; updateChart(order[i]); }); } function updateProgress() { $("[data-percent]").each(function() { return $(this).css({ width : "" + ($(this).attr("data-percent")) + "%" }); }); } function loadBullitenBoard() { $.getJSON("loadBullitenBoard.htm?topOnly=true", function(data) { var lines = ""; $.each(data, function(idx, ele) { var date = ele.date.split("-"); lines += "<div class='box-section news with-icons'>"; lines += "<div class='" + ele.avatarClass + "'><i class='" + ele.iconClass + "'></i></div>"; lines += "<div class='news-time'><span>" + date[0] + "</span> " + date[1] + "</div>"; lines += "<div class='news-content'>"; lines += "<div class='news-title'>"; lines += "<a href='#'>" + ele.title + "</a>"; lines += "</div>"; lines += "<div class='news-text'>" + ele.text + "</div>"; lines += "</div></div>"; }); $("#bullitenContent").html(lines); }); }
JavaScript
$(document).ready( function() { initKendoGrid('orders', 'ordersTemplate', 'http://demos.telerik.com/kendo-ui/service/products'); $("#orders button[btnaction='addNew']").click(function() { alert('Add new button fired'); }); $("#orders button[btnaction='edit']").click(function() { alert('Edit button fired'); }); });
JavaScript
function toolbar_click() { alert("Toolbar command is clicked!"); return false; } function initKendoGrid(containerId, toolbarId, dataUrl) { var dataSource = new kendo.data.DataSource({ transport : { read : { url : dataUrl, dataType : "jsonp" } }, serverPaging : false, serverSorting : false, serverFiltering : false, pageSize : 10 }); $("#" + containerId).kendoGrid({ toolbar : [ { template : kendo.template($("#" + toolbarId).html()) } ], dataSource : dataSource, scrollable : false, sortable : true, groupable : true, filterable : true, pageable : { buttonCount : 4 }, columns : [ { field : "ProductID", width : "70px" }, { field : "ProductName", title : "Product Name", width : "20%" }, { field : "UnitPrice", title : "Unit Price" } ] }); }
JavaScript
$(document).ready(function() { $(".search-query").keyup(function(e) { if (e.which == 13) initQuickSearch($(this).val()); }); $(".search-query").focus(function() { $(this).select(); }); loadLists(); loadSideBarContents(); }); function initQuickSearch(value) { alert(value); } function loadLists() { $("select[url]").each( function(idx, obj) { $.getJSON($(obj).attr("url"), function(data) { $.each(data, function(idx, ele) { $(obj).append( "<option value='" + ele.value + "'>" + ele.text + "</option>"); }); }); }); } function loadSideBarContents() { var a = function(url, selector) { $ .getJSON( url, function(data) { var lines = ""; $ .each( data, function(idx, ele) { lines += "<li class='list-group-item'><a href='loadObject?type=" + ele.type; if(ele.hasOwnProperty('id')) lines+=+ "&id=" + ele.id ; if(ele.hasOwnProperty('title')) lines += "' title='" + ele.title + "'"; lines += "><i class='fa " + ele.iconClass + "'></i><span>" + ele.text + "</span></a></li>"; }); $(selector).html(lines); }); }; a('loadBookmarks.htm?topOnly=true', "#bookmarks ul"); a('loadReports.htm?topOnly=true', "#reports ul"); a('loadProjectNavigator.htm?topOnly=true', "#navigator ul"); }
JavaScript
$(document).ready(function() { $("#scheduler").kendoScheduler({ date : new Date("2013/6/6"), showWorkHours : true, height : 500, views : [ { type : "day", title : "D" }, { type : "week", title : "W" }, { type : "month", title : "M" } ], dataSource : [ { id : 1, start : new Date("2013/6/6 08:00 AM"), end : new Date("2013/6/6 09:00 AM"), title : "Interview" } ] }); }); function drawRotationChart() { var chData = ""; var chartId = "dashBoardChart"; var order = [ 0, 1, 2 ], i = 0, rotateTimer, t = 5000; $ .getJSON( 'resources/app/js/chartData1.json', function(result) { chData = result.da; if (chData && chData.length > 0) { updateChart(0); rotateTimer = setTimeout(rotateChart, t); } else { $("#" + chartId) .html( "<div Style='min-height: inherit;line-height:170px;text-align:center;'>Configure charts on dashboard using <i class='fa fa-cog'></i></div>"); } }).error(function(xhr, ajaxOptions, thrownError) { alert(thrownError); }); function rotateChart() { i += 1; i = (i >= order.length) ? 0 : i; updateChart(order[i]); rotateTimer = setTimeout(rotateChart, t); } $("#btnStopTimer").click(function() { if (rotateTimer) { clearTimeout(rotateTimer); rotateTimer = null; $(this).find("i").removeClass("fa-pause"); $(this).find("i").addClass("fa-play"); } else { rotateTimer = setTimeout(rotateChart, 1000); $(this).find("i").removeClass("fa-play"); $(this).find("i").addClass("fa-pause"); } }); $("#btnPrevChart").click(function() { i -= 1; i = (i <= -1) ? order.length - 1 : i; updateChart(order[i]); }); $("#btnNextChart").click(function() { i += 1; i = (i >= order.length) ? 0 : i; updateChart(order[i]); }); function updateChart(i) { var chartConfig = chData[i].configuration; chartConfig.dataSource = { data : chData[i].chartData }; $("#" + chartId).kendoChart(chartConfig); $(".title[for='" + chartId + "']").html(chartConfig.title.text); } } $(document).ready(function() { drawRotationChart(); updateProgress(); }); function updateProgress() { $("[data-percent]").each(function() { return $(this).css({ width : "" + ($(this).attr("data-percent")) + "%" }); }); }
JavaScript
$(document).ready(function () { "use strict"; var $input1; module("Setup jQuery, DOM and autocompleter"); test("Create INPUT tag", function() { $input1 = $('<input type="text" id="input1">'); $('#qunit-fixture').append($input1); $input1 = $("#input1"); equal($input1.attr("id"), "input1"); }); test("Create autocompleter", function() { $input1.autocomplete(); equal($input1.data("autocompleter") instanceof $.Autocompleter, true); }); test("Check default options", function() { var ac = $input1.data("autocompleter"); var defaultOptions = $.fn.autocomplete.defaults; var acOptions = ac.options; $.each(defaultOptions, function(index) { equal(defaultOptions[index], acOptions[index]); }); }); });
JavaScript
/*! * jQuery Autocompleter * jquery.autocomplete.js * http://code.google.com/p/jquery-autocomplete/ * Copyright 2011, Dylan Verheul * Licensed under the MIT license */ (function($) { "use strict"; /** * Default settings for options */ var defaultOptions = { inputClass: 'acInput', loadingClass: 'acLoading', resultsClass: 'acResults', selectClass: 'acSelect', queryParamName: 'q', limitParamName: 'limit', extraParams: {}, remoteDataType: false, lineSeparator: '\n', cellSeparator: '|', minChars: 2, maxItemsToShow: 10, delay: 400, useCache: true, maxCacheLength: 10, matchSubset: true, matchCase: false, matchInside: true, mustMatch: false, selectFirst: false, selectOnly: false, showResult: null, preventDefaultReturn: true, preventDefaultTab: false, autoFill: false, filterResults: true, sortResults: true, sortFunction: null, onItemSelect: null, onNoMatch: null, onFinish: null, matchStringConverter: null, beforeUseConverter: null, autoWidth: 'min-width' }; /** * Autocompleter Object * @param {jQuery} $elem jQuery object with one input tag * @param {Object=} options Settings * @constructor */ $.Autocompleter = function($elem, options) { /** * Assert parameters */ if (!$elem || !($elem instanceof jQuery) || $elem.length !== 1 || $elem.get(0).tagName.toUpperCase() !== 'INPUT') { throw new Error('Invalid parameter for jquery.Autocompleter, jQuery object with one element with INPUT tag expected.'); } /** * Init options */ this.options = options; /** * Shortcut to self * @type Object * @private */ var self = this; /** * Cached data * @type Object * @private */ this.cacheData_ = {}; /** * Number of cached data items * @type number * @private */ this.cacheLength_ = 0; /** * Class name to mark selected item * @type string * @private */ this.selectClass_ = 'jquery-autocomplete-selected-item'; /** * Handler to activation timeout * @type ?number * @private */ this.keyTimeout_ = null; /** * Last key pressed in the input field (store for behavior) * @type ?number * @private */ this.lastKeyPressed_ = null; /** * Last value processed by the autocompleter * @type ?string * @private */ this.lastProcessedValue_ = null; /** * Last value selected by the user * @type ?string * @private */ this.lastSelectedValue_ = null; /** * Is this autocompleter active? * Set by showResults() if we have results to show * @type boolean * @private */ this.active_ = false; /** * Is it OK to finish on blur? * @type boolean * @private */ this.finishOnBlur_ = true; /** * Sanitize minChars */ this.options.minChars = parseInt(this.options.minChars, 10); if (isNaN(this.options.minChars) || this.options.minChars < 1) { this.options.minChars = defaultOptions.minChars; } /** * Sanitize maxItemsToShow */ this.options.maxItemsToShow = parseInt(this.options.maxItemsToShow, 10); if (isNaN(this.options.maxItemsToShow) || this.options.maxItemsToShow < 1) { this.options.maxItemsToShow = defaultOptions.maxItemsToShow; } /** * Sanitize maxCacheLength */ this.options.maxCacheLength = parseInt(this.options.maxCacheLength, 10); if (isNaN(this.options.maxCacheLength) || this.options.maxCacheLength < 1) { this.options.maxCacheLength = defaultOptions.maxCacheLength; } /** * Init DOM elements repository */ this.dom = {}; /** * Store the input element we're attached to in the repository */ this.dom.$elem = $elem; /** * Switch off the native autocomplete and add the input class */ this.dom.$elem.attr('autocomplete', 'off').addClass(this.options.inputClass); /** * Create DOM element to hold results */ this.dom.$results = $('<div></div>').hide().addClass(this.options.resultsClass).css({ position: 'absolute' }); $('body').append(this.dom.$results); /** * Attach keyboard monitoring to $elem */ $elem.keydown(function(e) { self.lastKeyPressed_ = e.keyCode; switch(self.lastKeyPressed_) { case 38: // up e.preventDefault(); if (self.active_) { self.focusPrev(); } else { self.activate(); } return false; case 40: // down e.preventDefault(); if (self.active_) { self.focusNext(); } else { self.activate(); } return false; case 9: // tab if (self.active_) { self.selectCurrent(); if (self.options.preventDefaultTab) { e.preventDefault(); return false; } } break; case 13: // return if (self.active_) { self.selectCurrent(); if (self.options.preventDefaultReturn) { e.preventDefault(); return false; } } break; case 27: // escape if (self.active_) { e.preventDefault(); self.finish(); return false; } break; default: self.activate(); } }); /** * Finish on blur event */ $elem.blur(function() { if (self.finishOnBlur_) { setTimeout(function() { self.finish(); }, 200); } }); }; /** * Position output DOM elements */ $.Autocompleter.prototype.position = function() { var offset = this.dom.$elem.offset(); this.dom.$results.css({ top: offset.top + this.dom.$elem.outerHeight(), left: offset.left }); }; /** * Read from cache */ $.Autocompleter.prototype.cacheRead = function(filter) { var filterLength, searchLength, search, maxPos, pos; if (this.options.useCache) { filter = String(filter); filterLength = filter.length; if (this.options.matchSubset) { searchLength = 1; } else { searchLength = filterLength; } while (searchLength <= filterLength) { if (this.options.matchInside) { maxPos = filterLength - searchLength; } else { maxPos = 0; } pos = 0; while (pos <= maxPos) { search = filter.substr(0, searchLength); if (this.cacheData_[search] !== undefined) { return this.cacheData_[search]; } pos++; } searchLength++; } } return false; }; /** * Write to cache */ $.Autocompleter.prototype.cacheWrite = function(filter, data) { if (this.options.useCache) { if (this.cacheLength_ >= this.options.maxCacheLength) { this.cacheFlush(); } filter = String(filter); if (this.cacheData_[filter] !== undefined) { this.cacheLength_++; } this.cacheData_[filter] = data; return this.cacheData_[filter]; } return false; }; /** * Flush cache */ $.Autocompleter.prototype.cacheFlush = function() { this.cacheData_ = {}; this.cacheLength_ = 0; }; /** * Call hook * Note that all called hooks are passed the autocompleter object */ $.Autocompleter.prototype.callHook = function(hook, data) { var f = this.options[hook]; if (f && $.isFunction(f)) { return f(data, this); } return false; }; /** * Set timeout to activate autocompleter */ $.Autocompleter.prototype.activate = function() { var self = this; var activateNow = function() { self.activateNow(); }; var delay = parseInt(this.options.delay, 10); if (isNaN(delay) || delay <= 0) { delay = 250; } if (this.keyTimeout_) { clearTimeout(this.keyTimeout_); } this.keyTimeout_ = setTimeout(activateNow, delay); }; /** * Activate autocompleter immediately */ $.Autocompleter.prototype.activateNow = function() { var value = this.beforeUseConverter(this.dom.$elem.val()); if (value !== this.lastProcessedValue_ && value !== this.lastSelectedValue_) { if (value.length >= this.options.minChars) { this.lastProcessedValue_ = value; this.fetchData(value); } } }; /** * Get autocomplete data for a given value */ $.Autocompleter.prototype.fetchData = function(value) { if (this.options.data) { this.filterAndShowResults(this.options.data, value); } else { var self = this; this.fetchRemoteData(value, function(remoteData) { self.filterAndShowResults(remoteData, value); }); } }; /** * Get remote autocomplete data for a given value */ $.Autocompleter.prototype.fetchRemoteData = function(filter, callback) { var data = this.cacheRead(filter); if (data) { callback(data); } else { var self = this; this.dom.$elem.addClass(this.options.loadingClass); var ajaxCallback = function(data) { var parsed = false; if (data !== false) { parsed = self.parseRemoteData(data); self.cacheWrite(filter, parsed); } self.dom.$elem.removeClass(self.options.loadingClass); callback(parsed); }; $.ajax({ url: this.makeUrl(filter), success: ajaxCallback, error: function() { ajaxCallback(false); }, dataType: 'text' }); } }; /** * Create or update an extra parameter for the remote request */ $.Autocompleter.prototype.setExtraParam = function(name, value) { var index = $.trim(String(name)); if (index) { if (!this.options.extraParams) { this.options.extraParams = {}; } if (this.options.extraParams[index] !== value) { this.options.extraParams[index] = value; this.cacheFlush(); } } }; /** * Build the url for a remote request */ $.Autocompleter.prototype.makeUrl = function(param) { var self = this; var url = this.options.url; var params = $.extend({}, this.options.extraParams); // If options.queryParamName === false, append query to url // instead of using a GET parameter if (this.options.queryParamName === false) { url += encodeURIComponent(param); } else { params[this.options.queryParamName] = param; } if (this.options.limitParamName && this.options.maxItemsToShow) { params[this.options.limitParamName] = this.options.maxItemsToShow; } var urlAppend = []; $.each(params, function(index, value) { urlAppend.push(self.makeUrlParam(index, value)); }); if (urlAppend.length) { url += url.indexOf('?') === -1 ? '?' : '&'; url += urlAppend.join('&'); } return url; }; /** * Create partial url for a name/value pair */ $.Autocompleter.prototype.makeUrlParam = function(name, value) { return [name, encodeURIComponent(value)].join('='); }; /** * Parse data received from server */ $.Autocompleter.prototype.parseRemoteData = function(remoteData) { var remoteDataType = this.options.remoteDataType; if (remoteDataType === 'json') { return this.parseRemoteJSON(remoteData); } return this.parseRemoteText(remoteData); }; /** * Parse data received in text format */ $.Autocompleter.prototype.parseRemoteText = function(remoteData) { var results = []; var text = String(remoteData).replace('\r\n', this.options.lineSeparator); var i, j, data, line, lines = text.split(this.options.lineSeparator); var value; for (i = 0; i < lines.length; i++) { line = lines[i].split(this.options.cellSeparator); data = []; for (j = 0; j < line.length; j++) { data.push(decodeURIComponent(line[j])); } value = data.shift(); results.push({ value: value, data: data }); } return results; }; /** * Parse data received in JSON format */ $.Autocompleter.prototype.parseRemoteJSON = function(remoteData) { return $.parseJSON(remoteData); }; /** * Filter results and show them * @param results * @param filter */ $.Autocompleter.prototype.filterAndShowResults = function(results, filter) { this.showResults(this.filterResults(results, filter), filter); }; /** * Filter results * @param results * @param filter */ $.Autocompleter.prototype.filterResults = function(results, filter) { var filtered = []; var value, data, i, result, type, include; var pattern, testValue; for (i = 0; i < results.length; i++) { result = results[i]; type = typeof result; if (type === 'string') { value = result; data = {}; } else if ($.isArray(result)) { value = result[0]; data = result.slice(1); } else if (type === 'object') { value = result.value; data = result.data; } value = String(value); if (value > '') { if (typeof data !== 'object') { data = {}; } if (this.options.filterResults) { pattern = this.matchStringConverter(filter); testValue = this.matchStringConverter(value); if (!this.options.matchCase) { pattern = pattern.toLowerCase(); testValue = testValue.toLowerCase(); } include = testValue.indexOf(pattern); if (this.options.matchInside) { include = include > -1; } else { include = include === 0; } } else { include = true; } if (include) { filtered.push({ value: value, data: data }); } } } if (this.options.sortResults) { filtered = this.sortResults(filtered, filter); } if (this.options.maxItemsToShow > 0 && this.options.maxItemsToShow < filtered.length) { filtered.length = this.options.maxItemsToShow; } return filtered; }; /** * Sort results * @param results * @param filter */ $.Autocompleter.prototype.sortResults = function(results, filter) { var self = this; var sortFunction = this.options.sortFunction; if (!$.isFunction(sortFunction)) { sortFunction = function(a, b, f) { return self.sortValueAlpha(a, b, f); }; } results.sort(function(a, b) { return sortFunction(a, b, filter); }); return results; }; /** * Default sort filter * @param a * @param b */ $.Autocompleter.prototype.sortValueAlpha = function(a, b) { a = String(a.value); b = String(b.value); if (!this.options.matchCase) { a = a.toLowerCase(); b = b.toLowerCase(); } if (a > b) { return 1; } if (a < b) { return -1; } return 0; }; /** * Convert string before matching * @param s * @param a * @param b */ $.Autocompleter.prototype.matchStringConverter = function(s, a, b) { var converter = this.options.matchStringConverter; if ($.isFunction(converter)) { s = converter(s, a, b); } return s; }; /** * Convert string before use * @param s * @param a * @param b */ $.Autocompleter.prototype.beforeUseConverter = function(s, a, b) { var converter = this.options.beforeUseConverter; if ($.isFunction(converter)) { s = converter(s, a, b); } return s; }; /** * Enable finish on blur event */ $.Autocompleter.prototype.enableFinishOnBlur = function() { this.finishOnBlur_ = true; }; /** * Disable finish on blur event */ $.Autocompleter.prototype.disableFinishOnBlur = function() { this.finishOnBlur_ = false; }; /** * Create a results item (LI element) from a result * @param result */ $.Autocompleter.prototype.createItemFromResult = function(result) { var self = this; var $li = $('<li>' + this.showResult(result.value, result.data) + '</li>'); $li.data({value: result.value, data: result.data}) .click(function() { self.selectItem($li); }) .mousedown(self.disableFinishOnBlur) .mouseup(self.enableFinishOnBlur) ; return $li; }; /** * Show all results * @param results * @param filter */ $.Autocompleter.prototype.showResults = function(results, filter) { var numResults = results.length; if (numResults === 0) { return this.finish(); } var self = this; var $ul = $('<ul></ul>'); var i, result, $li, autoWidth, first = false, $first = false; for (i = 0; i < numResults; i++) { result = results[i]; $li = this.createItemFromResult(result); $ul.append($li); if (first === false) { first = String(result.value); $first = $li; $li.addClass(this.options.firstItemClass); } if (i === numResults - 1) { $li.addClass(this.options.lastItemClass); } } // Always recalculate position before showing since window size or // input element location may have changed. this.position(); this.dom.$results.html($ul).show(); if (this.options.autoWidth) { autoWidth = this.dom.$elem.outerWidth() - this.dom.$results.outerWidth() + this.dom.$results.width(); this.dom.$results.css(this.options.autoWidth, autoWidth); } $('li', this.dom.$results).hover( function() { self.focusItem(this); }, function() { /* void */ } ); if (this.autoFill(first, filter) || this.options.selectFirst || (this.options.selectOnly && numResults === 1)) { this.focusItem($first); } this.active_ = true; }; $.Autocompleter.prototype.showResult = function(value, data) { if ($.isFunction(this.options.showResult)) { return this.options.showResult(value, data); } else { return value; } }; $.Autocompleter.prototype.autoFill = function(value, filter) { var lcValue, lcFilter, valueLength, filterLength; if (this.options.autoFill && this.lastKeyPressed_ !== 8) { lcValue = String(value).toLowerCase(); lcFilter = String(filter).toLowerCase(); valueLength = value.length; filterLength = filter.length; if (lcValue.substr(0, filterLength) === lcFilter) { this.dom.$elem.val(value); this.selectRange(filterLength, valueLength); return true; } } return false; }; $.Autocompleter.prototype.focusNext = function() { this.focusMove(+1); }; $.Autocompleter.prototype.focusPrev = function() { this.focusMove(-1); }; $.Autocompleter.prototype.focusMove = function(modifier) { var $items = $('li', this.dom.$results); modifier = parseInt(modifier, 10); for (var i = 0; i < $items.length; i++) { if ($($items[i]).hasClass(this.selectClass_)) { this.focusItem(i + modifier); return; } } this.focusItem(0); }; $.Autocompleter.prototype.focusItem = function(item) { var $item, $items = $('li', this.dom.$results); if ($items.length) { $items.removeClass(this.selectClass_).removeClass(this.options.selectClass); if (typeof item === 'number') { item = parseInt(item, 10); if (item < 0) { item = 0; } else if (item >= $items.length) { item = $items.length - 1; } $item = $($items[item]); } else { $item = $(item); } if ($item) { $item.addClass(this.selectClass_).addClass(this.options.selectClass); } } }; $.Autocompleter.prototype.selectCurrent = function() { var $item = $('li.' + this.selectClass_, this.dom.$results); if ($item.length === 1) { this.selectItem($item); } else { this.finish(); } }; $.Autocompleter.prototype.selectItem = function($li) { var value = $li.data('value'); var data = $li.data('data'); var displayValue = this.displayValue(value, data); var processedDisplayValue = this.beforeUseConverter(displayValue); this.lastProcessedValue_ = processedDisplayValue; this.lastSelectedValue_ = processedDisplayValue; this.dom.$elem.val(displayValue).focus(); this.setCaret(displayValue.length); this.callHook('onItemSelect', { value: value, data: data }); this.finish(); }; $.Autocompleter.prototype.displayValue = function(value, data) { if ($.isFunction(this.options.displayValue)) { return this.options.displayValue(value, data); } return value; }; $.Autocompleter.prototype.finish = function() { if (this.keyTimeout_) { clearTimeout(this.keyTimeout_); } if (this.beforeUseConverter(this.dom.$elem.val()) !== this.lastSelectedValue_) { if (this.options.mustMatch) { this.dom.$elem.val(''); } this.callHook('onNoMatch'); } this.dom.$results.hide(); this.lastKeyPressed_ = null; this.lastProcessedValue_ = null; if (this.active_) { this.callHook('onFinish'); } this.active_ = false; }; $.Autocompleter.prototype.selectRange = function(start, end) { var input = this.dom.$elem.get(0); if (input.setSelectionRange) { input.focus(); input.setSelectionRange(start, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }; $.Autocompleter.prototype.setCaret = function(pos) { this.selectRange(pos, pos); }; /** * jQuery autocomplete plugin */ $.fn.autocomplete = function(options) { var url; if (arguments.length > 1) { url = options; options = arguments[1]; options.url = url; } else if (typeof options === 'string') { url = options; options = { url: url }; } var opts = $.extend({}, $.fn.autocomplete.defaults, options); return this.each(function() { var $this = $(this); $this.data('autocompleter', new $.Autocompleter( $this, $.meta ? $.extend({}, opts, $this.data()) : opts )); }); }; /** * Store default options */ $.fn.autocomplete.defaults = defaultOptions; })(jQuery);
JavaScript
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v2.1.3 (2011-02-07) * * (c) 2009-2010 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*jslint forin: true */ /*global document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $ */ (function() { // encapsulated variables var doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isIE = /msie/i.test(userAgent) && !win.opera, docMode8 = doc.documentMode == 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), //hasSVG = win.SVGAngle || doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"), hasSVG = !!doc.createElementNS && !!doc.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGRect, SVG_NS = 'http://www.w3.org/2000/svg', hasTouch = 'ontouchstart' in doc.documentElement, colorCounter, symbolCounter, symbolSizes = {}, idCounter = 0, timeFactor = 1, // 1 = JavaScript time, 1000 = Unix time garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, // some constants for frequently used strings UNDEFINED, DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', /* * Empirical lowest possible opacities for TRACKER_FILL * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,'+ (hasSVG ? 0.000001 : 0.002) +')', // invisible but clickable NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // check for a custom HighchartsAdapter defined prior to this file globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}, // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. each = adapter.each, grep = adapter.grep, map = adapter.map, merge = adapter.merge, hyphenate = adapter.hyphenate, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, animate = adapter.animate, stop = adapter.stop, // lookup over the types and the associated classes seriesTypes = {}, hoverChart; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { if (!a) { a = {}; } for (var n in b) { a[n] = b[n]; } return a; } /** * Shortcut for parseInt * @param {Object} s */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s == 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj == 'object'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n == 'number'; } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] == item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined (obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, setAttribute = 'setAttribute', ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem[setAttribute](prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem[setAttribute](key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { if (!obj || obj.constructor != Array) { obj = [obj]; } return obj; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Make a style string from a JS object * @param {Object} style */ function serializeCSS(style) { var s = '', key; // serialize the declaration for (key in style) { s += hyphenate(key) +':'+ style[key] + ';'; } return s; } /** * Set CSS on a give element * @param {Object} el * @param {Object} styles */ function css (el, styles) { if (isIE) { if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity='+ (styles.opacity * 100) +')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement (tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /* * Define the adapter for frameworks. If an external adapter is not defined, * Highcharts reverts to the built-in jQuery adapter. */ if (globalAdapter && globalAdapter.init) { globalAdapter.init(); } if (!globalAdapter && win.jQuery) { var jQ = jQuery; /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ each = function(arr, fn) { for (var i = 0, len = arr.length; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Filter an array */ grep = jQ.grep; /** * Map an array * @param {Array} arr * @param {Function} fn */ map = function(arr, fn){ //return jQuery.map(arr, fn); var results = []; for (var i = 0, len = arr.length; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }; /** * Deep merge two objects and return a third object */ merge = function(){ var args = arguments; return jQ.extend(true, null, args[0], args[1], args[2], args[3]); }; /** * Convert a camelCase string to a hyphenated string * @param {String} str */ hyphenate = function (str) { return str.replace(/([A-Z])/g, function(a, b){ return '-'+ b.toLowerCase(); }); }; /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent = function (el, event, fn){ jQ(el).bind(event, fn); }; /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent = function(el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jquery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jquery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && !el[func]) { el[func] = function() {}; } jQ(el).unbind(eventType, handler); }; /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent = function(el, type, eventArguments, defaultFunction) { var event = jQ.Event(type), detachedType = 'detached'+ type; extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // trigger it jQ(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented()) { defaultFunction(event); } }; /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate = function (el, params, options) { var $el = jQ(el); if (params.d) { el.toD = params.d; // keep the array form for paths, used in jQ.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); $el.animate(params, options); }; /** * Stop running animation */ stop = function (el) { jQ(el).stop(); }; // extend jQuery jQ.extend( jQ.easing, { easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // extend the animate function to allow SVG animations var oldStepDefault = jQuery.fx.step._default, oldCur = jQuery.fx.prototype.cur; // do the step jQ.fx.step._default = function(fx){ var elem = fx.elem; if (elem.attr) { // is SVG element wrapper elem.attr(fx.prop, fx.now); } else { oldStepDefault.apply(this, arguments); } }; // animate paths jQ.fx.step.d = function(fx) { var elem = fx.elem; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { var ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // get the current value jQ.fx.prototype.cur = function() { var elem = this.elem, r; if (elem.attr) { // is SVG element wrapper r = elem.attr(this.prop); } else { r = oldCur.apply(this, arguments); } return r; }; } /** * Add a global listener for mousemove events */ /*addEvent(doc, 'mousemove', function(e) { if (globalMouseMove) { globalMouseMove(e); } });*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function(elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function(arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] == M) { arr.splice(i + 1, 0, arr[i+1], arr[i+2], arr[i+1], arr[i+2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift) { end = [].concat(end).splice(0, numParams).concat(end); elem.shift = false; // reset for following animations } // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function(start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos == 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i == end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC; makeTime = useUTC ? Date.UTC : function(year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = useUTC ? 'getUTCMinutes' : 'getMinutes'; getHours = useUTC ? 'getUTCHours' : 'getHours'; getDay = useUTC ? 'getUTCDay' : 'getDay'; getDate = useUTC ? 'getUTCDate' : 'getDate'; getMonth = useUTC ? 'getUTCMonth' : 'getMonth'; getFullYear = useUTC ? 'getUTCFullYear' : 'getFullYear'; setMinutes = useUTC ? 'setUTCMinutes' : 'setMinutes'; setHours = useUTC ? 'setUTCHours' : 'setHours'; setDate = useUTC ? 'setUTCDate' : 'setDate'; setMonth = useUTC ? 'setUTCMonth' : 'setMonth'; setFullYear = useUTC ? 'setUTCFullYear' : 'setFullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { defaultOptions = merge(defaultOptions, options); // apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates a new object. */ function getOptions() { return defaultOptions; } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, align: 'center', x: 0, y: 15, /*formatter: function() { return this.value; },*/ style: { color: '#666', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacingTop: 10, spacingRight: 10, spacingBottom: 15, spacingLeft: 10, style: { fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0' //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' }, title: { text: 'Chart title', align: 'center', // floating: false, // margin: 15, // x: 0, // verticalAlign: 'top', y: 15, // docs style: { color: '#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', y: 30, // docs style: { color: '#6D869F' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //cursor: 'default', //dashStyle: null, //enableMouseTracking: true, events: {}, lineWidth: 2, shadow: true, // stacking: null, marker: { enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { enabled: false, y: -6, formatter: function() { return this.y; } }), //pointStart: 0, //pointInterval: 1, showInLegend: true, states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function() { return this.name; }, // lineHeight: 16, // docs: deprecated borderWidth: 1, borderColor: '#909090', borderRadius: 5, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, style: { padding: '5px' }, itemStyle: { cursor: 'pointer', color: '#3E576F' }, itemHoverStyle: { cursor: 'pointer', color: '#000000' }, itemHiddenStyle: { color: '#C0C0C0' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, // docs y: 0 // docs }, loading: { hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, showDuration: 100, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .85)', borderWidth: 2, borderRadius: 5, //formatter: defaultFormatter, shadow: true, //shared: false, snap: hasTouch ? 25 : 10, style: { color: '#333333', fontSize: '12px', padding: '5px', whiteSpace: 'nowrap' } }, toolbar: { itemStyle: { color: '#4572A7', cursor: 'pointer' } }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '10px' } } }; // Axis defaults var defaultXAxisOptions = { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // docs // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, max: null, min: null, minPadding: 0.01, maxPadding: 0.01, //maxZoom: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: false, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 5, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#6D869F', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //x: 0, //y: 0 }, type: 'linear' // linear or datetime }, defaultYAxisOptions = merge(defaultXAxisOptions, { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { align: 'right', x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Y-values' } }), defaultLeftAxisOptions = { labels: { align: 'right', x: -8, y: null // docs }, title: { rotation: 270 } }, defaultRightAxisOptions = { labels: { align: 'left', x: 8, y: null // docs }, title: { rotation: 90 } }, defaultBottomAxisOptions = { // horizontal axis labels: { align: 'center', x: 0, y: 14 // staggerLines: null }, title: { rotation: 0 } }, defaultTopAxisOptions = merge(defaultBottomAxisOptions, { labels: { y: -5 // staggerLines: null } }); // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; //defaultPlotOptions.line = merge(defaultSeriesOptions); defaultPlotOptions.spline = merge(defaultSeriesOptions); defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, states: { hover: { lineWidth: 0 } } }); defaultPlotOptions.area = merge(defaultSeriesOptions, { // threshold: 0, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, states: { hover: { brightness: 0.1, shadow: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } } }); defaultPlotOptions.bar = merge(defaultPlotOptions.column, { dataLabels: { align: 'left', x: 5, y: 0 } }); defaultPlotOptions.pie = merge(defaultSeriesOptions, { //dragType: '', // n/a borderColor: '#FFFFFF', borderWidth: 1, center: ['50%', '50%'], colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: '#606060', // connectorPadding: 5, distance: 30, enabled: true, formatter: function() { return this.point.name; }, y: 5 }, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: '75%', showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } } }); // set the default time methods setTimeMethods(); /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function(){}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var Color = function(input) { // declare variables var rgba = [], result; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // rgba if((result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input))) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } // hex else if((result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input))) { rgba = [pInt(result[1],16), pInt(result[2],16), pInt(result[3],16), 1]; } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; // it's NaN if gradient colors on a column chart if (rgba && !isNaN(rgba[0])) { if (format == 'rgb') { ret = 'rgb('+ rgba[0] +','+ rgba[1] +','+ rgba[2] +')'; } else if (format == 'a') { ret = rgba[3]; } else { ret = 'rgba('+ rgba.join(',') +')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, setOpacity: setOpacity }; }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat (number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = number, c = isNaN(decimals = mathAbs(decimals)) ? 2 : decimals, d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = pInt(n = mathAbs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { function pad (number) { return number.toString().replace(/^([0-9])$/, '0$1'); } if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp * timeFactor), // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, langMonths = lang.months, // list all format keys replacements = { // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) // Month 'b': langMonths[month].substr(0, 3), // Short month, like 'Jan' 'B': langMonths[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()) // Two digits seconds, 00 through 59 }; // do the replaces for (var key in replacements) { format = format.replace('%'+ key, replacements[key]); } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Loop up the node tree and add offsetWidth and offsetHeight to get the * total page offset for a given element. Used by Opera and iOS on hover and * all browsers on point click. * * @param {Object} el * */ function getPosition (el) { var p = { left: el.offsetLeft, top: el.offsetTop }; while ((el = el.offsetParent)) { p.left += el.offsetLeft; p.top += el.offsetTop; if (el != doc.body && el != doc.documentElement) { p.left -= el.scrollLeft; p.top -= el.scrollTop; } } return p; } /** * A wrapper object for SVG elements */ function SVGElement () {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function(renderer, nodeName) { this.element = doc.createElementNS(SVG_NS, nodeName); this.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function(params, options, complete) { var animOptions = pick(options, globalAnimation, true); if (animOptions) { animOptions = merge(animOptions); if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function(hash, val) { var key, value, i, child, element = this.element, nodeName = element.nodeName, renderer = this.renderer, skipAttr, shadows = this.shadows, hasSetSymbolSize, ret = this; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName == 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key == 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || this[key] || 0; if (key != 'd' && key != 'visibility') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // paths if (key == 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } this.d = value; // shortcut for animations // update child tspans x values } else if (key == 'x' && nodeName == 'text') { for (i = 0; i < element.childNodes.length; i++ ) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') == attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } if (this.rotation) { attr(element, 'transform', 'rotate('+ this.rotation +' '+ value +' '+ pInt(hash.y || attr(element, 'y')) +')'); } // apply gradients } else if (key == 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName == 'circle' && (key == 'x' || key == 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // translation and text rotation } else if (key == 'translateX' || key == 'translateY' || key == 'rotation' || key == 'verticalAlign') { this[key] = value; this.updateTransform(); skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key == 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key == 'dashstyle') { key = 'stroke-dasharray'; if (value) { value = value.toLowerCase() .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * hash['stroke-width']; } value = value.join(','); } // special } else if (key == 'isTracker') { this[key] = value; // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key == 'width') { value = pInt(value); // Text alignment } else if (key == 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; } // jQuery animate changes case if (key == 'strokeWidth') { key = 'stroke-width'; } // Chrome/Win < 6 bug (http://code.google.com/p/chromium/issues/detail?id=15461) if (isWebKit && key == 'stroke-width' && value === 0) { value = 0.000001; } // symbols if (this.symbolName && /^(x|y|r|start|end|innerR)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d)$/.test(key)) { i = shadows.length; while (i--) { attr(shadows[i], key, value); } } /* trows errors in Chrome if ((key == 'width' || key == 'height') && nodeName == 'rect' && value < 0) { console.log(element); } */ if (key == 'text') { // only one node allowed this.textStr = value; if (this.added) { renderer.buildText(this); } } else if (!skipAttr) { //element.setAttribute(key, value); attr(element, key, value); } } } return ret; }, /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function(hash) { var wrapper = this; wrapper.x = pick(hash.x, wrapper.x); wrapper.y = pick(hash.y, wrapper.y); // mootools animation bug needs parseFloat wrapper.r = pick(hash.r, wrapper.r); wrapper.start = pick(hash.start, wrapper.start); wrapper.end = pick(hash.end, wrapper.end); wrapper.width = pick(hash.width, wrapper.width); wrapper.height = pick(hash.height, wrapper.height); wrapper.innerR = pick(hash.innerR, wrapper.innerR); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName](wrapper.x, wrapper.y, wrapper.r, { start: wrapper.start, end: wrapper.end, width: wrapper.width, height: wrapper.height, innerR: wrapper.innerR }) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function(clipRect) { return this.attr('clip-path', 'url('+ this.renderer.url +'#'+ clipRect.id +')'); }, /** * Set styles for the element * @param {Object} styles */ css: function(styles) { var elemWrapper = this, elem = elemWrapper.element, textWidth = styles && styles.width && elem.nodeName == 'text'; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // save the styles in an object styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; // serialize and set style attribute if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute if (textWidth) { delete styles.width; } css(elemWrapper.element, styles); } else { elemWrapper.attr({ style: serializeCSS(styles) }); } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function(eventType, handler) { var fn = handler; // touch if (hasTouch && eventType == 'click') { eventType = 'touchstart'; fn = function(e) { e.preventDefault(); handler(); } } // simplest possible event model for internal use this.element['on'+ eventType] = fn; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function(x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function() { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function() { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, inverted = wrapper.inverted, rotation = wrapper.rotation, transform = []; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // apply translate if (translateX || translateY) { transform.push('translate('+ translateX +','+ translateY +')'); } // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate('+ rotation +' '+ wrapper.x +' '+ wrapper.y +')'); } if (transform.length) { attr(wrapper.element, 'transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function() { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {Object} box The box to align to, needs a width and height * */ align: function(alignOptions, alignByTranslate, box) { if (!alignOptions) { // called on resize alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; } else { // first call on instanciate this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box) { // boxes other than renderer handle this internally this.renderer.alignedObjects.push(this); } } box = pick(box, this.renderer); var align = alignOptions.align, vAlign = alignOptions.verticalAlign, x = (box.x || 0) + (alignOptions.x || 0), // default: left align y = (box.y || 0) + (alignOptions.y || 0), // default: top align attribs = {}; // align if (/^(right|center)$/.test(align)) { x += (box.width - (alignOptions.width || 0) ) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = x; // vertical align if (/^(bottom|middle)$/.test(vAlign)) { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = y; // animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function() { var bBox, width, height, rotation = this.rotation, rad = rotation * deg2rad; try { // fails in Firefox if the container has display: none // use extend because IE9 is not allowed to change width and height in case // of rotation (below) bBox = extend({}, this.element.getBBox()); } catch(e) { bBox = { width: 0, height: 0 }; } width = bBox.width; height = bBox.height; // adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } return bBox; }, /* * * Manually compute width and height of rotated text from non-rotated. Shared by SVG and VML * @param {Object} bBox * @param {number} rotation * / rotateBBox: function(bBox, rotation) { var rad = rotation * math.PI * 2 / 360, // radians width = bBox.width, height = bBox.height; },*/ /** * Show the element */ show: function() { return this.attr({ visibility: VISIBLE }); }, /** * Hide the element */ hide: function() { return this.attr({ visibility: HIDDEN }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function(parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i; // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement != element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); return this; } } } // default: append at the end parentNode.appendChild(element); this.added = true; return this; }, /** * Destroy the element and element wrapper */ destroy: function() { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentNode = element.parentNode, key; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = null; stop(wrapper); // stop running animations // remove element if (parentNode) { parentNode.removeChild(element); } // destroy shadows if (shadows) { each(shadows, function(shadow) { parentNode = shadow.parentNode; if (parentNode) { // the entire chart HTML can be overwritten parentNode.removeChild(shadow); } }); } // remove from alignObjects erase(wrapper.renderer.alignedObjects, wrapper); for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Empty a group element */ empty: function() { var element = this.element, childNodes = element.childNodes, i = childNodes.length; while (i--) { element.removeChild(childNodes[i]); } }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean} apply */ shadow: function(apply) { var shadows = [], i, shadow, element = this.element, // compensate for inverted plot area transform = this.parentInverted ? '(-1,-1)' : '(1,1)'; if (apply) { for (i = 1; i <= 3; i++) { shadow = element.cloneNode(0); attr(shadow, { 'isShadow': 'true', 'stroke': 'rgb(0, 0, 0)', 'stroke-opacity': 0.05 * i, 'stroke-width': 7 - 2 * i, 'transform': 'translate'+ transform, 'fill': NONE }); element.parentNode.insertBefore(shadow, element); shadows.push(shadow); } this.shadows = shadows; } return this; } }; /** * The default SVG renderer */ var SVGRenderer = function() { this.init.apply(this, arguments); }; SVGRenderer.prototype = { /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function(container, width, height, forExport) { var renderer = this, loc = location, boxWrapper; renderer.Element = SVGElement; boxWrapper = renderer.createElement('svg') .attr({ xmlns: SVG_NS, version: '1.1' }); container.appendChild(boxWrapper.element); // object properties renderer.box = boxWrapper.element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; renderer.url = isIE ? '' : loc.href.replace(/#.*?$/, ''); // page url used for internal references renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.setSize(width, height, false); }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function(nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function(wrapper) { var textNode = wrapper.element, lines = pick(wrapper.textStr, '').toString() .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br[^>]?>/g), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="([^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, reverse = isFirefox && textStyles && textStyles.HcDirection == 'rtl' && !this.forExport, // issue #38 arr, width = textStyles && pInt(textStyles.width), textLineHeight = textStyles && textStyles.lineHeight, lastLine, i = childNodes.length; // remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } each(lines, function(line, lineNo) { var spans, spanNo = 0, lineHeight; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length == 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'); if (styleRegex.test(span)) { attr( tspan, 'style', span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2') ); } if (hrefRegex.test(span)) { attr(tspan, 'onclick', 'location.href=\"'+ span.match(hrefRegex)[1] +'\"'); css(tspan, { cursor: 'pointer' }); } span = span.replace(/<(.|\n)*?>/g, '') || ' '; // issue #38 workaround. if (reverse) { arr = []; i = span.length; while (i--) { arr.push(span.charAt(i)) } span = arr.join(''); } // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { // Firefox ignores spaces at the front or end of the tspan attributes.dx = 3; // space } // first span on subsequent line, add the line height if (!spanNo) { if (lineNo) { // Webkit and opera sometimes return 'normal' as the line height. In that // case, webkit uses offsetHeight, while Opera falls back to 18 lineHeight = pInt(window.getComputedStyle(lastLine, null).getPropertyValue('line-height')); if (isNaN(lineHeight)) { lineHeight = textLineHeight || lastLine.offsetHeight || 18; } attr(tspan, 'dy', lineHeight); } lastLine = tspan; // record for use in next line } // add attributes attr(tspan, attributes); // append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/-/g, '- ').split(' '), tooLong, actualWidth, rest = []; while (words.length || rest.length) { actualWidth = textNode.getBBox().width; tooLong = actualWidth > width; if (!tooLong || words.length == 1) { // new line needed words = rest; rest = []; if (words.length) { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { x: parentX, dy: textLineHeight || 16 }); textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } }); }); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function(points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] == points[4]) { points[1] = points[4] = mathRound(points[1]) + (width % 2 / 2); } if (points[2] == points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { return this.createElement('path').attr({ d: path, fill: NONE }); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }; return this.createElement('circle').attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { // arcs are defined as symbols for the ability to set // attributes in attr and animate if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } return this.symbol('arc', x || 0, y || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { if (arguments.length > 1) { var normalizer = (strokeWidth || 0) % 2 / 2; // normalize for crisp edges x = mathRound(x || 0) + normalizer; y = mathRound(y || 0) + normalizer; width = mathRound((width || 0) - 2 * normalizer); height = mathRound((height || 0) - 2 * normalizer); } var attr = isObject(x) ? x : // the attributes can be passed as the first argument { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; return this.createElement('rect').attr(extend(attr, { rx: r || attr.r, ry: r || attr.r, fill: NONE })); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function(width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function(name) { return this.createElement('g').attr( defined(name) && { 'class': PREFIX + name } ); }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function(src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function(symbol, x, y, radius, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( x, y, radius, options ), imageRegex = /^url\((.*?)\)$/, imageSrc; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, r: radius }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { imageSrc = symbol.match(imageRegex)[1]; // create the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); // create a dummy JavaScript image to get the width and height createElement('img', { onload: function() { var img = this, size = symbolSizes[img.src] || [img.width, img.height]; obj.attr({ width: size[0], height: size[1] }).translate( -mathRound(size[0] / 2), -mathRound(size[1] / 2) ); }, src: imageSrc }); // default circles } else { obj = this.circle(x, y, radius); } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'square': function (x, y, radius) { var len = 0.707 * radius; return [ M, x-len, y-len, L, x+len, y-len, x+len, y+len, x-len, y+len, 'Z' ]; }, 'triangle': function (x, y, radius) { return [ M, x, y-1.33 * radius, L, x+radius, y + 0.67 * radius, x-radius, y + 0.67 * radius, 'Z' ]; }, 'triangle-down': function (x, y, radius) { return [ M, x, y + 1.33 * radius, L, x-radius, y-0.67 * radius, x+radius, y-0.67 * radius, 'Z' ]; }, 'diamond': function (x, y, radius) { return [ M, x, y-radius, L, x+radius, y, x, y+radius, x-radius, y, 'Z' ]; }, 'arc': function (x, y, radius, options) { var start = options.start, end = options.end - 0.000001, // to prevent cos and sin of start and end from becoming equal on 360 arcs innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, 'Z' // close ]; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object * * @param {Object} color The color or config object */ color: function(color, elem, prop) { var colorObject, regexRgba = /^rgba/; if (color && color.linearGradient) { var renderer = this, strLinearGradient = 'linearGradient', linearGradient = color[strLinearGradient], id = PREFIX + idCounter++, gradientObject, stopColor, stopOpacity; gradientObject = renderer.createElement(strLinearGradient).attr({ id: id, gradientUnits: 'userSpaceOnUse', x1: linearGradient[0], y1: linearGradient[1], x2: linearGradient[2], y2: linearGradient[3] }).add(renderer.defs); each(color.stops, function(stop) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); }); return 'url('+ this.url +'#'+ id +')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop +'-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { return color; } }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position */ text: function(str, x, y) { // declare variables var defaultChartStyle = defaultOptions.chart.style, wrapper; x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = this.createElement('text') .attr({ x: x, y: y, text: str }) .css({ 'font-family': defaultChartStyle.fontFamily, 'font-size': defaultChartStyle.fontSize }); wrapper.x = x; wrapper.y = y; return wrapper; } }; // end SVGRenderer /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ var VMLRenderer; if (!hasSVG) { /** * The VML element wrapper. */ var VMLElement = extendClass( SVGElement, { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function(renderer, nodeName) { var markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';']; // divs and shapes need size if (nodeName == 'shape' || nodeName == DIV) { style.push('left:0;top:0;width:10px;height:10px;'); } if (docMode8) { style.push('visibility: ', nodeName == DIV ? HIDDEN : VISIBLE); } markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = nodeName == DIV || nodeName == 'span' || nodeName == 'img' ? markup.join('') : renderer.prepVML(markup); this.element = createElement(markup); } this.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function(parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // issue #140 workaround - related to #61 and #74 if (docMode8 && parentNode.gVis == HIDDEN) { css(element, { visibility: HIDDEN }); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.updateTransform(); } return wrapper; }, /** * Get or set attributes */ attr: function(hash, val) { var key, value, i, element = this.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = this.renderer, symbolName = this.symbolName, childNodes, hasSetSymbolSize, shadows = this.shadows, skipAttr, ret = this; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key == 'strokeWidth' || key == 'stroke-width') { ret = this.strokeweight; } else { ret = this[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR)/.test(key)) { // if one of the symbol size affecting parameters are changed, // check all the others only once for each call to an element's // .attr() method if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key == 'd') { value = value || []; this.d = value.join(' '); // used in getter for animation // convert paths i = value.length; var convertedPath = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { convertedPath[i] = mathRound(value[i] * 10) - 5; } // close the path else if (value[i] == 'Z') { convertedPath[i] = 'x'; } else { convertedPath[i] = value[i]; } } value = convertedPath.join(' ') || 'x'; element.path = value; // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = value; } } skipAttr = true; // directly mapped to css } else if (key == 'zIndex' || key == 'visibility') { // issue 61 workaround if (docMode8 && key == 'visibility' && nodeName == 'DIV') { element.gVis = value; childNodes = element.childNodes; i = childNodes.length; while (i--) { css(childNodes[i], { visibility: value }); } if (value == VISIBLE) { // issue 74 value = null; } } if (value) { elemStyle[key] = value; } skipAttr = true; // width and height } else if (/^(width|height)$/.test(key)) { // clipping rectangle special if (this.updateClipping) { this[key] = value; this.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // x and y } else if (/^(x|y)$/.test(key)) { this[key] = value; // used in getter if (element.tagName == 'SPAN') { this.updateTransform(); } else { elemStyle[{ x: 'left', y: 'top' }[key]] = value; } // class name } else if (key == 'class') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key == 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key == 'stroke-width' || key == 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key == 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key == 'fill') { if (nodeName == 'SPAN') { // text color elemStyle.color = value; } else { element.filled = value != NONE ? true : false; value = renderer.color(value, element, key); key = 'fillcolor'; } // translation for animation } else if (key == 'translateX' || key == 'translateY' || key == 'rotation' || key == 'align') { if (key == 'align') { key = 'textAlign'; } this[key] = value; this.updateTransform(); skipAttr = true; } // text for rotated and non-rotated elements else if (key == 'text') { element.innerHTML = value; skipAttr = true; } // let the shadow follow the main element if (shadows && key == 'visibility') { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } return ret; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function(clipRect) { var wrapper = this, clipMembers = clipRect.members; clipMembers.push(wrapper); wrapper.destroyClip = function() { erase(clipMembers, wrapper); }; return wrapper.css(clipRect.getCSS(wrapper.inverted)); }, /** * Set styles for the element * @param {Object} styles */ css: function(styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName == 'SPAN' && styles.width; /*if (textWidth) { extend(styles, { display: 'block', whiteSpace: 'normal' }); }*/ if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function() { var wrapper = this; if (wrapper.destroyClip) { wrapper.destroyClip(); } SVGElement.prototype.destroy.apply(wrapper); }, /** * Remove all child nodes of a group, except the v:group element */ empty: function() { var element = this.element, childNodes = element.childNodes, i = childNodes.length, node; while (i--) { node = childNodes[i]; node.parentNode.removeChild(node); } }, /** * VML override for calculating the bounding box based on offsets * * @return {Object} A hash containing values for x, y, width and height */ getBBox: function() { var element = this.element; // faking getBBox in exported SVG in legacy IE if (element.nodeName == 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function(eventType, handler) { // simplest possible event model for internal use this.element['on'+ eventType] = function() { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ updateTransform: function(hash) { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], nonLeft = align && align != 'left'; // apply translate if (translateX || translateY) { wrapper.css({ marginLeft: translateX, marginTop: translateY }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function(child) { wrapper.renderer.invertChild(child, elem); }); } if (elem.tagName == 'SPAN') { var width, height, rotation = wrapper.rotation, lineHeight, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform != wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); // Adjust for alignment and rotation. // Test case: http://highcharts.com/tests/?file=text-rotation css(elem, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); } width = elem.offsetWidth; height = elem.offsetHeight; // update textWidth if (width > textWidth) { css(elem, { width: textWidth +PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y lineHeight = mathRound(pInt(elem.style.fontSize || 12) * 1.2); xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for lineHeight and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * lineHeight * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * lineHeight * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: x + xCorr, top: y + yCorr }); // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean} apply */ shadow: function(apply) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path; // the path is some mysterious string-like object that can be cast to a string if (''+ element.path === '') { path = 'x'; } if (apply) { for (i = 1; i <= 3; i++) { markup = ['<shape isShadow="true" strokeweight="', ( 7 - 2 * i ) , '" filled="false" path="', path, '" coordsize="100,100" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + 1, top: pInt(elemStyle.top) + 1 } ); // apply the opacity markup = ['<stroke color="black" opacity="', (0.05 * i), '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it element.parentNode.insertBefore(shadow, element); // record it shadows.push(shadow); } this.shadows = shadows; } return this; } }); /** * The VML renderer */ VMLRenderer = function() { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge( SVGRenderer.prototype, { // inherit SVGRenderer isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function(container, width, height) { var renderer = this, boxWrapper; renderer.Element = VMLElement; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); container.appendChild(boxWrapper.element); // generate the containing box renderer.box = boxWrapper.element; renderer.boxWrapper = boxWrapper; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // setup default css doc.createStyleSheet().cssText = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke'+ '{ behavior:url(#default#VML); display: inline-block; } '; } }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: x, top: y, width: width, height: height, getCSS: function(inverted) { var rect = this,//clipRect.element.style, top = rect.top, left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect('+ mathRound(inverted ? left : top) + 'px,'+ mathRound(inverted ? bottom : right) + 'px,'+ mathRound(inverted ? right : bottom) + 'px,'+ mathRound(inverted ? top : left) +'px)' }; // issue 74 workaround if (!inverted && docMode8) { extend(ret, { width: right +PX, height: bottom +PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function() { each(clipRect.members, function(member) { member.css(clipRect.getCSS(member.inverted)); }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function(color, elem, prop) { var colorObject, regexRgba = /^rgba/, markup; if (color && color.linearGradient) { var stopColor, stopOpacity, linearGradient = color.linearGradient, angle, color1, opacity1, color2, opacity2; each(color.stops, function(stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } if (!i) { // first color1 = stopColor; opacity1 = stopOpacity; } else { color2 = stopColor; opacity2 = stopOpacity; } }); // calculate the angle based on the linear vector angle = 90 - math.atan( (linearGradient[3] - linearGradient[1]) / // y vector (linearGradient[2] - linearGradient[0]) // x vector ) * 180 / mathPI; // when colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<', prop, ' colors="0% ', color1, ',100% ', color2, '" angle="', angle, '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="gradient" focus="100%" />']; createElement(this.prepVML(markup), null, null, elem); // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName != 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); return colorObject.get('rgb'); } else { return color; } }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function(markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') == -1) { markup = markup.replace('/>', ' style="'+ vmlStyle +'" />'); } else { markup = markup.replace('style="', 'style="'+ vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: function(str, x, y) { var defaultChartStyle = defaultOptions.chart.style; return this.createElement('span') .attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); }, /** * Create and return a path element * @param {Array} path */ path: function (path) { // create the shape return this.createElement('shape').attr({ // subpixel precision down to 0.1 (width and height = 10px) coordsize: '100 100', d: path }); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function(x, y, r) { return this.path(this.symbols.circle(x, y, r)); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function(name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function(src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.css({ left: x, top: y, width: width, height: height }); } return obj; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function(x, y, width, height, r, strokeWidth) { // todo: share this code with SVG if (arguments.length > 1) { var normalizer = (strokeWidth || 0) % 2 / 2; // normalize for crisp edges x = mathRound(x || 0) + normalizer; y = mathRound(y || 0) + normalizer; width = mathRound((width || 0) - 2 * normalizer); height = mathRound((height || 0) - 2 * normalizer); } if (isObject(x)) { // the attributes can be passed as the first argument y = x.y; width = x.width; height = x.height; r = x.r; x = x.x; } return this.symbol('rect', x || 0, y || 0, r || 0, { width: width || 0, height: height || 0 }); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function(element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 10, top: pInt(parentStyle.height) - 10, rotation: -90 }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, radius, options) { var start = options.start, end = options.end, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), innerRadius = options.innerR, circleCorrection = 0.07 / radius, innerCorrection = innerRadius && 0.1 / innerRadius || 0; if (end - start === 0) { // no angle, don't show it. return ['x']; //} else if (end - start == 2 * mathPI) { // full circle } else if (2 * mathPI - end + start < circleCorrection) { // full circle // empirical correction found by trying out the limits for different radii cosEnd = - circleCorrection; } else if (end - start < innerCorrection) { // issue #186, another mysterious VML arc problem cosEnd = mathCos(start + innerCorrection); } return [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd, // end y 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ]; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, r) { return [ 'wa', // clockwisearcto x - r, // left y - r, // top x + r, // right y + r, // bottom x + r, // start x y, // start y x + r, // end x y, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape * * @param {Object} left Left position * @param {Object} top Top position * @param {Object} r Border radius * @param {Object} options Width and height */ rect: function (left, top, r, options) { var width = options.width, height = options.height, right = left + width, bottom = top + height; r = mathMin(r, width, height); return [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } } }); } /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /** * General renderer */ var Renderer = hasSVG ? SVGRenderer : VMLRenderer; /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart (options, callback) { defaultXAxisOptions = merge(defaultXAxisOptions, defaultOptions.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, defaultOptions.yAxis); defaultOptions.xAxis = defaultOptions.yAxis = null; // Handle regular options options = merge(defaultOptions, options); // Define chart variables var optionsChart = options.chart, optionsMargin = optionsChart.margin, margin = isObject(optionsMargin) ? optionsMargin : [optionsMargin, optionsMargin, optionsMargin, optionsMargin], optionsMarginTop = pick(optionsChart.marginTop, margin[0]), optionsMarginRight = pick(optionsChart.marginRight, margin[1]), optionsMarginBottom = pick(optionsChart.marginBottom, margin[2]), optionsMarginLeft = pick(optionsChart.marginLeft, margin[3]), spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, spacingBox, chartTitleOptions, chartSubtitleOptions, plotTop, marginRight, marginBottom, plotLeft, axisOffset, renderTo, renderToClone, container, containerId, containerWidth, containerHeight, chartWidth, chartHeight, oldChartWidth, oldChartHeight, chartBackground, plotBackground, plotBGImage, plotBorder, chart = this, chartEvents = optionsChart.events, runChartClick = chartEvents && !!chartEvents.click, eventType, isInsidePlot, // function tooltip, mouseIsDown, loadingDiv, loadingSpan, loadingShown, plotHeight, plotWidth, tracker, trackerGroup, placeTrackerGroup, legend, legendWidth, legendHeight, chartPosition,// = getPosition(container), hasCartesianSeries = optionsChart.showAxes, isResizing = 0, axes = [], maxTicks, // handle the greatest amount of ticks on grouped axes series = [], inverted, renderer, tooltipTick, tooltipInterval, hoverX, drawChartBox, // function getMargins, // function resetMargins, // function setChartSize, // function resize, zoom, // function zoomOut; // function /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis (chart, options) { // Define variables var isXAxis = options.isX, opposite = options.opposite, // needed in setOptions horiz = inverted ? !isXAxis : isXAxis, side = horiz ? (opposite ? 0 /* top */ : 2 /* bottom */) : (opposite ? 1 /* right*/ : 3 /* left */ ), stacks = {}; options = merge( isXAxis ? defaultXAxisOptions : defaultYAxisOptions, [defaultTopAxisOptions, defaultRightAxisOptions, defaultBottomAxisOptions, defaultLeftAxisOptions][side], options ); var axis = this, isDatetimeAxis = options.type == 'datetime', offset = options.offset || 0, xOrY = isXAxis ? 'x' : 'y', axisLength, transA, // translation factor oldTransA, // used for prerendering transB = horiz ? plotLeft : marginBottom, // translation addend translate, // fn getPlotLinePath, // fn axisGroup, gridGroup, axisLine, dataMin, dataMax, associatedSeries, userSetMin, userSetMax, max = null, min = null, oldMin, oldMax, minPadding = options.minPadding, maxPadding = options.maxPadding, isLinked = defined(options.linkedTo), ignoreMinPadding, // can be set to true by a column or bar series ignoreMaxPadding, usePercentage, events = options.events, eventType, plotLinesAndBands = [], tickInterval, minorTickInterval, magnitude, tickPositions, // array containing predefined positions ticks = {}, minorTicks = {}, alternateBands = {}, tickAmount, labelOffset, axisTitleMargin,// = options.title.margin, dateTimeLabelFormat, categories = options.categories, labelFormatter = options.labels.formatter || // can be overwritten by dynamic format function() { var value = this.value, ret; if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (tickInterval % 1000000 === 0) { // use M abbreviation ret = (value / 1000000) +'M'; } else if (tickInterval % 1000 === 0) { // use k abbreviation ret = (value / 1000) +'k'; } else if (!categories && value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // strings (categories) and small numbers ret = value; } return ret; }, staggerLines = horiz && options.labels.staggerLines, reversed = options.reversed, tickmarkOffset = (categories && options.tickmarkPlacement == 'between') ? 0.5 : 0; /** * The Tick class */ function Tick(pos, minor) { var tick = this; tick.pos = pos; tick.minor = minor; tick.isNew = true; if (!minor) { tick.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function() { var pos = this.pos, labelOptions = options.labels, str, withLabel = !((pos == min && !pick(options.showFirstLabel, 1)) || (pos == max && !pick(options.showLastLabel, 0))), width = categories && horiz && categories.length && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && plotWidth / categories.length || !horiz && plotWidth / 2, css, label = this.label; // get the string str = labelFormatter.call({ isFirst: pos == tickPositions[0], isLast: pos == tickPositions[tickPositions.length - 1], dateTimeLabelFormat: dateTimeLabelFormat, value: (categories && categories[pos] ? categories[pos] : pos) }); // prepare CSS css = width && { width: (width - 2 * (labelOptions.padding || 10)) +PX }; css = extend(css, labelOptions.style); // first call if (label === UNDEFINED) { this.label = defined(str) && withLabel && labelOptions.enabled ? renderer.text( str, 0, 0 ) .attr({ align: labelOptions.align, rotation: labelOptions.rotation }) // without position absolute, IE export sometimes is wrong .css(css) .add(axisGroup): null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function() { var label = this.label; return label ? ((this.labelBBox = label.getBBox()))[horiz ? 'height' : 'width'] : 0; }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function(index, old) { var tick = this, major = !tick.minor, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridLineWidth = major ? options.gridLineWidth : options.minorGridLineWidth, gridLineColor = major ? options.gridLineColor : options.minorGridLineColor, dashStyle = major ? options.gridLineDashStyle : options.minorGridLineDashStyle, gridLinePath, mark = tick.mark, markPath, tickLength = major ? options.tickLength : options.minorTickLength, tickWidth = major ? options.tickWidth : (options.minorTickWidth || 0), tickColor = major ? options.tickColor : options.minorTickColor, tickPosition = major ? options.tickPosition : options.minorTickPosition, step = labelOptions.step, cHeight = old && oldChartHeight || chartHeight, attribs, x, y; // get x and y position for ticks and labels x = horiz ? translate(pos + tickmarkOffset, null, null, old) + transB : plotLeft + offset + (opposite ? (old && oldChartWidth || chartWidth) - marginRight - plotLeft : 0); y = horiz ? cHeight - marginBottom + offset - (opposite ? plotHeight : 0) : cHeight - translate(pos + tickmarkOffset, null, null, old) - transB; // create the grid line if (gridLineWidth) { gridLinePath = getPlotLinePath(pos + tickmarkOffset, gridLineWidth, old); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(gridGroup) : null; } if (gridLine && gridLinePath) { gridLine.animate({ d: gridLinePath }); } } // create the tick mark if (tickWidth) { // negate the length if (tickPosition == 'inside') { tickLength = -tickLength; } if (opposite) { tickLength = -tickLength; } markPath = renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); if (mark) { // updating mark.animate({ d: markPath }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth }).add(axisGroup); } } // the label is created on init - now move it into place if (label) { x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // vertically centered if (!defined(labelOptions.y)) { y += parseInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // correct for staggered labels if (staggerLines) { y += (index % staggerLines) * 16; } // apply step if (step) { // show those indices dividable by step label[index % step ? 'hide' : 'show'](); } label[tick.isNew ? 'attr' : 'animate']({ x: x, y: y }); } tick.isNew = false; }, /** * Destructor for the tick prototype */ destroy: function() { var tick = this, n; for (n in tick) { if (tick[n] && tick[n].destroy) { tick[n].destroy(); } } } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ function PlotLineOrBand(options) { var plotLine = this; if (options) { plotLine.options = options; plotLine.id = options.id; } //plotLine.render() return plotLine; } PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, toPath, // bands only from = options.from, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs; // plot line if (width) { path = getPlotLinePath(options.value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } // plot band else if (defined(from) && defined(to)) { // keep within plot area from = mathMax(from, min); to = mathMin(to, max); toPath = getPlotLinePath(to); path = getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } attribs = { fill: color }; } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function() { svgElem.show(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function(eventType) { svgElem.on(eventType, function(e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && plotWidth > 0 && plotHeight > 0) { // apply defaults optionsLabel = merge({ align: horiz && toPath && 'center', x: horiz ? !toPath && 4 : 10, verticalAlign : !horiz && toPath && 'middle', y: horiz ? toPath ? 16 : 10 : toPath ? 6 : -4, rotation: horiz && !toPath && 90 }, optionsLabel); // add the SVG element if (!label) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0 ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], path[6] || path[1]]; ys = [path[2], path[5], path[7] || path[2]]; x = mathMin.apply(math, xs); y = mathMin.apply(math, ys); label.align(optionsLabel, false, { x: x, y: y, width: mathMax.apply(math, xs) - x, height: mathMax.apply(math, ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function() { var obj = this, n; for (n in obj) { if (obj[n] && obj[n].destroy) { obj[n].destroy(); // destroy SVG wrappers } delete obj[n]; } // remove it from the lookup erase(plotLinesAndBands, obj); } }; /** * Get the minimum and maximum for the series of each axis */ function getSeriesExtremes() { var posStack = [], negStack = [], run; // reset dataMin and dataMax in case we're redrawing dataMin = dataMax = null; // get an overview of what series are associated with this axis associatedSeries = []; each(series, function(serie) { run = false; // match this axis against the series' given or implicated axis each(['xAxis', 'yAxis'], function(strAxis) { if ( // the series is a cartesian type, and... serie.isCartesian && // we're in the right x or y dimension, and... (strAxis == 'xAxis' && isXAxis || strAxis == 'yAxis' && !isXAxis) && ( // the axis number is given in the options and matches this axis index, or (serie.options[strAxis] == options.index) || // the axis index is not given (serie.options[strAxis] === UNDEFINED && options.index === 0) ) ) { serie[strAxis] = axis; associatedSeries.push(serie); // the series is visible, run the min/max detection run = true; } }); // ignore hidden series if opted if (!serie.visible && optionsChart.ignoreHiddenSeries) { run = false; } if (run) { var stacking, posPointStack, negPointStack, stackKey, negKey; if (!isXAxis) { stacking = serie.options.stacking; usePercentage = stacking == 'percent'; // create a stack for this particular series type if (stacking) { stackKey = serie.type + pick(serie.options.stack, ''); negKey = '-'+ stackKey; serie.stackKey = stackKey; // used in translate posPointStack = posStack[stackKey] || []; // contains the total values for each x posStack[stackKey] = posPointStack; negPointStack = negStack[negKey] || []; negStack[negKey] = negPointStack; } if (usePercentage) { dataMin = 0; dataMax = 99; } } if (serie.isCartesian) { // line, column etc. need axes, pie doesn't each(serie.data, function(point, i) { var pointX = point.x, pointY = point.y, isNegative = pointY < 0, pointStack = isNegative ? negPointStack : posPointStack, key = isNegative ? negKey : stackKey, totalPos, pointLow; // initial values if (dataMin === null) { // start out with the first point dataMin = dataMax = point[xOrY]; } // x axis if (isXAxis) { if (pointX > dataMax) { dataMax = pointX; } else if (pointX < dataMin) { dataMin = pointX; } } // y axis else if (defined(pointY)) { if (stacking) { pointStack[pointX] = defined(pointStack[pointX]) ? pointStack[pointX] + pointY : pointY; } totalPos = pointStack ? pointStack[pointX] : pointY; pointLow = pick(point.low, totalPos); if (!usePercentage) { if (totalPos > dataMax) { dataMax = totalPos; } else if (pointLow < dataMin) { dataMin = pointLow; } } if (stacking) { // add the series if (!stacks[key]) { stacks[key] = {}; } stacks[key][pointX] = { total: totalPos, cum: totalPos }; } } }); // For column, areas and bars, set the minimum automatically to zero // and prevent that minPadding is added in setScale if (/(area|column|bar)/.test(serie.type) && !isXAxis) { if (dataMin >= 0) { dataMin = 0; ignoreMinPadding = true; } else if (dataMax < 0) { dataMax = 0; ignoreMaxPadding = true; } } } } }); } /** * Translate from axis value to pixel position on the chart, or back * */ translate = function(val, backwards, cvsCoord, old) { var sign = 1, cvsOffset = 0, localA = old ? oldTransA : transA, localMin = old ? oldMin : min, returnValue; if (!localA) { localA = transA; } if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axisLength; } if (reversed) { // reversed axis sign *= -1; cvsOffset -= sign * axisLength; } if (backwards) { // reverse translation if (reversed) { val = axisLength - val; } returnValue = val / localA + localMin; // from chart pixel to value } else { // normal translation returnValue = sign * (val - localMin) * localA + cvsOffset; // from value to chart pixel } return returnValue; }; /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath = function(value, lineWidth, old) { var x1, y1, x2, y2, translatedValue = translate(value, null, null, old), cHeight = old && oldChartHeight || chartHeight, cWidth = old && oldChartWidth || chartWidth, skip; x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (horiz) { y1 = plotTop; y2 = cHeight - marginBottom; if (x1 < plotLeft || x1 > plotLeft + plotWidth) { skip = true; } } else { x1 = plotLeft; x2 = cWidth - marginRight; if (y1 < plotTop || y1 > plotTop + plotHeight) { skip = true; } } return skip ? null : renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }; /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval */ function normalizeTickInterval(interval, multiples) { var normalized; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = multiples ? 1 : math.pow(10, mathFloor(math.log(interval) / math.LN10)); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; //multiples = [1, 2, 2.5, 4, 5, 7.5, 10]; // the allowDecimals option if (options.allowDecimals === false) { if (magnitude == 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (var i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i+1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. */ function setDateTimeTickPositions() { tickPositions = []; var i, useUTC = defaultOptions.global.useUTC, oneSecond = 1000 / timeFactor, oneMinute = 60000 / timeFactor, oneHour = 3600000 / timeFactor, oneDay = 24 * 3600000 / timeFactor, oneWeek = 7 * 24 * 3600000 / timeFactor, oneMonth = 30 * 24 * 3600000 / timeFactor, oneYear = 31556952000 / timeFactor, units = [[ 'second', // unit name oneSecond, // fixed incremental unit [1, 2, 5, 10, 15, 30] // allowed multiples ], [ 'minute', // unit name oneMinute, // fixed incremental unit [1, 2, 5, 10, 15, 30] // allowed multiples ], [ 'hour', // unit name oneHour, // fixed incremental unit [1, 2, 3, 4, 6, 8, 12] // allowed multiples ], [ 'day', // unit name oneDay, // fixed incremental unit [1, 2] // allowed multiples ], [ 'week', // unit name oneWeek, // fixed incremental unit [1, 2] // allowed multiples ], [ 'month', oneMonth, [1, 2, 3, 4, 6] ], [ 'year', oneYear, null ]], unit = units[6], // default unit is years interval = unit[1], multiples = unit[2]; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = unit[1]; multiples = unit[2]; if (units[i+1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + units[i + 1][1]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval == oneYear && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the minimum value by flooring the date var multitude = normalizeTickInterval(tickInterval / interval, multiples), minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min * timeFactor); minDate.setMilliseconds(0); if (interval >= oneSecond) { // second minDate.setSeconds(interval >= oneMinute ? 0 : multitude * mathFloor(minDate.getSeconds() / multitude)); } if (interval >= oneMinute) { // minute minDate[setMinutes](interval >= oneHour ? 0 : multitude * mathFloor(minDate[getMinutes]() / multitude)); } if (interval >= oneHour) { // hour minDate[setHours](interval >= oneDay ? 0 : multitude * mathFloor(minDate[getHours]() / multitude)); } if (interval >= oneDay) { // day minDate[setDate](interval >= oneMonth ? 1 : multitude * mathFloor(minDate[getDate]() / multitude)); } if (interval >= oneMonth) { // month minDate[setMonth](interval >= oneYear ? 0 : multitude * mathFloor(minDate[getMonth]() / multitude)); minYear = minDate[getFullYear](); } if (interval >= oneYear) { // year minYear -= minYear % multitude; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval == oneWeek) { // get start of current week, independent of multitude minDate[setDate](minDate[getDate]() - minDate[getDay]() + options.startOfWeek); } // get tick positions i = 1; // prevent crash just in case minYear = minDate[getFullYear](); var time = minDate.getTime() / timeFactor, minMonth = minDate[getMonth](), minDateDate = minDate[getDate](); // iterate and add tick positions at appropriate values while (time < max && i < plotWidth) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval == oneYear) { time = makeTime(minYear + i * multitude, 0) / timeFactor; // if the interval is months, use Date.UTC to increase months } else if (interval == oneMonth) { time = makeTime(minYear, minMonth + i * multitude) / timeFactor; // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval == oneDay || interval == oneWeek)) { time = makeTime(minYear, minMonth, minDateDate + i * multitude * (interval == oneDay ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * multitude; } i++; } // push the last time tickPositions.push(time); // dynamic label formatter dateTimeLabelFormat = options.dateTimeLabelFormats[unit[0]]; } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { var invMag, ret = num; if (defined(magnitude)) { invMag = (magnitude < 1 ? mathRound(1 / magnitude) : 1) * 10; ret = mathRound(num * invMag) / invMag; } return ret; } /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ function setLinearTickPositions() { var i, roundedMin = mathFloor(min / tickInterval) * tickInterval, roundedMax = mathCeil(max / tickInterval) * tickInterval; tickPositions = []; // populate the intermediate values i = correctFloat(roundedMin); while (i <= roundedMax) { tickPositions.push(i); i = correctFloat(i + tickInterval); } } /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ function setTickPositions(secondPass) { var length, catPad, linkedParent, linkedParentExtremes, tickIntervalOption = options.tickInterval, tickPixelIntervalOption = options.tickPixelInterval, maxZoom = options.maxZoom || ( isXAxis ? mathMin(chart.smallestInterval * 5, dataMax - dataMin) : null ), zoomOffset; axisLength = horiz ? plotWidth : plotHeight; // linked axis gets the extremes from the parent axis if (isLinked) { linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo]; linkedParentExtremes = linkedParent.getExtremes(); min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); } // initial min and max from the extreme data values else { min = pick(userSetMin, options.min, dataMin); max = pick(userSetMax, options.max, dataMax); } // maxZoom exceeded, just center the selection if (max - min < maxZoom) { zoomOffset = (maxZoom - max + min) / 2; // if min and max options have been set, don't go beyond it min = mathMax(min - zoomOffset, pick(options.min, min - zoomOffset), dataMin); max = mathMin(min + maxZoom, pick(options.max, min + maxZoom), dataMax); } // pad the values to get clear of the chart's edges if (!categories && !usePercentage && !isLinked && defined(min) && defined(max)) { length = (max - min) || 1; if (!defined(options.min) && !defined(userSetMin) && minPadding && (dataMin < 0 || !ignoreMinPadding)) { min -= length * minPadding; } if (!defined(options.max) && !defined(userSetMax) && maxPadding && (dataMax > 0 || !ignoreMaxPadding)) { max += length * maxPadding; } } // get tickInterval if (min == max) { tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption == linkedParent.options.tickPixelInterval) { tickInterval = linkedParent.tickInterval; } else { tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : (max - min) * tickPixelIntervalOption / axisLength ); } if (!isDatetimeAxis && !defined(options.tickInterval)) { // linear tickInterval = normalizeTickInterval(tickInterval); } axis.tickInterval = tickInterval; // record for linked axis // get minorTickInterval minorTickInterval = options.minorTickInterval === 'auto' && tickInterval ? tickInterval / 5 : options.minorTickInterval; // find the tick positions if (isDatetimeAxis) { setDateTimeTickPositions(); } else { setLinearTickPositions(); } if (!isLinked) { // pad categorised axis to nearest half unit if (categories || (isXAxis && chart.hasColumn)) { catPad = (categories ? 1 : tickInterval) * 0.5; if (categories || !defined(pick(options.min, userSetMin))) { min -= catPad; } if (categories || !defined(pick(options.max, userSetMax))) { max += catPad; } } // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1]; if (options.startOnTick) { min = roundedMin; } else if (min > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { max = roundedMax; } else if (max < roundedMax) { tickPositions.pop(); } // record the greatest number of ticks for multi axis if (!maxTicks) { // first call, or maxTicks have been reset after a zoom operation maxTicks = { x: 0, y: 0 }; } if (!isDatetimeAxis && tickPositions.length > maxTicks[xOrY]) { maxTicks[xOrY] = tickPositions.length; } } } /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ function adjustTickAmount() { if (maxTicks && !isDatetimeAxis && !categories && !isLinked) { // only apply to linear scale var oldTickAmount = tickAmount, calculatedTickAmount = tickPositions.length; // set the axis-level tickAmount to use below tickAmount = maxTicks[xOrY]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push( correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } transA *= (calculatedTickAmount - 1) / (tickAmount - 1); max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount != oldTickAmount) { axis.isDirty = true; } } } /** * Set the scale based on data min and max, user set min and max or options * */ function setScale() { var type, i; oldMin = min; oldMax = max; // get data extremes if needed getSeriesExtremes(); // get fixed positions based on tickInterval setTickPositions(); // the translation factor used in translate function oldTransA = transA; transA = axisLength / ((max - min) || 1); // reset stacks if (!isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // mark as dirty if it is not already set to dirty and extremes have changed if (!axis.isDirty) { axis.isDirty = (min != oldMin || max != oldMax); } } /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ function setExtremes(newMin, newMax, redraw, animation) { redraw = pick(redraw, true); // defaults to true fireEvent(axis, 'setExtremes', { // fire an event to enable syncing of multiple charts min: newMin, max: newMax }, function() { // the default event handler userSetMin = newMin; userSetMax = newMax; // redraw if (redraw) { chart.redraw(animation); } }); } /** * Get the actual axis extremes */ function getExtremes() { return { min: min, max: max, dataMin: dataMin, dataMax: dataMax }; } /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ function getThreshold(threshold) { if (min > threshold) { threshold = min; } else if (max < threshold) { threshold = max; } return translate(threshold, 0, 1); } /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ function addPlotBandOrLine(options) { var obj = new PlotLineOrBand(options).render(); plotLinesAndBands.push(obj); return obj; } /** * Render the tick labels to a preliminary position to get their sizes */ function getOffset() { var hasData = associatedSeries.length && defined(min) && defined(max), titleOffset = 0, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, directionFactor = [-1, 1, 1, -1][side]; if (!axisGroup) { axisGroup = renderer.g('axis') .attr({ zIndex: 7 }) .add(); gridGroup = renderer.g('grid') .attr({ zIndex: 1 }) .add(); } labelOffset = 0; // reset if (hasData || isLinked) { each(tickPositions, function(pos) { if (!ticks[pos]) { ticks[pos] = new Tick(pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } // left side must be align: right and right side must have align: left for labels if (side === 0 || side == 2 || { 1: 'left', 3: 'right' }[side] == labelOptions.align) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (staggerLines) { labelOffset += (staggerLines - 1) * 16; } } else { // doesn't have data for (var n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0 ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .css(axisTitleOptions.style) .add(); } titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); } // handle automatic or user set offset offset = directionFactor * (options.offset || axisOffset[side]); axisTitleMargin = labelOffset + (side != 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) + titleMargin; axisOffset[side] = mathMax( axisOffset[side], axisTitleMargin + titleOffset + directionFactor * offset ); } /** * Render the axis */ function render() { var axisTitleOptions = options.title, alternateGridColor = options.alternateGridColor, lineWidth = options.lineWidth, lineLeft, lineTop, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(oldMin) && !isNaN(oldMin), hasData = associatedSeries.length && defined(min) && defined(max); // update metrics axisLength = horiz ? plotWidth : plotHeight; transA = axisLength / ((max - min) || 1); transB = horiz ? plotLeft : marginBottom; // translation addend // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (minorTickInterval && !categories) { var pos = min + (tickPositions[0] - min) % minorTickInterval; for (pos; pos <= max; pos += minorTickInterval) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(pos, true); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].isActive = true; minorTicks[pos].render(); } } // major ticks each(tickPositions, function(pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= min && pos <= max)) { // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true); } ticks[pos].isActive = true; ticks[pos].render(i); } }); // alternate grid color if (alternateGridColor) { each(tickPositions, function(pos, i) { if (i % 2 === 0 && pos < max) { /*plotLinesAndBands.push(new PlotLineOrBand({ from: pos, to: tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] : max, color: alternateGridColor }));*/ if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(); } alternateBands[pos].options = { from: pos, to: tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] : max, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot bands (behind grid lines) /*if (!hasRendered) { // only first time each(options.plotBands || [], function(plotBandOptions) { plotLinesAndBands.push(new PlotLineOrBand( extend({ zIndex: 1 }, plotBandOptions) ).render()); }); }*/ // custom plot lines and bands if (!hasRendered) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function(plotLineOptions) { plotLinesAndBands.push(new PlotLineOrBand(plotLineOptions).render()); }); } } // end if hasData // remove inactive ticks each([ticks, minorTicks, alternateBands], function(coll) { for (var pos in coll) { if (!coll[pos].isActive) { coll[pos].destroy(); delete coll[pos]; } else { coll[pos].isActive = false; // reset } } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { lineLeft = plotLeft + (opposite ? plotWidth : 0) + offset; lineTop = chartHeight - marginBottom - (opposite ? plotHeight : 0) + offset; linePath = renderer.crispLine([ M, horiz ? plotLeft: lineLeft, horiz ? lineTop: plotTop, L, horiz ? chartWidth - marginRight : lineLeft, horiz ? lineTop: chartHeight - marginBottom ], lineWidth); if (!axisLine) { axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(); } else { axisLine.animate({ d: linePath }); } } if (axis.axisTitle) { // compute anchor points for each of the title align options var margin = horiz ? plotLeft : plotTop, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? plotTop + plotHeight : plotLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes axisTitleMargin + //(isIE ? fontSize / 3 : 0)+ // preliminary fix for vml's centerline (side == 2 ? fontSize : 0); axis.axisTitle[hasRendered ? 'animate' : 'attr']({ x: horiz ? alongAxis: offAxis + (opposite ? plotWidth : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? plotHeight : 0) + offset: alongAxis + (axisTitleOptions.y || 0) // y }); } axis.isDirty = false; } /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ function removePlotBandOrLine(id) { for (var i = 0; i < plotLinesAndBands.length; i++) { if (plotLinesAndBands[i].id == id) { plotLinesAndBands[i].destroy(); } } } /** * Redraw the axis to reflect changes in the data or axis extremes */ function redraw() { // hide tooltip and hover states if (tracker.resetTracker) { tracker.resetTracker(); } // render the axis render(); // move plot lines and bands each(plotLinesAndBands, function(plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(associatedSeries, function(series) { series.isDirty = true; }); } /** * Set new axis categories and optionally redraw * @param {Array} newCategories * @param {Boolean} doRedraw */ function setCategories(newCategories, doRedraw) { // set the categories axis.categories = categories = newCategories; // force reindexing tooltips each(associatedSeries, function(series) { series.translate(); series.setTooltipPoints(true); }); // optionally redraw axis.isDirty = true; if (pick(doRedraw, true)) { chart.redraw(); } } // Run Axis // inverted charts have reversed xAxes as default if (inverted && isXAxis && reversed === UNDEFINED) { reversed = true; } // expose some variables extend(axis, { addPlotBand: addPlotBandOrLine, addPlotLine: addPlotBandOrLine, adjustTickAmount: adjustTickAmount, categories: categories, getExtremes: getExtremes, getPlotLinePath: getPlotLinePath, getThreshold: getThreshold, isXAxis: isXAxis, options: options, plotLinesAndBands: plotLinesAndBands, getOffset: getOffset, render: render, setCategories: setCategories, setExtremes: setExtremes, setScale: setScale, setTickPositions: setTickPositions, translate: translate, redraw: redraw, removePlotBand: removePlotBandOrLine, removePlotLine: removePlotBandOrLine, reversed: reversed, stacks: stacks }); // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // set min and max setScale(); } // end Axis /** * The toolbar object * * @param {Object} chart */ function Toolbar(chart) { var buttons = {}; function add(id, text, title, fn) { if (!buttons[id]) { var button = renderer.text( text, 0, 0 ) .css(options.toolbar.itemStyle) .align({ align: 'right', x: - marginRight - 20, y: plotTop + 30 }) .on('click', fn) /*.on('touchstart', function(e) { e.stopPropagation(); // don't fire the container event fn(); })*/ .attr({ align: 'right', zIndex: 20 }) .add(); buttons[id] = button; } } function remove(id) { discardElement(buttons[id].element); buttons[id] = null; } // public return { add: add, remove: remove }; } /** * The tooltip object * @param {Object} options Tooltip options */ function Tooltip (options) { var currentSeries, borderWidth = options.borderWidth, crosshairsOptions = options.crosshairs, crosshairs = [], style = options.style, shared = options.shared, padding = pInt(style.padding), boxOffLeft = borderWidth + padding, // off left/top position as IE can't //properly handle negative positioned shapes tooltipIsHidden = true, boxWidth, boxHeight, currentX = 0, currentY = 0; // remove padding CSS and apply padding on box instead style.padding = 0; // create the elements var group = renderer.g('tooltip') .attr({ zIndex: 8 }) .add(), box = renderer.rect(boxOffLeft, boxOffLeft, 0, 0, options.borderRadius, borderWidth) .attr({ fill: options.backgroundColor, 'stroke-width': borderWidth }) .add(group) .shadow(options.shadow), label = renderer.text('', padding + boxOffLeft, pInt(style.fontSize) + padding + boxOffLeft) .attr({ zIndex: 1 }) .css(style) .add(group); group.hide(); /** * In case no user defined formatter is given, this will be used */ function defaultFormatter() { var pThis = this, items = pThis.points || splat(pThis), xAxis = items[0].series.xAxis, x = pThis.x, isDateTime = xAxis && xAxis.options.type == 'datetime', useHeader = isString(x) || isDateTime, series, s; // build the header s = useHeader ? ['<span style="font-size: 10px">', (isDateTime ? dateFormat('%A, %b %e, %Y', x) : x), '</span><br/>'] : []; // build the values each(items, function(item) { s.push(item.point.tooltipFormatter(useHeader)); }); return s.join(''); } /** * Provide a soft movement for the tooltip * * @param {Number} finalX * @param {Number} finalY */ function move(finalX, finalY) { currentX = tooltipIsHidden ? finalX : (2 * currentX + finalX) / 3; currentY = tooltipIsHidden ? finalY : (currentY + finalY) / 2; group.translate(currentX, currentY); // run on next tick of the mouse tracker if (mathAbs(finalX - currentX) > 1 || mathAbs(finalY - currentY) > 1) { tooltipTick = function() { move(finalX, finalY); }; } else { tooltipTick = null; } } /** * Hide the tooltip */ function hide() { if (!tooltipIsHidden) { var hoverPoints = chart.hoverPoints; group.hide(); each(crosshairs, function(crosshair) { if (crosshair) { crosshair.hide(); } }); // hide previous hoverPoints and set new if (hoverPoints) { each (hoverPoints, function(point) { point.setState(); }); } chart.hoverPoints = null; tooltipIsHidden = true; } } /** * Refresh the tooltip's text and position. * @param {Object} point * */ function refresh(point) { var x, y, boxX, boxY, show, bBox, plotX, plotY = 0, textConfig = {}, text, pointConfig = [], tooltipPos = point.tooltipPos, formatter = options.formatter || defaultFormatter, hoverPoints = chart.hoverPoints, getConfig = function(point) { return { series: point.series, point: point, x: point.category, y: point.y, percentage: point.percentage, total: point.total || point.stackTotal }; }; // shared tooltip, array is sent over if (shared) { // hide previous hoverPoints and set new if (hoverPoints) { each (hoverPoints, function(point) { point.setState(); }); } chart.hoverPoints = point; each(point, function(item, i) { /*var series = item.series, hoverPoint = series.hoverPoint; if (hoverPoint) { hoverPoint.setState(); } series.hoverPoint = item;*/ item.setState(HOVER_STATE); plotY += item.plotY; // for average pointConfig.push(getConfig(item)); }); plotX = point[0].plotX; plotY = mathRound(plotY) / point.length; // mathRound because Opera 10 has problems here textConfig = { x: point[0].category }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = getConfig(point); } text = formatter.call(textConfig); // register the current series currentSeries = point.series; // get the reference point coordinates (pie charts use tooltipPos) plotX = shared ? plotX : point.plotX; plotY = shared ? plotY : point.plotY; x = mathRound(tooltipPos ? tooltipPos[0] : (inverted ? plotWidth - plotY : plotX)); y = mathRound(tooltipPos ? tooltipPos[1] : (inverted ? plotHeight - plotX : plotY)); // hide tooltip if the point falls outside the plot show = shared || !point.series.isCartesian || isInsidePlot(x, y); // update the inner HTML if (text === false || !show) { hide(); } else { // show it if (tooltipIsHidden) { group.show(); tooltipIsHidden = false; } // update text label.attr({ text: text }); // get the bounding box bBox = label.getBBox(); boxWidth = bBox.width + 2 * padding; boxHeight = bBox.height + 2 * padding; // set the size of the box box.attr({ width: boxWidth, height: boxHeight, stroke: options.borderColor || point.color || currentSeries.color || '#606060' }); // keep the box within the chart area boxX = x - boxWidth + plotLeft - 25; boxY = y - boxHeight + plotTop + 10; // it is too far to the left, adjust it if (boxX < 7) { boxX = 7; boxY -= 30; } if (boxY < 5) { boxY = 5; // above } else if (boxY + boxHeight > chartHeight) { boxY = chartHeight - boxHeight - 5; // below } // do the move move(mathRound(boxX - boxOffLeft), mathRound(boxY - boxOffLeft)); } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis; while (i--) { if (crosshairsOptions[i] && (axis = point.series[i ? 'yAxis' : 'xAxis'])) { path = axis .getPlotLinePath(point[i ? 'y' : 'x'], 1); if (crosshairs[i]) { crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } crosshairs[i] = renderer.path(path) .attr(attribs) .add(); } } } } } // public members return { shared: shared, refresh: refresh, hide: hide }; } /** * The mouse tracker object * @param {Object} chart * @param {Object} options */ function MouseTracker (chart, options) { var mouseDownX, mouseDownY, hasDragged, selectionMarker, zoomType = optionsChart.zoomType, zoomX = /x/.test(zoomType), zoomY = /y/.test(zoomType), zoomHor = zoomX && !inverted || zoomY && inverted, zoomVert = zoomY && !inverted || zoomX && inverted; /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ function normalizeMouseEvent(e) { var ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // iOS ePos = e.touches ? e.touches.item(0) : e; // in certain cases, get mouse position if (e.type != 'mousemove' || win.opera) { // only Opera needs position on mouse move, see below chartPosition = getPosition(container); } // chartX and chartY if (isIE) { // IE including IE9 that has chartX but in a different meaning e.chartX = e.x; e.chartY = e.y; } else { if (ePos.layerX === UNDEFINED) { // Opera and iOS e.chartX = ePos.pageX - chartPosition.left; e.chartY = ePos.pageY - chartPosition.top; } else { e.chartX = e.layerX; e.chartY = e.layerY; } } return e; } /** * Get the click position in terms of axis values. * * @param {Object} e A mouse event */ function getMouseCoordinates(e) { var coordinates = { xAxis: [], yAxis: [] }; each(axes, function(axis, i) { var translate = axis.translate, isXAxis = axis.isXAxis, isHorizontal = inverted ? !isXAxis : isXAxis; coordinates[isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: translate( isHorizontal ? e.chartX - plotLeft : plotHeight - e.chartY + plotTop, true ) }); }); return coordinates; } /** * With line type charts with a single tracker, get the point closest to the mouse */ function onmousemove (e) { var point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chartWidth, index = inverted ? e.chartY : e.chartX - plotLeft; // wtf? // shared tooltip if (tooltip && options.shared) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; point._dist = mathAbs(index - point.plotX); distance = mathMin(distance, point._dist); points.push(point); } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].plotX != hoverX)) { tooltip.refresh(points); hoverX = points[0].plotX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point != hoverPoint) { // trigger the events point.onMouseOver(); } } } /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point */ function resetTracker() { var hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint; if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); } hoverX = null; } /** * Mouse up or outside the plot area */ function drop() { if (selectionMarker) { var selectionData = { xAxis: [], yAxis: [] }, selectionBox = selectionMarker.getBBox(), selectionLeft = selectionBox.x - plotLeft, selectionTop = selectionBox.y - plotTop; // a selection has been made if (hasDragged) { // record each axis' min and max each(axes, function(axis, i) { var translate = axis.translate, isXAxis = axis.isXAxis, isHorizontal = inverted ? !isXAxis : isXAxis, selectionMin = translate( isHorizontal ? selectionLeft : plotHeight - selectionTop - selectionBox.height, true ), selectionMax = translate( isHorizontal ? selectionLeft + selectionBox.width : plotHeight - selectionTop, true ); selectionData[isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); }); fireEvent(chart, 'selection', selectionData, zoom); } selectionMarker = selectionMarker.destroy(); } chart.mouseIsDown = mouseIsDown = hasDragged = false; removeEvent(doc, hasTouch ? 'touchend' : 'mouseup', drop); } /** * Set the JS events on the container element */ function setDOMEvents () { var lastWasOutsidePlot = true; /* * Record the starting position of a dragoperation */ container.onmousedown = function(e) { e = normalizeMouseEvent(e); // record the start position //e.preventDefault && e.preventDefault(); chart.mouseIsDown = mouseIsDown = true; mouseDownX = e.chartX; mouseDownY = e.chartY; addEvent(doc, hasTouch ? 'touchend' : 'mouseup', drop); }; // The mousemove, touchmove and touchstart event handler var mouseMove = function(e) { // let the system handle multitouch operations like two finger scroll // and pinching if (e && e.touches && e.touches.length > 1) { return; } // normalize e = normalizeMouseEvent(e); if (!hasTouch) { // not for touch devices e.returnValue = false; } var chartX = e.chartX, chartY = e.chartY, isOutsidePlot = !isInsidePlot(chartX - plotLeft, chartY - plotTop); // on touch devices, only trigger click if a handler is defined if (hasTouch && e.type == 'touchstart') { if (attr(e.target, 'isTracker')) { if (!chart.runTrackerClick) { e.preventDefault(); } } else if (!runChartClick && !isOutsidePlot) { e.preventDefault(); } } // cancel on mouse outside if (isOutsidePlot) { if (!lastWasOutsidePlot) { // reset the tracker resetTracker(); } // drop the selection if any and reset mouseIsDown and hasDragged //drop(); if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } } if (mouseIsDown && e.type != 'touchstart') { // make selection // determine if the mouse has moved more than 10px if ((hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ) > 10)) { // make a selection if (hasCartesianSeries && (zoomX || zoomY) && isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop)) { if (!selectionMarker) { selectionMarker = renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (selectionMarker && zoomHor) { var xSize = chartX - mouseDownX; selectionMarker.attr({ width: mathAbs(xSize), x: (xSize > 0 ? 0 : xSize) + mouseDownX }); } // adjust the height of the selection marker if (selectionMarker && zoomVert) { var ySize = chartY - mouseDownY; selectionMarker.attr({ height: mathAbs(ySize), y: (ySize > 0 ? 0 : ySize) + mouseDownY }); } } } else if (!isOutsidePlot) { // show the tooltip onmousemove(e); } lastWasOutsidePlot = isOutsidePlot; // when outside plot, allow touch-drag by returning true return isOutsidePlot || !hasCartesianSeries; }; /* * When the mouse enters the container, run mouseMove */ container.onmousemove = mouseMove; /* * When the mouse leaves the container, hide the tracking (tooltip). */ addEvent(container, 'mouseleave', resetTracker); container.ontouchstart = function(e) { // For touch devices, use touchmove to zoom if (zoomX || zoomY) { container.onmousedown(e); } // Show tooltip and prevent the lower mouse pseudo event mouseMove(e); }; /* * Allow dragging the finger over the chart to read the values on touch * devices */ container.ontouchmove = mouseMove; /* * Allow dragging the finger over the chart to read the values on touch * devices */ container.ontouchend = function() { if (hasDragged) { resetTracker(); } }; // MooTools 1.2.3 doesn't fire this in IE when using addEvent container.onclick = function(e) { var hoverPoint = chart.hoverPoint; e = normalizeMouseEvent(e); e.cancelBubble = true; // IE specific if (!hasDragged) { if (hoverPoint && attr(e.target, 'isTracker')) { var plotX = hoverPoint.plotX, plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event hoverPoint.firePointEvent('click', e); } else { extend(e, getMouseCoordinates(e)); // fire a click event in the chart if (isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } // reset mouseIsDown and hasDragged hasDragged = false; }; } /** * Create the image map that listens for mouseovers */ placeTrackerGroup = function() { // first create - plot positions is not final at this stage if (!trackerGroup) { chart.trackerGroup = trackerGroup = renderer.g('tracker') .attr({ zIndex: 9 }) .add(); // then position - this happens on load and after resizing and changing // axis or box positions } else { trackerGroup.translate(plotLeft, plotTop); if (inverted) { trackerGroup.attr({ width: chart.plotWidth, height: chart.plotHeight }).invert(); } } }; // Run MouseTracker placeTrackerGroup(); if (options.enabled) { chart.tooltip = tooltip = Tooltip(options); } setDOMEvents(); // set the fixed interval ticking for the smooth tooltip tooltipInterval = setInterval(function() { if (tooltipTick) { tooltipTick(); } }, 32); // expose properties extend(this, { zoomX: zoomX, zoomY: zoomY, resetTracker: resetTracker }); } /** * The overview of the chart's series * @param {Object} chart */ var Legend = function(chart) { var options = chart.options.legend; if (!options.enabled) { return; } var horizontal = options.layout == 'horizontal', symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, allItems, style = options.style, itemStyle = options.itemStyle, itemHoverStyle = options.itemHoverStyle, itemHiddenStyle = options.itemHiddenStyle, padding = pInt(style.padding), rightPadding = 20, //lineHeight = options.lineHeight || 16, y = 18, initialItemX = 4 + padding + symbolWidth + symbolPadding, itemX, itemY, lastItemY, itemHeight = 0, box, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor, legendGroup, offsetWidth, widthOption = options.width, series = chart.series, reversedLegend = options.reversed; /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ function colorizeItem(item, visible) { var legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? item.color : hiddenColor; if (legendItem) { legendItem.css({ fill: textColor }); } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { legendSymbol.attr({ stroke: symbolColor, fill: symbolColor }); } } /** * Position the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ function positionItem(item, itemX, itemY) { var legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, checkbox = item.checkbox; if (legendItem) { legendItem.attr({ x: itemX, y: itemY }); } if (legendLine) { legendLine.translate(itemX, itemY - 4); } if (legendSymbol) { legendSymbol.attr({ x: itemX + legendSymbol.xOff, y: itemY + legendSymbol.yOff }); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } } /** * Destroy a single legend item * @param {Object} item The series or point */ function destroyItem(item) { var checkbox = item.checkbox; // pull out from the array //erase(allItems, item); // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol'], function(key) { if (item[key]) { item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } } /** * Position the checkboxes after the width is determined */ function positionCheckboxes() { each(allItems, function(item) { var checkbox = item.checkbox; if (checkbox) { css(checkbox, { left: (legendGroup.attr('translateX') + item.legendItemWidth + checkbox.x - 40) +PX, top: (legendGroup.attr('translateY') + checkbox.y - 11) + PX }); } }); } /** * Render a single specific legend item * @param {Object} item A series or point */ function renderItem(item) { var bBox, itemWidth, legendSymbol, symbolX, symbolY, attribs, simpleSymbol, li = item.legendItem, series = item.series || item, i = allItems.length; if (!li) { // generate it once, later move it // let these series types use a simple symbol simpleSymbol = /^(bar|pie|area|column)$/.test(series.type); // generate the list item text item.legendItem = li = renderer.text( options.labelFormatter.call(item), 0, 0 ) .css(item.visible ? itemStyle : itemHiddenStyle) .on('mouseover', function() { item.setState(HOVER_STATE); li.css(itemHoverStyle); }) .on('mouseout', function() { li.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function(event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function() { item.setVisible(); }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, null, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, null, fnLegendItemClick); } }) .attr({ zIndex: 2 }) .add(legendGroup); // draw the line if (!simpleSymbol && item.options && item.options.lineWidth) { var itemOptions = item.options; attribs = { 'stroke-width': itemOptions.lineWidth, zIndex: 2 }; if (itemOptions.dashStyle) { attribs.dashstyle = itemOptions.dashStyle; } item.legendLine = renderer.path([ M, -symbolWidth - symbolPadding, 0, L, -symbolPadding, 0 ]) .attr(attribs) .add(legendGroup); } // draw a simple symbol if (simpleSymbol) { // bar|pie|area|column //legendLayer.drawRect( legendSymbol = renderer.rect( (symbolX = -symbolWidth - symbolPadding), (symbolY = -11), symbolWidth, 12, 2 ).attr({ 'stroke-width': 0, zIndex: 3 }).add(legendGroup); } // draw the marker else if (item.options && item.options.marker && item.options.marker.enabled) { legendSymbol = renderer.symbol( item.symbol, (symbolX = -symbolWidth / 2 - symbolPadding), (symbolY = -4), item.options.marker.radius ) .attr(item.pointAttr[NORMAL_STATE]) .attr({ zIndex: 3 }) .add(legendGroup); } if (legendSymbol) { legendSymbol.xOff = symbolX; legendSymbol.yOff = symbolY; } item.legendSymbol = legendSymbol; // colorize the items colorizeItem(item, item.visible); // add the HTML checkbox on top if (item.options && item.options.showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, container); addEvent(item.checkbox, 'click', function(event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function() { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + rightPadding; itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && itemX - initialItemX + itemWidth > (widthOption || (chartWidth - 2 * padding - initialItemX))) { itemX = initialItemX; itemY += itemHeight; } lastItemY = itemY; // position the newly generated or reordered items positionItem(item, itemX, itemY); // advance if (horizontal) { itemX += itemWidth; } else { itemY += itemHeight; } // the width of the widest item offsetWidth = widthOption || mathMax( horizontal ? itemX - initialItemX : itemWidth, offsetWidth ); // add it all to an array to use below allItems.push(item); } /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ function renderLegend() { itemX = initialItemX; itemY = y; offsetWidth = 0; lastItemY = 0; allItems = []; if (!legendGroup) { legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); } // add HTML for each series if (reversedLegend) { series.reverse(); } each(series, function(serie) { if (!serie.options.showInLegend) { return; } // use points or series for the legend item depending on legendType var items = (serie.options.legendType == 'point') ? serie.data : [serie]; // render all items each(items, renderItem); }); if (reversedLegend) { // restore series.reverse(); } // Draw the border legendWidth = widthOption || offsetWidth; legendHeight = lastItemY - y + itemHeight; if (legendBorderWidth || legendBackgroundColor) { legendWidth += 2 * padding; legendHeight += 2 * padding; if (!box) { box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); } else if (legendWidth > 0 && legendHeight > 0) { box.animate({ width: legendWidth, height: legendHeight }); } // hide the border if no items box[allItems.length ? 'show' : 'hide'](); } // 1.x compatibility: positioning based on style var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while(i--) { prop = props[i]; if (style[prop] && style[prop] != 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(style[prop]) * (i % 2 ? -1 : 1); } } legendGroup.align(extend(options, { width: legendWidth, height: legendHeight }), true, spacingBox); if (!isResizing) { positionCheckboxes(); } } // run legend renderLegend(); // move checkboxes addEvent(chart, 'endResize', positionCheckboxes); // expose return { colorizeItem: colorizeItem, destroyItem: destroyItem, renderLegend: renderLegend }; }; /** * Initialize an individual series, called internally before render time */ function initSeries(options) { var type = options.type || optionsChart.type || optionsChart.defaultSeriesType, typeClass = seriesTypes[type], serie, hasRendered = chart.hasRendered; // an inverted chart can't take a column series and vice versa if (hasRendered) { if (inverted && type == 'column') { typeClass = seriesTypes.bar; } else if (!inverted && type == 'bar') { typeClass = seriesTypes.column; } } serie = new typeClass(); serie.init(chart, options); // set internal chart properties if (!hasRendered && serie.inverted) { inverted = true; } if (serie.isCartesian) { hasCartesianSeries = serie.isCartesian; } series.push(serie); return serie; } /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ function addSeries(options, redraw, animation) { var series; if (options) { setAnimation(animation, chart); redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function() { series = initSeries(options); series.isDirty = true; chart.isDirtyLegend = true; // the series array is out of sync with the display if (redraw) { chart.redraw(); } }); } return series; } /** * Check whether a given point is within the plot area * * @param {Number} x Pixel x relative to the coordinateSystem * @param {Number} y Pixel y relative to the coordinateSystem */ isInsidePlot = function(x, y) { return x >= 0 && x <= plotWidth && y >= 0 && y <= plotHeight; }; /** * Adjust all axes tick amounts */ function adjustTickAmounts() { if (optionsChart.alignTicks !== false) { each(axes, function(axis) { axis.adjustTickAmount(); }); } maxTicks = null; } /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ function redraw(animation) { var redrawLegend = chart.isDirtyLegend, hasStackedSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, clipRect = chart.clipRect, serie; setAnimation(animation, chart); // link stacked series while (i--) { serie = series[i]; if (serie.isDirty && serie.options.stacking) { hasStackedSeries = true; break; } } if (hasStackedSeries) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function(serie) { if (serie.isDirty) { // prepare the data so axis can read it serie.cleanData(); serie.getSegments(); if (serie.options.legendType == 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.renderLegend) { // series or pie points are added or removed // draw legend graphics legend.renderLegend(); chart.isDirtyLegend = false; } if (hasCartesianSeries) { if (!isResizing) { // reset maxTicks maxTicks = null; // set axes scales each(axes, function(axis) { axis.setScale(); }); } adjustTickAmounts(); getMargins(); // redraw axes each(axes, function(axis) { if (axis.isDirty || isDirtyBox) { axis.redraw(); isDirtyBox = true; // always redraw box to reflect changes in the axis labels } }); } // the plot areas size has changed if (isDirtyBox) { drawChartBox(); placeTrackerGroup(); // move clip rect if (clipRect) { stop(clipRect); clipRect.animate({ // for chart resize width: chart.plotSizeX, height: chart.plotSizeY }); } } // redraw affected series each(series, function(serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // hide tooltip and hover states if (tracker && tracker.resetTracker) { tracker.resetTracker(); } // fire the event fireEvent(chart, 'redraw'); } /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ function showLoading(str) { var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { loadingDiv = createElement(DIV, { className: 'highcharts-loading' }, extend(loadingOptions.style, { left: plotLeft + PX, top: plotTop + PX, width: plotWidth + PX, height: plotHeight + PX, zIndex: 10, display: NONE }), container); loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text loadingSpan.innerHTML = str || options.lang.loading; // show it if (!loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration }); loadingShown = true; } } /** * Hide the loading layer */ function hideLoading() { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration, complete: function() { css(loadingDiv, { display: NONE }); } }); loadingShown = false; } /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ function get(id) { var i, j, data; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id == id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id == id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { data = series[i].data; for (j = 0; j < data.length; j++) { if (data[j].id == id) { return data[j]; } } } return null; } /** * Create the Axis instances based on the config options */ function getAxes() { var xAxisOptions = options.xAxis || {}, yAxisOptions = options.yAxis || {}, axis; // make sure the options are arrays and add some members xAxisOptions = splat(xAxisOptions); each(xAxisOptions, function(axis, i) { axis.index = i; axis.isX = true; }); yAxisOptions = splat(yAxisOptions); each(yAxisOptions, function(axis, i) { axis.index = i; }); // concatenate all axis options into one array axes = xAxisOptions.concat(yAxisOptions); // loop the options and construct axis objects chart.xAxis = []; chart.yAxis = []; axes = map(axes, function(axisOptions) { axis = new Axis(chart, axisOptions); chart[axis.isXAxis ? 'xAxis' : 'yAxis'].push(axis); return axis; }); adjustTickAmounts(); } /** * Get the currently selected points from all series */ function getSelectedPoints() { var points = []; each(series, function(serie) { points = points.concat( grep( serie.data, function(point) { return point.selected; })); }); return points; } /** * Get the currently selected series */ function getSelectedSeries() { return grep(series, function (serie) { return serie.selected; }); } /** * Zoom out to 1:1 */ zoomOut = function () { fireEvent(chart, 'selection', { resetSelection: true }, zoom); chart.toolbar.remove('zoom'); }; /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom = function (event) { // add button to reset selection var lang = defaultOptions.lang, animate = chart.pointCount < 100; chart.toolbar.add('zoom', lang.resetZoom, lang.resetZoomTitle, zoomOut); // if zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(axes, function(axis) { axis.setExtremes(null, null, false, animate); }); } // else, zoom in on all axes else { each(event.xAxis.concat(event.yAxis), function(axisData) { var axis = axisData.axis; // don't zoom more than maxZoom if (chart.tracker[axis.isXAxis ? 'zoomX' : 'zoomY']) { axis.setExtremes(axisData.min, axisData.max, false, animate); } }); } // redraw chart redraw(); }; /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ function setTitle (titleOptions, subtitleOptions) { chartTitleOptions = merge(options.title, titleOptions); chartSubtitleOptions = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function(arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { title.destroy(); // remove old title = null; } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = renderer.text( chartTitleOptions.text, 0, 0 ) .attr({ align: chartTitleOptions.align, 'class': 'highcharts-'+ name, zIndex: 1 }) .css(chartTitleOptions.style) .add() .align(chartTitleOptions, false, spacingBox); } }); } /** * Get chart width and height according to options and container size */ function getChartSize() { containerWidth = (renderToClone || renderTo).offsetWidth; containerHeight = (renderToClone || renderTo).offsetHeight; chart.chartWidth = chartWidth = optionsChart.width || containerWidth || 600; chart.chartHeight = chartHeight = optionsChart.height || // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: (containerHeight > 19 ? containerHeight : 400); } /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ function getContainer() { renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { renderTo = doc.getElementById(renderTo); } // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly if (!renderTo.offsetWidth) { renderToClone = renderTo.cloneNode(0); css(renderToClone, { position: ABSOLUTE, top: '-9999px', display: '' }); doc.body.appendChild(renderToClone); } // get the width and height getChartSize(); // create the inner container chart.container = container = createElement(DIV, { className: 'highcharts-container' + (optionsChart.className ? ' '+ optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left' }, optionsChart.style), renderToClone || renderTo ); chart.renderer = renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { subPixelFix = function() { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (-rect.left % 1) + PX, top: (-rect.top % 1) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); // remove it on chart destroy addEvent(chart, 'destroy', function() { removeEvent(win, 'resize', subPixelFix); }); } } /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins = function() { var legendOptions = options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset; resetMargins(); // adjust for title and subtitle if ((chart.title || chart.subtitle) && !defined(optionsMarginTop)) { titleOffset = mathMax( chart.title && !chartTitleOptions.floating && !chartTitleOptions.verticalAlign && chartTitleOptions.y || 0, chart.subtitle && !chartSubtitleOptions.floating && !chartSubtitleOptions.verticalAlign && chartSubtitleOptions.y || 0 ); if (titleOffset) { plotTop = mathMax(plotTop, titleOffset + pick(chartTitleOptions.margin, 15) + spacingTop); } } // adjust for legend if (legendOptions.enabled && !legendOptions.floating) { if (align == 'right') { // horizontal alignment handled first if (!defined(optionsMarginRight)) { marginRight = mathMax( marginRight, legendWidth - legendX + legendMargin + spacingRight ); } } else if (align == 'left') { if (!defined(optionsMarginLeft)) { plotLeft = mathMax( plotLeft, legendWidth + legendX + legendMargin + spacingLeft ); } } else if (verticalAlign == 'top') { if (!defined(optionsMarginTop)) { plotTop = mathMax( plotTop, legendHeight + legendY + legendMargin + spacingTop ); } } else if (verticalAlign == 'bottom') { if (!defined(optionsMarginBottom)) { marginBottom = mathMax( marginBottom, legendHeight - legendY + legendMargin + spacingBottom ); } } } // pre-render axes to get labels offset width if (hasCartesianSeries) { each(axes, function(axis) { axis.getOffset(); }); } if (!defined(optionsMarginLeft)) { plotLeft += axisOffset[3]; } if (!defined(optionsMarginTop)) { plotTop += axisOffset[0]; } if (!defined(optionsMarginBottom)) { marginBottom += axisOffset[2]; } if (!defined(optionsMarginRight)) { marginRight += axisOffset[1]; } setChartSize(); }; /** * Add the event handlers necessary for auto resizing * */ function initReflow() { var reflowTimeout; function reflow() { var width = optionsChart.width || renderTo.offsetWidth, height = optionsChart.height || renderTo.offsetHeight; if (width && height) { // means container is display:none if (width != containerWidth || height != containerHeight) { clearTimeout(reflowTimeout); reflowTimeout = setTimeout(function() { resize(width, height, false); }, 100); } containerWidth = width; containerHeight = height; } } addEvent(window, 'resize', reflow); addEvent(chart, 'destroy', function() { removeEvent(window, 'resize', reflow); }); } /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ resize = function(width, height, animation) { var chartTitle = chart.title, chartSubtitle = chart.subtitle; isResizing += 1; // set the animation for the current process setAnimation(animation, chart); oldChartHeight = chartHeight; oldChartWidth = chartWidth; chartWidth = mathRound(width); chartHeight = mathRound(height); css(container, { width: chartWidth + PX, height: chartHeight + PX }); renderer.setSize(chartWidth, chartHeight, animation); // update axis lengths for more correct tick intervals: plotWidth = chartWidth - plotLeft - marginRight; plotHeight = chartHeight - plotTop - marginBottom; // handle axes maxTicks = null; each(axes, function(axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(series, function(serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border getMargins(); // move titles if (chartTitle) { chartTitle.align(null, null, spacingBox); } if (chartSubtitle) { chartSubtitle.align(null, null, spacingBox); } redraw(animation); oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back setTimeout(function() { fireEvent(chart, 'endResize', null, function() { isResizing -= 1; }); }, globalAnimation && globalAnimation.duration || 500); }; /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize = function() { chart.plotLeft = plotLeft = mathRound(plotLeft); chart.plotTop = plotTop = mathRound(plotTop); chart.plotWidth = plotWidth = mathRound(chartWidth - plotLeft - marginRight); chart.plotHeight = plotHeight = mathRound(chartHeight - plotTop - marginBottom); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; spacingBox = { x: spacingLeft, y: spacingTop, width: chartWidth - spacingLeft - spacingRight, height: chartHeight - spacingTop - spacingBottom }; }; /** * Initial margins before auto size margins are applied */ resetMargins = function() { plotTop = pick(optionsMarginTop, spacingTop); marginRight = pick(optionsMarginRight, spacingRight); marginBottom = pick(optionsMarginBottom, spacingBottom); plotLeft = pick(optionsMarginLeft, spacingLeft); axisOffset = [0, 0, 0, 0]; // top, right, bottom, left }; /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox = function() { var chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, mgn, plotSize = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr({ stroke: optionsChart.borderColor, 'stroke-width': chartBorderWidth, fill: chartBackgroundColor || NONE }) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate({ width: chartWidth - mgn, height:chartHeight - mgn }); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotSize); } } if (plotBackgroundImage) { if (!plotBGImage) { plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotSize); } } // Plot area border if (optionsChart.plotBorderWidth) { if (!plotBorder) { plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, optionsChart.plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': optionsChart.plotBorderWidth, zIndex: 4 }) .add(); } else { plotBorder.animate(plotSize); } } // reset chart.isDirtyBox = false; }; /** * Render all graphics for the chart */ function render () { var labels = options.labels, credits = options.credits, creditsHref; // Title setTitle(); // Legend legend = chart.legend = new Legend(chart); // Get margins by pre-rendering axes getMargins(); each(axes, function(axis) { axis.setTickPositions(true); // update to reflect the new margins }); adjustTickAmounts(); getMargins(); // second pass to check for new labels // Draw the borders and backgrounds drawChartBox(); // Axes if (hasCartesianSeries) { each(axes, function(axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } each(series, function(serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // Labels if (labels.items) { each(labels.items, function() { var style = extend(labels.style, this.style), x = pInt(style.left) + plotLeft, y = pInt(style.top) + plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( this.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Toolbar (don't redraw) if (!chart.toolbar) { chart.toolbar = Toolbar(chart); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; renderer.text( credits.text, 0, 0 ) .on('click', function() { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } placeTrackerGroup(); // Set flag chart.hasRendered = true; // If the chart was rendered outside the top container, put it back in if (renderToClone) { renderTo.appendChild(container); discardElement(renderToClone); //updatePosition(container); } } /** * Clean up memory usage */ function destroy() { var i = series.length, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // remove events removeEvent(win, 'unload', destroy); removeEvent(chart); each(axes, function(axis) { removeEvent(axis); }); // destroy each series while (i--) { series[i].destroy(); } // remove container and all SVG if (defined(container)) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { parentNode.removeChild(container); } } // IE6 leak container = null; // IE7 leak renderer.alignedObjects = null; // memory and CPU leak clearInterval(tooltipInterval); // clean it all up for (i in chart) { delete chart[i]; } } /** * Prepare for first rendering after all data are loaded */ function firstRender() { // VML namespaces can't be added until after complete. Listening // for Perini's doScroll hack is not enough. var onreadystatechange = 'onreadystatechange'; if (!hasSVG && !win.parent && doc.readyState != 'complete') { doc.attachEvent(onreadystatechange, function() { doc.detachEvent(onreadystatechange, firstRender); firstRender(); }); return; } // create the container getContainer(); resetMargins(); setChartSize(); // Initialize the series each(options.series || [], function(serieOptions) { initSeries(serieOptions); }); // Set the common inversion and transformation for inverted series after initSeries chart.inverted = inverted = pick(inverted, options.chart.inverted); getAxes(); chart.render = render; // depends on inverted and on margins being set chart.tracker = tracker = new MouseTracker(chart, options.tooltip); //globalAnimation = false; render(); fireEvent(chart, 'load'); //globalAnimation = true; // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function(fn) { fn.apply(chart, [chart]); }); } // Run chart // Set to zero for each new chart colorCounter = 0; symbolCounter = 0; // Destroy the chart and free up memory. addEvent(win, 'unload', destroy); // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', initReflow); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.options = options; chart.series = series; // Expose methods and variables chart.addSeries = addSeries; chart.animation = pick(optionsChart.animation, true); chart.destroy = destroy; chart.get = get; chart.getSelectedPoints = getSelectedPoints; chart.getSelectedSeries = getSelectedSeries; chart.hideLoading = hideLoading; chart.isInsidePlot = isInsidePlot; chart.redraw = redraw; chart.setSize = resize; chart.setTitle = setTitle; chart.showLoading = showLoading; chart.pointCount = 0; /* if ($) $(function() { $container = $('#container'); var origChartWidth, origChartHeight; if ($container) { $('<button>+</button>') .insertBefore($container) .click(function() { if (origChartWidth === UNDEFINED) { origChartWidth = chartWidth; origChartHeight = chartHeight; } chart.resize(chartWidth *= 1.1, chartHeight *= 1.1); }); $('<button>-</button>') .insertBefore($container) .click(function() { if (origChartWidth === UNDEFINED) { origChartWidth = chartWidth; origChartHeight = chartHeight; } chart.resize(chartWidth *= 0.9, chartHeight *= 0.9); }); $('<button>1:1</button>') .insertBefore($container) .click(function() { if (origChartWidth === UNDEFINED) { origChartWidth = chartWidth; origChartHeight = chartHeight; } chart.resize(origChartWidth, origChartHeight); }); } }) */ firstRender(); } // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function() {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function(series, options) { var point = this, defaultColors; point.series = series; point.applyOptions(options); point.pointAttr = {}; if (series.options.colorByPoint) { defaultColors = series.chart.options.colors; if (!point.options) { point.options = {}; } point.color = point.options.color = point.color || defaultColors[colorCounter++]; // loop back to zero if (colorCounter >= defaultColors.length) { colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function(options) { var point = this, series = point.series; point.config = options; // onedimensional array input if (isNumber(options) || options === null) { point.y = options; } // object input else if (isObject(options) && !isNumber(options.length)) { // copy options directly to point extend(point, options); point.options = options; } // categorized data with name in first position else if (isString(options[0])) { point.name = options[0]; point.y = options[1]; } // two-dimentional array else if (isNumber(options[0])) { point.x = options[0]; point.y = options[1]; } /* * If no x is set by now, get auto incremented value. All points must have an * x value, however the y value can be null to create a gap in the series */ if (point.x === UNDEFINED) { point.x = series.autoIncrement(); } }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function() { var point = this, series = point.series, prop; series.chart.pointCount--; if (point == series.chart.hoverPoint) { point.onMouseOut(); } series.chart.hoverPoints = null; // remove reference // remove all events removeEvent(point); each(['graphic', 'tracker', 'group', 'dataLabel', 'connector'], function(prop) { if (point[prop]) { point[prop].destroy(); } }); if (point.legendItem) { // pies have legend items point.series.chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function(selected, accumulate) { var point = this, series = point.series, chart = series.chart; point.selected = selected = pick(selected, !point.selected); //series.isDirty = true; point.firePointEvent(selected ? 'select' : 'unselect'); point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint != point) { loopPoint.selected = false; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }, onMouseOver: function() { var point = this, chart = point.series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint != point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && !tooltip.shared) { tooltip.refresh(point); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, onMouseOut: function() { var point = this; point.firePointEvent('mouseOut'); point.setState(); point.series.chart.hoverPoint = null; }, /** * Extendable method for formatting each point's tooltip line * * @param {Boolean} useHeader Whether a common header is used for multiple series in the tooltip * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function(useHeader) { var point = this, series = point.series; return ['<span style="color:'+ series.color +'">', (point.name || series.name), '</span>: ', (!useHeader ? ('<b>x = '+ (point.name || point.x) + ',</b> ') : ''), '<b>', (!useHeader ? 'y = ' : '' ), point.y, '</b><br/>'].join(''); }, /** * Get the formatted text for this point's data label * * @return {String} The formatted data label pseudo-HTML */ getDataLabelText: function() { var point = this; return this.series.options.dataLabels.formatter.call({ x: point.x, y: point.y, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }); }, /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function(options, redraw, animation) { var point = this, series = point.series, dataLabel = point.dataLabel, chart = series.chart; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function() { point.applyOptions(options); if (dataLabel) { dataLabel.attr({ text: point.getDataLabelText() }) } // update visuals if (isObject(options)) { series.getAttribs(); point.graphic.attr(point.pointAttr[series.state]); } // redraw series.isDirty = true; if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function(redraw, animation) { var point = this, series = point.series, chart = series.chart, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function() { erase(data, point); point.destroy(); // redraw series.isDirty = true; if (redraw) { chart.redraw(); } }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function(eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || ( point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType == 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function() { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function(state) { var point = this, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, chart = series.chart, pointAttr = point.pointAttr; if (!state) { state = NORMAL_STATE; // empty string } if ( // already has this state state == point.state || // selected points don't respond to hover (point.selected && state != SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // point marker's state options is disabled (state && (stateDisabled || normalDisabled && !markerStateOptions.enabled)) ) { return; } // apply hover styles to the existing point if (point.graphic) { point.graphic.attr(pointAttr[state]); } // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state else { if (state) { if (!stateMarkerGraphic) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.circle( 0, 0, pointAttr[state].r ) .attr(pointAttr[state]) .add(series.group); } stateMarkerGraphic.translate( point.plotX, point.plotY ); } if (stateMarkerGraphic) { stateMarkerGraphic[state ? 'show' : 'hide'](); } } point.state = state; } }; /** * The base function which all other series types inherit from * @param {Object} chart * @param {Object} options */ var Series = function() {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, init: function(chart, options) { var series = this, eventType, events, //pointEvent, index = chart.series.length; series.chart = chart; options = series.setOptions(options); // merge with plotOptions // set some variables extend(series, { index: index, options: options, name: options.name || 'Series '+ (index + 1), state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // set the data series.setData(options.data, false); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function() { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Sort the data and remove duplicates */ cleanData: function() { var series = this, chart = series.chart, data = series.data, closestPoints, smallestInterval, chartSmallestInterval = chart.smallestInterval, interval, i; // sort the data points data.sort(function(a, b){ return (a.x - b.x); }); // remove points with equal x values // record the closest distance for calculation of column widths for (i = data.length - 1; i >= 0; i--) { if (data[i - 1]) { if (data[i - 1].x == data[i].x) { data.splice(i - 1, 1); // remove the duplicate } } } // find the closes pair of points for (i = data.length - 1; i >= 0; i--) { if (data[i - 1]) { interval = data[i].x - data[i - 1].x; if (smallestInterval === UNDEFINED || interval < smallestInterval) { smallestInterval = interval; closestPoints = i; } } } if (chartSmallestInterval === UNDEFINED || smallestInterval < chartSmallestInterval) { chart.smallestInterval = smallestInterval; } series.closestPoints = closestPoints; }, /** * Divide the series data into segments divided by null values. Also sort * the data points and delete duplicate values. */ getSegments: function() { var lastNull = -1, segments = [], data = this.data; // create the segments each(data, function(point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(data.slice(lastNull + 1, i)); } lastNull = i; } else if (i == data.length - 1) { // last value segments.push(data.slice(lastNull + 1, i + 1)); } }); this.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function(itemOptions) { var plotOptions = this.chart.options.plotOptions, options = merge( plotOptions[this.type], plotOptions.series, itemOptions ); return options; }, /** * Get the series' color */ getColor: function(){ var defaultColors = this.chart.options.colors; this.color = this.options.color || defaultColors[colorCounter++] || '#0000ff'; if (colorCounter >= defaultColors.length) { colorCounter = 0; } }, /** * Get the series' symbol */ getSymbol: function(){ var defaultSymbols = this.chart.options.symbols, symbol = this.options.marker.symbol || defaultSymbols[symbolCounter++]; this.symbol = symbol; if (symbolCounter >= defaultSymbols.length) { symbolCounter = 0; } }, /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function(options, redraw, shift, animation) { var series = this, data = series.data, graph = series.graph, area = series.area, chart = series.chart, point = (new series.pointClass()).init(series, options); setAnimation(animation, chart); if (graph && shift) { // make graph animate sideways graph.shift = shift; } if (area) { area.shift = shift; area.isArea = true; } redraw = pick(redraw, true); data.push(point); if (shift) { data[0].remove(false); } // redraw series.isDirty = true; if (redraw) { chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function(data, redraw) { var series = this, oldData = series.data, initialColor = series.initialColor, chart = series.chart, i = oldData && oldData.length || 0; series.xIncrement = null; // reset for new data if (defined(initialColor)) { // reset colors for pie colorCounter = initialColor; } data = map(splat(data || []), function(pointOptions) { return (new series.pointClass()).init(series, pointOptions); }); // destroy old points while (i--) { oldData[i].destroy(); } // set the data series.data = data; series.cleanData(); series.getSegments(); // redraw series.isDirty = true; chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(false); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function(redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function() { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function() { var series = this, chart = series.chart, stacking = series.options.stacking, categories = series.xAxis.categories, yAxis = series.yAxis, data = series.data, i = data.length; // do the translation while (i--) { var point = data[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(yValue < 0 ? '-' : '') + series.stackKey], pointStack, pointStackTotal; point.plotX = series.xAxis.translate(xValue); // calculate the bottom y value for stacked series if (stacking && series.visible && stack[xValue]) { pointStack = stack[xValue]; pointStackTotal = pointStack.total; pointStack.cum = yBottom = pointStack.cum - yValue; // start from top yValue = yBottom + yValue; if (stacking == 'percent') { yBottom = pointStackTotal ? yBottom * 100 / pointStackTotal : 0; yValue = pointStackTotal ? yValue * 100 / pointStackTotal : 0; } point.percentage = pointStackTotal ? point.y * 100 / pointStackTotal : 0; point.stackTotal = pointStackTotal; } if (defined(yBottom)) { point.yBottom = yAxis.translate(yBottom, 0, 1); } // set the y value if (yValue !== null) { point.plotY = yAxis.translate(yValue, 0, 1); } // set client related positions for mouse tracking point.clientX = chart.inverted ? chart.plotHeight - point.plotX : point.plotX; // for mouse tracking // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, chart = series.chart, inverted = chart.inverted, data = [], plotSize = mathRound((inverted ? chart.plotTop : chart.plotLeft) + chart.plotSizeX), low, high, tooltipPoints = []; // a lookup array for each pixel in the x dimension // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments, function(segment){ data = data.concat(segment); }); // loop the concatenated data and apply each point to all the closest // pixel positions if (series.xAxis && series.xAxis.reversed) { data = data.reverse();//reverseArray(data); } each(data, function(point, i) { low = data[i - 1] ? data[i - 1].high + 1 : 0; high = point.high = data[i + 1] ? ( mathFloor((point.plotX + (data[i + 1] ? data[i + 1].plotX : plotSize)) / 2)) : plotSize; while (low <= high) { tooltipPoints[inverted ? plotSize - low++ : low++] = point; } }); series.tooltipPoints = tooltipPoints; }, /** * Series mouse over handler */ onMouseOver: function() { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; if (!hasTouch && chart.mouseIsDown) { return; } // set normal state to previous series if (hoverSeries && hoverSeries != series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // bring to front // Todo: optimize. This is one of two operations slowing down the tooltip in Firefox. // Can the tracking be done otherwise? if (series.tracker) { series.tracker.toFront(); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function() { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Animate in the series */ animate: function(init) { var series = this, chart = series.chart, clipRect = series.clipRect, animation = series.options.animation; if (animation && !isObject(animation)) { animation = {}; } if (init) { // initialize the animation if (!clipRect.isAnimating) { // apply it only for one of the series clipRect.attr( 'width', 0 ); clipRect.isAnimating = true; } } else { // run the animation clipRect.animate({ width: chart.plotSizeX }, animation); // delete this function to allow it only once this.animate = null; } }, /** * Draw the markers */ drawPoints: function(){ var series = this, pointAttr, data = series.data, chart = series.chart, plotX, plotY, i, point, radius, graphic; if (series.options.marker.enabled) { i = data.length; while (i--) { point = data[i]; plotX = point.plotX; plotY = point.plotY; graphic = point.graphic; // only draw the point if y is defined if (plotY !== UNDEFINED && !isNaN(plotY)) { /* && removed this code because points stayed after zoom point.plotX >= 0 && point.plotX <= chart.plotSizeX && point.plotY >= 0 && point.plotY <= chart.plotSizeY*/ // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; radius = pointAttr.r; if (graphic) { // update graphic.animate({ x: plotX, y: plotY, r: radius }); } else { point.graphic = chart.renderer.symbol( pick(point.marker && point.marker.symbol, series.symbol), plotX, plotY, radius ) .attr(pointAttr) .add(series.group); } } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function(options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function() { var series = this, normalOptions = defaultPlotOptions[series.type].marker ? series.options.marker : series.options, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, data = series.data, i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions; // series type specific modifications if (series.options.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function(state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = data.length; while (i--) { point = data[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } hasPointSpecificOptions = false; // check if the point has specific visual options if (point.options) { for (var key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // if no hover color is given, brighten the normal color if (!series.options.marker) { // column, bar, point pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.options.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Clear DOM objects and free up memory */ destroy: function() { var series = this, chart = series.chart, //chartSeries = series.chart.series, clipRect = series.clipRect, issue134 = /\/5[0-9\.]+ Safari\//.test(userAgent), // todo: update when Safari bug is fixed destroy, prop; // remove all events removeEvent(series); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements each(series.data, function(point) { point.destroy(); }); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'tracker'], function(prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop == 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries == series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Draw the data labels */ drawDataLabels: function() { if (this.options.dataLabels.enabled) { var series = this, x, y, data = series.data, options = series.options.dataLabels, str, dataLabelsGroup = series.dataLabelsGroup, chart = series.chart, inverted = chart.inverted, seriesType = series.type, color; // create a separate group for the data labels to avoid rotation if (!dataLabelsGroup) { dataLabelsGroup = series.dataLabelsGroup = chart.renderer.g(PREFIX +'data-labels') .attr({ visibility: series.visible ? VISIBLE : HIDDEN, zIndex: 5 }) .translate(chart.plotLeft, chart.plotTop) .add(); } // determine the color color = options.color; if (color == 'auto') { // 1.0 backwards compatibility color = null; } options.style.color = pick(color, series.color); // make the labels for each point each(data, function(point, i){ var barX = point.barX, plotX = barX && barX + point.barW / 2 || point.plotX || -999, plotY = pick(point.plotY, -999), dataLabel = point.dataLabel, align = options.align; // get the string str = point.getDataLabelText(); x = (inverted ? chart.plotWidth - plotY : plotX) + options.x; y = (inverted ? chart.plotHeight - plotX : plotY) + options.y; // in columns, align the string to the column if (seriesType == 'column') { x += { left: -1, right: 1 }[align] * point.barW / 2 || 0; } if (dataLabel) { dataLabel.animate({ x: x, y: y }); } else if (defined(str)) { dataLabel = point.dataLabel = chart.renderer.text( str, x, y ) .attr({ align: align, rotation: options.rotation, zIndex: 1 }) .css(options.style) .add(dataLabelsGroup); } // vertically centered if (inverted && !options.y) { dataLabel.attr({ y: y + parseInt(dataLabel.styles.lineHeight) * 0.9 - dataLabel.getBBox().height / 2 }); } /*if (series.isCartesian) { dataLabel[chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); }*/ }); } }, /** * Draw the actual graph */ drawGraph: function(state) { var series = this, options = series.options, chart = series.chart, graph = series.graph, graphPath = [], fillColor, area = series.area, group = series.group, color = options.lineColor || series.color, lineWidth = options.lineWidth, dashStyle = options.dashStyle, segmentPath, renderer = chart.renderer, translatedThreshold = series.yAxis.getThreshold(options.threshold || 0), useArea = /^area/.test(series.type), singlePoints = [], // used in drawTracker areaPath = [], attribs; // divide into segments and build graph and area paths each(series.segments, function(segment) { segmentPath = []; // build the segment line each(segment, function(point, i) { if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (i && options.step) { var lastPoint = segment[i - 1]; segmentPath.push( point.plotX, lastPoint.plotY ); } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } // build the area if (useArea) { var areaSegmentPath = [], i, segLength = segmentPath.length; for (i = 0; i < segLength; i++) { areaSegmentPath.push(segmentPath[i]); } if (segLength == 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && series.type != 'areaspline') { // follow stack back. Todo: implement areaspline for (i = segment.length - 1; i >= 0; i--) { areaSegmentPath.push(segment[i].plotX, segment[i].yBottom); } } else { // follow zero line back areaSegmentPath.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); } areaPath = areaPath.concat(areaSegmentPath); } }); // used in drawTracker: series.graphPath = graphPath; series.singlePoints = singlePoints; // draw the area if area series or areaspline if (useArea) { fillColor = pick( options.fillColor, Color(series.color).setOpacity(options.fillOpacity || 0.75).get() ); if (area) { area.animate({ d: areaPath }); } else { // draw the area series.area = series.chart.renderer.path(areaPath) .attr({ fill: fillColor }).add(group); } } // draw the graph if (graph) { //graph.animate({ d: graphPath.join(' ') }); graph.animate({ d: graphPath }); } else { if (lineWidth) { attribs = { 'stroke': color, 'stroke-width': lineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } series.graph = renderer.path(graphPath) .attr(attribs).add(group).shadow(options.shadow); } } }, /** * Render the graph and markers */ render: function() { var series = this, chart = series.chart, group, setInvert, options = series.options, animation = options.animation, doAnimation = animation && series.animate, duration = doAnimation ? animation && animation.duration || 500 : 0, clipRect = series.clipRect, renderer = chart.renderer; // Add plot area clipping rectangle. If this is before chart.hasRendered, // create one shared clipRect. if (!clipRect) { clipRect = series.clipRect = !chart.hasRendered && chart.clipRect ? chart.clipRect : renderer.clipRect(0, 0, chart.plotSizeX, chart.plotSizeY); if (!chart.clipRect) { chart.clipRect = clipRect; } } // the group if (!series.group) { group = series.group = renderer.g('series'); if (chart.inverted) { setInvert = function() { group.attr({ width: chart.plotWidth, height: chart.plotHeight }).invert(); }; setInvert(); // do it now addEvent(chart, 'resize', setInvert); // do it on resize } group.clip(series.clipRect) .attr({ visibility: series.visible ? VISIBLE : HIDDEN, zIndex: options.zIndex }) .translate(chart.plotLeft, chart.plotTop) .add(chart.seriesGroup); } series.drawDataLabels(); // initiate the animation if (doAnimation) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // draw the graph if any if (series.drawGraph) { series.drawGraph(); } // draw the points series.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } // run the animation if (doAnimation) { series.animate(); } // finish the individual clipRect setTimeout(function() { clipRect.isAnimating = false; group = series.group; // can be destroyed during the timeout if (group && clipRect != chart.clipRect && clipRect.renderer) { group.clip((series.clipRect = chart.clipRect)); clipRect.destroy(); } }, duration); series.isDirty = false; // means data is in accordance with what you see }, /** * Redraw the series after an update in the axes. */ redraw: function() { var series = this, chart = series.chart, clipRect = series.clipRect, group = series.group; /*if (clipRect) { stop(clipRect); clipRect.animate({ // for chart resize width: chart.plotSizeX, height: chart.plotSizeY }); }*/ // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: chart.plotLeft, translateY: chart.plotTop }); } series.translate(); series.setTooltipPoints(true); series.render(); }, /** * Set the state of the graph */ setState: function(state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth; state = state || NORMAL_STATE; if (series.state != state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML graph.attr({ // use attr because animate will cause any other animation on the graph to stop 'stroke-width': lineWidth }, state ? 0 : 500); } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function(vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, seriesGroup = series.group, seriesTracker = series.tracker, dataLabelsGroup = series.dataLabelsGroup, showOrHide, i, data = series.data, point, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide series if (seriesGroup) { // pies don't have one seriesGroup[showOrHide](); } // show or hide trackers if (seriesTracker) { seriesTracker[showOrHide](); } else { i = data.length; while (i--) { point = data[i]; if (point.tracker) { point.tracker[showOrHide](); } } } if (dataLabelsGroup) { dataLabelsGroup[showOrHide](); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function(otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function() { this.setVisible(true); }, /** * Hide the graph */ hide: function() { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function(selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTracker: function() { var series = this, options = series.options, trackerPath = [].concat(series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] == M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] == M) || i == trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = chart.renderer.path(trackerPath) .attr({ isTracker: true, stroke: TRACKER_FILL, fill: NONE, 'stroke-width' : options.lineWidth + 2 * snap, visibility: series.visible ? VISIBLE : HIDDEN, zIndex: 1 }) .on(hasTouch ? 'touchstart' : 'mouseover', function() { if (chart.hoverSeries != series) { series.onMouseOver(); } }) .on('mouseout', function() { if (!options.stickyTracking) { series.onMouseOut(); } }) .css(css) .add(chart.trackerGroup); } } }; // end Series prototype /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area' }); seriesTypes.area = AreaSeries; /** * SplineSeries object */ var SplineSeries = extendClass( Series, { type: 'spline', /** * Draw the actual graph */ getPointSpline: function(segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (i && i < segment.length - 1) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } // curve from last point to this else { ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * AreaSplineSeries object */ var AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline' }); seriesTypes.areaspline = AreaSplineSeries; /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, init: function() { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // flag the chart in order to pad the x axis chart.hasColumn = true; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function(otherSeries) { if (otherSeries.type == series.type) { otherSeries.isDirty = true; } }); } }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function() { var series = this, chart = series.chart, columnCount = 0, reversedXAxis = series.xAxis.reversed, categories = series.xAxis.categories, stackGroups = {}, stackKey, columnIndex; Series.prototype.translate.apply(series); // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries each(chart.series, function(otherSeries) { if (otherSeries.type == series.type) { if (otherSeries.options.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else { columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); // calculate the width and position of each column based on // the number of column series in the plot, the groupPadding // and the pointPadding options var options = series.options, data = series.data, closestPoints = series.closestPoints, categoryWidth = mathAbs( data[1] ? data[closestPoints].plotX - data[closestPoints - 1].plotX : chart.plotSizeX / (categories ? categories.length : 1) ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = mathMax(pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), 1), colIndex = (reversedXAxis ? columnCount - series.columnIndex : series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth -(categoryWidth / 2)) * (reversedXAxis ? -1 : 1), threshold = options.threshold || 0, translatedThreshold = series.yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5); // record the new values each(data, function(point) { var plotY = point.plotY, yBottom = point.yBottom || translatedThreshold, barX = point.plotX + pointXOffset, barY = mathCeil(mathMin(plotY, yBottom)), barH = mathCeil(mathMax(plotY, yBottom) - barY), trackerY; // handle options.minPointLength and tracker for small points if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (plotY <= translatedThreshold ? minPointLength : 0); } trackerY = barY - 3; } extend(point, { barX: barX, barY: barY, barW: pointWidth, barH: barH }); point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: pointWidth, height: barH, r: options.borderRadius }; // make small columns responsive to mouse point.trackerArgs = defined(trackerY) && merge(point.shapeArgs, { height: mathMax(6, barH + 3), y: trackerY }); }); }, getSymbol: function(){ }, /** * Columns have no graph */ drawGraph: function() {}, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function() { var series = this, options = series.options, renderer = series.chart.renderer, graphic, shapeArgs; // draw the columns each(series.data, function(point) { var plotY = point.plotY; if (plotY !== UNDEFINED && !isNaN(plotY)) { graphic = point.graphic; shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(shapeArgs); } else { point.graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow); } } }); }, /** * Draw the individual tracker elements. * This method is inherited by scatter and pie charts too. */ drawTracker: function() { var series = this, chart = series.chart, renderer = chart.renderer, shapeArgs, tracker, trackerLabel = +new Date(), cursor = series.options.cursor, css = cursor && { cursor: cursor }, rel; each(series.data, function(point) { tracker = point.tracker; shapeArgs = point.trackerArgs || point.shapeArgs; if (point.y !== null) { if (tracker) {// update tracker.attr(shapeArgs); } else { point.tracker = renderer[point.shapeType](shapeArgs) .attr({ isTracker: trackerLabel, fill: TRACKER_FILL, visibility: series.visible ? VISIBLE : HIDDEN, zIndex: 1 }) .on(hasTouch ? 'touchstart' : 'mouseover', function(event) { rel = event.relatedTarget || event.fromElement; if (chart.hoverSeries != series && attr(rel, 'isTracker') != trackerLabel) { series.onMouseOver(); } point.onMouseOver(); }) .on('mouseout', function(event) { if (!series.options.stickyTracking) { rel = event.relatedTarget || event.toElement; if (attr(rel, 'isTracker') != trackerLabel) { series.onMouseOut(); } } }) .css(css) .add(chart.trackerGroup); } } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function(init) { var series = this, data = series.data; if (!init) { // run the animation /* * Note: Ideally the animation should be initialized by calling * series.group.hide(), and then calling series.group.show() * after the animation was started. But this rendered the shadows * invisible in IE8 standards mode. If the columns flicker on large * datasets, this is the cause. */ each(data, function(point) { var graphic = point.graphic; if (graphic) { // start values graphic.attr({ height: 0, y: series.yAxis.translate(0, 0, 1) }); // animate graphic.animate({ height: point.barH, y: point.barY }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Remove this series from the chart */ remove: function() { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function(otherSeries) { if (otherSeries.type == series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; var BarSeries = extendClass(ColumnSeries, { type: 'bar', init: function(chart) { chart.inverted = this.inverted = true; ColumnSeries.prototype.init.apply(this, arguments); } }); seriesTypes.bar = BarSeries; /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', /** * Extend the base Series' translate method by adding shape type and * arguments for the point trackers */ translate: function() { var series = this; Series.prototype.translate.apply(series); each(series.data, function(point) { point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: series.chart.options.tooltip.snap }; }); }, /** * Create individual tracker elements for each point */ //drawTracker: ColumnSeries.prototype.drawTracker, drawTracker: function() { var series = this, cursor = series.options.cursor, css = cursor && { cursor: cursor }, graphic; each(series.data, function(point) { graphic = point.graphic; if (graphic) { // doesn't exist for null points graphic .attr({ isTracker: true }) .on('mouseover', function(event) { series.onMouseOver(); point.onMouseOver(); }) .on('mouseout', function(event) { if (!series.options.stickyTracking) { series.onMouseOut(); } }) .css(css); } }); }, /** * Cleaning the data is not necessary in a scatter plot */ cleanData: function() {} }); seriesTypes.scatter = ScatterSeries; /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function() { point.slice(); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function(vis) { var point = this, chart = point.series.chart, tracker = point.tracker, dataLabel = point.dataLabel, connector = point.connector, method; // if called without an argument, toggle visibility point.visible = vis = vis === UNDEFINED ? !point.visible : vis; method = vis ? 'show' : 'hide'; point.group[method](); if (tracker) { tracker[method](); } if (dataLabel) { dataLabel[method](); } if (connector) { connector[method](); } if (point.legendItem) { chart.legend.colorizeItem(point, vis); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function(sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, slicedTranslation = point.slicedTranslation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle sliced = point.sliced = defined(sliced) ? sliced : !point.sliced; point.group.animate({ translateX: (sliced ? slicedTranslation[0] : chart.plotLeft), translateY: (sliced ? slicedTranslation[1] : chart.plotTop) }); } }); /** * The Pie series class */ var PieSeries = extendClass(Series, { type: 'pie', isCartesian: false, pointClass: PiePoint, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: function() { // record first color for use in setData this.initialColor = colorCounter; }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function(init) { var series = this, data = series.data; each(data, function(point) { var graphic = point.graphic, args = point.shapeArgs, up = -mathPI / 2; if (graphic) { // start values graphic.attr({ r: 0, start: up, end: up }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; }, /** * Do translation for pie slices */ translate: function() { var total = 0, series = this, cumulative = -0.25, // start at top precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, positions = options.center, chart = series.chart, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, start, end, angle, data = series.data, circ = 2 * mathPI, fraction, smallestSize = mathMin(plotWidth, plotHeight), isPercent, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance; // get positions - either an integer or a percentage string must be given positions.push(options.size, options.innerSize || 0); positions = map(positions, function(length, i) { isPercent = /%$/.test(length); return isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100: length; }); // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function(y, left) { angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // set center for later use series.center = positions; // get the total sum each(data, function(point) { total += point.y; }); each(data, function(point) { // set start and end angle fraction = total ? point.y / total : 0; start = mathRound(cumulative * circ * precision) / precision; cumulative += fraction; end = mathRound(cumulative * circ * precision) / precision; // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: start, end: end }; // center for the sliced out slice angle = (end + start) / 2; point.slicedTranslation = map([ mathCos(angle) * slicedOffset + chart.plotLeft, mathSin(angle) * slicedOffset + chart.plotTop ], mathRound); // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; // set the anchor point for data labels point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : angle < circ / 4 ? 'left' : 'right', // alignment angle // center angle ]; // API properties point.percentage = fraction * 100; point.total = total; }); this.setTooltipPoints(); }, /** * Render the slices */ render: function() { var series = this; // cache attributes for shapes series.getAttribs(); this.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } this.drawDataLabels(); if (series.options.animation && series.animate) { series.animate(); } series.isDirty = false; // means data is in accordance with what you see }, /** * Draw the data points */ drawPoints: function() { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, group, shapeArgs; // draw the slices each(series.data, function(point) { graphic = point.graphic; shapeArgs = point.shapeArgs; group = point.group; // create the group the first time if (!group) { group = point.group = renderer.g('point') .attr({ zIndex: 5 }) .add(); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : [chart.plotLeft, chart.plotTop]; group.translate(groupTranslation[0], groupTranslation[1]) // draw the slice if (graphic) { graphic.animate(shapeArgs); } else { point.graphic = renderer.arc(shapeArgs) .attr(extend( point.pointAttr[NORMAL_STATE], { 'stroke-linejoin': 'round' } )) .add(point.group); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Override the base drawDataLabels method by pie specific functionality */ drawDataLabels: function() { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), connector, connectorPath, outside = options.distance > 0, dataLabel, labelPos, labelHeight, lastY, centerY = series.center[1], quarters = [// divide the points into quarters for anti collision [], // top right [], // bottom right [], // bottom left [] // top left ], x, y, visibility, overlapping, rankArr, secondPass, sign, lowerHalf, sort, i = 4, j; // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function(point) { var angle = point.labelPos[7], quarter; if (angle < 0) { quarter = 0; } else if (angle < mathPI / 2) { quarter = 1; } else if (angle < mathPI) { quarter = 2; } else { quarter = 3; } quarters[quarter].push(point); }); quarters[1].reverse(); quarters[3].reverse(); // define the sorting algorithm sort = function(a,b) { return a.y > b.y; }; /* Loop over the points in each quartile, starting from the top and bottom * of the pie to detect overlapping labels. */ while (i--) { overlapping = 0; // create an array for sorting and ranking the points within each quarter rankArr = [].concat(quarters[i]); rankArr.sort(sort); j = rankArr.length; while (j--) { rankArr[j].rank = j; } /* In the first pass, count the number of overlapping labels. In the second * pass, remove the labels with lowest rank/values. */ for (secondPass = 0; secondPass < 2; secondPass++) { lowerHalf = i % 3; lastY = lowerHalf ? 9999 : -9999; sign = lowerHalf ? -1 : 1; for (j = 0; j < quarters[i].length; j++) { point = quarters[i][j]; if ((dataLabel = point.dataLabel)) { labelPos = point.labelPos; visibility = VISIBLE; x = labelPos[0]; y = labelPos[1]; // assume all labels have equal height if (!labelHeight) { labelHeight = dataLabel && dataLabel.getBBox().height; } // anticollision if (outside) { if (secondPass && point.rank < overlapping) { visibility = HIDDEN; } else if ((!lowerHalf && y < lastY + labelHeight) || (lowerHalf && y > lastY - labelHeight)) { y = lastY + sign * labelHeight; x = series.getX(y, i > 1); if ((!lowerHalf && y + labelHeight > centerY) || (lowerHalf && y -labelHeight < centerY)) { if (secondPass) { visibility = HIDDEN; } else { overlapping++; } } } } if (point.visible === false) { visibility = HIDDEN; } if (visibility == VISIBLE) { lastY = y; } if (secondPass) { // move or place the data label dataLabel .attr({ visibility: visibility, align: labelPos[6] }) [dataLabel.moved ? 'animate' : 'attr']({ x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y }); dataLabel.moved = true; // draw the connector if (outside && connectorWidth) { connector = point.connector; connectorPath = [ M, x + (labelPos[6] == 'left' ? 5 : -5), y, // end of the string at the label L, x, y, // first break, next to the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || '#606060', visibility: visibility, zIndex: 3 }) .translate(chart.plotLeft, chart.plotTop) .add(); } } } } } } } }, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Pies don't have point marker symbols */ getSymbol: function() {} }); seriesTypes.pie = PieSeries; // global variables win.Highcharts = { Chart: Chart, dateFormat: dateFormat, pathAnim: pathAnim, getOptions: getOptions, numberFormat: numberFormat, Point: Point, Color: Color, Renderer: Renderer, seriesTypes: seriesTypes, setOptions: setOptions, Series: Series, // Expose utility funcitons for modules addEvent: addEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, extendClass: extendClass, version: '2.1.3' }; })();
JavaScript
/** * @license Highcharts JS v2.1.3 (2011-02-07) * MooTools adapter * * (c) 2010 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, Fx, $, $extend, $each, $merge, Events, Event */ var HighchartsAdapter = { /** * Initialize the adapter. This is run once as Highcharts is first run. */ init: function() { var fxProto = Fx.prototype, fxStart = fxProto.start, morphProto = Fx.Morph.prototype, morphCompute = morphProto.compute; // override Fx.start to allow animation of SVG element wrappers fxProto.start = function(from, to) { var fx = this, elem = fx.element; // special for animating paths if (from.d) { //this.fromD = this.element.d.split(' '); fx.paths = Highcharts.pathAnim.init( elem, elem.d, fx.toD ); } fxStart.apply(fx, arguments); }; // override Fx.step to allow animation of SVG element wrappers morphProto.compute = function(from, to, delta) { var fx = this, paths = fx.paths; if (paths) { fx.element.attr( 'd', Highcharts.pathAnim.step(paths[0], paths[1], delta, fx.toD) ); } else { return morphCompute.apply(fx, arguments); } }; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var isSVGElement = el.attr, effect, complete = options && options.complete; if (isSVGElement && !el.setStyle) { // add setStyle and getStyle methods for internal use in Moo el.getStyle = el.attr; el.setStyle = function() { // property value is given as array in Moo - break it down var args = arguments; el.attr.call(el, args[0], args[1][0]); } // dirty hack to trick Moo into handling el as an element wrapper el.$family = el.uid = true; } // stop running animations HighchartsAdapter.stop(el); // define and run the effect effect = new Fx.Morph( isSVGElement ? el : $(el), $extend({ transition: Fx.Transitions.Quad.easeInOut }, options) ); // special treatment for paths if (params.d) { effect.toD = params.d; } // jQuery-like events if (complete) { effect.addEvent('complete', complete); } // run effect.start(params); // record for use in stop method el.fx = effect; }, /** * MooTool's each function * */ each: $each, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn){ return arr.map(fn); }, /** * Grep or filter an array * @param {Array} arr * @param {Function} fn */ grep: function(arr, fn) { return arr.filter(fn); }, /** * Deep merge two objects and return a third */ merge: $merge, /** * Hyphenate a string, like minWidth becomes min-width * @param {Object} str */ hyphenate: function (str){ return str.hyphenate(); }, /** * Add an event listener * @param {Object} el HTML element or custom object * @param {String} type Event type * @param {Function} fn Event handler */ addEvent: function (el, type, fn) { if (typeof type == 'string') { // chart broke due to el being string, type function if (type == 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } // if the addEvent method is not defined, el is a custom Highcharts object // like series or point if (!el.addEvent) { if (el.nodeName) { el = $(el); // a dynamically generated node } else { $extend(el, new Events()); // a custom object } } el.addEvent(type, fn); } }, removeEvent: function(el, type, fn) { if (type) { if (type == 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } el.removeEvent(type, fn); } }, fireEvent: function(el, event, eventArguments, defaultFunction) { // create an event object that keeps all functions event = new Event({ type: event, target: el }); event = $extend(event, eventArguments); // override the preventDefault function to be able to use // this for custom events event.preventDefault = function() { defaultFunction = null; }; // if fireEvent is not available on the object, there hasn't been added // any events to it above if (el.fireEvent) { el.fireEvent(event.type, event); } // fire the default if it is passed and it is not prevented above if (defaultFunction) { defaultFunction(event); } }, /** * Stop running animations on the object */ stop: function (el) { if (el.fx) { el.fx.cancel(); } } };
JavaScript
/** * Ajax upload * Project page - http://valums.com/ajax-upload/ * Copyright (c) 2008 Andris Valums, http://valums.com * Licensed under the MIT license (http://valums.com/mit-license/) * Version 3.5 (23.06.2009) */ /** * Changes from the previous version: * 1. Added better JSON handling that allows to use 'application/javascript' as a response * 2. Added demo for usage with jQuery UI dialog * 3. Fixed IE "mixed content" issue when used with secure connections * * For the full changelog please visit: * http://valums.com/ajax-upload-changelog/ */ (function(){ var d = document, w = window; /** * Get element by id */ function get(element){ if (typeof element == "string") element = d.getElementById(element); return element; } /** * Attaches event to a dom element */ function addEvent(el, type, fn){ if (w.addEventListener){ el.addEventListener(type, fn, false); } else if (w.attachEvent){ var f = function(){ fn.call(el, w.event); }; el.attachEvent('on' + type, f) } } /** * Creates and returns element from html chunk */ var toElement = function(){ var div = d.createElement('div'); return function(html){ div.innerHTML = html; var el = div.childNodes[0]; div.removeChild(el); return el; } }(); function hasClass(ele,cls){ return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } // getOffset function copied from jQuery lib (http://jquery.com/) if (document.documentElement["getBoundingClientRect"]){ // Get Offset using getBoundingClientRect // http://ejohn.org/blog/getboundingclientrect-is-awesome/ var getOffset = function(el){ var box = el.getBoundingClientRect(), doc = el.ownerDocument, body = doc.body, docElem = doc.documentElement, // for ie clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, // In Internet Explorer 7 getBoundingClientRect property is treated as physical, // while others are logical. Make all logical, like in IE8. zoom = 1; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left)/body.clientWidth; } if (zoom > 1){ clientTop = 0; clientLeft = 0; } var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop, left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft; return { top: top, left: left }; } } else { // Get offset adding all offsets var getOffset = function(el){ if (w.jQuery){ return jQuery(el).offset(); } var top = 0, left = 0; do { top += el.offsetTop || 0; left += el.offsetLeft || 0; } while (el = el.offsetParent); return { left: left, top: top }; } } function getBox(el){ var left, right, top, bottom; var offset = getOffset(el); left = offset.left; top = offset.top; right = left + el.offsetWidth; bottom = top + el.offsetHeight; return { left: left, right: right, top: top, bottom: bottom }; } /** * Crossbrowser mouse coordinates */ function getMouseCoords(e){ // pageX/Y is not supported in IE // http://www.quirksmode.org/dom/w3c_cssom.html if (!e.pageX && e.clientX){ // In Internet Explorer 7 some properties (mouse coordinates) are treated as physical, // while others are logical (offset). var zoom = 1; var body = document.body; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left)/body.clientWidth; } return { x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft, y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop }; } return { x: e.pageX, y: e.pageY }; } /** * Function generates unique id */ var getUID = function(){ var id = 0; return function(){ return 'ValumsAjaxUpload' + id++; } }(); function fileFromPath(file){ return file.replace(/.*(\/|\\)/, ""); } function getExt(file){ return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : ''; } // Please use AjaxUpload , Ajax_upload will be removed in the next version Ajax_upload = AjaxUpload = function(button, options){ if (button.jquery){ // jquery object was passed button = button[0]; } else if (typeof button == "string" && /^#.*/.test(button)){ button = button.slice(1); } button = get(button); this._input = null; this._button = button; this._disabled = false; this._submitting = false; // Variable changes to true if the button was clicked // 3 seconds ago (requred to fix Safari on Mac error) this._justClicked = false; this._parentDialog = d.body; if (window.jQuery && jQuery.ui && jQuery.ui.dialog){ var parentDialog = jQuery(this._button).parents('.ui-dialog'); if (parentDialog.length){ this._parentDialog = parentDialog[0]; } } this._settings = { // Location of the server-side upload script action: 'upload.php', // File upload name name: 'userfile', // Additional data to send data: {}, // Submit file as soon as it's selected autoSubmit: true, // The type of data that you're expecting back from the server. // Html and xml are detected automatically. // Only useful when you are using json data as a response. // Set to "json" in that case. responseType: false, // When user selects a file, useful with autoSubmit disabled onChange: function(file, extension){}, // Callback to fire before file is uploaded // You can return false to cancel upload onSubmit: function(file, extension){}, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! onComplete: function(file, response) {} }; // Merge the users options with our defaults for (var i in options) { this._settings[i] = options[i]; } this._createInput(); this._rerouteClicks(); } // assigning methods to our class AjaxUpload.prototype = { setData : function(data){ this._settings.data = data; }, disable : function(){ this._disabled = true; }, enable : function(){ this._disabled = false; }, // removes ajaxupload destroy : function(){ if(this._input){ if(this._input.parentNode){ this._input.parentNode.removeChild(this._input); } this._input = null; } }, /** * Creates invisible file input above the button */ _createInput : function(){ var self = this; var input = d.createElement("input"); input.setAttribute('type', 'file'); input.setAttribute('name', this._settings.name); var styles = { 'position' : 'absolute' ,'margin': '-5px 0 0 -175px' ,'padding': 0 ,'width': '220px' ,'height': '30px' ,'fontSize': '14px' ,'opacity': 0 ,'cursor': 'pointer' ,'display' : 'none' ,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x // Strange, I expected 2147483647 }; for (var i in styles){ input.style[i] = styles[i]; } // Make sure that element opacity exists // (IE uses filter instead) if ( ! (input.style.opacity === "0")){ input.style.filter = "alpha(opacity=0)"; } this._parentDialog.appendChild(input); addEvent(input, 'change', function(){ // get filename from input var file = fileFromPath(this.value); if(self._settings.onChange.call(self, file, getExt(file)) == false ){ return; } // Submit form when value is changed if (self._settings.autoSubmit){ self.submit(); } }); // Fixing problem with Safari // The problem is that if you leave input before the file select dialog opens // it does not upload the file. // As dialog opens slowly (it is a sheet dialog which takes some time to open) // there is some time while you can leave the button. // So we should not change display to none immediately addEvent(input, 'click', function(){ self.justClicked = true; setTimeout(function(){ // we will wait 3 seconds for dialog to open self.justClicked = false; }, 3000); }); this._input = input; }, _rerouteClicks : function (){ var self = this; // IE displays 'access denied' error when using this method // other browsers just ignore click() // addEvent(this._button, 'click', function(e){ // self._input.click(); // }); var box, dialogOffset = {top:0, left:0}, over = false; addEvent(self._button, 'mouseover', function(e){ if (!self._input || over) return; over = true; box = getBox(self._button); if (self._parentDialog != d.body){ dialogOffset = getOffset(self._parentDialog); } }); // we can't use mouseout on the button, // because invisible input is over it addEvent(document, 'mousemove', function(e){ var input = self._input; if (!input || !over) return; if (self._disabled){ removeClass(self._button, 'hover'); input.style.display = 'none'; return; } var c = getMouseCoords(e); if ((c.x >= box.left) && (c.x <= box.right) && (c.y >= box.top) && (c.y <= box.bottom)){ input.style.top = c.y - dialogOffset.top + 'px'; input.style.left = c.x - dialogOffset.left + 'px'; input.style.display = 'block'; addClass(self._button, 'hover'); } else { // mouse left the button over = false; if (!self.justClicked){ input.style.display = 'none'; } removeClass(self._button, 'hover'); } }); }, /** * Creates iframe with unique name */ _createIframe : function(){ // unique name // We cannot use getTime, because it sometimes return // same value in safari :( var id = getUID(); // Remove ie6 "This page contains both secure and nonsecure items" prompt // http://tinyurl.com/77w9wh var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />'); iframe.id = id; iframe.style.display = 'none'; d.body.appendChild(iframe); return iframe; }, /** * Upload file without refreshing the page */ submit : function(){ var self = this, settings = this._settings; if (this._input.value === ''){ // there is no file return; } // get filename from input var file = fileFromPath(this._input.value); // execute user event if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) { // Create new iframe for this submission var iframe = this._createIframe(); // Do not submit if user function returns false var form = this._createForm(iframe); form.appendChild(this._input); form.submit(); d.body.removeChild(form); form = null; this._input = null; // create new input this._createInput(); var toDeleteFlag = false; addEvent(iframe, 'load', function(e){ if (// For Safari iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For FF, IE iframe.src == "javascript:'<html></html>';"){ // First time around, do not delete. if( toDeleteFlag ){ // Fix busy state in FF3 setTimeout( function() { d.body.removeChild(iframe); }, 0); } return; } var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document; // fixing Opera 9.26 if (doc.readyState && doc.readyState != 'complete'){ // Opera fires load event multiple times // Even when the DOM is not ready yet // this fix should not affect other browsers return; } // fixing Opera 9.64 if (doc.body && doc.body.innerHTML == "false"){ // In Opera 9.64 event was fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec return; } var response; if (doc.XMLDocument){ // response is a xml document IE property response = doc.XMLDocument; } else if (doc.body){ // response is html document or plain text response = doc.body.innerHTML; if (settings.responseType && settings.responseType.toLowerCase() == 'json'){ // If the document was sent as 'application/javascript' or // 'text/javascript', then the browser wraps the text in a <pre> // tag and performs html encoding on the contents. In this case, // we need to pull the original text content from the text node's // nodeValue property to retrieve the unmangled content. // Note that IE6 only understands text/html if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){ response = doc.body.firstChild.firstChild.nodeValue; } if (response) { response = window["eval"]("(" + response + ")"); } else { response = {}; } } } else { // response is a xml document var response = doc; } settings.onComplete.call(self, file, response); // Reload blank page, so that reloading main page // does not re-submit the post. Also, remember to // delete the frame toDeleteFlag = true; // Fix IE mixed content issue iframe.src = "javascript:'<html></html>';"; }); } else { // clear input to allow user to select same file // Doesn't work in IE6 // this._input.value = ''; d.body.removeChild(this._input); this._input = null; // create new input this._createInput(); } }, /** * Creates form, that will be submitted to iframe */ _createForm : function(iframe){ var settings = this._settings; // method, enctype must be specified here // because changing this attr on the fly is not allowed in IE 6/7 var form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.style.display = 'none'; form.action = settings.action; form.target = iframe.name; d.body.appendChild(form); // Create hidden input element for each data key for (var prop in settings.data){ var el = d.createElement("input"); el.type = 'hidden'; el.name = prop; el.value = settings.data[prop]; form.appendChild(el); } return form; } }; })();
JavaScript
$(document).ready(function(){ $("#formPaises").validate({ rules: {codigo:{digits:true}}, messages:{ codigo:'El codigo debe ser Numerico'} }); $("#formBuques").validate({ rules: {codigo:{digits:true}}, messages:{codigo:'El codigo debe ser Numerico'}}); $("#formDespachante").validate({ rules:{ cuit: {digits:true}}, messages:{cuit:'El codigo debe ser Numerico'}}); $("#formaduanas").validate({ rules:{ codigo: {digits:true}}, messages:{codigo:'El codigo debe ser Numerico'}}); $("#formDestinaciones").validate({ rules:{ codigo: {digits:true}}, messages:{codigo:'El codigo debe ser Numerico'}}); $("#formcolores").validate({ rules:{ codigo: {digits:true}}, messages:{codigo:'El codigo debe ser Numerico'}}); $("#formAniosModelo").validate({ rules:{ anioModelo: {digits:true}}, messages:{anioModelo:'El codigo debe ser Numerico'}}); $("#formaniosModeloExcepciones").validate({ rules:{ anioModelo: {digits:true}}, messages:{anioModelo:'El codigo debe ser Numerico'}}); $("#formmarca").validate({ rules:{ rpa: {digits:true}}, messages:{rpa:'El codigo debe ser Numerico'}}); $("#formModelosLcm").validate({ rules:{lcm:{digits:true}}, messages:{lcm:'El codigo debe ser Numerico'}}); $("#formRegimen").validate(); });
JavaScript
/** * @license Highcharts JS v2.1.3 (2011-02-07) * Exporting module * * (c) 2010 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, Math, setTimeout */ (function() { // encapsulate // create shortcuts var HC = Highcharts, Chart = HC.Chart, addEvent = HC.addEvent, createElement = HC.createElement, discardElement = HC.discardElement, css = HC.css, merge = HC.merge, each = HC.each, extend = HC.extend, math = Math, mathMax = math.max, doc = document, win = window, hasTouch = 'ontouchstart' in doc.documentElement, M = 'M', L = 'L', DIV = 'div', HIDDEN = 'hidden', NONE = 'none', PREFIX = 'highcharts-', ABSOLUTE = 'absolute', PX = 'px', // Add language and get the defaultOptions defaultOptions = HC.setOptions({ lang: { downloadPNG: 'Download PNG image', downloadJPEG: 'Download JPEG image', downloadPDF: 'Download PDF document', downloadSVG: 'Download SVG vector image', exportButtonTitle: 'Export to raster or vector image', printButtonTitle: 'Print the chart' } }); // Buttons and menus are collected in a separate config option set called 'navigation'. // This can be extended later to add control buttons like zoom and pan right click menus. defaultOptions.navigation = { menuStyle: { border: '1px solid #A0A0A0', background: '#FFFFFF' }, menuItemStyle: { padding: '0 5px', background: NONE, color: '#303030', fontSize: hasTouch ? '14px' : '11px' }, menuItemHoverStyle: { background: '#4572A5', color: '#FFFFFF' }, buttonOptions: { align: 'right', backgroundColor: { linearGradient: [0, 0, 0, 20], stops: [ [0.4, '#F7F7F7'], [0.6, '#E3E3E3'] ] }, borderColor: '#B0B0B0', borderRadius: 3, borderWidth: 1, //enabled: true, height: 20, hoverBorderColor: '#909090', hoverSymbolFill: '#81A7CF', hoverSymbolStroke: '#4572A5', symbolFill: '#E0E0E0', //symbolSize: 12, symbolStroke: '#A0A0A0', //symbolStrokeWidth: 1, symbolX: 11.5, symbolY: 10.5, verticalAlign: 'top', width: 24, y: 10 } }; // Add the export related options defaultOptions.exporting = { //enabled: true, //filename: 'chart', type: 'image/png', url: 'http://export.highcharts.com/', width: 800, buttons: { exportButton: { //enabled: true, symbol: 'exportIcon', x: -10, symbolFill: '#A8BF77', hoverSymbolFill: '#768F3E', _titleKey: 'exportButtonTitle', menuItems: [{ textKey: 'downloadPNG', onclick: function() { this.exportChart(); } }, { textKey: 'downloadJPEG', onclick: function() { this.exportChart({ type: 'image/jpeg' }); } }, { textKey: 'downloadPDF', onclick: function() { this.exportChart({ type: 'application/pdf' }); } }, { textKey: 'downloadSVG', onclick: function() { this.exportChart({ type: 'image/svg+xml' }); } }/*, { text: 'View SVG', onclick: function() { var svg = this.getSVG() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); doc.body.innerHTML = '<pre>'+ svg +'</pre>'; } }*/] }, printButton: { //enabled: true, symbol: 'printIcon', x: -36, symbolFill: '#B5C9DF', hoverSymbolFill: '#779ABF', _titleKey: 'printButtonTitle', onclick: function() { this.print(); } } } }; extend(Chart.prototype, { /** * Return an SVG representation of the chart * * @param additionalOptions {Object} Additional chart options for the generated SVG representation */ getSVG: function(additionalOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, config, pointOptions, pointMarker, options = merge(chart.options, additionalOptions); // copy the options and add extra options // IE compatibility hack for generating SVG content that it doesn't really understand if (!doc.createElementNS) { doc.createElementNS = function(ns, tagName) { var elem = doc.createElement(tagName); elem.getBBox = function() { return chart.renderer.Element.prototype.getBBox.apply({ element: elem }); }; return elem; }; } // create a sandbox where a new chart will be generated sandbox = createElement(DIV, null, { position: ABSOLUTE, top: '-9999em', width: chart.chartWidth + PX, height: chart.chartHeight + PX }, doc.body); // override some options extend(options.chart, { renderTo: sandbox, forExport: true }); options.exporting.enabled = false; // hide buttons in print options.chart.plotBackgroundImage = null; // the converter doesn't handle images // prepare for replicating the chart options.series = []; each(chart.series, function(serie) { seriesOptions = serie.options; seriesOptions.animation = false; // turn off animation seriesOptions.showCheckbox = false; // remove image markers if (seriesOptions && seriesOptions.marker && /^url\(/.test(seriesOptions.marker.symbol)) { seriesOptions.marker.symbol = 'circle'; } seriesOptions.data = []; each(serie.data, function(point) { // extend the options by those values that can be expressed in a number or array config config = point.config; pointOptions = extend( typeof config == 'object' && point.config && config.constructor != Array, { x: point.x, y: point.y, name: point.name } ); seriesOptions.data.push(pointOptions); // copy fresh updated data // remove image markers pointMarker = point.config && point.config.marker; if (pointMarker && /^url\(/.test(pointMarker.symbol)) { delete pointMarker.symbol; } }); options.series.push(seriesOptions); }); // generate the chart copy chartCopy = new Highcharts.Chart(options); // get the SVG from the container's innerHTML svg = chartCopy.container.innerHTML; // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); // sanitize svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/isShadow="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/isTracker="[^"]+"/g, '') .replace(/url\([^#]+#/g, 'url(#') /*.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ href=/, ' xlink:href=') .replace(/preserveAspectRatio="none">/g, 'preserveAspectRatio="none"/>')*/ /* This fails in IE < 8 .replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight return s2 +'.'+ s3[0]; })*/ // IE specific .replace(/id=([^" >]+)/g, 'id="$1"') .replace(/class=([^" ]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function(s) { return s.toLowerCase(); }); // IE9 beta bugs with innerHTML. Test again with final IE9. svg = svg.replace(/(url\(#highcharts-[0-9]+)&quot;/g, '$1') .replace(/&quot;/g, "'"); if (svg.match(/ xmlns="/g).length == 2) { svg = svg.replace(/xmlns="[^"]+"/, ''); } return svg; }, /** * Submit the SVG representation of the chart to the server * @param {Object} options Exporting options. Possible members are url, type and width. * @param {Object} chartOptions Additional chart options for the SVG representation of the chart */ exportChart: function(options, chartOptions) { var form, chart = this, svg = chart.getSVG(chartOptions); // merge the options options = merge(chart.options.exporting, options); // create the form form = createElement('form', { method: 'post', action: options.url }, { display: NONE }, doc.body); // add the values each(['filename', 'type', 'width', 'svg'], function(name) { createElement('input', { type: HIDDEN, name: name, value: { filename: options.filename || 'chart', type: options.type, width: options.width, svg: svg }[name] }, null, form); }); // submit form.submit(); // clean up discardElement(form); }, /** * Print the chart */ print: function() { var chart = this, container = chart.container, origDisplay = [], origParent = container.parentNode, body = doc.body, childNodes = body.childNodes; if (chart.isPrinting) { // block the button while in printing mode return; } chart.isPrinting = true; // hide all body content each(childNodes, function(node, i) { if (node.nodeType == 1) { origDisplay[i] = node.style.display; node.style.display = NONE; } }); // pull out the chart body.appendChild(container); // print win.print(); // allow the browser to prepare before reverting setTimeout(function() { // put the chart back in origParent.appendChild(container); // restore all body content each(childNodes, function(node, i) { if (node.nodeType == 1) { node.style.display = origDisplay[i]; } }); chart.isPrinting = false; }, 1000); }, /** * Display a popup menu for choosing the export type * * @param {String} name An identifier for the menu * @param {Array} items A collection with text and onclicks for the items * @param {Number} x The x position of the opener button * @param {Number} y The y position of the opener button * @param {Number} width The width of the opener button * @param {Number} height The height of the opener button */ contextMenu: function(name, items, x, y, width, height) { var chart = this, navOptions = chart.options.navigation, menuItemStyle = navOptions.menuItemStyle, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-'+ name, menu = chart[cacheName], menuPadding = mathMax(width, height), // for mouse leave detection boxShadow = '3px 3px 10px #888', innerMenu, hide, menuStyle; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart[cacheName] = menu = createElement(DIV, { className: PREFIX + name }, { position: ABSOLUTE, zIndex: 1000, padding: menuPadding + PX }, chart.container); innerMenu = createElement(DIV, null, extend({ MozBoxShadow: boxShadow, WebkitBoxShadow: boxShadow, boxShadow: boxShadow }, navOptions.menuStyle) , menu); // hide on mouse out hide = function() { css(menu, { display: NONE }); }; addEvent(menu, 'mouseleave', hide); // create the items each(items, function(item) { if (item) { var div = createElement(DIV, { onmouseover: function() { css(this, navOptions.menuItemHoverStyle); }, onmouseout: function() { css(this, menuItemStyle); }, innerHTML: item.text || HC.getOptions().lang[item.textKey] }, extend({ cursor: 'pointer' }, menuItemStyle), innerMenu); div[hasTouch ? 'ontouchstart' : 'onclick'] = function() { hide(); item.onclick.apply(chart, arguments); }; } }); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + PX; } else { menuStyle.left = (x - menuPadding) + PX; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight) { menuStyle.bottom = (chartHeight - y - menuPadding) + PX; } else { menuStyle.top = (y + height - menuPadding) + PX; } css(menu, menuStyle); }, /** * Add the export button to the chart */ addButton: function(options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, /*position = chart.getAlignment(btnOptions), buttonLeft = position.x, buttonTop = position.y,*/ buttonWidth = btnOptions.width, buttonHeight = btnOptions.height, box, symbol, button, borderWidth = btnOptions.borderWidth, boxAttr = { stroke: btnOptions.borderColor }, symbolAttr = { stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill }; if (btnOptions.enabled === false) { return; } // element to capture the click function revert() { symbol.attr(symbolAttr); box.attr(boxAttr); } // the box border box = renderer.rect( 0, 0, buttonWidth, buttonHeight, btnOptions.borderRadius, borderWidth ) //.translate(buttonLeft, buttonTop) // to allow gradients .align(btnOptions, true) .attr(extend({ fill: btnOptions.backgroundColor, 'stroke-width': borderWidth, zIndex: 19 }, boxAttr)).add(); // the invisible element to track the clicks button = renderer.rect( 0, 0, buttonWidth, buttonHeight, 0 ) .align(btnOptions) .attr({ fill: 'rgba(255, 255, 255, 0.001)', title: HC.getOptions().lang[btnOptions._titleKey], zIndex: 21 }).css({ cursor: 'pointer' }) .on('mouseover', function() { symbol.attr({ stroke: btnOptions.hoverSymbolStroke, fill: btnOptions.hoverSymbolFill }); box.attr({ stroke: btnOptions.hoverBorderColor }); }) .on('mouseout', revert) .on('click', revert) .add(); //addEvent(button.element, 'click', revert); // add the click event if (menuItems) { onclick = function(e) { revert(); var bBox = button.getBBox(); chart.contextMenu('export-menu', menuItems, bBox.x, bBox.y, buttonWidth, buttonHeight); }; } /*addEvent(button.element, 'click', function() { onclick.apply(chart, arguments); });*/ button.on('click', function() { onclick.apply(chart, arguments); }); // the icon symbol = renderer.symbol( btnOptions.symbol, btnOptions.symbolX, btnOptions.symbolY, (btnOptions.symbolSize || 12) / 2 ) .align(btnOptions, true) .attr(extend(symbolAttr, { 'stroke-width': btnOptions.symbolStrokeWidth || 1, zIndex: 20 })).add(); } }); // Create the export icon HC.Renderer.prototype.symbols.exportIcon = function(x, y, radius) { return [ M, // the disk x - radius, y + radius, L, x + radius, y + radius, x + radius, y + radius * 0.5, x - radius, y + radius * 0.5, 'Z', M, // the arrow x, y + radius * 0.5, L, x - radius * 0.5, y - radius / 3, x - radius / 6, y - radius / 3, x - radius / 6, y - radius, x + radius / 6, y - radius, x + radius / 6, y - radius / 3, x + radius * 0.5, y - radius / 3, 'Z' ]; }; // Create the print icon HC.Renderer.prototype.symbols.printIcon = function(x, y, radius) { return [ M, // the printer x - radius, y + radius * 0.5, L, x + radius, y + radius * 0.5, x + radius, y - radius / 3, x - radius, y - radius / 3, 'Z', M, // the upper sheet x - radius * 0.5, y - radius / 3, L, x - radius * 0.5, y - radius, x + radius * 0.5, y - radius, x + radius * 0.5, y - radius / 3, 'Z', M, // the lower sheet x - radius * 0.5, y + radius * 0.5, L, x - radius * 0.75, y + radius, x + radius * 0.75, y + radius, x + radius * 0.5, y + radius * 0.5, 'Z' ]; }; // Add the buttons on chart load Chart.prototype.callbacks.push(function(chart) { var n, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons; if (exportingOptions.enabled !== false) { for (n in buttons) { chart.addButton(buttons[n]); } } }); })();
JavaScript
/* * jQuery Autocomplete plugin 1.1 * * Copyright (c) 2009 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $ */ ;(function($) { $.fn.extend({ autocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // a keypress means the input has focus // avoids issue where input had focus before the autocomplete was applied hasFocus = 1; // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { var seperator = options.multipleSeparator.length; var cursorAt = $(input).selection().start; var wordAt, progress = 0; $.each(words, function(i, word) { progress += word.length; if (cursorAt <= progress) { wordAt = i; return false; } progress += seperator; }); words[wordAt] = v; // TODO this should set the cursor to the right position, but it gets overriden somewhere //$.Autocompleter.Selection(input, progress + seperator, progress + seperator); v = words.join( options.multipleSeparator ); } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if (!value) return [""]; if (!options.multiple) return [$.trim(value)]; return $.map(value.split(options.multipleSeparator), function(word) { return $.trim(value).length ? $.trim(word) : null; }); } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); if (words.length == 1) return words[0]; var cursorAt = $(input).selection().start; if (cursorAt == value.length) { words = trimWords(value) } else { words = trimWords(value.replace(value.substring(cursorAt), "")); } return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $(input).selection(previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else { $input.val( "" ); $input.trigger("result", null); } } } ); } }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word"){ i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.fn.selection = function(start, end) { if (start !== undefined) { return this.each(function() { if( this.createTextRange ){ var selRange = this.createTextRange(); if (end === undefined || start == end) { selRange.move("character", start); selRange.select(); } else { selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } } else if( this.setSelectionRange ){ this.setSelectionRange(start, end); } else if( this.selectionStart ){ this.selectionStart = start; this.selectionEnd = end; } }); } var field = this[0]; if ( field.createTextRange ) { var range = document.selection.createRange(), orig = field.value, teststring = "<->", textLength = range.text.length; range.text = teststring; var caretAt = field.value.indexOf(teststring); field.value = orig; this.selection(caretAt, caretAt + textLength); return { start: caretAt, end: caretAt + textLength } } else if( field.selectionStart !== undefined ){ return { start: field.selectionStart, end: field.selectionEnd } } }; })(jQuery);
JavaScript
/* * jQuery RTE plugin 0.3 - create a rich text form for Mozilla, Opera, and Internet Explorer * * Copyright (c) 2007 Batiste Bieler * Distributed under the GPL (GPL-LICENSE.txt) licenses. */ // define the rte light plugin jQuery.fn.rte = function(css_url, media_url) { if(document.designMode || document.contentEditable) { $(this).each( function(){ var textarea = $(this); enableDesignMode(textarea); }); } function formatText(iframe, command, option) { iframe.contentWindow.focus(); try{ iframe.contentWindow.document.execCommand(command, false, option); }catch(e){console.log(e)} iframe.contentWindow.focus(); } function tryEnableDesignMode(iframe, doc, callback) { try { iframe.contentWindow.document.open(); iframe.contentWindow.document.write(doc); iframe.contentWindow.document.close(); } catch(error) { console.log(error) } if (document.contentEditable) { iframe.contentWindow.document.designMode = "On"; callback(); return true; } else if (document.designMode != null) { try { iframe.contentWindow.document.designMode = "on"; callback(); return true; } catch (error) { console.log(error) } } setTimeout(function(){tryEnableDesignMode(iframe, doc, callback)}, 250); return false; } function enableDesignMode(textarea) { // need to be created this way var iframe = document.createElement("iframe"); iframe.frameBorder=0; iframe.frameMargin=0; iframe.framePadding=0; iframe.height=200; iframe.width=744; if(textarea.attr('class')) iframe.className = textarea.attr('class'); if(textarea.attr('id')) iframe.id = textarea.attr('id'); if(textarea.attr('name')) iframe.title = textarea.attr('name'); textarea.after(iframe); var css = ""; if(css_url) var css = "<link type='text/css' rel='stylesheet' href='"+css_url+"' />" var content = textarea.val(); // Mozilla need this to display caret if($.trim(content)=='') content = '<br>'; var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>"; tryEnableDesignMode(iframe, doc, function() { $("#toolbar-"+iframe.title).remove(); $(iframe).before(toolbar(iframe)); textarea.remove(); }); } function disableDesignMode(iframe, submit) { var content = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML; if(submit==true) var textarea = $('<input type="hidden" />'); else var textarea = $('<textarea cols="40" rows="10"></textarea>'); textarea.val(content); t = textarea.get(0); if(iframe.className) t.className = iframe.className; if(iframe.id) t.id = iframe.id; if(iframe.title) t.name = iframe.title; $(iframe).before(textarea); if(submit!=true) $(iframe).remove(); return textarea; } function toolbar(iframe) { var tb = $("<div class='rte-toolbar' id='toolbar-"+iframe.title+"'><div>\ <p>\ <select>\ <option value=''>Bloc style</option>\ <option value='p'>Paragraph</option>\ <option value='h3'>Title</option>\ </select>\ <a href='#' class='bold'><img src='"+media_url+"bold.gif' alt='bold' /></a>\ <a href='#' class='italic'><img src='"+media_url+"italic.gif' alt='italic' /></a>\ <a href='#' class='unorderedlist'><img src='"+media_url+"unordered.gif' alt='unordered list' /></a>\ <a href='#' class='link'><img src='"+media_url+"link.png' alt='link' /></a>\ <a href='#' class='image'><img src='"+media_url+"image.png' alt='image' /></a>\ <a href='#' class='disable'><img src='"+media_url+"close.gif' alt='close rte' /></a>\ </p></div></div>"); $('select', tb).change(function(){ var index = this.selectedIndex; if( index!=0 ) { var selected = this.options[index].value; formatText(iframe, "formatblock", '<'+selected+'>'); } }); $('.bold', tb).click(function(){ formatText(iframe, 'bold');return false; }); $('.italic', tb).click(function(){ formatText(iframe, 'italic');return false; }); $('.unorderedlist', tb).click(function(){ formatText(iframe, 'insertunorderedlist');return false; }); $('.link', tb).click(function(){ var p=prompt("URL:"); if(p) formatText(iframe, 'CreateLink', p); return false; }); $('.image', tb).click(function(){ var p=prompt("image URL:"); if(p) formatText(iframe, 'InsertImage', p); return false; }); $('.disable', tb).click(function() { var txt = disableDesignMode(iframe); var edm = $('<a href="#">Enable design mode</a>'); tb.empty().append(edm); edm.click(function(){ enableDesignMode(txt); return false; }); return false; }); $(iframe).parents('form').submit(function(){ disableDesignMode(iframe, true); }); var iframeDoc = $(iframe.contentWindow.document); var select = $('select', tb)[0]; iframeDoc.mouseup(function(){ setSelectedType(getSelectionElement(iframe), select); return true; }); iframeDoc.keyup(function(){ setSelectedType(getSelectionElement(iframe), select); var body = $('body', iframeDoc); if(body.scrollTop()>0) iframe.height = Math.min(350, parseInt(iframe.height)+body.scrollTop()); return true; }); return tb; } function setSelectedType(node, select) { while(node.parentNode) { var nName = node.nodeName.toLowerCase(); for(var i=0;i<select.options.length;i++) { if(nName==select.options[i].value){ select.selectedIndex=i; return true; } } node = node.parentNode; } select.selectedIndex=0; return true; } function getSelectionElement(iframe) { if (iframe.contentWindow.document.selection) { // IE selections selection = iframe.contentWindow.document.selection; range = selection.createRange(); try { node = range.parentElement(); } catch (e) { return false; } } else { // Mozilla selections try { selection = iframe.contentWindow.getSelection(); range = selection.getRangeAt(0); } catch(e){ return false; } node = range.commonAncestorContainer; } return node; } }
JavaScript
tinymce.addI18n('es',{ "Cut": "Cortar", "Header 2": "Header 2 ", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Tu navegador no soporta acceso directo al portapapeles. Por favor usa las teclas Crtl+X\/C\/V de tu teclado", "Div": "Capa", "Paste": "Pegar", "Close": "Cerrar", "Font Family": "Familia de fuentes", "Pre": "Pre", "Align right": "Alinear a la derecha", "New document": "Nuevo documento", "Blockquote": "Bloque de cita", "Numbered list": "Lista numerada", "Increase indent": "Incrementar sangr\u00eda", "Formats": "Formatos", "Headers": "Headers", "Select all": "Seleccionar todo", "Header 3": "Header 3", "Blocks": "Bloques", "Undo": "Deshacer", "Strikethrough": "Tachado", "Bullet list": "Lista de vi\u00f1etas", "Header 1": "Header 1", "Superscript": "Super\u00edndice", "Clear formatting": "Limpiar formato", "Font Sizes": "Tama\u00f1os de fuente", "Subscript": "Sub\u00edndice", "Header 6": "Header 6", "Redo": "Rehacer", "Paragraph": "P\u00e1rrafo", "Ok": "Ok", "Bold": "Negrita", "Code": "C\u00f3digo", "Italic": "It\u00e1lica", "Align center": "Alinear al centro", "Header 5": "Header 5 ", "Decrease indent": "Disminuir sangr\u00eda", "Header 4": "Header 4", "Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Pegar est\u00e1 ahora en modo de texto plano. El contenido se pegar\u00e1 como texto plano hasta que desactive esta opci\u00f3n.", "Underline": "Subrayado", "Cancel": "Cancelar", "Justify": "Justificar", "Inline": "en l\u00ednea", "Copy": "Copiar", "Align left": "Alinear a la izquierda", "Visual aids": "Ayudas visuales", "Lower Greek": "Inferior Griega", "Square": "Cuadrado", "Default": "Por defecto", "Lower Alpha": "Inferior Alfa", "Circle": "C\u00edrculo", "Disc": "Disco", "Upper Alpha": "Superior Alfa", "Upper Roman": "Superior Romana", "Lower Roman": "Inferior Romana", "Name": "Nombre", "Anchor": "Ancla", "You have unsaved changes are you sure you want to navigate away?": "Tiene cambios sin guardar. \u00bfEst\u00e1 seguro de que quiere salir?", "Restore last draft": "Restaurar el \u00faltimo borrador", "Special character": "Car\u00e1cter especial", "Source code": "C\u00f3digo fuente", "Right to left": "De derecha a izquierda", "Left to right": "De izquierda a derecha", "Emoticons": "Emoticonos", "Robots": "Robots", "Document properties": "Propiedades del documento", "Title": "T\u00edtulo", "Keywords": "Palabras clave", "Encoding": "Codificaci\u00f3n", "Description": "Descripci\u00f3n", "Author": "Autor", "Fullscreen": "Pantalla completa", "Horizontal line": "L\u00ednea horizontal", "Horizontal space": "Espacio horizontal", "Insert\/edit image": "Insertar\/editar imagen", "General": "General", "Advanced": "Avanzado", "Source": "Fuente", "Border": "Borde", "Constrain proportions": "Restringir proporciones", "Vertical space": "Espacio vertical", "Image description": "Descripci\u00f3n de la imagen", "Style": "Estilo", "Dimensions": "Dimensiones", "Insert image": "Insertar imagen", "Insert date\/time": "Insertar fecha\/hora", "Remove link": "Quitar enlace", "Url": "Url", "Text to display": "Texto para mostrar", "Anchors": "Anclas", "Insert link": "Insertar enlace", "New window": "Nueva ventana", "None": "Ninguno", "Target": "Destino", "Insert\/edit link": "Insertar\/editar enlace", "Insert\/edit video": "Insertar\/editar video", "Poster": "Miniatura", "Alternative source": "Fuente alternativa", "Paste your embed code below:": "Pega tu c\u00f3digo embebido debajo", "Insert video": "Insertar video", "Embed": "Incrustado", "Nonbreaking space": "Espacio fijo", "Page break": "Salto de p\u00e1gina", "Paste as text": "Pegar como texto", "Preview": "Previsualizar", "Print": "Imprimir", "Save": "Guardar", "Could not find the specified string.": "No se encuentra la cadena de texto especificada", "Replace": "Reemplazar", "Next": "Siguiente", "Whole words": "Palabras completas", "Find and replace": "Buscar y reemplazar", "Replace with": "Reemplazar con", "Find": "Buscar", "Replace all": "Reemplazar todo", "Match case": "Coincidencia exacta", "Prev": "Anterior", "Spellcheck": "Corrector ortogr\u00e1fico", "Finish": "Finalizar", "Ignore all": "Ignorar todos", "Ignore": "Ignorar", "Insert row before": "Insertar fila antes", "Rows": "Filas", "Height": "Alto", "Paste row after": "Pegar la fila despu\u00e9s", "Alignment": "Alineaci\u00f3n", "Column group": "Grupo de columnas", "Row": "Fila", "Insert column before": "Insertar columna antes", "Split cell": "Dividir celdas", "Cell padding": "Relleno de celda", "Cell spacing": "Espacio entre celdas", "Row type": "Tipo de fila", "Insert table": "Insertar tabla", "Body": "Cuerpo", "Caption": "Subt\u00edtulo", "Footer": "Pie de p\u00e1gina", "Delete row": "Eliminar fila", "Paste row before": "Pegar la fila antes", "Scope": "\u00c1mbito", "Delete table": "Eliminar tabla", "Header cell": "Celda de la cebecera", "Column": "Columna", "Cell": "Celda", "Header": "Cabecera", "Cell type": "Tipo de celda", "Copy row": "Copiar fila", "Row properties": "Propiedades de la fila", "Table properties": "Propiedades de la tabla", "Row group": "Grupo de filas", "Right": "Derecha", "Insert column after": "Insertar columna despu\u00e9s", "Cols": "Columnas", "Insert row after": "Insertar fila despu\u00e9s ", "Width": "Ancho", "Cell properties": "Propiedades de la celda", "Left": "Izquierda", "Cut row": "Cortar fila", "Delete column": "Eliminar columna", "Center": "Centrado", "Merge cells": "Combinar celdas", "Insert template": "Insertar plantilla", "Templates": "Plantillas", "Background color": "Color de fondo", "Text color": "Color del texto", "Show blocks": "Mostrar bloques", "Show invisible characters": "Mostrar caracteres invisibles", "Words: {0}": "Palabras: {0}", "Insert": "Insertar", "File": "Archivo", "Edit": "Editar", "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "\u00c1rea de texto enriquecido. Pulse ALT-F9 para el menu. Pulse ALT-F10 para la barra de herramientas. Pulse ALT-0 para ayuda", "Tools": "Herramientas", "View": "Ver", "Table": "Tabla", "Format": "Formato" });
JavaScript
function setSidebarHeight(){ setTimeout(function(){ var height = $(document).height(); $('.grid_12').each(function () { height -= $(this).outerHeight(); }); height -= $('#site_info').outerHeight(); height-=1; //salert(height); $('.sidemenu').css('height', height); },100); } //Dashboard chart function setupDashboardChart(containerElementId) { var s1 = [200, 300, 400, 500, 600, 700, 800, 900, 1000]; var s2 = [190, 290, 390, 490, 590, 690, 790, 890, 990]; var s3 = [250, 350, 450, 550, 650, 750, 850, 950, 1050]; var s4 = [2000, 1600, 1400, 1100, 900, 800, 1550, 1950, 1050]; // Can specify a custom tick Array. // Ticks should match up one for each y value (category) in the series. var ticks = ['March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November']; var plot1 = $.jqplot(containerElementId, [s1, s2, s3, s4], { // The "seriesDefaults" option is an options object that will // be applied to all series in the chart. seriesDefaults: { renderer: $.jqplot.BarRenderer, rendererOptions: { fillToZero: true } }, // Custom labels for the series are specified with the "label" // option on the series option. Here a series option object // is specified for each series. series: [ { label: 'Apples' }, { label: 'Oranges' }, { label: 'Mangoes' }, { label: 'Grapes' } ], // Show the legend and put it outside the grid, but inside the // plot container, shrinking the grid to accomodate the legend. // A value of "outside" would not shrink the grid and allow // the legend to overflow the container. legend: { show: true, placement: 'outsideGrid' }, axes: { // Use a category axis on the x axis and use our custom ticks. xaxis: { renderer: $.jqplot.CategoryAxisRenderer, ticks: ticks }, // Pad the y axis just a little so bars can get close to, but // not touch, the grid boundaries. 1.2 is the default padding. yaxis: { pad: 1.05, tickOptions: { formatString: '$%d' } } } }); } //points charts function drawPointsChart(containerElement) { var cosPoints = []; for (var i = 0; i < 2 * Math.PI; i += 0.4) { cosPoints.push([i, Math.cos(i)]); } var sinPoints = []; for (var i = 0; i < 2 * Math.PI; i += 0.4) { sinPoints.push([i, 2 * Math.sin(i - .8)]); } var powPoints1 = []; for (var i = 0; i < 2 * Math.PI; i += 0.4) { powPoints1.push([i, 2.5 + Math.pow(i / 4, 2)]); } var powPoints2 = []; for (var i = 0; i < 2 * Math.PI; i += 0.4) { powPoints2.push([i, -2.5 - Math.pow(i / 4, 2)]); } var plot3 = $.jqplot(containerElement, [cosPoints, sinPoints, powPoints1, powPoints2], { title: 'Line Style Options', // Series options are specified as an array of objects, one object // for each series. series: [ { // Change our line width and use a diamond shaped marker. lineWidth: 2, markerOptions: { style: 'dimaond' } }, { // Don't show a line, just show markers. // Make the markers 7 pixels with an 'x' style showLine: false, markerOptions: { size: 7, style: "x" } }, { // Use (open) circlular markers. markerOptions: { style: "circle" } }, { // Use a thicker, 5 pixel line and 10 pixel // filled square markers. lineWidth: 5, markerOptions: { style: "filledSquare", size: 10 } } ] } ); } //draw pie chart function drawPieChart(containerElement) { var data = [ ['Heavy Industry', 12], ['Retail', 9], ['Light Industry', 14], ['Out of home', 16], ['Commuting', 7], ['Orientation', 9] ]; var plot1 = jQuery.jqplot('chart1', [data], { seriesDefaults: { // Make this a pie chart. renderer: jQuery.jqplot.PieRenderer, rendererOptions: { // Put data labels on the pie slices. // By default, labels show the percentage of the slice. showDataLabels: true } }, legend: { show: true, location: 'e' } } ); } //draw donut chart function drawDonutChart(containerElement) { var s1 = [['a', 6], ['b', 8], ['c', 14], ['d', 20]]; var s2 = [['a', 8], ['b', 12], ['c', 6], ['d', 9]]; var plot3 = $.jqplot(containerElement, [s1, s2], { seriesDefaults: { // make this a donut chart. renderer: $.jqplot.DonutRenderer, rendererOptions: { // Donut's can be cut into slices like pies. sliceMargin: 3, // Pies and donuts can start at any arbitrary angle. startAngle: -90, showDataLabels: true, // By default, data labels show the percentage of the donut/pie. // You can show the data 'value' or data 'label' instead. dataLabels: 'value' } } }); } //draw bar chart function drawBarchart(containerElement) { var s1 = [200, 600, 700, 1000]; var s2 = [460, -210, 690, 820]; var s3 = [-260, -440, 320, 200]; // Can specify a custom tick Array. // Ticks should match up one for each y value (category) in the series. var ticks = ['May', 'June', 'July', 'August']; var plot1 = $.jqplot(containerElement, [s1, s2, s3], { // The "seriesDefaults" option is an options object that will // be applied to all series in the chart. seriesDefaults: { renderer: $.jqplot.BarRenderer, rendererOptions: { fillToZero: true } }, // Custom labels for the series are specified with the "label" // option on the series option. Here a series option object // is specified for each series. series: [ { label: 'Hotel' }, { label: 'Event Regristration' }, { label: 'Airfare' } ], // Show the legend and put it outside the grid, but inside the // plot container, shrinking the grid to accomodate the legend. // A value of "outside" would not shrink the grid and allow // the legend to overflow the container. legend: { show: true, placement: 'outsideGrid' }, axes: { // Use a category axis on the x axis and use our custom ticks. xaxis: { renderer: $.jqplot.CategoryAxisRenderer, ticks: ticks }, // Pad the y axis just a little so bars can get close to, but // not touch, the grid boundaries. 1.2 is the default padding. yaxis: { pad: 1.05, tickOptions: { formatString: '$%d' } } } }); } //draw bubble chart function drawBubbleChart(containerElement) { var arr = [[11, 123, 1236, ""], [45, 92, 1067, ""], [24, 104, 1176, ""], [50, 23, 610, "A"], [18, 17, 539, ""], [7, 89, 864, ""], [2, 13, 1026, ""]]; var plot1b = $.jqplot(containerElement, [arr], { seriesDefaults: { renderer: $.jqplot.BubbleRenderer, rendererOptions: { bubbleAlpha: 0.6, highlightAlpha: 0.8, showLabels: false }, shadow: true, shadowAlpha: 0.05 } }); // Legend is a simple table in the html. // Dynamically populate it with the labels from each data value. $.each(arr, function (index, val) { $('#' + containerElement).append('<tr><td>' + val[3] + '</td><td>' + val[2] + '</td></tr>'); }); // Now bind function to the highlight event to show the tooltip // and highlight the row in the legend. $('#' + containerElement).bind('jqplotDataHighlight', function (ev, seriesIndex, pointIndex, data, radius) { var chart_left = $('#' + containerElement).offset().left, chart_top = $('#' + containerElement).offset().top, x = plot1b.axes.xaxis.u2p(data[0]), // convert x axis unita to pixels y = plot1b.axes.yaxis.u2p(data[1]); // convert y axis units to pixels var color = 'rgb(50%,50%,100%)'; $('#tooltip1b').css({ left: chart_left + x + radius + 5, top: chart_top + y }); $('#tooltip1b').html('<span style="font-size:14px;font-weight:bold;color:' + color + ';">' + data[3] + '</span><br />' + 'x: ' + data[0] + '<br />' + 'y: ' + data[1] + '<br />' + 'r: ' + data[2]); $('#tooltip1b').show(); $('#legend1b tr').css('background-color', '#ffffff'); $('#legend1b tr').eq(pointIndex + 1).css('background-color', color); }); // Bind a function to the unhighlight event to clean up after highlighting. $('#' + containerElement).bind('jqplotDataUnhighlight', function (ev, seriesIndex, pointIndex, data) { $('#tooltip1b').empty(); $('#tooltip1b').hide(); $('#' + containerElement + ' tr').css('background-color', '#ffffff'); }); } //-------------------------------------------------------------- */ // Gallery Actions //-------------------------------------------------------------- */ function initializeGallery() { // When hovering over gallery li element $("ul.gallery li").hover(function () { var $image = (this); // Shows actions when hovering $(this).find(".actions").show(); // If the "x" icon is pressed, show confirmation (#dialog-confirm) $(this).find(".actions .delete").click(function () { // Confirmation $("#dialog-confirm").dialog({ resizable: false, modal: true, minHeight: 0, draggable: false, buttons: { "Delete": function () { $(this).dialog("close"); // Removes image if delete is pressed $($image).fadeOut('slow', function () { $($image).remove(); }); }, // Removes dialog if cancel is pressed Cancel: function () { $(this).dialog("close"); } } }); return false; }); // Changes opacity of the image $(this).find("img").css("opacity", "0.5"); // On hover off $(this).hover(function () { }, function () { // Hides actions when hovering off $(this).find(".actions").hide(); // Changes opacity of the image back to normal $(this).find("img").css("opacity", "1"); }); }); } function setupGallery() { initializeGallery(); //-------------------------------------------------------------- */ // // **** Gallery Sorting (Quicksand) **** // // For more information go to: // http://razorjack.net/quicksand/ // //-------------------------------------------------------------- */ $('ul.gallery').each(function () { // get the action filter option item on page load var $fileringType = $("ul.sorting li.active a[data-type]").first().before(this); var $filterType = $($fileringType).attr('data-id'); var $gallerySorting = $(this).parent().prev().children('ul.sorting'); // get and assign the ourHolder element to the // $holder varible for use later var $holder = $(this); // clone all items within the pre-assigned $holder element var $data = $holder.clone(); // attempt to call Quicksand when a filter option // item is clicked $($gallerySorting).find("a[data-type]").click(function (e) { // reset the active class on all the buttons $($gallerySorting).find("a[data-type].active").removeClass('active'); // assign the class of the clicked filter option // element to our $filterType variable var $filterType = $(this).attr('data-type'); $(this).addClass('active'); if ($filterType == 'all') { // assign all li items to the $filteredData var when // the 'All' filter option is clicked var $filteredData = $data.find('li'); } else { // find all li elements that have our required $filterType // values for the data-type element var $filteredData = $data.find('li[data-type=' + $filterType + ']'); } // call quicksand and assign transition parameters $holder.quicksand($filteredData, { duration: 800, easing: 'easeInOutQuad', useScaling: true, adjustHeight: 'auto' }, function () { $('.popup').facebox(); initializeGallery(); }); return false; }); }); } //setup pretty-photo function setupPrettyPhoto() { $("a[rel^='prettyPhoto']").prettyPhoto(); } //setup tinyMCE function setupTinyMCE() { $('textarea.tinymce').tinymce({ // Location of TinyMCE script script_url: 'js/tiny-mce/tiny_mce.js', // General options theme: "advanced", plugins: "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist", // Theme options theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_resizing: true, // Example content CSS (should be your site CSS) content_css: "css/content.css", // Drop lists for link/image/media/template dialogs template_external_list_url: "lists/template_list.js", external_link_list_url: "lists/link_list.js", external_image_list_url: "lists/image_list.js", media_external_list_url: "lists/media_list.js", // Replace values for the template plugin template_replace_values: { username: "Some User", staffid: "991234" } }); } //setup DatePicker function setDatePicker(containerElement) { var datePicker = $('#' + containerElement); datePicker.datepicker({ showOn: "button", buttonImage: "img/calendar.gif", buttonImageOnly: true }); } //setup progressbar function setupProgressbar(containerElement) { $("#" + containerElement).progressbar({ value: 59 }); } //setup dialog box function setupDialogBox(containerElement, associatedButton) { $.fx.speeds._default = 1000; $("#" + containerElement).dialog({ autoOpen: false, show: "blind", hide: "explode" }); $("#" + associatedButton).click(function () { $("#" + containerElement).dialog("open"); return false; }); } //setup accordion function setupAccordion(containerElement) { $("#" + containerElement).accordion(); } //setup radios and checkboxes //function setupGrumbleToolTip(elementid) { // initializeGrumble(elementid); // $('#' + elementid).focus(function () { // initializeGrumble(elementid); // }); //} //function initializeGrumble(elementid) { // $('#' + elementid).grumble( // { // text: 'Whoaaa, this is a lot of text that i couldn\'t predict', // angle: 85, // distance: 50, // showAfter: 1000, // hideAfter: 2000 // } //); //} //setup left menu function setupLeftMenu() { $("#section-menu") .accordion({ "header": "a.menuitem" }) .bind("accordionchangestart", function (e, data) { data.newHeader.next().andSelf().addClass("current"); data.oldHeader.next().andSelf().removeClass("current"); }) .find("a.menuitem:first").addClass("current") .next().addClass("current"); $('#section-menu .submenu').css('height','auto'); }
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgb(48, 96, 48)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { backgroundColor: { linearGradient: [0, 0, 0, 20], stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, borderColor: '#000000', symbolStroke: '#C0C0C0', hoverSymbolStroke: '#FFFFFF' } }, exporting: { buttons: { exportButton: { symbolFill: '#55BE3B' }, printButton: { symbolFill: '#7797BE' } } }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgb(48, 48, 96)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { backgroundColor: { linearGradient: [0, 0, 0, 20], stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, borderColor: '#000000', symbolStroke: '#C0C0C0', hoverSymbolStroke: '#FFFFFF' } }, exporting: { buttons: { exportButton: { symbolFill: '#55BE3B' }, printButton: { symbolFill: '#7797BE' } } }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Grid theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], chart: { backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] } , borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineWidth: 1, lineColor: '#000', tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { minorTickInterval: 'auto', lineColor: '#000', lineWidth: 1, tickWidth: 1, tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle: { color: '#039' }, itemHiddenStyle: { color: 'gray' } }, labels: { style: { color: '#99b' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Gray theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#7798BF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 0, 400], stops: [ [0, 'rgb(96, 96, 96)'], [1, 'rgb(16, 16, 16)'] ] }, borderWidth: 0, borderRadius: 15, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { style: { color: '#FFF', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#DDD', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#999', tickColor: '#999', labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: null, minorTickInterval: null, gridLineColor: 'rgba(255, 255, 255, .1)', lineWidth: 0, tickWidth: 0, labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#333' } }, labels: { style: { color: '#CCC' } }, tooltip: { backgroundColor: { linearGradient: [0, 0, 0, 50], stops: [ [0, 'rgba(96, 96, 96, .8)'], [1, 'rgba(16, 16, 16, .8)'] ] }, borderWidth: 0, style: { color: '#FFF' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } } }, toolbar: { itemStyle: { color: '#CCC' } }, navigation: { buttonOptions: { backgroundColor: { linearGradient: [0, 0, 0, 20], stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, borderColor: '#000000', symbolStroke: '#C0C0C0', hoverSymbolStroke: '#FFFFFF' } }, exporting: { buttons: { exportButton: { symbolFill: '#55BE3B' }, printButton: { symbolFill: '#7797BE' } } }, // special colors for some of the demo examples legendBackgroundColor: 'rgba(48, 48, 48, 0.8)', legendBackgroundColorSolid: 'rgb(70, 70, 70)', dataLabelsColor: '#444', textColor: '#E0E0E0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; if (!JSON) { JSON = {}; } (function () { "use strict"; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
JavaScript
// main function to process the fade request // function colorFade(id,element,start,end,steps,speed) { var startrgb,endrgb,er,eg,eb,step,rint,gint,bint,step; var target = document.getElementById(id); steps = steps || 20; speed = speed || 20; clearInterval(target.timer); endrgb = colorConv(end); er = endrgb[0]; eg = endrgb[1]; eb = endrgb[2]; if(!target.r) { startrgb = colorConv(start); r = startrgb[0]; g = startrgb[1]; b = startrgb[2]; target.r = r; target.g = g; target.b = b; } rint = Math.round(Math.abs(target.r-er)/steps); gint = Math.round(Math.abs(target.g-eg)/steps); bint = Math.round(Math.abs(target.b-eb)/steps); if(rint == 0) { rint = 1 } if(gint == 0) { gint = 1 } if(bint == 0) { bint = 1 } target.step = 1; target.timer = setInterval( function() { animateColor(id,element,steps,er,eg,eb,rint,gint,bint) }, speed); } // incrementally close the gap between the two colors // function animateColor(id,element,steps,er,eg,eb,rint,gint,bint) { var target = document.getElementById(id); var color; if(target.step <= steps) { var r = target.r; var g = target.g; var b = target.b; if(r >= er) { r = r - rint; } else { r = parseInt(r) + parseInt(rint); } if(g >= eg) { g = g - gint; } else { g = parseInt(g) + parseInt(gint); } if(b >= eb) { b = b - bint; } else { b = parseInt(b) + parseInt(bint); } color = 'rgb(' + r + ',' + g + ',' + b + ')'; if(element == 'background') { target.style.backgroundColor = color; } else if(element == 'border') { target.style.borderColor = color; } else { target.style.color = color; } target.r = r; target.g = g; target.b = b; target.step = target.step + 1; } else { clearInterval(target.timer); color = 'rgb(' + er + ',' + eg + ',' + eb + ')'; if(element == 'background') { target.style.backgroundColor = color; } else if(element == 'border') { target.style.borderColor = color; } else { target.style.color = color; } } } // convert the color to rgb from hex // function colorConv(color) { var rgb = [parseInt(color.substring(0,2),16), parseInt(color.substring(2,4),16), parseInt(color.substring(4,6),16)]; return rgb; }
JavaScript
var banner_index=0;//图片下标值 var time; var banner_ico_now_count=0;//活动按钮当前值 var banner_url=""; function imagePlayer(){ if(images[banner_index]!=null) { APpendBannerIco(); } banner_index++; if(banner_index>=images.length)//循环完一次,重新初始化index { banner_index=0; } time= setTimeout("imagePlayer()",15000); } //为banner中背景及选中"按钮"一一对应赋值 function APpendBannerIco() { var temp = images.length; if(banner_ico_now_count >= images.length)//活动按钮循环完一次,清空重复加载 { $("banner_ico").innerHTML=""; } var ul =document.createElement("ul");//加载图片和对应按钮的值 for(var i = 0;i < images.length;i++) { temp--; var li =document.createElement("li"); li.style.width="20px"; li.innerHTML="<img src='/images/imgPlayer_dot.gif' width='12' height='12' style='cursor:pointer;' onmouseover=\"go("+i+");\"/>"; if(i==banner_index) { $("banner").style.background="url("+images[temp].imageUrl+")"; banner_url=images[temp].linkUrl; li.innerHTML="<img src='/images/imgPlayer_active.gif' width='12' height='12' style='cursor:pointer;' onmouseover=\"go("+i+");\"/>"; } ul.appendChild(li); banner_ico_now_count++; $("banner_link").innerHTML=""; $("banner_link").innerHTML="<a href='"+banner_url+"' target='_blank'><div style='width:510px; height:275px;cursor:pointer;'></div></a>"; } var ul_temp = document.createElement("ul");//最初创建顺序为至右往左反向,依次倒序调整。 var ul_count=ul.childNodes.length; var i_temp = ul.childNodes.length; for(var i=0;i< ul_count; i++) { i_temp--; var li_temp =document.createElement("li"); li_temp= ul.childNodes[i_temp]; ul_temp.appendChild(li_temp); } $("banner_ico").appendChild(ul_temp); } //点击按钮进行"跳转"图片操作 function go(index) { clearTimeout(time); banner_index = index; APpendBannerIco(); time= setTimeout("imagePlayer()",15000); } imagePlayer(); function ChangeImg(now_obj,change_img) { now_obj.src="/images/"+change_img; }
JavaScript
function $(str){ return document.getElementById(str); } function CheckAll(obj) { var checkAll = true; var checkList = document.getElementsByTagName("input"); if(obj == 2) { $("cb_All").checked = !$("cb_All").checked; } if(!$("cb_All").checked) checkAll = false; for(var i = 0 ; i < checkList.length ; i++) { if(checkList[i].type == 'checkbox' && checkList[i].id.indexOf("cb_Xoa") >= 0 ) { checkList[i].checked = checkAll; } } }
JavaScript
/** * jquery.slider - Slider ui control in jQuery * * Written by * Egor Khmelev (hmelyoff@gmail.com) * * @author Egor Khmelev * @version 1.1.0-RELEASE ($Id$) * * Dependencies: * * jQuery (http://jquery.com) * jshashtable http://www.timdown.co.uk/jshashtable * jquery.numberformatter (http://code.google.com/p/jquery-numberformatter/) * tmpl (http://ejohn.org/blog/javascript-micro-templating/) * jquery.dependClass - Attach class based on first class in list of current element * draggable - Class allows to make any element draggable **/ /** * jshashtable v2.1 - 21 March 2010 */ var Hashtable = (function () { var FUNCTION = "function"; var arrayRemoveAt = (typeof Array.prototype.splice == FUNCTION) ? function (arr, idx) { arr.splice(idx, 1); } : function (arr, idx) { var itemsAfterDeleted, i, len; if (idx === arr.length - 1) { arr.length = idx; } else { itemsAfterDeleted = arr.slice(idx + 1); arr.length = idx; for (i = 0, len = itemsAfterDeleted.length; i < len; ++i) { arr[idx + i] = itemsAfterDeleted[i]; } } }; function hashObject(obj) { var hashCode; if (typeof obj == "string") { return obj; } else if (typeof obj.hashCode == FUNCTION) { // Check the hashCode method really has returned a string hashCode = obj.hashCode(); return (typeof hashCode == "string") ? hashCode : hashObject(hashCode); } else if (typeof obj.toString == FUNCTION) { return obj.toString(); } else { try { return String(obj); } catch (ex) { // For host objects (such as ActiveObjects in IE) that have no toString() method and throw an error when // passed to String() return Object.prototype.toString.call(obj); } } } function equals_fixedValueHasEquals(fixedValue, variableValue) { return fixedValue.equals(variableValue); } function equals_fixedValueNoEquals(fixedValue, variableValue) { return (typeof variableValue.equals == FUNCTION) ? variableValue.equals(fixedValue) : (fixedValue === variableValue); } function createKeyValCheck(kvStr) { return function (kv) { if (kv === null) { throw new Error("null is not a valid " + kvStr); } else if (typeof kv == "undefined") { throw new Error(kvStr + " must not be undefined"); } }; } var checkKey = createKeyValCheck("key"), checkValue = createKeyValCheck("value"); /*----------------------------------------------------------------------------------------------------------------*/ function Bucket(hash, firstKey, firstValue, equalityFunction) { this[0] = hash; this.entries = []; this.addEntry(firstKey, firstValue); if (equalityFunction !== null) { this.getEqualityFunction = function () { return equalityFunction; }; } } var EXISTENCE = 0, ENTRY = 1, ENTRY_INDEX_AND_VALUE = 2; function createBucketSearcher(mode) { return function (key) { var i = this.entries.length, entry, equals = this.getEqualityFunction(key); while (i--) { entry = this.entries[i]; if (equals(key, entry[0])) { switch (mode) { case EXISTENCE: return true; case ENTRY: return entry; case ENTRY_INDEX_AND_VALUE: return [i, entry[1]]; } } } return false; }; } function createBucketLister(entryProperty) { return function (aggregatedArr) { var startIndex = aggregatedArr.length; for (var i = 0, len = this.entries.length; i < len; ++i) { aggregatedArr[startIndex + i] = this.entries[i][entryProperty]; } }; } Bucket.prototype = { getEqualityFunction: function (searchValue) { return (typeof searchValue.equals == FUNCTION) ? equals_fixedValueHasEquals : equals_fixedValueNoEquals; }, getEntryForKey: createBucketSearcher(ENTRY), getEntryAndIndexForKey: createBucketSearcher(ENTRY_INDEX_AND_VALUE), removeEntryForKey: function (key) { var result = this.getEntryAndIndexForKey(key); if (result) { arrayRemoveAt(this.entries, result[0]); return result[1]; } return null; }, addEntry: function (key, value) { this.entries[this.entries.length] = [key, value]; }, keys: createBucketLister(0), values: createBucketLister(1), getEntries: function (entries) { var startIndex = entries.length; for (var i = 0, len = this.entries.length; i < len; ++i) { // Clone the entry stored in the bucket before adding to array entries[startIndex + i] = this.entries[i].slice(0); } }, containsKey: createBucketSearcher(EXISTENCE), containsValue: function (value) { var i = this.entries.length; while (i--) { if (value === this.entries[i][1]) { return true; } } return false; } }; /*----------------------------------------------------------------------------------------------------------------*/ // Supporting functions for searching hashtable buckets function searchBuckets(buckets, hash) { var i = buckets.length, bucket; while (i--) { bucket = buckets[i]; if (hash === bucket[0]) { return i; } } return null; } function getBucketForHash(bucketsByHash, hash) { var bucket = bucketsByHash[hash]; // Check that this is a genuine bucket and not something inherited from the bucketsByHash's prototype return (bucket && (bucket instanceof Bucket)) ? bucket : null; } /*----------------------------------------------------------------------------------------------------------------*/ function Hashtable(hashingFunctionParam, equalityFunctionParam) { var that = this; var buckets = []; var bucketsByHash = {}; var hashingFunction = (typeof hashingFunctionParam == FUNCTION) ? hashingFunctionParam : hashObject; var equalityFunction = (typeof equalityFunctionParam == FUNCTION) ? equalityFunctionParam : null; this.put = function (key, value) { checkKey(key); checkValue(value); var hash = hashingFunction(key), bucket, bucketEntry, oldValue = null; // Check if a bucket exists for the bucket key bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it already contains this key bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so replace old value and we're done. oldValue = bucketEntry[1]; bucketEntry[1] = value; } else { // The bucket does not contain an entry for this key, so add one bucket.addEntry(key, value); } } else { // No bucket exists for the key, so create one and put our key/value mapping in bucket = new Bucket(hash, key, value, equalityFunction); buckets[buckets.length] = bucket; bucketsByHash[hash] = bucket; } return oldValue; }; this.get = function (key) { checkKey(key); var hash = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it contains this key var bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so return the value. return bucketEntry[1]; } } return null; }; this.containsKey = function (key) { checkKey(key); var bucketKey = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, bucketKey); return bucket ? bucket.containsKey(key) : false; }; this.containsValue = function (value) { checkValue(value); var i = buckets.length; while (i--) { if (buckets[i].containsValue(value)) { return true; } } return false; }; this.clear = function () { buckets.length = 0; bucketsByHash = {}; }; this.isEmpty = function () { return !buckets.length; }; var createBucketAggregator = function (bucketFuncName) { return function () { var aggregated = [], i = buckets.length; while (i--) { buckets[i][bucketFuncName](aggregated); } return aggregated; }; }; this.keys = createBucketAggregator("keys"); this.values = createBucketAggregator("values"); this.entries = createBucketAggregator("getEntries"); this.remove = function (key) { checkKey(key); var hash = hashingFunction(key), bucketIndex, oldValue = null; // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Remove entry from this bucket for this key oldValue = bucket.removeEntryForKey(key); if (oldValue !== null) { // Entry was removed, so check if bucket is empty if (!bucket.entries.length) { // Bucket is empty, so remove it from the bucket collections bucketIndex = searchBuckets(buckets, hash); arrayRemoveAt(buckets, bucketIndex); delete bucketsByHash[hash]; } } } return oldValue; }; this.size = function () { var total = 0, i = buckets.length; while (i--) { total += buckets[i].entries.length; } return total; }; this.each = function (callback) { var entries = that.entries(), i = entries.length, entry; while (i--) { entry = entries[i]; callback(entry[0], entry[1]); } }; this.putAll = function (hashtable, conflictCallback) { var entries = hashtable.entries(); var entry, key, value, thisValue, i = entries.length; var hasConflictCallback = (typeof conflictCallback == FUNCTION); while (i--) { entry = entries[i]; key = entry[0]; value = entry[1]; // Check for a conflict. The default behaviour is to overwrite the value for an existing key if (hasConflictCallback && (thisValue = that.get(key))) { value = conflictCallback(key, thisValue, value); } that.put(key, value); } }; this.clone = function () { var clone = new Hashtable(hashingFunctionParam, equalityFunctionParam); clone.putAll(that); return clone; }; } return Hashtable; })(); /** * jquery.numberformatter - Formatting/Parsing Numbers in jQuery * @version 1.2.3-SNAPSHOT **/ (function (jQuery) { var nfLocales = new Hashtable(); var nfLocalesLikeUS = ['ae', 'au', 'ca', 'cn', 'eg', 'gb', 'hk', 'il', 'in', 'jp', 'sk', 'th', 'tw', 'us']; var nfLocalesLikeDE = ['at', 'br', 'de', 'dk', 'es', 'gr', 'it', 'nl', 'pt', 'tr', 'vn']; var nfLocalesLikeFR = ['cz', 'fi', 'fr', 'ru', 'se', 'pl']; var nfLocalesLikeCH = ['ch']; var nfLocaleFormatting = [ [".", ","], [",", "."], [",", " "], [".", "'"] ]; var nfAllLocales = [nfLocalesLikeUS, nfLocalesLikeDE, nfLocalesLikeFR, nfLocalesLikeCH] function FormatData(dec, group, neg) { this.dec = dec; this.group = group; this.neg = neg; }; function init() { // write the arrays into the hashtable for (var localeGroupIdx = 0; localeGroupIdx < nfAllLocales.length; localeGroupIdx++) { localeGroup = nfAllLocales[localeGroupIdx]; for (var i = 0; i < localeGroup.length; i++) { nfLocales.put(localeGroup[i], localeGroupIdx); } } }; function formatCodes(locale, isFullLocale) { if (nfLocales.size() == 0) init(); // default values var dec = "."; var group = ","; var neg = "-"; if (isFullLocale == false) { // Extract and convert to lower-case any language code from a real 'locale' formatted string, if not use as-is // (To prevent locale format like : "fr_FR", "en_US", "de_DE", "fr_FR", "en-US", "de-DE") if (locale.indexOf('_') != -1) locale = locale.split('_')[1].toLowerCase(); else if (locale.indexOf('-') != -1) locale = locale.split('-')[1].toLowerCase(); } // hashtable lookup to match locale with codes var codesIndex = nfLocales.get(locale); if (codesIndex) { var codes = nfLocaleFormatting[codesIndex]; if (codes) { dec = codes[0]; group = codes[1]; } } return new FormatData(dec, group, neg); }; /* Formatting Methods */ /** * Formats anything containing a number in standard js number notation. * * @param {Object} options The formatting options to use * @param {Boolean} writeBack (true) If the output value should be written back to the subject * @param {Boolean} giveReturnValue (true) If the function should return the output string */ jQuery.fn.formatNumber = function (options, writeBack, giveReturnValue) { return this.each(function () { // enforce defaults if (writeBack == null) writeBack = true; if (giveReturnValue == null) giveReturnValue = true; // get text var text; if (jQuery(this).is(":input")) text = new String(jQuery(this).val()); else text = new String(jQuery(this).text()); // format var returnString = jQuery.formatNumber(text, options); // set formatted string back, only if a success // if (returnString) { if (writeBack) { if (jQuery(this).is(":input")) jQuery(this).val(returnString); else jQuery(this).text(returnString); } if (giveReturnValue) return returnString; // } // return ''; }); }; /** * First parses a string and reformats it with the given options. * * @param {Object} numberString * @param {Object} options */ jQuery.formatNumber = function (numberString, options) { var options = jQuery.extend({}, jQuery.fn.formatNumber.defaults, options); var formatData = formatCodes(options.locale.toLowerCase(), options.isFullLocale); var dec = formatData.dec; var group = formatData.group; var neg = formatData.neg; var validFormat = "0#-,."; // strip all the invalid characters at the beginning and the end // of the format, and we'll stick them back on at the end // make a special case for the negative sign "-" though, so // we can have formats like -$23.32 var prefix = ""; var negativeInFront = false; for (var i = 0; i < options.format.length; i++) { if (validFormat.indexOf(options.format.charAt(i)) == -1) prefix = prefix + options.format.charAt(i); else if (i == 0 && options.format.charAt(i) == '-') { negativeInFront = true; continue; } else break; } var suffix = ""; for (var i = options.format.length - 1; i >= 0; i--) { if (validFormat.indexOf(options.format.charAt(i)) == -1) suffix = options.format.charAt(i) + suffix; else break; } options.format = options.format.substring(prefix.length); options.format = options.format.substring(0, options.format.length - suffix.length); // now we need to convert it into a number //while (numberString.indexOf(group) > -1) // numberString = numberString.replace(group, ''); //var number = new Number(numberString.replace(dec, ".").replace(neg, "-")); var number = new Number(numberString); return jQuery._formatNumber(number, options, suffix, prefix, negativeInFront); }; /** * Formats a Number object into a string, using the given formatting options * * @param {Object} numberString * @param {Object} options */ jQuery._formatNumber = function (number, options, suffix, prefix, negativeInFront) { var options = jQuery.extend({}, jQuery.fn.formatNumber.defaults, options); var formatData = formatCodes(options.locale.toLowerCase(), options.isFullLocale); var dec = formatData.dec; var group = formatData.group; var neg = formatData.neg; var forcedToZero = false; if (isNaN(number)) { if (options.nanForceZero == true) { number = 0; forcedToZero = true; } else return null; } // special case for percentages if (suffix == "%") number = number * 100; var returnString = ""; if (options.format.indexOf(".") > -1) { var decimalPortion = dec; var decimalFormat = options.format.substring(options.format.lastIndexOf(".") + 1); // round or truncate number as needed if (options.round == true) number = new Number(number.toFixed(decimalFormat.length)); else { var numStr = number.toString(); numStr = numStr.substring(0, numStr.lastIndexOf('.') + decimalFormat.length + 1); number = new Number(numStr); } var decimalValue = number % 1; var decimalString = new String(decimalValue.toFixed(decimalFormat.length)); decimalString = decimalString.substring(decimalString.lastIndexOf(".") + 1); for (var i = 0; i < decimalFormat.length; i++) { if (decimalFormat.charAt(i) == '#' && decimalString.charAt(i) != '0') { decimalPortion += decimalString.charAt(i); continue; } else if (decimalFormat.charAt(i) == '#' && decimalString.charAt(i) == '0') { var notParsed = decimalString.substring(i); if (notParsed.match('[1-9]')) { decimalPortion += decimalString.charAt(i); continue; } else break; } else if (decimalFormat.charAt(i) == "0") decimalPortion += decimalString.charAt(i); } returnString += decimalPortion } else number = Math.round(number); var ones = Math.floor(number); if (number < 0) ones = Math.ceil(number); var onesFormat = ""; if (options.format.indexOf(".") == -1) onesFormat = options.format; else onesFormat = options.format.substring(0, options.format.indexOf(".")); var onePortion = ""; if (!(ones == 0 && onesFormat.substr(onesFormat.length - 1) == '#') || forcedToZero) { // find how many digits are in the group var oneText = new String(Math.abs(ones)); var groupLength = 9999; if (onesFormat.lastIndexOf(",") != -1) groupLength = onesFormat.length - onesFormat.lastIndexOf(",") - 1; var groupCount = 0; for (var i = oneText.length - 1; i > -1; i--) { onePortion = oneText.charAt(i) + onePortion; groupCount++; if (groupCount == groupLength && i != 0) { onePortion = group + onePortion; groupCount = 0; } } // account for any pre-data padding if (onesFormat.length > onePortion.length) { var padStart = onesFormat.indexOf('0'); if (padStart != -1) { var padLen = onesFormat.length - padStart; // pad to left with 0's or group char var pos = onesFormat.length - onePortion.length - 1; while (onePortion.length < padLen) { var padChar = onesFormat.charAt(pos); // replace with real group char if needed if (padChar == ',') padChar = group; onePortion = padChar + onePortion; pos--; } } } } if (!onePortion && onesFormat.indexOf('0', onesFormat.length - 1) !== -1) onePortion = '0'; returnString = onePortion + returnString; // handle special case where negative is in front of the invalid characters if (number < 0 && negativeInFront && prefix.length > 0) prefix = neg + prefix; else if (number < 0) returnString = neg + returnString; if (!options.decimalSeparatorAlwaysShown) { if (returnString.lastIndexOf(dec) == returnString.length - 1) { returnString = returnString.substring(0, returnString.length - 1); } } returnString = prefix + returnString + suffix; return returnString; }; /* Parsing Methods */ /** * Parses a number of given format from the element and returns a Number object. * @param {Object} options */ jQuery.fn.parseNumber = function (options, writeBack, giveReturnValue) { // enforce defaults if (writeBack == null) writeBack = true; if (giveReturnValue == null) giveReturnValue = true; // get text var text; if (jQuery(this).is(":input")) text = new String(jQuery(this).val()); else text = new String(jQuery(this).text()); // parse text var number = jQuery.parseNumber(text, options); if (number) { if (writeBack) { if (jQuery(this).is(":input")) jQuery(this).val(number.toString()); else jQuery(this).text(number.toString()); } if (giveReturnValue) return number; } }; /** * Parses a string of given format into a Number object. * * @param {Object} string * @param {Object} options */ jQuery.parseNumber = function (numberString, options) { var options = jQuery.extend({}, jQuery.fn.parseNumber.defaults, options); var formatData = formatCodes(options.locale.toLowerCase(), options.isFullLocale); var dec = formatData.dec; var group = formatData.group; var neg = formatData.neg; var valid = "1234567890.-"; // now we need to convert it into a number while (numberString.indexOf(group) > -1) numberString = numberString.replace(group, ''); numberString = numberString.replace(dec, ".").replace(neg, "-"); var validText = ""; var hasPercent = false; if (numberString.charAt(numberString.length - 1) == "%" || options.isPercentage == true) hasPercent = true; for (var i = 0; i < numberString.length; i++) { if (valid.indexOf(numberString.charAt(i)) > -1) validText = validText + numberString.charAt(i); } var number = new Number(validText); if (hasPercent) { number = number / 100; var decimalPos = validText.indexOf('.'); if (decimalPos != -1) { var decimalPoints = validText.length - decimalPos - 1; number = number.toFixed(decimalPoints + 2); } else { number = number.toFixed(validText.length - 1); } } return number; }; jQuery.fn.parseNumber.defaults = { locale: "us", decimalSeparatorAlwaysShown: false, isPercentage: false, isFullLocale: false }; jQuery.fn.formatNumber.defaults = { format: "#,###.00", locale: "us", decimalSeparatorAlwaysShown: false, nanForceZero: true, round: true, isFullLocale: false }; Number.prototype.toFixed = function (precision) { return jQuery._roundNumber(this, precision); }; jQuery._roundNumber = function (number, decimalPlaces) { var power = Math.pow(10, decimalPlaces || 0); var value = String(Math.round(number * power) / power); // ensure the decimal places are there if (decimalPlaces > 0) { var dp = value.indexOf("."); if (dp == -1) { value += '.'; dp = 0; } else { dp = value.length - (dp + 1); } while (dp < decimalPlaces) { value += '0'; dp++; } } return value; }; })(jQuery); /** * tmpl - Simple JavaScript Templating **/ (function () { var cache = {}; this.tmpl = function tmpl(str, data) { // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn(data) : fn; }; })(); /** * draggable **/ (function ($) { function Draggable() { this._init.apply(this, arguments); }; Draggable.prototype.oninit = function () { }; Draggable.prototype.events = function () { }; Draggable.prototype.onmousedown = function () { this.ptr.css({ position: "absolute" }); }; Draggable.prototype.onmousemove = function (evt, x, y) { this.ptr.css({ left: x, top: y }); }; Draggable.prototype.onmouseup = function () { }; Draggable.prototype.isDefault = { drag: false, clicked: false, toclick: true, mouseup: false }; Draggable.prototype._init = function () { if (arguments.length > 0) { this.ptr = $(arguments[0]); this.outer = $(".draggable-outer"); this.is = {}; $.extend(this.is, this.isDefault); var _offset = this.ptr.offset(); this.d = { left: _offset.left, top: _offset.top, width: this.ptr.width(), height: this.ptr.height() }; this.oninit.apply(this, arguments); this._events(); } }; Draggable.prototype._getPageCoords = function (event) { if (event.targetTouches && event.targetTouches[0]) { return { x: event.targetTouches[0].pageX, y: event.targetTouches[0].pageY }; } else return { x: event.pageX, y: event.pageY }; }; Draggable.prototype._bindEvent = function (ptr, eventType, handler) { var self = this; if (this.supportTouches_) ptr.get(0).addEventListener(this.events_[eventType], handler, false); else ptr.bind(this.events_[eventType], handler); }; Draggable.prototype._events = function () { var self = this; this.supportTouches_ = 'ontouchend' in document; this.events_ = { "click": this.supportTouches_ ? "touchstart" : "click", "down": this.supportTouches_ ? "touchstart" : "mousedown", "move": this.supportTouches_ ? "touchmove" : "mousemove", "up": this.supportTouches_ ? "touchend" : "mouseup" }; this._bindEvent($(document), "move", function (event) { if (self.is.drag) { event.stopPropagation(); event.preventDefault(); self._mousemove(event); } }); this._bindEvent($(document), "down", function (event) { if (self.is.drag) { event.stopPropagation(); event.preventDefault(); } }); this._bindEvent($(document), "up", function (event) { self._mouseup(event); }); this._bindEvent(this.ptr, "down", function (event) { self._mousedown(event); return false; }); this._bindEvent(this.ptr, "up", function (event) { self._mouseup(event); }); this.ptr.find("a") .click(function () { self.is.clicked = true; if (!self.is.toclick) { self.is.toclick = true; return false; } }) .mousedown(function (event) { self._mousedown(event); return false; }); this.events(); }; Draggable.prototype._mousedown = function (evt) { this.is.drag = true; this.is.clicked = false; this.is.mouseup = false; var _offset = this.ptr.offset(); var coords = this._getPageCoords(evt); this.cx = coords.x - _offset.left; this.cy = coords.y - _offset.top; $.extend(this.d, { left: _offset.left, top: _offset.top, width: this.ptr.width(), height: this.ptr.height() }); if (this.outer && this.outer.get(0)) { this.outer.css({ height: Math.max(this.outer.height(), $(document.body).height()), overflow: "hidden" }); } this.onmousedown(evt); }; Draggable.prototype._mousemove = function (evt) { this.is.toclick = false; var coords = this._getPageCoords(evt); this.onmousemove(evt, coords.x - this.cx, coords.y - this.cy); }; Draggable.prototype._mouseup = function (evt) { var oThis = this; if (this.is.drag) { this.is.drag = false; if (this.outer && this.outer.get(0)) { if ($.browser.mozilla) { this.outer.css({ overflow: "hidden" }); } else { this.outer.css({ overflow: "visible" }); } if ($.browser.msie && $.browser.version == '6.0') { this.outer.css({ height: "100%" }); } else { this.outer.css({ height: "auto" }); } } this.onmouseup(evt); } }; window.Draggable = Draggable; })(jQuery); /** * jquery.dependClass **/ (function ($) { $.baseClass = function (obj) { obj = $(obj); return obj.get(0).className.match(/([^ ]+)/)[1]; }; $.fn.addDependClass = function (className, delimiter) { var options = { delimiter: delimiter ? delimiter : '-' } return this.each(function () { var baseClass = $.baseClass(this); if (baseClass) $(this).addClass(baseClass + options.delimiter + className); }); }; $.fn.removeDependClass = function (className, delimiter) { var options = { delimiter: delimiter ? delimiter : '-' } return this.each(function () { var baseClass = $.baseClass(this); if (baseClass) $(this).removeClass(baseClass + options.delimiter + className); }); }; $.fn.toggleDependClass = function (className, delimiter) { var options = { delimiter: delimiter ? delimiter : '-' } return this.each(function () { var baseClass = $.baseClass(this); if (baseClass) if ($(this).is("." + baseClass + options.delimiter + className)) $(this).removeClass(baseClass + options.delimiter + className); else $(this).addClass(baseClass + options.delimiter + className); }); }; })(jQuery); /** * jslider **/ (function ($) { function isArray(value) { if (typeof value == "undefined") return false; if (value instanceof Array || (!(value instanceof Object) && (Object.prototype.toString.call((value)) == '[object Array]') || typeof value.length == 'number' && typeof value.splice != 'undefined' && typeof value.propertyIsEnumerable != 'undefined' && !value.propertyIsEnumerable('splice'))) { return true; } return false; } $.slider = function (node, settings) { var jNode = $(node); if (!jNode.data("jslider")) jNode.data("jslider", new jSlider(node, settings)); return jNode.data("jslider"); }; $.fn.slider = function (action, opt_value) { var returnValue, args = arguments; function isDef(val) { return val !== undefined; }; function isDefAndNotNull(val) { return val != null; }; this.each(function () { var self = $.slider(this, action); // do actions if (typeof action == "string") { switch (action) { case "value": if (isDef(args[1]) && isDef(args[2])) { var pointers = self.getPointers(); if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) { pointers[0].set(args[1]); pointers[0].setIndexOver(); } if (isDefAndNotNull(pointers[1]) && isDefAndNotNull(args[2])) { pointers[1].set(args[2]); pointers[1].setIndexOver(); } } else if (isDef(args[1])) { var pointers = self.getPointers(); if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) { pointers[0].set(args[1]); pointers[0].setIndexOver(); } } else returnValue = self.getValue(); break; case "prc": if (isDef(args[1]) && isDef(args[2])) { var pointers = self.getPointers(); if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) { pointers[0]._set(args[1]); pointers[0].setIndexOver(); } if (isDefAndNotNull(pointers[1]) && isDefAndNotNull(args[2])) { pointers[1]._set(args[2]); pointers[1].setIndexOver(); } } else if (isDef(args[1])) { var pointers = self.getPointers(); if (isDefAndNotNull(pointers[0]) && isDefAndNotNull(args[1])) { pointers[0]._set(args[1]); pointers[0].setIndexOver(); } } else returnValue = self.getPrcValue(); break; case "calculatedValue": var value = self.getValue().split(";"); returnValue = ""; for (var i = 0; i < value.length; i++) { returnValue += (i > 0 ? ";" : "") + self.nice(value[i]); }; break; case "skin": self.setSkin(args[1]); break; }; } // return actual object else if (!action && !opt_value) { if (!isArray(returnValue)) returnValue = []; returnValue.push(self); } }); // flatten array just with one slider if (isArray(returnValue) && returnValue.length == 1) returnValue = returnValue[0]; return returnValue || this; }; var OPTIONS = { settings: { from: 1, to: 10, step: 1, smooth: true, limits: true, round: 0, format: { format: "#,##0.##" }, value: "5;7", dimension: "" }, className: "jslider", selector: ".jslider-", template: tmpl( '<span class="<%=className%>">' + '<table><tr><td>' + '<div class="<%=className%>-bg">' + '<i class="l"></i><i class="f"></i><i class="r"></i>' + '<i class="v"></i>' + '</div>' + '<div class="<%=className%>-pointer"></div>' + '<div class="<%=className%>-pointer <%=className%>-pointer-to"></div>' + '<div class="<%=className%>-label"><span><%=settings.from%></span></div>' + '<div class="<%=className%>-label <%=className%>-label-to"><%=settings.dimension%><span><%=settings.to%></span></div>' + '<div class="<%=className%>-value"><%=settings.dimension%><span></span></div>' + '<div class="<%=className%>-value <%=className%>-value-to"><%=settings.dimension%><span></span></div>' + '<div class="<%=className%>-scale"><%=scale%></div>' + '</td></tr></table>' + '</span>') }; function jSlider() { return this.init.apply(this, arguments); }; jSlider.prototype.init = function (node, settings) { this.settings = $.extend(true, {}, OPTIONS.settings, settings ? settings : {}); // obj.sliderHandler = this; this.inputNode = $(node).hide(); this.settings.interval = this.settings.to - this.settings.from; this.settings.value = this.inputNode.attr("value"); if (this.settings.calculate && $.isFunction(this.settings.calculate)) this.nice = this.settings.calculate; if (this.settings.onstatechange && $.isFunction(this.settings.onstatechange)) this.onstatechange = this.settings.onstatechange; this.is = { init: false }; this.o = {}; this.create(); }; jSlider.prototype.onstatechange = function () { }; jSlider.prototype.create = function () { var $this = this; this.domNode = $(OPTIONS.template({ className: OPTIONS.className, settings: { from: this.nice(this.settings.from), to: this.nice(this.settings.to), dimension: this.settings.dimension }, scale: this.generateScale() })); this.inputNode.after(this.domNode); this.drawScale(); // set skin class if (this.settings.skin && this.settings.skin.length > 0) this.setSkin(this.settings.skin); this.sizes = { domWidth: this.domNode.width(), domOffset: this.domNode.offset() }; // find some objects $.extend(this.o, { pointers: {}, labels: { 0: { o: this.domNode.find(OPTIONS.selector + "value").not(OPTIONS.selector + "value-to") }, 1: { o: this.domNode.find(OPTIONS.selector + "value").filter(OPTIONS.selector + "value-to") } }, limits: { 0: this.domNode.find(OPTIONS.selector + "label").not(OPTIONS.selector + "label-to"), 1: this.domNode.find(OPTIONS.selector + "label").filter(OPTIONS.selector + "label-to") } }); $.extend(this.o.labels[0], { value: this.o.labels[0].o.find("span") }); $.extend(this.o.labels[1], { value: this.o.labels[1].o.find("span") }); if (!$this.settings.value.split(";")[1]) { this.settings.single = true; this.domNode.addDependClass("single"); } if (!$this.settings.limits) this.domNode.addDependClass("limitless"); this.domNode.find(OPTIONS.selector + "pointer").each(function (i) { var value = $this.settings.value.split(";")[i]; if (value) { $this.o.pointers[i] = new jSliderPointer(this, i, $this); var prev = $this.settings.value.split(";")[i - 1]; if (prev && new Number(value) < new Number(prev)) value = prev; value = value < $this.settings.from ? $this.settings.from : value; value = value > $this.settings.to ? $this.settings.to : value; $this.o.pointers[i].set(value, true); } }); this.o.value = this.domNode.find(".v"); this.is.init = true; $.each(this.o.pointers, function (i) { $this.redraw(this); }); (function (self) { $(window).resize(function () { self.onresize(); }); })(this); }; jSlider.prototype.setSkin = function (skin) { if (this.skin_) this.domNode.removeDependClass(this.skin_, "_"); this.domNode.addDependClass(this.skin_ = skin, "_"); }; jSlider.prototype.setPointersIndex = function (i) { $.each(this.getPointers(), function (i) { this.index(i); }); }; jSlider.prototype.getPointers = function () { return this.o.pointers; }; jSlider.prototype.generateScale = function () { if (this.settings.scale && this.settings.scale.length > 0) { var str = ""; var s = this.settings.scale; var prc = Math.round((100 / (s.length - 1)) * 10) / 10; for (var i = 0; i < s.length; i++) { str += '<span style="left: ' + i * prc + '%">' + (s[i] != '|' ? '<ins>' + s[i] + '</ins>' : '') + '</span>'; }; return str; } else return ""; return ""; }; jSlider.prototype.drawScale = function () { this.domNode.find(OPTIONS.selector + "scale span ins").each(function () { $(this).css({ marginLeft: -$(this).outerWidth() / 2 }); }); }; jSlider.prototype.onresize = function () { var self = this; this.sizes = { domWidth: this.domNode.width(), domOffset: this.domNode.offset() }; $.each(this.o.pointers, function (i) { self.redraw(this); }); }; jSlider.prototype.update = function () { this.onresize(); this.drawScale(); }; jSlider.prototype.limits = function (x, pointer) { // smooth if (!this.settings.smooth) { var step = this.settings.step * 100 / (this.settings.interval); x = Math.round(x / step) * step; } var another = this.o.pointers[1 - pointer.uid]; if (another && pointer.uid && x < another.value.prc) x = another.value.prc; if (another && !pointer.uid && x > another.value.prc) x = another.value.prc; // base limit if (x < 0) x = 0; if (x > 100) x = 100; return Math.round(x * 10) / 10; }; jSlider.prototype.redraw = function (pointer) { if (!this.is.init) return false; this.setValue(); // redraw range line if (this.o.pointers[0] && this.o.pointers[1]) this.o.value.css({ left: this.o.pointers[0].value.prc + "%", width: (this.o.pointers[1].value.prc - this.o.pointers[0].value.prc) + "%" }); this.o.labels[pointer.uid].value.html( this.nice( pointer.value.origin)); // redraw position of labels this.redrawLabels(pointer); }; jSlider.prototype.redrawLabels = function (pointer) { function setPosition(label, sizes, prc) { sizes.margin = -sizes.label / 2; // left limit label_left = sizes.border + sizes.margin; if (label_left < 0) sizes.margin -= label_left; // right limit if (sizes.border + sizes.label / 2 > self.sizes.domWidth) { sizes.margin = 0; sizes.right = true; } else sizes.right = false; label.o.css({ left: prc + "%", marginLeft: sizes.margin, right: "auto" }); if (sizes.right) label.o.css({ left: "auto", right: 0 }); return sizes; } var self = this; var label = this.o.labels[pointer.uid]; var prc = pointer.value.prc; var sizes = { label: label.o.outerWidth(), right: false, border: (prc * this.sizes.domWidth) / 100 }; if (!this.settings.single) { // glue if near; var another = this.o.pointers[1 - pointer.uid]; var another_label = this.o.labels[another.uid]; switch (pointer.uid) { case 0: if (sizes.border + sizes.label / 2 > another_label.o.offset().left - this.sizes.domOffset.left) { another_label.o.css({ visibility: "hidden" }); another_label.value.html(this.nice(another.value.origin)); label.o.css({ visibility: "visible" }); prc = (another.value.prc - prc) / 2 + prc; if (another.value.prc != pointer.value.prc) { label.value.html(this.nice(pointer.value.origin) + "&nbsp;&ndash;&nbsp;" + this.nice(another.value.origin)); sizes.label = label.o.outerWidth(); sizes.border = (prc * this.sizes.domWidth) / 100; } } else { another_label.o.css({ visibility: "visible" }); } break; case 1: if (sizes.border - sizes.label / 2 < another_label.o.offset().left - this.sizes.domOffset.left + another_label.o.outerWidth()) { another_label.o.css({ visibility: "hidden" }); another_label.value.html(this.nice(another.value.origin)); label.o.css({ visibility: "visible" }); prc = (prc - another.value.prc) / 2 + another.value.prc; if (another.value.prc != pointer.value.prc) { label.value.html(this.nice(another.value.origin) + "&nbsp;&ndash;&nbsp;" + this.nice(pointer.value.origin)); sizes.label = label.o.outerWidth(); sizes.border = (prc * this.sizes.domWidth) / 100; } } else { another_label.o.css({ visibility: "visible" }); } break; } } sizes = setPosition(label, sizes, prc); /* draw second label */ if (another_label) { var sizes = { label: another_label.o.outerWidth(), right: false, border: (another.value.prc * this.sizes.domWidth) / 100 }; sizes = setPosition(another_label, sizes, another.value.prc); } this.redrawLimits(); }; jSlider.prototype.redrawLimits = function () { if (this.settings.limits) { var limits = [true, true]; for (key in this.o.pointers) { if (!this.settings.single || key == 0) { var pointer = this.o.pointers[key]; var label = this.o.labels[pointer.uid]; var label_left = label.o.offset().left - this.sizes.domOffset.left; var limit = this.o.limits[0]; if (label_left < limit.outerWidth()) limits[0] = false; var limit = this.o.limits[1]; if (label_left + label.o.outerWidth() > this.sizes.domWidth - limit.outerWidth()) limits[1] = false; } }; for (var i = 0; i < limits.length; i++) { if (limits[i]) this.o.limits[i].fadeIn("fast"); else this.o.limits[i].fadeOut("fast"); }; } }; jSlider.prototype.setValue = function () { var value = this.getValue(); this.inputNode.attr("value", value); this.onstatechange.call(this, value); }; jSlider.prototype.getValue = function () { if (!this.is.init) return false; var $this = this; var value = ""; $.each(this.o.pointers, function (i) { if (this.value.prc != undefined && !isNaN(this.value.prc)) value += (i > 0 ? ";" : "") + $this.prcToValue(this.value.prc); }); return value; }; jSlider.prototype.getPrcValue = function () { if (!this.is.init) return false; var $this = this; var value = ""; $.each(this.o.pointers, function (i) { if (this.value.prc != undefined && !isNaN(this.value.prc)) value += (i > 0 ? ";" : "") + this.value.prc; }); return value; }; jSlider.prototype.prcToValue = function (prc) { if (this.settings.heterogeneity && this.settings.heterogeneity.length > 0) { var h = this.settings.heterogeneity; var _start = 0; var _from = this.settings.from; for (var i = 0; i <= h.length; i++) { if (h[i]) var v = h[i].split("/"); else var v = [100, this.settings.to]; v[0] = new Number(v[0]); v[1] = new Number(v[1]); if (prc >= _start && prc <= v[0]) { var value = _from + ((prc - _start) * (v[1] - _from)) / (v[0] - _start); } _start = v[0]; _from = v[1]; }; } else { var value = this.settings.from + (prc * this.settings.interval) / 100; } return this.round(value); }; jSlider.prototype.valueToPrc = function (value, pointer) { if (this.settings.heterogeneity && this.settings.heterogeneity.length > 0) { var h = this.settings.heterogeneity; var _start = 0; var _from = this.settings.from; for (var i = 0; i <= h.length; i++) { if (h[i]) var v = h[i].split("/"); else var v = [100, this.settings.to]; v[0] = new Number(v[0]); v[1] = new Number(v[1]); if (value >= _from && value <= v[1]) { var prc = pointer.limits(_start + (value - _from) * (v[0] - _start) / (v[1] - _from)); } _start = v[0]; _from = v[1]; }; } else { var prc = pointer.limits((value - this.settings.from) * 100 / this.settings.interval); } return prc; }; jSlider.prototype.round = function (value) { value = Math.round(value / this.settings.step) * this.settings.step; if (this.settings.round) value = Math.round(value * Math.pow(10, this.settings.round)) / Math.pow(10, this.settings.round); else value = Math.round(value); return value; }; jSlider.prototype.nice = function (value) { value = value.toString().replace(/,/gi, ".").replace(/ /gi, "");; if ($.formatNumber) { return $.formatNumber(new Number(value), this.settings.format || {}).replace(/-/gi, "&minus;"); } else { return new Number(value); } }; function jSliderPointer() { Draggable.apply(this, arguments); } jSliderPointer.prototype = new Draggable(); jSliderPointer.prototype.oninit = function (ptr, id, _constructor) { this.uid = id; this.parent = _constructor; this.value = {}; this.settings = this.parent.settings; }; jSliderPointer.prototype.onmousedown = function (evt) { this._parent = { offset: this.parent.domNode.offset(), width: this.parent.domNode.width() }; this.ptr.addDependClass("hover"); this.setIndexOver(); }; jSliderPointer.prototype.onmousemove = function (evt, x) { var coords = this._getPageCoords(evt); this._set(this.calc(coords.x)); }; jSliderPointer.prototype.onmouseup = function (evt) { if (this.parent.settings.callback && $.isFunction(this.parent.settings.callback)) this.parent.settings.callback.call(this.parent, this.parent.getValue()); this.ptr.removeDependClass("hover"); }; jSliderPointer.prototype.setIndexOver = function () { this.parent.setPointersIndex(1); this.index(2); }; jSliderPointer.prototype.index = function (i) { this.ptr.css({ zIndex: i }); }; jSliderPointer.prototype.limits = function (x) { return this.parent.limits(x, this); }; jSliderPointer.prototype.calc = function (coords) { var x = this.limits(((coords - this._parent.offset.left) * 100) / this._parent.width); return x; }; jSliderPointer.prototype.set = function (value, opt_origin) { this.value.origin = this.parent.round(value); this._set(this.parent.valueToPrc(value, this), opt_origin); }; jSliderPointer.prototype._set = function (prc, opt_origin) { if (!opt_origin) this.value.origin = this.parent.prcToValue(prc); this.value.prc = prc; this.ptr.css({ left: prc + "%" }); this.parent.redraw(this); }; })(jQuery);
JavaScript
var $ = jQuery; // Topmenu <ul> replace to <select> function responsive(mainNavigation) { var $ = jQuery; var screenRes = $('.body_wrap').width(); if (screenRes < 700) { //jQuery('ul.dropdown').css('display', 'none'); /* Replace unordered list with a "select" element to be populated with options, and create a variable to select our new empty option menu */ $('#topmenu').html('<select class="select_styled" id="topm-select"></select>'); var selectMenu = $('#topm-select'); /* Navigate our nav clone for information needed to populate options */ $(mainNavigation).children('ul').children('li').each(function () { /* Get top-level link and text */ var href = $(this).children('a').attr('href'); var text = $(this).children('a').text(); /* Append this option to our "select" */ if ($(this).is(".current-menu-item") && href != '#') { $(selectMenu).append('<option value="' + href + '" selected>' + text + '</option>'); } else if (href == '#') { $(selectMenu).append('<option value="' + href + '" disabled="disabled">' + text + '</option>'); } else { $(selectMenu).append('<option value="' + href + '">' + text + '</option>'); } /* Check for "children" and navigate for more options if they exist */ if ($(this).children('ul').length > 0) { $(this).children('ul').children('li').not(".mega-nav-widget").each(function () { /* Get child-level link and text */ var href2 = $(this).children('a').attr('href'); var text2 = $(this).children('a').text(); /* Append this option to our "select" */ if ($(this).is(".current-menu-item") && href2 != '#') { $(selectMenu).append('<option value="'+href2+'" selected> - '+text2+'</option>'); } else if (href2 == '#') { $(selectMenu).append('<option value="'+href2+'" disabled="disabled"># '+text2+'</option>'); } else { $(selectMenu).append('<option value="'+href2+'"> - '+text2+'</option>'); } /* Check for "children" and navigate for more options if they exist */ if ($(this).children('ul').length > 0) { $(this).children('ul').children('li').each(function () { /* Get child-level link and text */ var href3 = $(this).children('a').attr('href'); var text3 = $(this).children('a').text(); /* Append this option to our "select" */ if ($(this).is(".current-menu-item")) { $(selectMenu).append('<option value="' + href3 + '" class="select-current" selected>' + text3 + '</option>'); } else { $(selectMenu).append('<option value="' + href3 + '"> -- ' + text3 + '</option>'); } }); } }); } }); } else { jQuery('#topm-select').css('display', 'none'); jQuery('#menu-menu').css('display', 'inline-block'); } /* When our select menu is changed, change the window location to match the value of the selected option. */ $(selectMenu).change(function () { location = this.options[this.selectedIndex].value; }); } jQuery(document).ready(function($) { // Remove links outline in IE 7 $("a").attr("hideFocus", "true").css("outline", "none"); // Styled MultiSelect (listbox of checkboxes) if ($(".row").hasClass("field_multiselect")) { $(".mutli_select").click (function() { $(".cusel").removeClass("cuselOpen"); $(".cusel-scroll-wrap").hide(); $(this).parent().toggleClass("open"); $(this).children('.mutli_select_box').css({"width": $(this).width()-3}).jScrollPane({ showArrows: true, mouseWheelSpeed: 15 }); }); $('body').click(function() { $(".field_multiselect").removeClass("open"); }); $('.field_multiselect, .field_multiselect .select_row').click(function(event){ event.stopPropagation(); }); } // style Select, Radio, Checkbox if ($("select").hasClass("select_styled")) { var deviceAgent = navigator.userAgent.toLowerCase(); var agentID = deviceAgent.match(/(iphone|ipod|ipad)/); if (agentID) { cuSel({changedEl: ".select_styled", visRows: 8, scrollArrows: true}); // Add arrows Up/Down for iPad/iPhone } else { cuSel({changedEl: ".select_styled", visRows: 8, scrollArrows: true}); } } if ($("div,p").hasClass("input_styled")) { $(".input_styled input").customInput(); } // centering dropdown submenu (not mega-nav) $(".dropdown > li:not(.mega-nav)").hover(function(){ var dropDown = $(this).children("ul"); var dropDownLi = $(this).children().children("li").innerWidth(); var posLeft = ((dropDownLi - $(this).innerWidth())/2); dropDown.css("left",-posLeft); }); // reload topmenu on Resize var mainNavigation = $('#topmenu').clone(); responsive(mainNavigation); $(window).resize(function() { var screenRes = $('.body_wrap').width(); responsive(mainNavigation); }); // responsive megamenu var screenRes = $(window).width(); if (screenRes < 750) { $(".dropdown li.mega-nav").removeClass("mega-nav"); } if (screenRes > 750) { mega_show(); } function mega_show(){ $('.dropdown li').hoverIntent({ sensitivity: 5, interval: 50, over: subm_show, timeout: 0, out: subm_hide }); } function subm_show(){ if ($(this).hasClass("parent")) { $(this).addClass("parentHover"); }; $(this).children("ul.submenu-1").fadeIn(50); } function subm_hide(){ $(this).removeClass("parentHover"); $(this).children("ul.submenu-1").fadeOut(50); } $(".dropdown ul").parent("li").addClass("parent"); $(".dropdown li:first-child, .pricing_box li:first-child, .sidebar .widget-container:first-child, .f_col .widget-container:first-child").addClass("first"); $(".dropdown li:last-child, .pricing_box li:last-child, .widget_twitter .tweet_item:last-child, .sidebar .widget-container:last-child, .f_col .widget-container li:last-child").addClass("last"); $(".dropdown li:only-child").removeClass("last").addClass("only"); $(".sidebar .current-menu-item, .sidebar .current-menu-ancestor").prev().addClass("current-prev"); // tabs if ($("ul").hasClass("tabs")) { $("ul.tabs").tabs("> .tabcontent", {tabs: 'li', effect: 'fade'}); } if ($("ul").is(".tabs.linked")) { $("ul.tabs").tabs("> .tabcontent", {effect: 'fade'}); } // odd/even $("ul.recent_posts > li:odd, ul.popular_posts > li:odd, .styled_table table>tbody>tr:odd, .boxed_list > .boxed_item:odd, .grid_layout .post-item:odd").addClass("odd"); $(".widget_recent_comments ul > li:even, .widget_recent_entries li:even, .widget_twitter .tweet_item:even, .widget_archive ul > li:even, .widget_categories ul > li:even, .widget_nav_menu ul > li:even, .widget_links ul > li:even, .widget_meta ul > li:even, .widget_pages ul > li:even, .offer_specification li:even").addClass("even"); // cols $(".row .col:first-child").addClass("alpha"); $(".row .col:last-child").addClass("omega"); // toggle content $(".toggle_content").hide(); $(".toggle").toggle(function(){ $(this).addClass("active"); }, function () { $(this).removeClass("active"); }); $(".toggle").click(function(){ $(this).next(".toggle_content").slideToggle(300,'easeInQuad'); }); // pricing if (screenRes > 750) { // style 2 $(".pricing_box ul").each(function () { $(".pricing_box .price_col").css('width',$(".pricing_box ul").width() / $(".pricing_box .price_col").size() - 10); }); var table_maxHeight = -1; $('.price_item .price_col_body ul').each(function() { table_maxHeight = table_maxHeight > $(this).height() ? table_maxHeight : $(this).height(); }); $('.price_item .price_col_body ul').each(function() { $(this).height(table_maxHeight); }); } // buttons $(".btn, .post-share a, .btn-submit").hover(function(){ $(this).stop().animate({"opacity": 0.80}); },function(){ $(this).stop().animate({"opacity": 1}); }); // Smooth Scroling of ID anchors function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace(/\/$/,''); } var locationPath = filterPath(location.pathname); var scrollElem = scrollableElement('html', 'body'); $('a[href*=#].anchor').each(function() { $(this).click(function(event) { var thisPath = filterPath(this.pathname) || locationPath; if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) { var $target = $(this.hash), target = this.hash; if (target && $target.length != 0) { var targetOffset = $target.offset().top; event.preventDefault(); $(scrollElem).animate({scrollTop: targetOffset}, 400, function() { location.hash = target; }); } } }); }); // use the first element that is "scrollable" function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; } // prettyPhoto lightbox, check if <a> has atrr data-rel and hide for Mobiles if($('a').is('[data-rel]') && screenRes > 600) { $('a[data-rel]').each(function() { $(this).attr('rel', $(this).data('rel')); }); $("a[rel^='prettyPhoto']").prettyPhoto({social_tools:false}); } }); $(window).load(function() { var $=jQuery; // mega dropdown menu $('.dropdown .mega-nav > ul.submenu-1').each(function(){ var liItems = $(this); var Sum = 0; var liHeight = 0; if (liItems.children('li').length > 1){ $(this).children('li').each(function(i, e){ Sum += $(e).outerWidth(true); }); $(this).width(Sum); liHeight = $(this).innerHeight(); $(this).children('li').css({"height":liHeight-30}); } var posLeft = 0; var halfSum = Sum/2; var screenRes = $(window).width(); if (screenRes > 960) { var mainWidth = 940; // width of main container to fit in. } else { var mainWidth = 744; // for iPad. } var parentWidth = $(this).parent().width(); var margLeft = $(this).parent().position(); margLeft = margLeft.left; var margRight = mainWidth - margLeft - parentWidth; var subCenter = halfSum - parentWidth/2; if (margLeft >= halfSum && margRight >= halfSum) { liItems.css("left",-subCenter); } else if (margLeft<halfSum) { liItems.css("left",-margLeft-1); } else if (margRight<halfSum) { posLeft = Sum - margRight - parentWidth - 10; liItems.css("left",-posLeft); } }); });
JavaScript
/** * -------------------------------------------------------------------- * jQuery customInput plugin * Author: Maggie Costello Wachs maggie@filamentgroup.com, Scott Jehl, scott@filamentgroup.com * Copyright (c) 2009 Filament Group * licensed under MIT (filamentgroup.com/examples/mit-license.txt) * -------------------------------------------------------------------- */ jQuery.fn.customInput = function() { return $(this).each(function() { if ($(this).is('[type=checkbox],[type=radio]')) { var input = $(this); // get the associated label using the input's id var label = $('label[for="' + input.attr('id') + '"]'); // wrap the input + label in a div input.add(label).wrapAll('<div class="custom-' + input.attr('type') + '"></div>'); // necessary for browsers that don't support the :hover pseudo class on labels label.hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); }); //bind custom event, trigger it, bind click,focus,blur events input.bind('updateState', function() { input.is(':checked') ? label.addClass('checked') : label.removeClass('checked checkedHover checkedFocus'); }) .trigger('updateState') .click(function() { $('input[name="' + $(this).attr('name') + '"]').trigger('updateState'); }) .focus(function() { label.addClass('focus'); if (input.is(':checked')) { $(this).addClass('checkedFocus'); } }) .blur(function() { label.removeClass('focus checkedFocus'); }); } }); };
JavaScript
jQuery(document).ready(function(){ tfuse_custom_form(); tfuse_feedback_form(); }); function tfuse_custom_form(){ var my_error; var url = jQuery("input[name=temp_url]").attr('value'); jQuery("#send").bind("click", function(){ my_error = false; jQuery(".ajax_form input, .ajax_form textarea, .ajax_form radio, .ajax_form select").each(function(i) { var surrounding_element = jQuery(this); var value = jQuery(this).attr("value"); var check_for = jQuery(this).attr("id"); var required = jQuery(this).hasClass("required"); if(check_for == "email"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/)){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(check_for == "name"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(value == "" || value == "Name"){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(check_for == "message"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(value == "" || value == "Message"){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(check_for == "phone"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(value == "" || value == "Phone number"){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(required && check_for != "email" && check_for != "message" && check_for != "name" && check_for != "phone"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(value == ""){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(jQuery(".ajax_form input, .ajax_form textarea, .ajax_form radio, .ajax_form select").length == i+1){ if(my_error == false){ jQuery(".ajax_form").slideUp(400); var $datastring = "ajax=true"; jQuery(".ajax_form input, .ajax_form textarea, .ajax_form radio, .ajax_form select").each(function(i) { var $name = jQuery(this).attr('name'); var $value = encodeURIComponent(jQuery(this).attr('value')); $datastring = $datastring + "&" + $name + "=" + $value; }); jQuery(".ajax_form #send").fadeOut(100); jQuery.ajax({ type: "POST", url: "./sendmail.php", data: $datastring, success: function(response){ jQuery(".ajax_form").before("<div class='ajaxresponse' style='display: none;'></div>"); jQuery(".ajaxresponse").html(response).slideDown(400); jQuery(".ajax_form #send").fadeIn(400); jQuery(".ajax_form input, .ajax_form textarea, .ajax_form radio, .ajax_form select").val(""); } }); } } }); return false; }); } function tfuse_feedback_form(){ var my_error; var url = jQuery("input[name=temp_url]").attr('value'); jQuery("#send_f").bind("click", function(){ my_error = false; jQuery(".feedback_ajax_form input, .feedback_ajax_form textarea, .feedback_ajax_form radio, .feedback_ajax_form select").each(function(i) { var surrounding_element = jQuery(this); var value = jQuery(this).attr("value"); var check_for = jQuery(this).attr("id"); var required = jQuery(this).hasClass("required"); if(check_for == "email_f"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/)){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(check_for == "name_f"){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(value == "" || value == "Name*"){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(required && check_for != "email_f" && check_for != "name_f" ){ surrounding_element.removeClass("error valid"); baseclases = surrounding_element.attr("class"); if(value == ""){ surrounding_element.attr("class",baseclases).addClass("error"); my_error = true; }else{ surrounding_element.attr("class",baseclases).addClass("valid"); } } if(jQuery(".feedback_ajax_form input, .feedback_ajax_form textarea, .feedback_ajax_form radio, .feedback_ajax_form select").length == i+1){ if(my_error == false){ jQuery(".feedback_ajax_form").slideUp(400); var $datastring = "ajax=true"; jQuery(".feedback_ajax_form input, .feedback_ajax_form textarea, .feedback_ajax_form radio, .feedback_ajax_form select").each(function(i) { var $name = jQuery(this).attr('name'); var $value = encodeURIComponent(jQuery(this).attr('value')); $datastring = $datastring + "&" + $name + "=" + $value; }); jQuery(".feedback_ajax_form #send_f").fadeOut(100); jQuery.ajax({ type: "POST", url: "./sendmail.php", data: $datastring, success: function(response){ jQuery(".feedback_ajax_form").before("<div class='ajaxresponse_f' style='display: none;'></div>"); jQuery(".ajaxresponse_f").html(response).slideDown(400); jQuery(".feedback_ajax_form #send_f").fadeIn(400); jQuery(".feedback_ajax_form input, .feedback_ajax_form textarea, .feedback_ajax_form radio, .feedback_ajax_form select").val(""); } }); } } }); 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
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
/** * @license * * Copyright 2011 Google Inc. * * 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 SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
// Copyright 2011 Google /** * 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. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
jQuery(document).ready(function(){ var navTag = '#gnav_' + jQuery('h2.menu_image').html() + ' a'; jQuery(navTag).attr("class", "current"); });
JavaScript
// ----------------------------------------------------------------------------------- // // Lightbox v2.04 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 2/9/08 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: 'images/loading.gif', fileBottomNavCloseImage: 'images/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.rel == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { // if caption is not null if (this.imageArray[this.activeImage][1] != ""){ this.caption.update(this.imageArray[this.activeImage][1]).show(); } // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
JavaScript
// script.aculo.us scriptaculous.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 // Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.9.0', require: function(libraryName) { try{ // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); } catch(e) { // for xhtml+xml served content, fall back to DOM methods var script = document.createElement('script'); script.type = 'text/javascript'; script.src = libraryName; document.getElementsByTagName('head')[0].appendChild(script); } }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } }; Scriptaculous.load();
JavaScript
// script.aculo.us builder.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 // Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return $(element); }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e); else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); }; }); } };
JavaScript
// ----------------------------------------------------------------------------------- // // Lightbox v2.05 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 3/18/11 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: '/wp-content/themes/999mastercontrol-dev/images/loading.gif', fileBottomNavCloseImage: '/wp-content/themes/999mastercontrol-dev/images/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.getAttribute("rel") == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; /*Bug Fixed by Andy Scott*/ this.lightboxImage.width = imgPreloader.width; this.lightboxImage.height = imgPreloader.height; /*End of Bug Fix*/ this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { this.caption.update(this.imageArray[this.activeImage][1]).show(); // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
JavaScript
goog.provide('bentlyschemistrylab.GamePlayer'); goog.require("lime.Sprite"); goog.require("lime.Label"); goog.require("lime.RoundedRect"); goog.require("lime.fill.Frame"); goog.require("lime.audio.Audio"); var objMap = { easy : [ {answer: "Hydrogen", x: 0, y: 0, width: 128, height: 128}, {answer: "Helium", x: 128, y: 0, width: 128, height: 128}, {answer: "Boron", x: 256, y: 0, width: 128, height: 128}, {answer: "Carbon", x: 384, y: 0, width: 128, height: 128}, {answer: "Nitrogen", x: 512, y: 0, width: 128, height: 128}, {answer: "Oxygen", x: 640, y: 0, width: 128, height: 128}, {answer: "Fluorine", x: 768, y: 0, width: 128, height: 128}, {answer: "Neon", x: 896, y: 0, width: 128, height: 128}, {answer: "Sodium", x: 1024, y: 0, width: 128, height: 128}, {answer: "Magnesium", x: 1152, y: 0, width: 128, height: 128}, {answer: "Aluminium", x: 1280, y: 0, width: 128, height: 128}, {answer: "Silicon", x: 1408, y: 0, width: 128, height: 128}, {answer: "Phosphorus", x: 1536, y: 0, width: 128, height: 128}, {answer: "Sulfur", x: 1664, y: 0, width: 128, height: 128}, {answer: "Chlorine", x: 1792, y: 0, width: 128, height: 128}, {answer: "Calcium", x: 0, y: 128, width: 128, height: 128}, {answer: "Titanium", x: 128, y: 128, width: 128, height: 128}, {answer: "Vanadium", x: 256, y: 128, width: 128, height: 128}, {answer: "Cobalt", x: 384, y: 128, width: 128, height: 128}, {answer: "Nickel", x: 512, y: 128, width: 128, height: 128}, {answer: "Copper", x: 640, y: 128, width: 128, height: 128}, {answer: "Zinc", x: 768, y: 128, width: 128, height: 128}, {answer: "Krypton", x: 896, y: 128, width: 128, height: 128}, {answer: "Iodine", x: 1024, y: 128, width: 128, height: 128}, {answer: "Xenon", x: 1152, y: 128, width: 128, height: 128}, {answer: "Platinum", x: 1280, y: 128, width: 128, height: 128}, {answer: "Radon", x: 1408, y: 128, width: 128, height: 128}, {answer: "Francium", x: 1536, y: 128, width: 128, height: 128}, {answer: "Radium", x: 1664, y: 128, width: 128, height: 128} ], medium: [ {answer: "Lithium", x: 0, y: 256, width: 128, height: 128}, {answer: "Beryllium", x: 128, y: 256, width: 128, height: 128}, {answer: "Potassium", x: 256, y: 256, width: 128, height: 128}, {answer: "Argon", x: 384, y: 256, width: 128, height: 128}, {answer: "Scandium", x: 512, y: 256, width: 128, height: 128}, {answer: "Iron", x: 640, y: 256, width: 128, height: 128}, {answer: "Chromium", x: 768, y: 256, width: 128, height: 128}, {answer: "Manganese", x: 896, y: 256, width: 128, height: 128}, {answer: "Gallium", x: 1024, y: 256, width: 128, height: 128}, {answer: "Germanium", x: 1152, y: 256, width: 128, height: 128}, {answer: "Arsenic", x: 1280, y: 256, width: 128, height: 128}, {answer: "Selenium", x: 1408, y: 256, width: 128, height: 128}, {answer: "Bromine", x: 1536, y: 256, width: 128, height: 128}, {answer: "Rubidium", x: 1664, y: 256, width: 128, height: 128}, {answer: "Strontium", x: 1792, y: 256, width: 128, height: 128}, {answer: "Yttrium", x: 0, y: 384, width: 128, height: 128}, {answer: "Silver", x: 128, y: 384, width: 128, height: 128}, {answer: "Tin", x: 256, y: 384, width: 128, height: 128}, {answer: "Zirconium", x: 384, y: 384, width: 128, height: 128}, {answer: "Ruthenium", x: 512, y: 384, width: 128, height: 128}, {answer: "Barium", x: 640, y: 384, width: 128, height: 128}, {answer: "Tungsten", x: 768, y: 384, width: 128, height: 128}, {answer: "Gold", x: 896, y: 384, width: 128, height: 128}, {answer: "Mercury", x: 1024, y: 384, width: 128, height: 128}, {answer: "Lead", x: 1152, y: 384, width: 128, height: 128}, {answer: "Bismuth", x: 1280, y: 384, width: 128, height: 128}, {answer: "Polonium", x: 1408, y: 384, width: 128, height: 128} ], hard: [ {answer: "Niobium", x: 0, y: 512, width: 128, height: 128}, {answer: "Molybdenum", x: 128, y: 512, width: 128, height: 128}, {answer: "Technetium", x: 256, y: 512, width: 128, height: 128}, {answer: "Rhodium", x: 384, y: 512, width: 128, height: 128}, {answer: "Palladium", x: 512, y: 512, width: 128, height: 128}, {answer: "Cadmium", x: 640, y: 512, width: 128, height: 128}, {answer: "Indium", x: 768, y: 512, width: 128, height: 128}, {answer: "Antimony", x: 896, y: 512, width: 128, height: 128}, {answer: "Tellurium", x: 1024, y: 512, width: 128, height: 128}, {answer: "Caesium", x: 1152, y: 512, width: 128, height: 128}, {answer: "Lanthanum", x: 1280, y: 512, width: 128, height: 128}, {answer: "Cerium", x: 1408, y: 512, width: 128, height: 128}, {answer: "Praseodymium", x: 1536, y: 512, width: 128, height: 128}, {answer: "Neodymium", x: 1664, y: 512, width: 128, height: 128}, {answer: "Promethium", x: 1792, y: 512, width: 128, height: 128}, {answer: "Samarium", x: 0, y: 640, width: 128, height: 128}, {answer: "Europium", x: 128, y: 640, width: 128, height: 128}, {answer: "Gadolinium", x: 256, y: 640, width: 128, height: 128}, {answer: "Terbium", x: 384, y: 640, width: 128, height: 128}, {answer: "Dysprosium", x: 512, y: 640, width: 128, height: 128}, {answer: "Holmium", x: 640, y: 640, width: 128, height: 128}, {answer: "Erbium", x: 768, y: 640, width: 128, height: 128}, {answer: "Thulium", x: 896, y: 640, width: 128, height: 128}, {answer: "Ytterbium", x: 1024, y: 640, width: 128, height: 128}, {answer: "Lutetium", x: 1152, y: 640, width: 128, height: 128}, {answer: "Hafnium", x: 1280, y: 640, width: 128, height: 128}, {answer: "Tantalum", x: 1408, y: 640, width: 128, height: 128} ], imageFile: "asset/graphic/game/Chemistry.png" }; var maxTimer = 10000; bentlyschemistrylab.GamePlayer = function(gameObj, gameLayer, gameOverCallback) { goog.base(this); this.gameObj = gameObj; this.gameLayer = gameLayer; this.gameOverCallback = gameOverCallback; this.setPosition(0, 0); this.setAnchorPoint(0, 0); this.setSize(gameObj.width, gameObj.height); this.setFill("asset/graphic/screen/GameScreen.png"); this.curTime = 0; this.timeIncrement = 5000; this.active = false; this.correctSound = new lime.audio.Audio("asset/sound/RightAnswer.wav"); this.wrongSound = new lime.audio.Audio("asset/sound/WrongAnswer.wav"); this.correctAnswer = new lime.Sprite().setAnchorPoint(0.5, 0.5); this.otherAnswer1 = new lime.Sprite().setAnchorPoint(0.5, 0.5); this.otherAnswer2 = new lime.Sprite().setAnchorPoint(0.5, 0.5); this.answerLabel = new lime.Label() .setAnchorPoint(0.5, 0.5) .setFontColor("#0000FF") .setFontSize(58); this.timeBar = new lime.RoundedRect() .setAnchorPoint(0, 0) .setRadius(0) .setPosition(0, 508) .setSize(gameObj.width, 5) .setFill("#00FF00"); goog.events.listen(this.correctAnswer, ["touchstart", "mousedown"], function(e) { this.getParent().correctSound.play(); this.getParent().increaseTimer(); this.getParent().nextQuestion(); }); goog.events.listen(this.otherAnswer1, ["touchstart", "mousedown"], function(e) { this.getParent().wrongSound.play(); this.getParent().decreaseTimer(); this.getParent().nextQuestion(); }); goog.events.listen(this.otherAnswer2, ["touchstart", "mousedown"], function(e) { this.getParent().wrongSound.play(); this.getParent().decreaseTimer(); this.getParent().nextQuestion(); }); this.appendChild(this.correctAnswer); this.appendChild(this.otherAnswer1); this.appendChild(this.otherAnswer2); this.appendChild(this.answerLabel); this.appendChild(this.timeBar); this.initialize(gameObj); lime.scheduleManager.schedule(function(dt) { this.update(dt); }, this); this.nextQuestion(); }; goog.inherits(bentlyschemistrylab.GamePlayer, lime.Sprite); bentlyschemistrylab.GamePlayer.prototype.initialize = function(gameObj) { this.curDifficulty = gameObj.curDifficulty; this.curTime = maxTimer; this.active = true; }; bentlyschemistrylab.GamePlayer.prototype.nextQuestion = function() { var choices = objMap; var imageFile = choices.imageFile; switch(this.curDifficulty){ case 1: choices = choices.easy; break; case 2: choices = choices.medium; break; case 3: choices = choices.hard; break; } var numChoices = choices.length; var cBtn = choices[Math.floor(Math.random() * numChoices)]; var iBtn1 = choices[Math.floor(Math.random() * numChoices)]; var iBtn2 = choices[Math.floor(Math.random() * numChoices)]; var cFrame = new lime.fill.Frame(imageFile, cBtn.x, cBtn.y, cBtn.width, cBtn.height); var iFrame1 = new lime.fill.Frame(imageFile, iBtn1.x, iBtn1.y, iBtn1.width, iBtn1.height); var iFrame2 = new lime.fill.Frame(imageFile, iBtn2.x, iBtn2.y, iBtn2.width, iBtn2.height); this.answerLabel.setText(cBtn.answer).setPosition(this.gameObj.width / 2, 585); var pos = [ {x: 240, y: 120}, {x: 100, y: 350}, {x: 380, y: 350}, {x: 240, y: 120}, {x: 100, y: 350} ]; var startPos = Math.floor(Math.random() * 3); this.correctAnswer .setSize(cBtn.width, cBtn.height) .setFill(cFrame).setPosition(pos[startPos].x, pos[startPos].y); this.otherAnswer1 .setSize(iBtn1.width, iBtn1.height) .setFill(iFrame1).setPosition(pos[startPos + 1].x, pos[startPos + 1].y); this.otherAnswer2 .setSize(iBtn2.width, iBtn2.height) .setFill(iFrame2).setPosition(pos[startPos + 2].x, pos[startPos + 2].y); }; bentlyschemistrylab.GamePlayer.prototype.update = function(dt) { if(this.active) { if(this.curTime > 0) { this.curTime -= dt; this.timeBar.setSize((this.curTime / maxTimer) * this.gameObj.width, 5); } else { this.active = false; this.gameOverCallback(); } } }; bentlyschemistrylab.GamePlayer.prototype.increaseTimer = function() { this.curTime += this.timeIncrement; if(this.curTime > maxTimer) { this.curTime = maxTimer; } }; bentlyschemistrylab.GamePlayer.prototype.decreaseTimer = function() { this.curTime -= 10; if(this.timeIncrement > 250) { this.timeIncrement -= 50; } };
JavaScript
//set main namespace goog.provide('bentlyschemistrylab'); //get requirements goog.require("lime.Director"); goog.require("lime.Scene"); goog.require("lime.Layer"); goog.require("lime.transitions.Dissolve"); goog.require("lime.audio.Audio"); goog.require('bentlyschemistrylab.GamePlayer'); // entrypoint bentlyschemistrylab.start = function() { var gameObj = { width: 480, height: 640, renderer: lime.Renderer.CANVAS, curMode: 1, curDifficulty: 1 }; var director = new lime.Director(document.getElementById("gameContainer"), gameObj.width, gameObj.height); var titleScene = new lime.Scene(); var difficultyScene = new lime.Scene(); var gameScene = new lime.Scene(); var creditScene = new lime.Scene(); var titleLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); var difficultyLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); var gameLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); var creditLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); titleScene.appendChild(titleLayer); difficultyScene.appendChild(difficultyLayer); gameScene.appendChild(gameLayer); creditScene.appendChild(creditLayer); var menuSound = new lime.audio.Audio("asset/sound/MenuSelect.wav"); // Title Screen Objects var titleImage = new lime.Sprite() .setSize(gameObj.width, gameObj.height) .setFill("asset/graphic/screen/TitleScreen.png") .setAnchorPoint(0, 0) .setPosition(0, 0); titleLayer.appendChild(titleImage); var startButton = new lime.Sprite() .setSize(320, 230) .setFill("asset/graphic/button/StartButton.png") .setAnchorPoint(0, 0) .setPosition(75, 330); titleLayer.appendChild(startButton); goog.events.listen(startButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); director.replaceScene(difficultyScene, lime.transitions.Dissolve, 0.5); difficultyLayer.setDirty(255); }); // Difficult Select Screen Objects var difficultySelectImage = new lime.Sprite() .setSize(gameObj.width, gameObj.height) .setFill("asset/graphic/screen/DifficultySelectScreen.png") .setAnchorPoint(0, 0) .setPosition(0, 0); difficultyLayer.appendChild(difficultySelectImage); var easyButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/EasyButton.png") .setAnchorPoint(0, 0) .setPosition(80, 250); difficultyLayer.appendChild(easyButton); goog.events.listen(easyButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); gameObj.curDifficulty = 1; gamePlayer.initialize(gameObj); director.replaceScene(gameScene, lime.transitions.Dissolve, 0.5); gameLayer.setDirty(255); }); var mediumButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/MediumButton.png") .setAnchorPoint(0, 0) .setPosition(80, 350); difficultyLayer.appendChild(mediumButton); goog.events.listen(mediumButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); gameObj.curDifficulty = 2; gamePlayer.initialize(gameObj); director.replaceScene(gameScene, lime.transitions.Dissolve, 0.5); gameLayer.setDirty(255); }); var hardButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/HardButton.png") .setAnchorPoint(0, 0) .setPosition(80, 450); difficultyLayer.appendChild(hardButton); goog.events.listen(hardButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); gameObj.curDifficulty = 3; gamePlayer.initialize(gameObj); director.replaceScene(gameScene, lime.transitions.Dissolve, 0.5); gameLayer.setDirty(255); }); // Game Screen Objects var gamePlayer = new bentlyschemistrylab.GamePlayer(gameObj, gameLayer, function() { director.replaceScene(creditScene, lime.transitions.Dissolve, 0.5); creditLayer.setDirty(255); }); gameLayer.appendChild(gamePlayer); // Credit Screen Objects var creditImage = new lime.Sprite() .setSize(gameObj.width, gameObj.height) .setFill("asset/graphic/screen/CreditScreen.png") .setAnchorPoint(0, 0) .setPosition(0, 0); creditLayer.appendChild(creditImage); var continueButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/ContinueButton.png") .setAnchorPoint(0, 0) .setPosition(80, 400); creditLayer.appendChild(continueButton); goog.events.listen(continueButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); director.replaceScene(titleScene, lime.transitions.Dissolve, 0.5); titleLayer.setDirty(255); }); director.makeMobileWebAppCapable(); director.replaceScene(titleScene); } //this is required for outside access after code is compiled in ADVANCED_COMPILATIONS mode goog.exportSymbol('bentlyschemistrylab.start', bentlyschemistrylab.start);
JavaScript
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $(function(){ var $window = $(window) // Disable certain links in docs $('section [href^=#]').click(function (e) { e.preventDefault() }) // side bar $('.bs-docs-sidenav').affix({ offset: { top: function () { return $window.width() <= 980 ? 290 : 210 } , bottom: 270 } }) // make code pretty window.prettyPrint && prettyPrint() // add-ons $('.add-on :checkbox').on('click', function () { var $this = $(this) , method = $this.attr('checked') ? 'addClass' : 'removeClass' $(this).parents('.add-on')[method]('active') }) // add tipsies to grid for scaffolding if ($('#gridSystem').length) { $('#gridSystem').tooltip({ selector: '.show-grid > div' , title: function () { return $(this).width() + 'px' } }) } // tooltip demo $('.tooltip-demo').tooltip({ selector: "a[rel=tooltip]" }) $('.tooltip-test').tooltip() $('.popover-test').popover() // popover demo $("a[rel=popover]") .popover() .click(function(e) { e.preventDefault() }) // button state demo $('#fat-btn') .click(function () { var btn = $(this) btn.button('loading') setTimeout(function () { btn.button('reset') }, 3000) }) // carousel demo $('#myCarousel').carousel() // javascript build logic var inputsComponent = $("#components.download input") , inputsPlugin = $("#plugins.download input") , inputsVariables = $("#variables.download input") // toggle all plugin checkboxes $('#components.download .toggle-all').on('click', function (e) { e.preventDefault() inputsComponent.attr('checked', !inputsComponent.is(':checked')) }) $('#plugins.download .toggle-all').on('click', function (e) { e.preventDefault() inputsPlugin.attr('checked', !inputsPlugin.is(':checked')) }) $('#variables.download .toggle-all').on('click', function (e) { e.preventDefault() inputsVariables.val('') }) // request built javascript $('.download-btn .btn').on('click', function () { var css = $("#components.download input:checked") .map(function () { return this.value }) .toArray() , js = $("#plugins.download input:checked") .map(function () { return this.value }) .toArray() , vars = {} , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png'] $("#variables.download input") .each(function () { $(this).val() && (vars[ $(this).prev().text() ] = $(this).val()) }) $.ajax({ type: 'POST' , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com' , dataType: 'jsonpi' , params: { js: js , css: css , vars: vars , img: img } }) }) }) // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi $.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) { var url = opts.url; return { send: function(_, completeCallback) { var name = 'jQuery_iframe_' + jQuery.now() , iframe, form iframe = $('<iframe>') .attr('name', name) .appendTo('head') form = $('<form>') .attr('method', opts.type) // GET or POST .attr('action', url) .attr('target', name) $.each(opts.params, function(k, v) { $('<input>') .attr('type', 'hidden') .attr('name', k) .attr('value', typeof v == 'string' ? v : JSON.stringify(v)) .appendTo(form) }) form.appendTo('body').submit() } } }) }(window.jQuery)
JavaScript
/* Holder - 1.6 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function text_size(width, height, template) { var dimension_arr = [height, width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); return { height: text_height } } function draw(ctx, dimensions, template, ratio) { var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (ctx.measureText(text).width / width > 1) { text_height = template.size / (ctx.measureText(text).width / width); } ctx.font = "bold " + (text_height * ratio) + "px sans-serif"; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var ratio = 1; if(window.devicePixelRatio && window.devicePixelRatio > 1){ ratio = window.devicePixelRatio; } if (mode == "image") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; if (fallback) { el.style.backgroundColor = theme.background; } else{ el.setAttribute("src", draw(ctx, dimensions, theme, ratio)); } } else { if (!fallback) { el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")"; el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px"; } } }; function fluid(el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var fluid = document.createElement("table"); fluid.setAttribute("cellspacing",0) fluid.setAttribute("cellpadding",0) fluid.setAttribute("border",0) var row = document.createElement("tr") .appendChild(document.createElement("td") .appendChild(document.createTextNode(theme.text))); fluid.style.backgroundColor = theme.background; fluid.style.color = theme.foreground; fluid.className = el.className + " holderjs-fluid"; fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px"); fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px"); fluid.id = el.id; var frag = document.createDocumentFragment(), tbody = document.createElement("tbody"), tr = document.createElement("tr"), td = document.createElement("td"); tr.appendChild(td); tbody.appendChild(tr); frag.appendChild(tbody); if (theme.text) { td.appendChild(document.createTextNode(theme.text)) fluid.appendChild(frag); } else { td.appendChild(document.createTextNode(dimensions_caption)) fluid.appendChild(frag); fluid_images.push(fluid); setTimeout(fluid_update, 0); } el.parentNode.replaceChild(fluid, el); } function fluid_update() { for (i in fluid_images) { var el = fluid_images[i]; var label = el.getElementsByTagName("td")[0].firstChild; label.data = el.offsetWidth + "x" + el.offsetHeight; } } function parse_flags(flags, options) { var ret = { theme: settings.themes.gray }, render = false; for (sl = flags.length, j = 0; j < sl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors ret.theme = options.themes[flag]; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } } return render ? ret : false; }; if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var fluid_images = []; var settings = { domain: "holder.js", images: "img", elements: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } }, stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}" }; app.flags = { dimensions: { regex: /(\d+)x(\d+)/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /([0-9%]+)x([0-9%]+)/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } } } for (var flag in app.flags) { app.flags[flag].match = function (val) { return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images_nodes = selector(options.images), elements = selector(options.elements), preempted = true, images = []; for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]); var holdercss = document.createElement("style"); holdercss.type = "text/css"; holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet; document.getElementsByTagName("head")[0].appendChild(holdercss); var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = elements.length, i = 0; i < l; i++) { var src = window.getComputedStyle(elements[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", elements[i], holder, src); } } } for (var l = images.length, i = 0; i < l; i++) { var src = images[i].getAttribute("src") || images[i].getAttribute("data-src"); if (src != null && src.indexOf(options.domain) >= 0) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { if (holder.fluid) { fluid(images[i], holder, src); } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", fluid_update, false); window.addEventListener("orientationchange", fluid_update, false); } else { window.attachEvent("onresize", fluid_update) } preempted || app.run(); }); })(Holder, window);
JavaScript
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $(function(){ var $window = $(window) // Disable certain links in docs $('section [href^=#]').click(function (e) { e.preventDefault() }) // side bar $('.bs-docs-sidenav').affix({ offset: { top: function () { return $window.width() <= 980 ? 290 : 210 } , bottom: 270 } }) // make code pretty window.prettyPrint && prettyPrint() // add-ons $('.add-on :checkbox').on('click', function () { var $this = $(this) , method = $this.attr('checked') ? 'addClass' : 'removeClass' $(this).parents('.add-on')[method]('active') }) // add tipsies to grid for scaffolding if ($('#gridSystem').length) { $('#gridSystem').tooltip({ selector: '.show-grid > div' , title: function () { return $(this).width() + 'px' } }) } // tooltip demo $('.tooltip-demo').tooltip({ selector: "a[rel=tooltip]" }) $('.tooltip-test').tooltip() $('.popover-test').popover() // popover demo $("a[rel=popover]") .popover() .click(function(e) { e.preventDefault() }) // button state demo $('#fat-btn') .click(function () { var btn = $(this) btn.button('loading') setTimeout(function () { btn.button('reset') }, 3000) }) // carousel demo $('#myCarousel').carousel() // javascript build logic var inputsComponent = $("#components.download input") , inputsPlugin = $("#plugins.download input") , inputsVariables = $("#variables.download input") // toggle all plugin checkboxes $('#components.download .toggle-all').on('click', function (e) { e.preventDefault() inputsComponent.attr('checked', !inputsComponent.is(':checked')) }) $('#plugins.download .toggle-all').on('click', function (e) { e.preventDefault() inputsPlugin.attr('checked', !inputsPlugin.is(':checked')) }) $('#variables.download .toggle-all').on('click', function (e) { e.preventDefault() inputsVariables.val('') }) // request built javascript $('.download-btn .btn').on('click', function () { var css = $("#components.download input:checked") .map(function () { return this.value }) .toArray() , js = $("#plugins.download input:checked") .map(function () { return this.value }) .toArray() , vars = {} , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png'] $("#variables.download input") .each(function () { $(this).val() && (vars[ $(this).prev().text() ] = $(this).val()) }) $.ajax({ type: 'POST' , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com' , dataType: 'jsonpi' , params: { js: js , css: css , vars: vars , img: img } }) }) }) // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi $.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) { var url = opts.url; return { send: function(_, completeCallback) { var name = 'jQuery_iframe_' + jQuery.now() , iframe, form iframe = $('<iframe>') .attr('name', name) .appendTo('head') form = $('<form>') .attr('method', opts.type) // GET or POST .attr('action', url) .attr('target', name) $.each(opts.params, function(k, v) { $('<input>') .attr('type', 'hidden') .attr('name', k) .attr('value', typeof v == 'string' ? v : JSON.stringify(v)) .appendTo(form) }) form.appendTo('body').submit() } } }) }(window.jQuery)
JavaScript
/* Holder - 1.6 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function text_size(width, height, template) { var dimension_arr = [height, width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); return { height: text_height } } function draw(ctx, dimensions, template, ratio) { var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (ctx.measureText(text).width / width > 1) { text_height = template.size / (ctx.measureText(text).width / width); } ctx.font = "bold " + (text_height * ratio) + "px sans-serif"; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var ratio = 1; if(window.devicePixelRatio && window.devicePixelRatio > 1){ ratio = window.devicePixelRatio; } if (mode == "image") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; if (fallback) { el.style.backgroundColor = theme.background; } else{ el.setAttribute("src", draw(ctx, dimensions, theme, ratio)); } } else { if (!fallback) { el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")"; el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px"; } } }; function fluid(el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var fluid = document.createElement("table"); fluid.setAttribute("cellspacing",0) fluid.setAttribute("cellpadding",0) fluid.setAttribute("border",0) var row = document.createElement("tr") .appendChild(document.createElement("td") .appendChild(document.createTextNode(theme.text))); fluid.style.backgroundColor = theme.background; fluid.style.color = theme.foreground; fluid.className = el.className + " holderjs-fluid"; fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px"); fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px"); fluid.id = el.id; var frag = document.createDocumentFragment(), tbody = document.createElement("tbody"), tr = document.createElement("tr"), td = document.createElement("td"); tr.appendChild(td); tbody.appendChild(tr); frag.appendChild(tbody); if (theme.text) { td.appendChild(document.createTextNode(theme.text)) fluid.appendChild(frag); } else { td.appendChild(document.createTextNode(dimensions_caption)) fluid.appendChild(frag); fluid_images.push(fluid); setTimeout(fluid_update, 0); } el.parentNode.replaceChild(fluid, el); } function fluid_update() { for (i in fluid_images) { var el = fluid_images[i]; var label = el.getElementsByTagName("td")[0].firstChild; label.data = el.offsetWidth + "x" + el.offsetHeight; } } function parse_flags(flags, options) { var ret = { theme: settings.themes.gray }, render = false; for (sl = flags.length, j = 0; j < sl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors ret.theme = options.themes[flag]; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } } return render ? ret : false; }; if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var fluid_images = []; var settings = { domain: "holder.js", images: "img", elements: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } }, stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}" }; app.flags = { dimensions: { regex: /(\d+)x(\d+)/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /([0-9%]+)x([0-9%]+)/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } } } for (var flag in app.flags) { app.flags[flag].match = function (val) { return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images_nodes = selector(options.images), elements = selector(options.elements), preempted = true, images = []; for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]); var holdercss = document.createElement("style"); holdercss.type = "text/css"; holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet; document.getElementsByTagName("head")[0].appendChild(holdercss); var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = elements.length, i = 0; i < l; i++) { var src = window.getComputedStyle(elements[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", elements[i], holder, src); } } } for (var l = images.length, i = 0; i < l; i++) { var src = images[i].getAttribute("src") || images[i].getAttribute("data-src"); if (src != null && src.indexOf(options.domain) >= 0) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { if (holder.fluid) { fluid(images[i], holder, src); } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", fluid_update, false); window.addEventListener("orientationchange", fluid_update, false); } else { window.attachEvent("onresize", fluid_update) } preempted || app.run(); }); })(Holder, window);
JavaScript
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $(function(){ var $window = $(window) // Disable certain links in docs $('section [href^=#]').click(function (e) { e.preventDefault() }) // side bar $('.bs-docs-sidenav').affix({ offset: { top: function () { return $window.width() <= 980 ? 290 : 210 } , bottom: 270 } }) // make code pretty window.prettyPrint && prettyPrint() // add-ons $('.add-on :checkbox').on('click', function () { var $this = $(this) , method = $this.attr('checked') ? 'addClass' : 'removeClass' $(this).parents('.add-on')[method]('active') }) // add tipsies to grid for scaffolding if ($('#gridSystem').length) { $('#gridSystem').tooltip({ selector: '.show-grid > div' , title: function () { return $(this).width() + 'px' } }) } // tooltip demo $('.tooltip-demo').tooltip({ selector: "a[rel=tooltip]" }) $('.tooltip-test').tooltip() $('.popover-test').popover() // popover demo $("a[rel=popover]") .popover() .click(function(e) { e.preventDefault() }) // button state demo $('#fat-btn') .click(function () { var btn = $(this) btn.button('loading') setTimeout(function () { btn.button('reset') }, 3000) }) // carousel demo $('#myCarousel').carousel() // javascript build logic var inputsComponent = $("#components.download input") , inputsPlugin = $("#plugins.download input") , inputsVariables = $("#variables.download input") // toggle all plugin checkboxes $('#components.download .toggle-all').on('click', function (e) { e.preventDefault() inputsComponent.attr('checked', !inputsComponent.is(':checked')) }) $('#plugins.download .toggle-all').on('click', function (e) { e.preventDefault() inputsPlugin.attr('checked', !inputsPlugin.is(':checked')) }) $('#variables.download .toggle-all').on('click', function (e) { e.preventDefault() inputsVariables.val('') }) // request built javascript $('.download-btn .btn').on('click', function () { var css = $("#components.download input:checked") .map(function () { return this.value }) .toArray() , js = $("#plugins.download input:checked") .map(function () { return this.value }) .toArray() , vars = {} , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png'] $("#variables.download input") .each(function () { $(this).val() && (vars[ $(this).prev().text() ] = $(this).val()) }) $.ajax({ type: 'POST' , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com' , dataType: 'jsonpi' , params: { js: js , css: css , vars: vars , img: img } }) }) }) // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi $.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) { var url = opts.url; return { send: function(_, completeCallback) { var name = 'jQuery_iframe_' + jQuery.now() , iframe, form iframe = $('<iframe>') .attr('name', name) .appendTo('head') form = $('<form>') .attr('method', opts.type) // GET or POST .attr('action', url) .attr('target', name) $.each(opts.params, function(k, v) { $('<input>') .attr('type', 'hidden') .attr('name', k) .attr('value', typeof v == 'string' ? v : JSON.stringify(v)) .appendTo(form) }) form.appendTo('body').submit() } } }) }(window.jQuery)
JavaScript
/* Holder - 1.6 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function text_size(width, height, template) { var dimension_arr = [height, width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); return { height: text_height } } function draw(ctx, dimensions, template, ratio) { var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (ctx.measureText(text).width / width > 1) { text_height = template.size / (ctx.measureText(text).width / width); } ctx.font = "bold " + (text_height * ratio) + "px sans-serif"; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var ratio = 1; if(window.devicePixelRatio && window.devicePixelRatio > 1){ ratio = window.devicePixelRatio; } if (mode == "image") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; if (fallback) { el.style.backgroundColor = theme.background; } else{ el.setAttribute("src", draw(ctx, dimensions, theme, ratio)); } } else { if (!fallback) { el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")"; el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px"; } } }; function fluid(el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var fluid = document.createElement("table"); fluid.setAttribute("cellspacing",0) fluid.setAttribute("cellpadding",0) fluid.setAttribute("border",0) var row = document.createElement("tr") .appendChild(document.createElement("td") .appendChild(document.createTextNode(theme.text))); fluid.style.backgroundColor = theme.background; fluid.style.color = theme.foreground; fluid.className = el.className + " holderjs-fluid"; fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px"); fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px"); fluid.id = el.id; var frag = document.createDocumentFragment(), tbody = document.createElement("tbody"), tr = document.createElement("tr"), td = document.createElement("td"); tr.appendChild(td); tbody.appendChild(tr); frag.appendChild(tbody); if (theme.text) { td.appendChild(document.createTextNode(theme.text)) fluid.appendChild(frag); } else { td.appendChild(document.createTextNode(dimensions_caption)) fluid.appendChild(frag); fluid_images.push(fluid); setTimeout(fluid_update, 0); } el.parentNode.replaceChild(fluid, el); } function fluid_update() { for (i in fluid_images) { var el = fluid_images[i]; var label = el.getElementsByTagName("td")[0].firstChild; label.data = el.offsetWidth + "x" + el.offsetHeight; } } function parse_flags(flags, options) { var ret = { theme: settings.themes.gray }, render = false; for (sl = flags.length, j = 0; j < sl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors ret.theme = options.themes[flag]; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } } return render ? ret : false; }; if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var fluid_images = []; var settings = { domain: "holder.js", images: "img", elements: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } }, stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}" }; app.flags = { dimensions: { regex: /(\d+)x(\d+)/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /([0-9%]+)x([0-9%]+)/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } } } for (var flag in app.flags) { app.flags[flag].match = function (val) { return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images_nodes = selector(options.images), elements = selector(options.elements), preempted = true, images = []; for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]); var holdercss = document.createElement("style"); holdercss.type = "text/css"; holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet; document.getElementsByTagName("head")[0].appendChild(holdercss); var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = elements.length, i = 0; i < l; i++) { var src = window.getComputedStyle(elements[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", elements[i], holder, src); } } } for (var l = images.length, i = 0; i < l; i++) { var src = images[i].getAttribute("src") || images[i].getAttribute("data-src"); if (src != null && src.indexOf(options.domain) >= 0) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { if (holder.fluid) { fluid(images[i], holder, src); } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", fluid_update, false); window.addEventListener("orientationchange", fluid_update, false); } else { window.attachEvent("onresize", fluid_update) } preempted || app.run(); }); })(Holder, window);
JavaScript
jQuery(document).ready(function () { jQuery(&quot;#facebook_right&quot;).hover(function () { jQuery(this) .stop(true, false) .animate({ right: 0 }, 500); }, function () { jQuery(&quot;#facebook_right&quot;) .stop(true, false).animate({ right: -200 }, 500); }); });
JavaScript
function confirmurl(url,message) { if(confirm(message)) redirect(url); } function redirect(url) { if(url.indexOf('://') == -1 && url.substr(0, 1) != '/' && url.substr(0, 1) != '?') url = $('base').attr('href')+url; location.href = url; } //滚动条 $(function(){ //inputStyle $(":text").addClass('input-text'); }) /** * 全选checkbox,注意:标识checkbox id固定为为check_box * @param string name 列表check名称,如 uid[] */ function selectall(name) { if ($("#check_box").attr("checked")==false) { $("input[name='"+name+"']").each(function() { this.checked=false; }); } else { $("input[name='"+name+"']").each(function() { this.checked=true; }); } }
JavaScript
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo * The DHTML Calendar, version 1.0 "It is happening again" * Details and latest version at: * www.dynarch.com/projects/calendar * This script is developed by Dynarch.com. Visit us at www.dynarch.com. * This script is distributed under the GNU Lesser General Public License. * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html // $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $ /** The Calendar object constructor. */ //document.createStyleSheet('/images/js/calendar/calendar-blue.css'); var head = document.getElementsByTagName('HEAD').item(0); var style = document.createElement('link'); style.href = '/statics/js/calendar/calendar-blue.css'; style.rel = 'stylesheet'; style.type = 'text/css'; head.appendChild(style); Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {this.activeDiv = null;this.currentDateEl = null;this.getDateStatus = null; this.getDateToolTip = null;this.getDateText = null; this.timeout = null;this.onSelected = onSelected || null; this.onClose = onClose || null; this.dragging = false; this.hidden = false; this.minYear = 1970; this.maxYear = 2050; this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"]; this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"]; this.isPopup = true; this.weekNumbers = true; this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; this.showsOtherMonths = false; this.dateStr = dateStr; this.ar_days = null; this.showsTime = false; this.time24 = true; this.yearStep = 2; this.hiliteToday = true; this.multiple = null;this.table = null; this.element = null; this.tbody = null;this.firstdayname = null;this.monthsCombo = null;this.yearsCombo = null;this.hilitedMonth = null;this.activeMonth = null;this.hilitedYear = null; this.activeYear = null;this.dateClicked = false; if (typeof Calendar._SDN == "undefined") {if (typeof Calendar._SDN_len == "undefined")Calendar._SDN_len = 3;var ar = new Array();for (var i = 8; i > 0;) {ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);}Calendar._SDN = ar;if (typeof Calendar._SMN_len == "undefined")Calendar._SMN_len = 3;ar = new Array();for (var i = 12; i > 0;) {ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);}Calendar._SMN = ar;}};Calendar._C = null;Calendar.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );Calendar.is_opera = /opera/i.test(navigator.userAgent);Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);Calendar.getAbsolutePos = function(el) {var SL = 0, ST = 0;var is_div = /^div$/i.test(el.tagName);if (is_div && el.scrollLeft)SL = el.scrollLeft;if (is_div && el.scrollTop)ST = el.scrollTop;var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };if (el.offsetParent) {var tmp = this.getAbsolutePos(el.offsetParent);r.x += tmp.x;r.y += tmp.y;}return r;};Calendar.isRelated = function (el, evt) {var related = evt.relatedTarget;if (!related) {var type = evt.type;if (type == "mouseover") {related = evt.fromElement;} else if (type == "mouseout") {related = evt.toElement;}}while (related) {if (related == el) {return true;}related = related.parentNode;}return false;};Calendar.removeClass = function(el, className) {if (!(el && el.className)) {return;}var cls = el.className.split(" ");var ar = new Array();for (var i = cls.length; i > 0;) {if (cls[--i] != className) {ar[ar.length] = cls[i];}}el.className = ar.join(" ");};Calendar.addClass = function(el, className) {Calendar.removeClass(el, className);el.className += " " + className;};Calendar.getElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;while (f.nodeType != 1 || /^div$/i.test(f.tagName))f = f.parentNode;return f;};Calendar.getTargetElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.target;while (f.nodeType != 1)f = f.parentNode;return f;};Calendar.stopEvent = function(ev) {ev || (ev = window.event);if (Calendar.is_ie) {ev.cancelBubble = true;ev.returnValue = false;} else {ev.preventDefault();ev.stopPropagation();}return false;};Calendar.addEvent = function(el, evname, func) {if (el.attachEvent) { el.attachEvent("on" + evname, func);} else if (el.addEventListener) { el.addEventListener(evname, func, true);} else {el["on" + evname] = func;}};Calendar.removeEvent = function(el, evname, func) {if (el.detachEvent) { el.detachEvent("on" + evname, func);} else if (el.removeEventListener) { el.removeEventListener(evname, func, true);} else {el["on" + evname] = null;}};Calendar.createElement = function(type, parent) {var el = null;if (document.createElementNS) {el = document.createElementNS("http://www.w3.org/1999/xhtml", type);} else {el = document.createElement(type);}if (typeof parent != "undefined") {parent.appendChild(el);}return el;};Calendar._add_evs = function(el) {with (Calendar) {addEvent(el, "mouseover", dayMouseOver);addEvent(el, "mousedown", dayMouseDown);addEvent(el, "mouseout", dayMouseOut);if (is_ie) {addEvent(el, "dblclick", dayMouseDblClick);el.setAttribute("unselectable", true);}}};Calendar.findMonth = function(el) {if (typeof el.month != "undefined") {return el;} else if (typeof el.parentNode.month != "undefined") {return el.parentNode;}return null;};Calendar.findYear = function(el) {if (typeof el.year != "undefined") {return el;} else if (typeof el.parentNode.year != "undefined") {return el.parentNode;}return null;};Calendar.showMonthsCombo = function () {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var mc = cal.monthsCombo;if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}if (cal.activeMonth) {Calendar.removeClass(cal.activeMonth, "active");}var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];Calendar.addClass(mon, "active");cal.activeMonth = mon;var s = mc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var mcw = mc.offsetWidth;if (typeof mcw == "undefined")mcw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";};Calendar.showYearsCombo = function (fwd) {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var yc = cal.yearsCombo;if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}if (cal.activeYear) {Calendar.removeClass(cal.activeYear, "active");}cal.activeYear = null;var Y = cal.date.getFullYear() + (fwd ? 1 : -1);var yr = yc.firstChild;var show = false;for (var i = 12; i > 0; --i) {if (Y >= cal.minYear && Y <= cal.maxYear) {yr.innerHTML = Y;yr.year = Y;yr.style.display = "block";show = true;} else {yr.style.display = "none";}yr = yr.nextSibling;Y += fwd ? cal.yearStep : -cal.yearStep;}if (show) {var s = yc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var ycw = yc.offsetWidth;if (typeof ycw == "undefined")ycw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";}};Calendar.tableMouseUp = function(ev) {var cal = Calendar._C;if (!cal) {return false;}if (cal.timeout) {clearTimeout(cal.timeout);}var el = cal.activeDiv;if (!el) {return false;}var target = Calendar.getTargetElement(ev);ev || (ev = window.event);Calendar.removeClass(el, "active");if (target == el || target.parentNode == el) {Calendar.cellClick(el, ev);}var mon = Calendar.findMonth(target);var date = null;if (mon) {date = new Date(cal.date);if (mon.month != date.getMonth()) {date.setMonth(mon.month);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}} else {var year = Calendar.findYear(target);if (year) {date = new Date(cal.date);if (year.year != date.getFullYear()) {date.setFullYear(year.year);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}}}with (Calendar) {removeEvent(document, "mouseup", tableMouseUp);removeEvent(document, "mouseover", tableMouseOver);removeEvent(document, "mousemove", tableMouseOver);cal._hideCombos();_C = null;return stopEvent(ev);}};Calendar.tableMouseOver = function (ev) {var cal = Calendar._C;if (!cal) {return;}var el = cal.activeDiv;var target = Calendar.getTargetElement(ev);if (target == el || target.parentNode == el) {Calendar.addClass(el, "hilite active");Calendar.addClass(el.parentNode, "rowhilite");} else {if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))Calendar.removeClass(el, "active");Calendar.removeClass(el, "hilite");Calendar.removeClass(el.parentNode, "rowhilite");}ev || (ev = window.event);if (el.navtype == 50 && target != el) {var pos = Calendar.getAbsolutePos(el);var w = el.offsetWidth;var x = ev.clientX;var dx;var decrease = true;if (x > pos.x + w) {dx = x - pos.x - w;decrease = false;} elsedx = pos.x - x;if (dx < 0) dx = 0;var range = el._range;var current = el._current;var count = Math.floor(dx / 10) % range.length;for (var i = range.length; --i >= 0;)if (range[i] == current) break; while (count-- > 0) if (decrease) { if (--i < 0) i = range.length - 1; } else if ( ++i >= range.length ) i = 0; var newval = range[i]; el.innerHTML = newval;cal.onUpdateTime(); } var mon = Calendar.findMonth(target); if (mon) { if (mon.month != cal.date.getMonth()) { if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } Calendar.addClass(mon, "hilite"); cal.hilitedMonth = mon; } else if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } } else { if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}var year = Calendar.findYear(target);if (year) {if (year.year != cal.date.getFullYear()) {if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}Calendar.addClass(year, "hilite");cal.hilitedYear = year;} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}}return Calendar.stopEvent(ev);};Calendar.tableMouseDown = function (ev) {if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {return Calendar.stopEvent(ev);}};Calendar.calDragIt = function (ev) {var cal = Calendar._C;if (!(cal && cal.dragging)) {return false;}var posX;var posY;if (Calendar.is_ie) {posY = window.event.clientY + document.body.scrollTop;posX = window.event.clientX + document.body.scrollLeft;} else {posX = ev.pageX;posY = ev.pageY;}cal.hideShowCovered();var st = cal.element.style;st.left = (posX - cal.xOffs) + "px";st.top = (posY - cal.yOffs) + "px";return Calendar.stopEvent(ev);};Calendar.calDragEnd = function (ev) {var cal = Calendar._C;if (!cal) {return false;}cal.dragging = false;with (Calendar) {removeEvent(document, "mousemove", calDragIt);removeEvent(document, "mouseup", calDragEnd);tableMouseUp(ev);}cal.hideShowCovered();};Calendar.dayMouseDown = function(ev) {var el = Calendar.getElement(ev); if (el.disabled) { return false; } var cal = el.calendar; cal.activeDiv = el; Calendar._C = cal; if (el.navtype != 300) with (Calendar) { if (el.navtype == 50) { el._current = el.innerHTML; addEvent(document, "mousemove", tableMouseOver); } else addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver); addClass(el, "hilite active"); addEvent(document, "mouseup", tableMouseUp); } else if (cal.isPopup) { cal._dragStart(ev); } if (el.navtype == -1 || el.navtype == 1) { if (cal.timeout) clearTimeout(cal.timeout); cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250); } else if (el.navtype == -2 || el.navtype == 2) { if (cal.timeout) clearTimeout(cal.timeout); cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250); } else { cal.timeout = null; } return Calendar.stopEvent(ev); };Calendar.dayMouseDblClick = function(ev) { Calendar.cellClick(Calendar.getElement(ev), ev || window.event); if (Calendar.is_ie) { document.selection.empty(); } };Calendar.dayMouseOver = function(ev) { var el = Calendar.getElement(ev); if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) { return false; } if (el.ttip) { if (el.ttip.substr(0, 1) == "_") { el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1); } el.calendar.tooltips.innerHTML = el.ttip; } if (el.navtype != 300) { Calendar.addClass(el, "hilite"); if (el.caldate) { Calendar.addClass(el.parentNode, "rowhilite"); } } return Calendar.stopEvent(ev); };Calendar.dayMouseOut = function(ev) { with (Calendar) { var el = getElement(ev); if (isRelated(el, ev) || _C || el.disabled) return false; removeClass(el, "hilite"); if (el.caldate) removeClass(el.parentNode, "rowhilite"); if (el.calendar) el.calendar.tooltips.innerHTML = _TT["SEL_DATE"]; return stopEvent(ev); } }; Calendar.cellClick = function(el, ev) { var cal = el.calendar; var closing = false; var newdate = false; var date = null; if (typeof el.navtype == "undefined") { if (cal.currentDateEl) { Calendar.removeClass(cal.currentDateEl, "selected"); Calendar.addClass(el, "selected"); closing = (cal.currentDateEl == el); if (!closing) { cal.currentDateEl = el; } } cal.date.setDateOnly(el.caldate); date = cal.date; var other_month = !(cal.dateClicked = !el.otherMonth); if (!other_month && !cal.currentDateEl) cal._toggleMultipleDate(new Date(date)); else newdate = !el.disabled;if (other_month) cal._init(cal.firstDayOfWeek, date); } else { if (el.navtype == 200) { Calendar.removeClass(el, "hilite"); cal.callCloseHandler(); return; } date = new Date(cal.date); if (el.navtype == 0) date.setDateOnly(new Date()); cal.dateClicked = false; var year = date.getFullYear(); var mon = date.getMonth(); function setMonth(m) { var day = date.getDate(); var max = date.getMonthDays(m); if (day > max) { date.setDate(max); } date.setMonth(m); }; switch (el.navtype) { case 400: Calendar.removeClass(el, "hilite"); var text = Calendar._TT["ABOUT"]; if (typeof text != "undefined") { text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : ""; } else {text = "Help and about box text is not translated into this language.\n" + "If you know this language and you feel generous please update\n" + "the corresponding file in \"lang\" subdir to match calendar-en.js\n" + "and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" + "Thank you!\n" + "http://dynarch.com/mishoo/calendar.epl\n"; } alert(text); return; case -2: if (year > cal.minYear) { date.setFullYear(year - 1); } break; case -1: if (mon > 0) { setMonth(mon - 1); } else if (year-- > cal.minYear) { date.setFullYear(year); setMonth(11); } break; case 1: if (mon < 11) { setMonth(mon + 1); } else if (year < cal.maxYear) { date.setFullYear(year + 1); setMonth(0); } break; case 2: if (year < cal.maxYear) { date.setFullYear(year + 1); } break; case 100: cal.setFirstDayOfWeek(el.fdow); return; case 50: var range = el._range; var current = el.innerHTML; for (var i = range.length; --i >= 0;) if (range[i] == current) break; if (ev && ev.shiftKey) { if (--i < 0) i = range.length - 1; } else if ( ++i >= range.length ) i = 0; var newval = range[i]; el.innerHTML = newval; cal.onUpdateTime(); return; case 0:if ((typeof cal.getDateStatus == "function") && cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) { return false; } break; } if (!date.equalsTo(cal.date)) { cal.setDate(date); newdate = true; } else if (el.navtype == 0) newdate = closing = true; } if (newdate) { ev && cal.callHandler(); } if (closing) { Calendar.removeClass(el, "hilite"); ev && cal.callCloseHandler(); } }; Calendar.prototype.create = function (_par) { var parent = null; if (! _par) { parent = document.getElementsByTagName("body")[0]; this.isPopup = true; } else { parent = _par; this.isPopup = false; } this.date = this.dateStr ? new Date(this.dateStr) : new Date();var table = Calendar.createElement("table"); this.table = table; table.cellSpacing = 0; table.cellPadding = 0; table.calendar = this; Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);var div = Calendar.createElement("div"); this.element = div; div.className = "calendar"; if (this.isPopup) { div.style.position = "absolute"; div.style.display = "none"; } div.appendChild(table);var thead = Calendar.createElement("thead", table); var cell = null; var row = null;var cal = this; var hh = function (text, cs, navtype) { cell = Calendar.createElement("td", row); cell.colSpan = cs; cell.className = "button"; if (navtype != 0 && Math.abs(navtype) <= 2) cell.className += " nav"; Calendar._add_evs(cell); cell.calendar = cal; cell.navtype = navtype; cell.innerHTML = "<div unselectable='on'>" + text + "</div>"; return cell; };row = Calendar.createElement("tr", thead); var title_length = 6; (this.isPopup) && --title_length; (this.weekNumbers) && ++title_length;hh("<div>?</div>", 1, 400).ttip = Calendar._TT["INFO"]; this.title = hh("", title_length, 300); this.title.className = "title"; if (this.isPopup) { this.title.ttip = Calendar._TT["DRAG_TO_MOVE"]; this.title.style.cursor = "move"; hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"]; }row = Calendar.createElement("tr", thead); row.className = "headrow";this._nav_py = hh("&#x00ab;", 1, -2); this._nav_py.ttip = Calendar._TT["PREV_YEAR"];this._nav_pm = hh("‹", 1, -1); this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0); this._nav_now.ttip = Calendar._TT["GO_TODAY"];this._nav_nm = hh("›", 1, 1); this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];this._nav_ny = hh("&#x00bb;", 1, 2); this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"]; row = Calendar.createElement("tr", thead); row.className = "daynames"; if (this.weekNumbers) { cell = Calendar.createElement("td", row); cell.className = "name wn"; cell.innerHTML = "<div>"+Calendar._TT["WK"]+"</div>"; } for (var i = 7; i > 0; --i) { cell = Calendar.createElement("td", row); if (!i) { cell.navtype = 100; cell.calendar = this; Calendar._add_evs(cell); } } this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild; this._displayWeekdays();var tbody = Calendar.createElement("tbody", table); this.tbody = tbody;for (i = 6; i > 0; --i) { row = Calendar.createElement("tr", tbody); if (this.weekNumbers) { cell = Calendar.createElement("td", row); } for (var j = 7; j > 0; --j) { cell = Calendar.createElement("td", row); cell.calendar = this; Calendar._add_evs(cell); } }if (this.showsTime) { row = Calendar.createElement("tr", tbody); row.className = "time";cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = this.weekNumbers ? 4 : 3;(function(){ function makeTimePart(className, init, range_start, range_end) { var part = Calendar.createElement("span", cell); part.className = className; part.innerHTML = init; part.calendar = cal; part.ttip = Calendar._TT["TIME_PART"]; part.navtype = 50; part._range = []; if (typeof range_start != "number") part._range = range_start; else { for (var i = range_start; i <= range_end; ++i) { var txt; if (i < 10 && range_end >= 10) txt = '0' + i; else txt = '' + i; part._range[part._range.length] = txt; } } Calendar._add_evs(part); return part; }; var hrs = cal.date.getHours(); var mins = cal.date.getMinutes(); var t12 = !cal.time24; var pm = (hrs > 12); if (t12 && pm) hrs -= 12; var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23); var span = Calendar.createElement("span", cell); span.innerHTML = ":"; span.className = "colon"; var M = makeTimePart("minute", mins, 0, 59); var AP = null; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; if (t12) AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]); else cell.innerHTML = "&nbsp;";cal.onSetTime = function() { var pm, hrs = this.date.getHours(), mins = this.date.getMinutes(); if (t12) { pm = (hrs >= 12); if (pm) hrs -= 12; if (hrs == 0) hrs = 12; AP.innerHTML = pm ? "pm" : "am"; } H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs; M.innerHTML = (mins < 10) ? ("0" + mins) : mins; };cal.onUpdateTime = function() { var date = this.date; var h = parseInt(H.innerHTML, 10); if (t12) { if (/pm/i.test(AP.innerHTML) && h < 12) h += 12; else if (/am/i.test(AP.innerHTML) && h == 12) h = 0; } var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); date.setHours(h); date.setMinutes(parseInt(M.innerHTML, 10)); date.setFullYear(y); date.setMonth(m); date.setDate(d); this.dateClicked = false; this.callHandler(); }; })(); } else { this.onSetTime = this.onUpdateTime = function() {}; }var tfoot = Calendar.createElement("tfoot", table);row = Calendar.createElement("tr", tfoot); row.className = "footrow";cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300); cell.className = "ttip"; if (this.isPopup) { cell.ttip = Calendar._TT["DRAG_TO_MOVE"]; cell.style.cursor = "move"; } this.tooltips = cell;div = Calendar.createElement("div", this.element); this.monthsCombo = div; div.className = "combo"; for (i = 0; i < Calendar._MN.length; ++i) { var mn = Calendar.createElement("div"); mn.className = Calendar.is_ie ? "label-IEfix" : "label"; mn.month = i; mn.innerHTML = Calendar._SMN[i]; div.appendChild(mn); }div = Calendar.createElement("div", this.element); this.yearsCombo = div; div.className = "combo"; for (i = 12; i > 0; --i) { var yr = Calendar.createElement("div"); yr.className = Calendar.is_ie ? "label-IEfix" : "label"; div.appendChild(yr); }this._init(this.firstDayOfWeek, this.date); parent.appendChild(this.element); }; Calendar._keyEvent = function(ev) { var cal = window._dynarch_popupCalendar; if (!cal || cal.multiple) return false; (Calendar.is_ie) && (ev = window.event); var act = (Calendar.is_ie || ev.type == "keypress"), K = ev.keyCode; if (ev.ctrlKey) { switch (K) { case 37: act && Calendar.cellClick(cal._nav_pm); break; case 38: act && Calendar.cellClick(cal._nav_py); break; case 39: act && Calendar.cellClick(cal._nav_nm); break; case 40: act && Calendar.cellClick(cal._nav_ny); break; default: return false; } } else switch (K) { case 32: Calendar.cellClick(cal._nav_now); break; case 27: act && cal.callCloseHandler(); break; case 37: case 38: case 39: case 40: if (act) { var prev, x, y, ne, el, step; prev = K == 37 || K == 38; step = (K == 37 || K == 39) ? 1 : 7; function setVars() { el = cal.currentDateEl; var p = el.pos; x = p & 15; y = p >> 4; ne = cal.ar_days[y][x]; };setVars(); function prevMonth() { var date = new Date(cal.date); date.setDate(date.getDate() - step); cal.setDate(date); }; function nextMonth() { var date = new Date(cal.date); date.setDate(date.getDate() + step); cal.setDate(date); }; while (1) { switch (K) { case 37: if (--x >= 0) ne = cal.ar_days[y][x]; else { x = 6; K = 38; continue; } break; case 38: if (--y >= 0) ne = cal.ar_days[y][x]; else { prevMonth(); setVars(); } break; case 39: if (++x < 7) ne = cal.ar_days[y][x]; else { x = 0; K = 40; continue; } break; case 40: if (++y < cal.ar_days.length) ne = cal.ar_days[y][x]; else { nextMonth(); setVars(); } break; } break; } if (ne) { if (!ne.disabled) Calendar.cellClick(ne); else if (prev) prevMonth(); else nextMonth(); } } break; case 13: if (act) Calendar.cellClick(cal.currentDateEl, ev); break; default: return false; } return Calendar.stopEvent(ev); }; Calendar.prototype._init = function (firstDayOfWeek, date) { var today = new Date(), TY = today.getFullYear(), TM = today.getMonth(), TD = today.getDate(); this.table.style.visibility = "hidden"; var year = date.getFullYear(); if (year < this.minYear) { year = this.minYear; date.setFullYear(year); } else if (year > this.maxYear) { year = this.maxYear; date.setFullYear(year); } this.firstDayOfWeek = firstDayOfWeek; this.date = new Date(date); var month = date.getMonth(); var mday = date.getDate(); var no_days = date.getMonthDays(); date.setDate(1); var day1 = (date.getDay() - this.firstDayOfWeek) % 7; if (day1 < 0) day1 += 7; date.setDate(-day1); date.setDate(date.getDate() + 1);var row = this.tbody.firstChild; var MN = Calendar._SMN[month]; var ar_days = this.ar_days = new Array(); var weekend = Calendar._TT["WEEKEND"]; var dates = this.multiple ? (this.datesCells = {}) : null; for (var i = 0; i < 6; ++i, row = row.nextSibling) { var cell = row.firstChild; if (this.weekNumbers) { cell.className = "day wn"; cell.innerHTML = "<div>"+date.getWeekNumber()+"</div>"; cell = cell.nextSibling; } row.className = "daysrow"; var hasdays = false, iday, dpos = ar_days[i] = []; for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) { iday = date.getDate(); var wday = date.getDay(); cell.className = "day"; cell.pos = i << 4 | j; dpos[j] = cell; var current_month = (date.getMonth() == month); if (!current_month) { if (this.showsOtherMonths) { cell.className += " othermonth"; cell.otherMonth = true; } else { cell.className = "emptycell"; cell.innerHTML = "&nbsp;"; cell.disabled = true; continue; } } else { cell.otherMonth = false; hasdays = true; } cell.disabled = false; cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday; if (dates) dates[date.print("%Y%m%d")] = cell; if (this.getDateStatus) { var status = this.getDateStatus(date, year, month, iday); if (this.getDateToolTip) { var toolTip = this.getDateToolTip(date, year, month, iday); if (toolTip) cell.title = toolTip; } if (status === true) { cell.className += " disabled"; cell.disabled = true; } else { if (/disabled/i.test(status)) cell.disabled = true; cell.className += " " + status; } } if (!cell.disabled) { cell.caldate = new Date(date); cell.ttip = "_"; if (!this.multiple && current_month && iday == mday && this.hiliteToday) { cell.className += " selected"; this.currentDateEl = cell; } if (date.getFullYear() == TY && date.getMonth() == TM && iday == TD) { cell.className += " today"; cell.ttip += Calendar._TT["PART_TODAY"]; } if (weekend.indexOf(wday.toString()) != -1) cell.className += cell.otherMonth ? " oweekend" : " weekend"; } } if (!(hasdays || this.showsOtherMonths)) row.className = "emptyrow"; } this.title.innerHTML = Calendar._MN[month] + ", " + year; this.onSetTime(); this.table.style.visibility = "visible"; this._initMultipleDates(); };Calendar.prototype._initMultipleDates = function() { if (this.multiple) { for (var i in this.multiple) { var cell = this.datesCells[i]; var d = this.multiple[i]; if (!d) continue; if (cell) cell.className += " selected"; } } };Calendar.prototype._toggleMultipleDate = function(date) { if (this.multiple) { var ds = date.print("%Y%m%d"); var cell = this.datesCells[ds]; if (cell) { var d = this.multiple[ds]; if (!d) { Calendar.addClass(cell, "selected"); this.multiple[ds] = date; } else { Calendar.removeClass(cell, "selected"); delete this.multiple[ds]; } } } };Calendar.prototype.setDateToolTipHandler = function (unaryFunction) { this.getDateToolTip = unaryFunction; }; Calendar.prototype.setDate = function (date) { if (!date.equalsTo(this.date)) { this._init(this.firstDayOfWeek, date); } }; Calendar.prototype.refresh = function () { this._init(this.firstDayOfWeek, this.date); }; Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) { this._init(firstDayOfWeek, this.date); this._displayWeekdays(); }; Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) { this.getDateStatus = unaryFunction; }; Calendar.prototype.setRange = function (a, z) { this.minYear = a; this.maxYear = z; }; Calendar.prototype.callHandler = function () { if (this.onSelected) { this.onSelected(this, this.date.print(this.dateFormat)); } }; Calendar.prototype.callCloseHandler = function () { if (this.onClose) { this.onClose(this); } this.hideShowCovered(); }; Calendar.prototype.destroy = function () { var el = this.element.parentNode; el.removeChild(this.element); Calendar._C = null; window._dynarch_popupCalendar = null; }; Calendar.prototype.reparent = function (new_parent) { var el = this.element; el.parentNode.removeChild(el); new_parent.appendChild(el); }; Calendar._checkCalendar = function(ev) { var calendar = window._dynarch_popupCalendar; if (!calendar) { return false; } var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev); for (; el != null && el != calendar.element; el = el.parentNode); if (el == null) {window._dynarch_popupCalendar.callCloseHandler(); return Calendar.stopEvent(ev); } }; Calendar.prototype.show = function () { var rows = this.table.getElementsByTagName("tr"); for (var i = rows.length; i > 0;) { var row = rows[--i]; Calendar.removeClass(row, "rowhilite"); var cells = row.getElementsByTagName("td"); for (var j = cells.length; j > 0;) { var cell = cells[--j]; Calendar.removeClass(cell, "hilite"); Calendar.removeClass(cell, "active"); } } this.element.style.display = "block"; this.hidden = false; if (this.isPopup) { window._dynarch_popupCalendar = this; Calendar.addEvent(document, "keydown", Calendar._keyEvent); Calendar.addEvent(document, "keypress", Calendar._keyEvent); Calendar.addEvent(document, "mousedown", Calendar._checkCalendar); } this.hideShowCovered(); }; Calendar.prototype.hide = function () { if (this.isPopup) { Calendar.removeEvent(document, "keydown", Calendar._keyEvent); Calendar.removeEvent(document, "keypress", Calendar._keyEvent); Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar); } this.element.style.display = "none"; this.hidden = true; this.hideShowCovered(); };Calendar.prototype.showAt = function (x, y) { var s = this.element.style; s.left = x + "px"; s.top = y + "px"; this.show(); }; Calendar.prototype.showAtElement = function (el, opts) { var self = this; var p = Calendar.getAbsolutePos(el); if (!opts || typeof opts != "string") { this.showAt(p.x, p.y + el.offsetHeight); return true; } function fixPosition(box) { if (box.x < 0) box.x = 0; if (box.y < 0) box.y = 0; var cp = document.createElement("div"); var s = cp.style; s.position = "absolute"; s.right = s.bottom = s.width = s.height = "0px"; document.body.appendChild(cp); var br = Calendar.getAbsolutePos(cp); document.body.removeChild(cp); if (Calendar.is_ie) { br.y += document.body.scrollTop; br.x += document.body.scrollLeft; } else { br.y += window.scrollY; br.x += window.scrollX; } var tmp = box.x + box.width - br.x; if (tmp > 0) box.x -= tmp; tmp = box.y + box.height - br.y; if (tmp > 0) box.y -= tmp; }; this.element.style.display = "block"; Calendar.continuation_for_the_fucking_khtml_browser = function() { var w = self.element.offsetWidth; var h = self.element.offsetHeight; self.element.style.display = "none"; var valign = opts.substr(0, 1); var halign = "l"; if (opts.length > 1) { halign = opts.substr(1, 1); }switch (valign) { case "T": p.y -= h; break; case "B": p.y += el.offsetHeight; break; case "C": p.y += (el.offsetHeight - h) / 2; break; case "t": p.y += el.offsetHeight - h; break; case "b": break; }switch (halign) { case "L": p.x -= w; break; case "R": p.x += el.offsetWidth; break; case "C": p.x += (el.offsetWidth - w) / 2; break; case "l": p.x += el.offsetWidth - w; break; case "r": break; } p.width = w; p.height = h + 40; self.monthsCombo.style.display = "none"; fixPosition(p); self.showAt(p.x, p.y); }; if (Calendar.is_khtml) setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10); else Calendar.continuation_for_the_fucking_khtml_browser(); }; Calendar.prototype.setDateFormat = function (str) { this.dateFormat = str; }; Calendar.prototype.setTtDateFormat = function (str) { this.ttDateFormat = str; }; Calendar.prototype.parseDate = function(str, fmt) { if (!fmt) fmt = this.dateFormat; this.setDate(Date.parseDate(str, fmt)); }; Calendar.prototype.hideShowCovered = function () { if (!Calendar.is_ie && !Calendar.is_opera) return; function getVisib(obj){ var value = obj.style.visibility; if (!value) { if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { if (!Calendar.is_khtml) value = document.defaultView. getComputedStyle(obj, "").getPropertyValue("visibility"); else value = ''; } else if (obj.currentStyle) { value = obj.currentStyle.visibility; } else value = ''; } return value; };var tags = new Array("applet", "iframe", "select"); var el = this.element;var p = Calendar.getAbsolutePos(el); var EX1 = p.x; var EX2 = el.offsetWidth + EX1; var EY1 = p.y; var EY2 = el.offsetHeight + EY1;for (var k = tags.length; k > 0; ) { var ar = document.getElementsByTagName(tags[--k]); var cc = null;for (var i = ar.length; i > 0;) { cc = ar[--i];p = Calendar.getAbsolutePos(cc); var CX1 = p.x; var CX2 = cc.offsetWidth + CX1; var CY1 = p.y; var CY2 = cc.offsetHeight + CY1;if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) { if (!cc.__msh_save_visibility) { cc.__msh_save_visibility = getVisib(cc); } cc.style.visibility = cc.__msh_save_visibility; } else { if (!cc.__msh_save_visibility) { cc.__msh_save_visibility = getVisib(cc); } cc.style.visibility = "hidden"; } } } }; Calendar.prototype._displayWeekdays = function () { var fdow = this.firstDayOfWeek; var cell = this.firstdayname; var weekend = Calendar._TT["WEEKEND"]; for (var i = 0; i < 7; ++i) { cell.className = "day name"; var realday = (i + fdow) % 7; if (i) { cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]); cell.navtype = 100; cell.calendar = this; cell.fdow = realday; Calendar._add_evs(cell); } if (weekend.indexOf(realday.toString()) != -1) { Calendar.addClass(cell, "weekend"); } cell.innerHTML = Calendar._SDN[(i + fdow) % 7]; cell = cell.nextSibling; } }; Calendar.prototype._hideCombos = function () { this.monthsCombo.style.display = "none"; this.yearsCombo.style.display = "none"; }; Calendar.prototype._dragStart = function (ev) { if (this.dragging) { return; } this.dragging = true; var posX; var posY; if (Calendar.is_ie) { posY = window.event.clientY + document.body.scrollTop; posX = window.event.clientX + document.body.scrollLeft; } else { posY = ev.clientY + window.scrollY; posX = ev.clientX + window.scrollX; } var st = this.element.style; this.xOffs = posX - parseInt(st.left); this.yOffs = posY - parseInt(st.top); with (Calendar) { addEvent(document, "mousemove", calDragIt); addEvent(document, "mouseup", calDragEnd); } }; Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31); Date.SECOND = 1000 /* milliseconds */; Date.MINUTE = 60 * Date.SECOND; Date.HOUR = 60 * Date.MINUTE; Date.DAY = 24 * Date.HOUR; Date.WEEK = 7 * Date.DAY;Date.parseDate = function(str, fmt) { var today = new Date(); var y = 0; var m = -1; var d = 0; var a = str.split(/\W+/); var b = fmt.match(/%./g); var i = 0, j = 0; var hr = 0; var min = 0; for (i = 0; i < a.length; ++i) { if (!a[i]) continue; switch (b[i]) { case "%d": case "%e": d = parseInt(a[i], 10); break; case "%m": m = parseInt(a[i], 10) - 1; break; case "%Y": case "%y": y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); break; case "%b": case "%B": for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; } } break; case "%H": case "%I": case "%k": case "%l": hr = parseInt(a[i], 10); break; case "%P": case "%p": if (/pm/i.test(a[i]) && hr < 12) hr += 12; else if (/am/i.test(a[i]) && hr >= 12) hr -= 12; break; case "%M": min = parseInt(a[i], 10); break; } } if (isNaN(y)) y = today.getFullYear(); if (isNaN(m)) m = today.getMonth(); if (isNaN(d)) d = today.getDate(); if (isNaN(hr)) hr = today.getHours(); if (isNaN(min)) min = today.getMinutes(); if (y != 0 && m != -1 && d != 0) return new Date(y, m, d, hr, min, 0); y = 0; m = -1; d = 0; for (i = 0; i < a.length; ++i) { if (a[i].search(/[a-zA-Z]+/) != -1) { var t = -1; for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; } } if (t != -1) { if (m != -1) { d = m+1; } m = t; } } else if (parseInt(a[i], 10) <= 12 && m == -1) { m = a[i]-1; } else if (parseInt(a[i], 10) > 31 && y == 0) { y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); } else if (d == 0) { d = a[i]; } } if (y == 0) y = today.getFullYear(); if (m != -1 && d != 0) return new Date(y, m, d, hr, min, 0); return today; }; Date.prototype.getMonthDays = function(month) { var year = this.getFullYear(); if (typeof month == "undefined") { month = this.getMonth(); } if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) { return 29; } else { return Date._MD[month]; } }; Date.prototype.getDayOfYear = function() { var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0); var time = now - then; return Math.floor(time / Date.DAY); }; Date.prototype.getWeekNumber = function() { var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var DoW = d.getDay(); d.setDate(d.getDate() - (DoW + 6) % 7 + 3); var ms = d.valueOf(); d.setMonth(0); d.setDate(4); return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1; }; Date.prototype.equalsTo = function(date) { return ((this.getFullYear() == date.getFullYear()) && (this.getMonth() == date.getMonth()) && (this.getDate() == date.getDate()) && (this.getHours() == date.getHours()) && (this.getMinutes() == date.getMinutes())); }; Date.prototype.setDateOnly = function(date) { var tmp = new Date(date); this.setDate(1); this.setFullYear(tmp.getFullYear()); this.setMonth(tmp.getMonth()); this.setDate(tmp.getDate()); }; Date.prototype.print = function (str) { var m = this.getMonth(); var d = this.getDate(); var y = this.getFullYear(); var wn = this.getWeekNumber(); var w = this.getDay(); var s = {}; var hr = this.getHours(); var pm = (hr >= 12); var ir = (pm) ? (hr - 12) : hr; var dy = this.getDayOfYear(); if (ir == 0) ir = 12; var min = this.getMinutes(); var sec = this.getSeconds(); s["%a"] = Calendar._SDN[w];s["%A"] = Calendar._DN[w];s["%b"] = Calendar._SMN[m];s["%B"] = Calendar._MN[m]; s["%C"] = 1 + Math.floor(y / 100);s["%d"] = (d < 10) ? ("0" + d) : d;s["%e"] = d;s["%H"] = (hr < 10) ? ("0" + hr) : hr;s["%I"] = (ir < 10) ? ("0" + ir) : ir;s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;s["%k"] = hr; s["%l"] = ir; s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m);s["%M"] = (min < 10) ? ("0" + min) : min;s["%n"] = "\n"; s["%p"] = pm ? "PM" : "AM"; s["%P"] = pm ? "pm" : "am"; s["%s"] = Math.floor(this.getTime() / 1000); s["%S"] = (sec < 10) ? ("0" + sec) : sec;s["%t"] = "\t";s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn; s["%u"] = w + 1; s["%w"] = w; s["%y"] = ('' + y).substr(2, 2);s["%Y"] = y; s["%%"] = "%"; var re = /%./g; if (!Calendar.is_ie5 && !Calendar.is_khtml) return str.replace(re, function (par) { return s[par] || par; });var a = str.match(re); for (var i = 0; i < a.length; i++) { var tmp = s[a[i]]; if (tmp) { re = new RegExp(a[i], 'g'); str = str.replace(re, tmp); } }return str; };Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear; Date.prototype.setFullYear = function(y) { var d = new Date(this); d.__msh_oldSetFullYear(y); if (d.getMonth() != this.getMonth()) this.setDate(28); this.__msh_oldSetFullYear(y); };window._dynarch_popupCalendar = null; Calendar._DN = new Array ("星期日","星期一","星期二","星期三","星期四","星期五","星期六","星期日"); Calendar._SDN = new Array ("日","一","二","三","四","五","六","日"); Calendar._FD = 0; Calendar._MN = new Array ("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"); Calendar._SMN = new Array ("一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"); Calendar._TT = {}; Calendar._TT["INFO"] = "帮助"; Calendar._TT["ABOUT"] = "选择日期:\n" + "- 点击 \xab, \xbb 按钮选择年份\n" + "- 点击 " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " 按钮选择月份\n" + "- 长按以上按钮可从菜单中快速选择年份或月份"; Calendar._TT["ABOUT_TIME"] = "\n\n" + "选择时间:\n" + "- 点击小时或分钟可使改数值加一\n" + "- 按住Shift键点击小时或分钟可使改数值减一\n" + "- 点击拖动鼠标可进行快速选择"; Calendar._TT["PREV_YEAR"] = "上一年 (按住出菜单)"; Calendar._TT["PREV_MONTH"] = "上一月 (按住出菜单)"; Calendar._TT["GO_TODAY"] = "转到今日"; Calendar._TT["NEXT_MONTH"] = "下一月 (按住出菜单)"; Calendar._TT["NEXT_YEAR"] = "下一年 (按住出菜单)"; Calendar._TT["SEL_DATE"] = "选择日期"; Calendar._TT["DRAG_TO_MOVE"] = "拖动"; Calendar._TT["PART_TODAY"] = " (今日)"; Calendar._TT["DAY_FIRST"] = "最左边显示%s"; Calendar._TT["WEEKEND"] = "0,6"; Calendar._TT["CLOSE"] = "关闭"; Calendar._TT["TODAY"] = "今日"; Calendar._TT["TIME_PART"] = "(Shift-)点击鼠标或拖动改变值"; Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d"; Calendar._TT["TT_DATE_FORMAT"] = "%A, %b %e日"; Calendar._TT["WK"] = "周"; Calendar._TT["TIME"] = "时间:"; Calendar.setup = function (params) { function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } }; param_default("inputField", null); param_default("displayArea", null); param_default("button", null); param_default("eventName", "click"); param_default("ifFormat", "%Y/%m/%d"); param_default("daFormat", "%Y/%m/%d"); param_default("singleClick", true); param_default("disableFunc", null); param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined param_default("dateText", null); param_default("firstDay", null); param_default("align", "Br"); param_default("range", [1900, 2999]); param_default("weekNumbers", true); param_default("flat", null); param_default("flatCallback", null); param_default("onSelect", null); param_default("onClose", null); param_default("onUpdate", null); param_default("date", null); param_default("showsTime", false); param_default("timeFormat", "24"); param_default("electric", true); param_default("step", 2); param_default("position", null); param_default("cache", false); param_default("showOthers", false); param_default("multiple", null); var tmp = ["inputField", "displayArea", "button"]; for (var i in tmp) { if (typeof params[tmp[i]] == "string") { params[tmp[i]] = document.getElementById(params[tmp[i]]); } } if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) { alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code"); return false; } function onSelect(cal) { var p = cal.params; var update = (cal.dateClicked || p.electric); if (update && p.inputField) { p.inputField.value = cal.date.print(p.ifFormat); if (typeof p.inputField.onchange == "function") p.inputField.onchange(); } if (update && p.displayArea) p.displayArea.innerHTML = cal.date.print(p.daFormat); if (update && typeof p.onUpdate == "function") p.onUpdate(cal); if (update && p.flat) { if (typeof p.flatCallback == "function") p.flatCallback(cal); } if (update && p.singleClick && cal.dateClicked) cal.callCloseHandler(); }; if (params.flat != null) { if (typeof params.flat == "string") params.flat = document.getElementById(params.flat); if (!params.flat) { alert("Calendar.setup:\n Flat specified but can't find parent."); return false; } var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect); cal.showsOtherMonths = params.showOthers; cal.showsTime = params.showsTime; cal.time24 = (params.timeFormat == "24"); cal.params = params; cal.weekNumbers = params.weekNumbers; cal.setRange(params.range[0], params.range[1]); cal.setDateStatusHandler(params.dateStatusFunc); cal.getDateText = params.dateText; if (params.ifFormat) { cal.setDateFormat(params.ifFormat); } if (params.inputField && typeof params.inputField.value == "string") { cal.parseDate(params.inputField.value); } cal.create(params.flat); cal.show(); return false; } var triggerEl = params.button || params.displayArea || params.inputField; triggerEl["on" + params.eventName] = function() { var dateEl = params.inputField || params.displayArea; var dateFmt = params.inputField ? params.ifFormat : params.daFormat; var mustCreate = false; var cal = window.calendar; if (dateEl) params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt); if (!(cal && params.cache)) { window.calendar = cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect, params.onClose || function(cal) { cal.hide(); }); cal.showsTime = params.showsTime; cal.time24 = (params.timeFormat == "24"); cal.weekNumbers = params.weekNumbers; mustCreate = true; } else { if (params.date) cal.setDate(params.date); cal.hide(); } if (params.multiple) { cal.multiple = {}; for (var i = params.multiple.length; --i >= 0;) { var d = params.multiple[i]; var ds = d.print("%Y%m%d"); cal.multiple[ds] = d; } } cal.showsOtherMonths = params.showOthers; cal.yearStep = params.step; cal.setRange(params.range[0], params.range[1]); cal.params = params; cal.setDateStatusHandler(params.dateStatusFunc); cal.getDateText = params.dateText; cal.setDateFormat(dateFmt); if (mustCreate) cal.create(); cal.refresh(); if (!params.position) cal.showAtElement(params.button || params.displayArea || params.inputField, params.align); else cal.showAt(params.position[0], params.position[1]); return false; }; return cal; };
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; };
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add('uicolor',{requires:['dialog'],lang:['en'],init:function(a){if(CKEDITOR.env.ie6Compat)return;a.addCommand('uicolor',new CKEDITOR.dialogCommand('uicolor'));a.ui.addButton('UIColor',{label:a.lang.uicolor.title,command:'uicolor',icon:this.path+'uicolor.gif'});CKEDITOR.dialog.add('uicolor',this.path+'dialogs/uicolor.js');CKEDITOR.scriptLoader.load(CKEDITOR.getUrl('plugins/uicolor/yui/yui.js'));a.element.getDocument().appendStyleSheet(CKEDITOR.getUrl('plugins/uicolor/yui/assets/yui.css'));}});
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
JavaScript
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
var regexEnum = { intege:"^-?[1-9]\\d*$", //整数 intege1:"^[1-9]\\d*$", //正整数 intege2:"^-[1-9]\\d*$", //负整数 num:"^([+-]?)\\d*\\.?\\d+$", //数字 num1:"^[1-9]\\d*|0$", //正数(正整数 + 0) num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0) decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数 decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$",   //正浮点数 decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$",  //负浮点数 decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$",  //浮点数 decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$",   //非负浮点数(正浮点数 + 0) decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$",  //非正浮点数(负浮点数 + 0) email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件 color:"^[a-fA-F0-9]{6}$", //颜色 url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文 ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符 zipcode:"^\\d{6}$", //邮编 mobile:"^(13|15)[0-9]{9}$", //手机 ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址 notempty:"^\\S+$", //非空 picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片 rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件 date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期 qq:"^[1-9]*[1-9][0-9]*$", //QQ号码 tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号) username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串 letter:"^[A-Za-z]+$", //字母 letter_u:"^[A-Z]+$", //大写字母 letter_l:"^[a-z]+$", //小写字母 idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证 ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _ } function isCardID(sId){ var iSum=0 ; var info="" ; if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误"; sId=sId.replace(/x$/i,"a"); if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法"; sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) ; if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法"; for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ; if(iSum%11!=1) return "你输入的身份证号非法"; return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") } //短时间,形如 (13:04:06) function isTime(str) { var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/); if (a == null) {return false} if (a[1]>24 || a[3]>60 || a[4]>60) { return false; } return true; } //短日期,形如 (2003-12-05) function isDate(str) { var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); if(r==null)return false; var d= new Date(r[1], r[3]-1, r[4]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); } //长时间,形如 (2003-12-05 13:04:06) function isDateTime(str) { var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; var r = str.match(reg); if(r==null) return false; var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]); }
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
/* * 在jquery.suggest 1.1基础上针对中文输入的特点做了部分修改,下载原版请到jquery插件库 * 修改者:wangshuai * * 修改部分已在文中标注 * * * jquery.suggest 1.1 - 2007-08-06 * * Uses code and techniques from following libraries: * 1. http://www.dyve.net/jquery/?autocomplete * 2. http://dev.jquery.com/browser/trunk/plugins/interface/iautocompleter.js * * All the new stuff written by Peter Vulgaris (www.vulgarisoip.com) * Feel free to do whatever you want with this file * */ (function($) { $.suggest = function(input, options) { var $input = $(input).attr("autocomplete", "off"); var $results = $("#sr_infos"); var timeout = false; // hold timeout ID for suggestion results to appear var prevLength = 0; // last recorded length of $input.val() $input.blur(function() { setTimeout(function() { $results.hide() }, 200); }); $results.mouseover(function() { $("#sr_infos ul li").removeClass(options.selectClass); }) // help IE users if possible try { $results.bgiframe(); } catch(e) { } // I really hate browser detection, but I don't see any other way //修改开始 //下面部分在作者原来代码的基本上针对中文输入的特点做了些修改 if ($.browser.mozilla) $input.keypress(processKey2); // onkeypress repeats arrow keys in Mozilla/Opera else $input.keydown(processKey2); // onkeydown repeats arrow keys in IE/Safari*/ //这里是自己改为keyup事件 $input.keyup(processKey); //修改结束 function processKey(e) { // handling up/down/escape requires results to be visible // handling enter/tab requires that AND a result to be selected if (/^32$|^9$/.test(e.keyCode) && getCurrentResult()) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; e.returnValue = false; selectCurrentResult(); } else if ($input.val().length != prevLength) { if (timeout) clearTimeout(timeout); timeout = setTimeout(suggest, options.delay); prevLength = $input.val().length; } } //此处针对上面介绍的修改增加的函数 function processKey2(e) { // handling up/down/escape requires results to be visible // handling enter/tab requires that AND a result to be selected if (/27$|38$|40$|13$/.test(e.keyCode) && $results.is(':visible')) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; e.returnValue = false; switch(e.keyCode) { case 38: // up prevResult(); break; case 40: // down nextResult(); break; case 27: // escape $results.hide(); break; case 13: // enter $currentResult = getCurrentResult(); if ($currentResult) { $input.val($currentResult.text()); window.location.href='?m=search&c=index&a=init&q='+$currentResult.text(); } break; } } else if ($input.val().length != prevLength) { if (timeout) clearTimeout(timeout); timeout = setTimeout(suggest, options.delay); prevLength = $input.val().length; } } function suggest() { var q = $input.val().replace(/ /g, ''); if (q.length >= options.minchars) { $.getScript(options.source+'&q='+q, function(){ }); $results.hide(); //var items = parseTxt(txt, q); //displayItems(items); $results.show(); } else { $results.hide(); } } function displayItems(items) { if (!items) return; if (!items.length) { $results.hide(); return; } var html = ''; for (var i = 0; i < items.length; i++) html += '<li>' + items[i] + '</li>'; $results.html(html).show(); $results .children('li') .mouseover(function() { $results.children('li').removeClass(options.selectClass); $(this).addClass(options.selectClass); }) .click(function(e) { e.preventDefault(); e.stopPropagation(); selectCurrentResult(); }); } function getCurrentResult() { if (!$results.is(':visible')) return false; //var $currentResult = $results.children('li.' + options.selectClass); var $currentResult = $("#sr_infos ul li."+ options.selectClass); if (!$currentResult.length) $currentResult = false; return $currentResult; } function selectCurrentResult() { $currentResult = getCurrentResult(); if ($currentResult) { $input.val($currentResult.text()); $results.hide(); if (options.onSelect) options.onSelect.apply($input[0]); } } function nextResult() { $currentResult = getCurrentResult(); if ($currentResult) { $currentResult.removeClass(options.selectClass).next().addClass(options.selectClass); } else { $("#sr_infos ul li:first-child'").addClass(options.selectClass); //$results.children('li:first-child').addClass(options.selectClass); } } function prevResult() { $currentResult = getCurrentResult(); if ($currentResult) $currentResult.removeClass(options.selectClass).prev().addClass(options.selectClass); else //$results.children('li:last-child').addClass(options.selectClass); $("#sr_infos ul li:last-child'").addClass(options.selectClass); } } $.fn.suggest = function(source, options) { if (!source) return; options = options || {}; options.source = source; options.delay = options.delay || 100; options.resultsClass = options.resultsClass || 'ac_results'; options.selectClass = options.selectClass || 'ac_over'; options.matchClass = options.matchClass || 'ac_match'; options.minchars = options.minchars || 1; options.delimiter = options.delimiter || '\n'; options.onSelect = options.onSelect || false; this.each(function() { new $.suggest(this, options); }); return this; }; })(jQuery);
JavaScript
function setmodel(value, id, siteid, q) { $("#typeid").val(value); $("#search a").removeClass(); id.addClass('on'); if(q!=null && q!='') { window.location='?m=search&c=index&a=init&siteid='+siteid+'&typeid='+value+'&q='+q; } }
JavaScript