code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
importClass(Packages.myschedule.quartz.extra.job.LoggerJob);
importClass(Packages.org.quartz.JobBuilder);
importClass(Packages.org.quartz.TriggerBuilder);
importClass(Packages.org.quartz.SimpleScheduleBuilder);
var job = JobBuilder
.newJob(LoggerJob)
.withIdentity("simpleJob")
.build();
var trigger = TriggerBuilder
.newTrigger()
.withIdentity("simpleJob")
.withSchedule(
SimpleScheduleBuilder.repeatHourlyForever())
.build();
scheduler.scheduleJob(job, trigger);
| JavaScript |
1 + 99; | JavaScript |
importClass(Packages.myschedule.quartz.extra.job.LoggerJob);
scheduler.scheduleSimpleJob("hourlyJob1", -1, 60 * 60 * 1000, LoggerJob); | JavaScript |
//logger.info("Current classpath " + java.lang.System.getProperty("java.class.path"));
//logger.info("Class: " + Packages.integration.myschedule.quartz.extra.ScriptingSchedulerPluginIT)
logger.info("Plugin initialize");
importClass(Packages.myschedule.quartz.extra.ScriptingSchedulerPluginTest);
ScriptingSchedulerPluginTest.RESULT_FILE.appendLine('name: ' + schedulerPlugin.getName());
ScriptingSchedulerPluginTest.RESULT_FILE.appendLine('initialize: ' + new Date());
| JavaScript |
Packages.java.lang.System.getProperty("user.name"); | JavaScript |
importClass(Packages.myschedule.quartz.extra.job.LoggerJob);
scheduler.scheduleSimpleJob("hourlyJob2", -1, 60 * 60 * 1000, LoggerJob); | JavaScript |
logger.info("Plugin shutdown");
importClass(Packages.myschedule.quartz.extra.ScriptingSchedulerPluginTest);
ScriptingSchedulerPluginTest.RESULT_FILE.appendLine('shutdown: ' + new Date());
| JavaScript |
logger.info("Plugin start");
importClass(Packages.myschedule.quartz.extra.ScriptingSchedulerPluginTest);
ScriptingSchedulerPluginTest.RESULT_FILE.appendLine('start: ' + new Date());
| JavaScript |
/*
Copyright 2010 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 Bookmark bubble library. This is meant to be included in the
* main JavaScript binary of a mobile web application.
*
* Supported browsers: iPhone / iPod / iPad Safari 3.0+
*/
var google = google || {};
google.bookmarkbubble = google.bookmarkbubble || {};
/**
* Binds a context object to the function.
* @param {Function} fn The function to bind to.
* @param {Object} context The "this" object to use when the function is run.
* @return {Function} A partially-applied form of fn.
*/
google.bind = function(fn, context) {
return function() {
return fn.apply(context, arguments);
};
};
/**
* Function used to define an abstract method in a base class. If a subclass
* fails to override the abstract method, then an error will be thrown whenever
* that method is invoked.
*/
google.abstractMethod = function() {
throw Error('Unimplemented abstract method.');
};
/**
* The bubble constructor. Instantiating an object does not cause anything to
* be rendered yet, so if necessary you can set instance properties before
* showing the bubble.
* @constructor
*/
google.bookmarkbubble.Bubble = function() {
/**
* Handler for the scroll event. Keep a reference to it here, so it can be
* unregistered when the bubble is destroyed.
* @type {function()}
* @private
*/
this.boundScrollHandler_ = google.bind(this.setPosition, this);
/**
* The bubble element.
* @type {Element}
* @private
*/
this.element_ = null;
/**
* Whether the bubble has been destroyed.
* @type {boolean}
* @private
*/
this.hasBeenDestroyed_ = false;
};
/**
* Shows the bubble if allowed. It is not allowed if:
* - The browser is not Mobile Safari, or
* - The user has dismissed it too often already, or
* - The hash parameter is present in the location hash, or
* - The application is in fullscreen mode, which means it was already loaded
* from a homescreen bookmark.
* @return {boolean} True if the bubble is being shown, false if it is not
* allowed to show for one of the aforementioned reasons.
*/
google.bookmarkbubble.Bubble.prototype.showIfAllowed = function() {
if (!this.isAllowedToShow_()) {
return false;
}
this.show_();
return true;
};
/**
* Shows the bubble if allowed after loading the icon image. This method creates
* an image element to load the image into the browser's cache before showing
* the bubble to ensure that the image isn't blank. Use this instead of
* showIfAllowed if the image url is http and cacheable.
* This hack is necessary because Mobile Safari does not properly render
* image elements with border-radius CSS.
* @param {function()} opt_callback Closure to be called if and when the bubble
* actually shows.
* @return {boolean} True if the bubble is allowed to show.
*/
google.bookmarkbubble.Bubble.prototype.showIfAllowedWhenLoaded =
function(opt_callback) {
if (!this.isAllowedToShow_()) {
return false;
}
var self = this;
// Attach to self to avoid garbage collection.
var img = self.loadImg_ = document.createElement('img');
img.src = self.getIconUrl_();
img.onload = function() {
if (img.complete) {
delete self.loadImg_;
img.onload = null; // Break the circular reference.
self.show_();
opt_callback && opt_callback();
}
};
img.onload();
return true;
};
/**
* Sets the parameter in the location hash. As it is
* unpredictable what hash scheme is to be used, this method must be
* implemented by the host application.
*
* This gets called automatically when the bubble is shown. The idea is that if
* the user then creates a bookmark, we can later recognize on application
* startup whether it was from a bookmark suggested with this bubble.
*
* NOTE: Using a hash parameter to track whether the bubble has been shown
* conflicts with the navigation system in jQuery Mobile. If you are using that
* library, you should implement this function to track the bubble's status in
* a different way, e.g. using window.localStorage in HTML5.
*/
google.bookmarkbubble.Bubble.prototype.setHashParameter = google.abstractMethod;
/**
* Whether the parameter is present in the location hash. As it is
* unpredictable what hash scheme is to be used, this method must be
* implemented by the host application.
*
* Call this method during application startup if you want to log whether the
* application was loaded from a bookmark with the bookmark bubble promotion
* parameter in it.
*
* @return {boolean} Whether the bookmark bubble parameter is present in the
* location hash.
*/
google.bookmarkbubble.Bubble.prototype.hasHashParameter = google.abstractMethod;
/**
* The number of times the user must dismiss the bubble before we stop showing
* it. This is a public property and can be changed by the host application if
* necessary.
* @type {number}
*/
google.bookmarkbubble.Bubble.prototype.NUMBER_OF_TIMES_TO_DISMISS = 2;
/**
* Time in milliseconds. If the user does not dismiss the bubble, it will auto
* destruct after this amount of time.
* @type {number}
*/
google.bookmarkbubble.Bubble.prototype.TIME_UNTIL_AUTO_DESTRUCT = 15000;
/**
* The prefix for keys in local storage. This is a public property and can be
* changed by the host application if necessary.
* @type {string}
*/
google.bookmarkbubble.Bubble.prototype.LOCAL_STORAGE_PREFIX = 'BOOKMARK_';
/**
* The key name for the dismissed state.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.DISMISSED_ = 'DISMISSED_COUNT';
/**
* The arrow image in base64 data url format.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IMAGE_ARROW_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAMAAABSrFY3AAABKVBMVEUAAAD///8AAAAAAAAAAAAAAAAAAADf398AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD09PQAAAAAAAAAAAC9vb0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD19fUAAAAAAAAAAAAAAADq6uoAAAAAAAAAAAC8vLzU1NTT09MAAADg4OAAAADs7OwAAAAAAAAAAAD///+cueenwerA0vC1y+3a5fb5+/3t8vr4+v3w9PuwyOy3zO3h6vfh6vjq8Pqkv+mat+fE1fHB0/Cduuifu+iuxuuivemrxOvC1PDz9vzJ2fKpwuqmwOrb5vapw+q/0vDf6ffK2vLN3PPprJISAAAAQHRSTlMAAAEGExES7FM+JhUoQSxIRwMbNfkJUgXXBE4kDQIMHSA0Tw4xIToeTSc4Chz4OyIjPfI3QD/X5OZR6zzwLSUPrm1y3gAAAQZJREFUeF5lzsVyw0AURNE3IMsgmZmZgszQZoeZOf//EYlG5Yrhbs+im4Dj7slM5wBJ4OJ+undAUr68gK/Hyb6Bcp5yBR/w8jreNeAr5Eg2XE7g6e2/0z6cGw1JQhpmHP3u5aiPPnTTkIK48Hj9Op7bD3btAXTfgUdwYjwSDCVXMbizO0O4uDY/x4kYC5SWFnfC6N1a9RCO7i2XEmQJj2mHK1Hgp9Vq3QBRl9shuBLGhcNtHexcdQCnDUoUGetxDD+H2DQNG2xh6uAWgG2/17o1EmLqYH0Xej0UjHAaFxZIV6rJ/WK1kg7QZH8HU02zmdJinKZJaDV3TVMjM5Q9yiqYpUwiMwa/1apDXTNESjsAAAAASUVORK5CYII=';
/**
* The close image in base64 data url format.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IMAGE_CLOSE_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAALVBMVEXM3fm+1Pfb5/rF2fjw9f23z/aavPOhwfTp8PyTt/L3+v7T4vqMs/K7zP////+qRWzhAAAAXElEQVQIW2O4CwUM996BwVskxtOqd++2rwMyPI+ve31GD8h4Madqz2mwms5jZ/aBGS/mHIDoen3m+DowY8/hOVUgxusz+zqPg7SvPA1UxQfSvu/du0YUK2AMmDMA5H1qhVX33T8AAAAASUVORK5CYII=';
/**
* The link used to locate the application's home screen icon to display inside
* the bubble. The default link used here is for an iPhone home screen icon
* without gloss. If your application uses a glossy icon, change this to
* 'apple-touch-icon'.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.REL_ICON_ =
'apple-touch-icon-precomposed';
/**
* Regular expression for detecting an iPhone or iPod or iPad.
* @type {!RegExp}
* @private
*/
google.bookmarkbubble.Bubble.prototype.MOBILE_SAFARI_USERAGENT_REGEX_ =
/iPhone|iPod|iPad/;
/**
* Regular expression for detecting an iPad.
* @type {!RegExp}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IPAD_USERAGENT_REGEX_ = /iPad/;
/**
* Regular expression for extracting the iOS version. Only matches 2.0 and up.
* @type {!RegExp}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IOS_VERSION_USERAGENT_REGEX_ =
/OS (\d)_(\d)(?:_(\d))?/;
/**
* Determines whether the bubble should be shown or not.
* @return {boolean} Whether the bubble should be shown or not.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isAllowedToShow_ = function() {
return this.isMobileSafari_() &&
!this.hasBeenDismissedTooManyTimes_() &&
!this.isFullscreen_() &&
!this.hasHashParameter();
};
/**
* Builds and shows the bubble.
* @private
*/
google.bookmarkbubble.Bubble.prototype.show_ = function() {
this.element_ = this.build_();
document.body.appendChild(this.element_);
this.element_.style.WebkitTransform =
'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)';
this.setHashParameter();
window.setTimeout(this.boundScrollHandler_, 1);
window.addEventListener('scroll', this.boundScrollHandler_, false);
// If the user does not dismiss the bubble, slide out and destroy it after
// some time.
window.setTimeout(google.bind(this.autoDestruct_, this),
this.TIME_UNTIL_AUTO_DESTRUCT);
};
/**
* Destroys the bubble by removing its DOM nodes from the document.
*/
google.bookmarkbubble.Bubble.prototype.destroy = function() {
if (this.hasBeenDestroyed_) {
return;
}
window.removeEventListener('scroll', this.boundScrollHandler_, false);
if (this.element_ && this.element_.parentNode == document.body) {
document.body.removeChild(this.element_);
this.element_ = null;
}
this.hasBeenDestroyed_ = true;
};
/**
* Remember that the user has dismissed the bubble once more.
* @private
*/
google.bookmarkbubble.Bubble.prototype.rememberDismissal_ = function() {
if (window.localStorage) {
try {
var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_;
var value = Number(window.localStorage[key]) || 0;
window.localStorage[key] = String(value + 1);
} catch (ex) {
// Looks like we've hit the storage size limit. Currently we have no
// fallback for this scenario, but we could use cookie storage instead.
// This would increase the code bloat though.
}
}
};
/**
* Whether the user has dismissed the bubble often enough that we will not
* show it again.
* @return {boolean} Whether the user has dismissed the bubble often enough
* that we will not show it again.
* @private
*/
google.bookmarkbubble.Bubble.prototype.hasBeenDismissedTooManyTimes_ =
function() {
if (!window.localStorage) {
// If we can not use localStorage to remember how many times the user has
// dismissed the bubble, assume he has dismissed it. Otherwise we might end
// up showing it every time the host application loads, into eternity.
return true;
}
try {
var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_;
// If the key has never been set, localStorage yields undefined, which
// Number() turns into NaN. In that case we'll fall back to zero for
// clarity's sake.
var value = Number(window.localStorage[key]) || 0;
return value >= this.NUMBER_OF_TIMES_TO_DISMISS;
} catch (ex) {
// If we got here, something is wrong with the localStorage. Make the same
// assumption as when it does not exist at all. Exceptions should only
// occur when setting a value (due to storage limitations) but let's be
// extra careful.
return true;
}
};
/**
* Whether the application is running in fullscreen mode.
* @return {boolean} Whether the application is running in fullscreen mode.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isFullscreen_ = function() {
return !!window.navigator.standalone;
};
/**
* Whether the application is running inside Mobile Safari.
* @return {boolean} True if the current user agent looks like Mobile Safari.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isMobileSafari_ = function() {
return this.MOBILE_SAFARI_USERAGENT_REGEX_.test(window.navigator.userAgent);
};
/**
* Whether the application is running on an iPad.
* @return {boolean} True if the current user agent looks like an iPad.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isIpad_ = function() {
return this.IPAD_USERAGENT_REGEX_.test(window.navigator.userAgent);
};
/**
* Creates a version number from 4 integer pieces between 0 and 127 (inclusive).
* @param {*=} opt_a The major version.
* @param {*=} opt_b The minor version.
* @param {*=} opt_c The revision number.
* @param {*=} opt_d The build number.
* @return {number} A representation of the version.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getVersion_ = function(opt_a, opt_b,
opt_c, opt_d) {
// We want to allow implicit conversion of any type to number while avoiding
// compiler warnings about the type.
return /** @type {number} */ (opt_a) << 21 |
/** @type {number} */ (opt_b) << 14 |
/** @type {number} */ (opt_c) << 7 |
/** @type {number} */ (opt_d);
};
/**
* Gets the iOS version of the device. Only works for 2.0+.
* @return {number} The iOS version.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getIosVersion_ = function() {
var groups = this.IOS_VERSION_USERAGENT_REGEX_.exec(
window.navigator.userAgent) || [];
groups.shift();
return this.getVersion_.apply(this, groups);
};
/**
* Positions the bubble at the bottom of the viewport using an animated
* transition.
*/
google.bookmarkbubble.Bubble.prototype.setPosition = function() {
this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-out';
this.element_.style.WebkitTransform =
'translate3d(0,' + this.getVisibleYPosition_() + 'px,0)';
};
/**
* Destroys the bubble by removing its DOM nodes from the document, and
* remembers that it was dismissed.
* @private
*/
google.bookmarkbubble.Bubble.prototype.closeClickHandler_ = function() {
this.destroy();
this.rememberDismissal_();
};
/**
* Gets called after a while if the user ignores the bubble.
* @private
*/
google.bookmarkbubble.Bubble.prototype.autoDestruct_ = function() {
if (this.hasBeenDestroyed_) {
return;
}
this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-in';
this.element_.style.WebkitTransform =
'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)';
window.setTimeout(google.bind(this.destroy, this), 700);
};
/**
* Gets the y offset used to show the bubble (i.e., position it on-screen).
* @return {number} The y offset.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getVisibleYPosition_ = function() {
return this.isIpad_() ? window.pageYOffset + 17 :
window.pageYOffset - this.element_.offsetHeight + window.innerHeight - 17;
};
/**
* Gets the y offset used to hide the bubble (i.e., position it off-screen).
* @return {number} The y offset.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getHiddenYPosition_ = function() {
return this.isIpad_() ? window.pageYOffset - this.element_.offsetHeight :
window.pageYOffset + window.innerHeight;
};
/**
* The url of the app's bookmark icon.
* @type {string|undefined}
* @private
*/
google.bookmarkbubble.Bubble.prototype.iconUrl_;
/**
* Scrapes the document for a link element that specifies an Apple favicon and
* returns the icon url. Returns an empty data url if nothing can be found.
* @return {string} A url string.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getIconUrl_ = function() {
if (!this.iconUrl_) {
var link = this.getLink(this.REL_ICON_);
if (!link || !(this.iconUrl_ = link.href)) {
this.iconUrl_ = 'data:image/png;base64,';
}
}
return this.iconUrl_;
};
/**
* Gets the requested link tag if it exists.
* @param {string} rel The rel attribute of the link tag to get.
* @return {Element} The requested link tag or null.
*/
google.bookmarkbubble.Bubble.prototype.getLink = function(rel) {
rel = rel.toLowerCase();
var links = document.getElementsByTagName('link');
for (var i = 0; i < links.length; ++i) {
var currLink = /** @type {Element} */ (links[i]);
if (currLink.getAttribute('rel').toLowerCase() == rel) {
return currLink;
}
}
return null;
};
/**
* Creates the bubble and appends it to the document.
* @return {Element} The bubble element.
* @private
*/
google.bookmarkbubble.Bubble.prototype.build_ = function() {
var bubble = document.createElement('div');
var isIpad = this.isIpad_();
bubble.style.position = 'absolute';
bubble.style.zIndex = 1000;
bubble.style.width = '100%';
bubble.style.left = '0';
bubble.style.top = '0';
var bubbleInner = document.createElement('div');
bubbleInner.style.position = 'relative';
bubbleInner.style.width = '214px';
bubbleInner.style.margin = isIpad ? '0 0 0 82px' : '0 auto';
bubbleInner.style.border = '2px solid #fff';
bubbleInner.style.padding = '20px 20px 20px 10px';
bubbleInner.style.WebkitBorderRadius = '8px';
bubbleInner.style.WebkitBoxShadow = '0 0 8px rgba(0, 0, 0, 0.7)';
bubbleInner.style.WebkitBackgroundSize = '100% 8px';
bubbleInner.style.backgroundColor = '#b0c8ec';
bubbleInner.style.background = '#cddcf3 -webkit-gradient(linear, ' +
'left bottom, left top, ' + isIpad ?
'from(#cddcf3), to(#b3caed)) no-repeat top' :
'from(#b3caed), to(#cddcf3)) no-repeat bottom';
bubbleInner.style.font = '13px/17px sans-serif';
bubble.appendChild(bubbleInner);
// The "Add to Home Screen" text is intended to be the exact same text
// that is displayed in the menu of Mobile Safari.
if (this.getIosVersion_() >= this.getVersion_(4, 2)) {
bubbleInner.innerHTML = 'Install this web app on your phone: ' +
'tap on the arrow and then <b>\'Add to Home Screen\'</b>';
} else {
bubbleInner.innerHTML = 'Install this web app on your phone: ' +
'tap <b style="font-size:15px">+</b> and then ' +
'<b>\'Add to Home Screen\'</b>';
}
var icon = document.createElement('div');
icon.style['float'] = 'left';
icon.style.width = '55px';
icon.style.height = '55px';
icon.style.margin = '-2px 7px 3px 5px';
icon.style.background =
'#fff url(' + this.getIconUrl_() + ') no-repeat -1px -1px';
icon.style.WebkitBackgroundSize = '57px';
icon.style.WebkitBorderRadius = '10px';
icon.style.WebkitBoxShadow = '0 2px 5px rgba(0, 0, 0, 0.4)';
bubbleInner.insertBefore(icon, bubbleInner.firstChild);
var arrow = document.createElement('div');
arrow.style.backgroundImage = 'url(' + this.IMAGE_ARROW_DATA_URL_ + ')';
arrow.style.width = '25px';
arrow.style.height = '19px';
arrow.style.position = 'absolute';
arrow.style.left = '111px';
if (isIpad) {
arrow.style.WebkitTransform = 'rotate(180deg)';
arrow.style.top = '-19px';
} else {
arrow.style.bottom = '-19px';
}
bubbleInner.appendChild(arrow);
var close = document.createElement('a');
close.onclick = google.bind(this.closeClickHandler_, this);
close.style.position = 'absolute';
close.style.display = 'block';
close.style.top = '-3px';
close.style.right = '-3px';
close.style.width = '16px';
close.style.height = '16px';
close.style.border = '10px solid transparent';
close.style.background =
'url(' + this.IMAGE_CLOSE_DATA_URL_ + ') no-repeat';
bubbleInner.appendChild(close);
return bubble;
};
| JavaScript |
/*
Copyright 2010 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 Example of how to use the bookmark bubble. */
window.addEventListener('load', function() {
window.setTimeout(function() {
var bubble = new google.bookmarkbubble.Bubble();
var parameter = 'bmb=1';
bubble.hasHashParameter = function() {
return window.location.hash.indexOf(parameter) != -1;
};
bubble.setHashParameter = function() {
if (!this.hasHashParameter()) {
window.location.hash += parameter;
}
};
bubble.getViewportHeight = function() {
window.console.log('Example of how to override getViewportHeight.');
return window.innerHeight;
};
bubble.getViewportScrollY = function() {
window.console.log('Example of how to override getViewportScrollY.');
return window.pageYOffset;
};
bubble.registerScrollHandler = function(handler) {
window.console.log('Example of how to override registerScrollHandler.');
window.addEventListener('scroll', handler, false);
};
bubble.deregisterScrollHandler = function(handler) {
window.console.log('Example of how to override deregisterScrollHandler.');
window.removeEventListener('scroll', handler, false);
};
bubble.showIfAllowed();
}, 1000);
}, false);
| JavaScript |
jQuery.easing.jswing=jQuery.easing.swing;
jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,a,c,b,d){return jQuery.easing[jQuery.easing.def](e,a,c,b,d)},easeInQuad:function(e,a,c,b,d){return b*(a/=d)*a+c},easeOutQuad:function(e,a,c,b,d){return-b*(a/=d)*(a-2)+c},easeInOutQuad:function(e,a,c,b,d){if((a/=d/2)<1)return b/2*a*a+c;return-b/2*(--a*(a-2)-1)+c},easeInCubic:function(e,a,c,b,d){return b*(a/=d)*a*a+c},easeOutCubic:function(e,a,c,b,d){return b*((a=a/d-1)*a*a+1)+c},easeInOutCubic:function(e,a,c,b,d){if((a/=d/2)<1)return b/
2*a*a*a+c;return b/2*((a-=2)*a*a+2)+c},easeInQuart:function(e,a,c,b,d){return b*(a/=d)*a*a*a+c},easeOutQuart:function(e,a,c,b,d){return-b*((a=a/d-1)*a*a*a-1)+c},easeInOutQuart:function(e,a,c,b,d){if((a/=d/2)<1)return b/2*a*a*a*a+c;return-b/2*((a-=2)*a*a*a-2)+c},easeInQuint:function(e,a,c,b,d){return b*(a/=d)*a*a*a*a+c},easeOutQuint:function(e,a,c,b,d){return b*((a=a/d-1)*a*a*a*a+1)+c},easeInOutQuint:function(e,a,c,b,d){if((a/=d/2)<1)return b/2*a*a*a*a*a+c;return b/2*((a-=2)*a*a*a*a+2)+c},easeInSine:function(e,
a,c,b,d){return-b*Math.cos(a/d*(Math.PI/2))+b+c},easeOutSine:function(e,a,c,b,d){return b*Math.sin(a/d*(Math.PI/2))+c},easeInOutSine:function(e,a,c,b,d){return-b/2*(Math.cos(Math.PI*a/d)-1)+c},easeInExpo:function(e,a,c,b,d){return a==0?c:b*Math.pow(2,10*(a/d-1))+c},easeOutExpo:function(e,a,c,b,d){return a==d?c+b:b*(-Math.pow(2,-10*a/d)+1)+c},easeInOutExpo:function(e,a,c,b,d){if(a==0)return c;if(a==d)return c+b;if((a/=d/2)<1)return b/2*Math.pow(2,10*(a-1))+c;return b/2*(-Math.pow(2,-10*--a)+2)+c},
easeInCirc:function(e,a,c,b,d){return-b*(Math.sqrt(1-(a/=d)*a)-1)+c},easeOutCirc:function(e,a,c,b,d){return b*Math.sqrt(1-(a=a/d-1)*a)+c},easeInOutCirc:function(e,a,c,b,d){if((a/=d/2)<1)return-b/2*(Math.sqrt(1-a*a)-1)+c;return b/2*(Math.sqrt(1-(a-=2)*a)+1)+c},easeInElastic:function(e,a,c,b,d){e=1.70158;var f=0,g=b;if(a==0)return c;if((a/=d)==1)return c+b;f||(f=d*0.3);if(g<Math.abs(b)){g=b;e=f/4}else e=f/(2*Math.PI)*Math.asin(b/g);return-(g*Math.pow(2,10*(a-=1))*Math.sin((a*d-e)*2*Math.PI/f))+c},easeOutElastic:function(e,
a,c,b,d){e=1.70158;var f=0,g=b;if(a==0)return c;if((a/=d)==1)return c+b;f||(f=d*0.3);if(g<Math.abs(b)){g=b;e=f/4}else e=f/(2*Math.PI)*Math.asin(b/g);return g*Math.pow(2,-10*a)*Math.sin((a*d-e)*2*Math.PI/f)+b+c},easeInOutElastic:function(e,a,c,b,d){e=1.70158;var f=0,g=b;if(a==0)return c;if((a/=d/2)==2)return c+b;f||(f=d*0.3*1.5);if(g<Math.abs(b)){g=b;e=f/4}else e=f/(2*Math.PI)*Math.asin(b/g);if(a<1)return-0.5*g*Math.pow(2,10*(a-=1))*Math.sin((a*d-e)*2*Math.PI/f)+c;return g*Math.pow(2,-10*(a-=1))*Math.sin((a*
d-e)*2*Math.PI/f)*0.5+b+c},easeInBack:function(e,a,c,b,d,f){if(f==undefined)f=1.70158;return b*(a/=d)*a*((f+1)*a-f)+c},easeOutBack:function(e,a,c,b,d,f){if(f==undefined)f=1.70158;return b*((a=a/d-1)*a*((f+1)*a+f)+1)+c},easeInOutBack:function(e,a,c,b,d,f){if(f==undefined)f=1.70158;if((a/=d/2)<1)return b/2*a*a*(((f*=1.525)+1)*a-f)+c;return b/2*((a-=2)*a*(((f*=1.525)+1)*a+f)+2)+c},easeInBounce:function(e,a,c,b,d){return b-jQuery.easing.easeOutBounce(e,d-a,0,b,d)+c},easeOutBounce:function(e,a,c,b,d){return(a/=
d)<1/2.75?b*7.5625*a*a+c:a<2/2.75?b*(7.5625*(a-=1.5/2.75)*a+0.75)+c:a<2.5/2.75?b*(7.5625*(a-=2.25/2.75)*a+0.9375)+c:b*(7.5625*(a-=2.625/2.75)*a+0.984375)+c},easeInOutBounce:function(e,a,c,b,d){if(a<d/2)return jQuery.easing.easeInBounce(e,a*2,0,b,d)*0.5+c;return jQuery.easing.easeOutBounce(e,a*2-d,0,b,d)*0.5+b*0.5+c}});
/**
* Isotope v1.5.25
* An exquisite jQuery plugin for magical layouts
* http://isotope.metafizzy.co
*
* Commercial use requires one-time license fee
* http://metafizzy.co/#licenses
*
* Copyright 2012 David DeSandro / Metafizzy
*/
(function(a,b,c){"use strict";var d=a.document,e=a.Modernizr,f=function(a){return a.charAt(0).toUpperCase()+a.slice(1)},g="Moz Webkit O Ms".split(" "),h=function(a){var b=d.documentElement.style,c;if(typeof b[a]=="string")return a;a=f(a);for(var e=0,h=g.length;e<h;e++){c=g[e]+a;if(typeof b[c]=="string")return c}},i=h("transform"),j=h("transitionProperty"),k={csstransforms:function(){return!!i},csstransforms3d:function(){var a=!!h("perspective");if(a){var c=" -o- -moz- -ms- -webkit- -khtml- ".split(" "),d="@media ("+c.join("transform-3d),(")+"modernizr)",e=b("<style>"+d+"{#modernizr{height:3px}}"+"</style>").appendTo("head"),f=b('<div id="modernizr" />').appendTo("html");a=f.height()===3,f.remove(),e.remove()}return a},csstransitions:function(){return!!j}},l;if(e)for(l in k)e.hasOwnProperty(l)||e.addTest(l,k[l]);else{e=a.Modernizr={_version:"1.6ish: miniModernizr for Isotope"};var m=" ",n;for(l in k)n=k[l](),e[l]=n,m+=" "+(n?"":"no-")+l;b("html").addClass(m)}if(e.csstransforms){var o=e.csstransforms3d?{translate:function(a){return"translate3d("+a[0]+"px, "+a[1]+"px, 0) "},scale:function(a){return"scale3d("+a+", "+a+", 1) "}}:{translate:function(a){return"translate("+a[0]+"px, "+a[1]+"px) "},scale:function(a){return"scale("+a+") "}},p=function(a,c,d){var e=b.data(a,"isoTransform")||{},f={},g,h={},j;f[c]=d,b.extend(e,f);for(g in e)j=e[g],h[g]=o[g](j);var k=h.translate||"",l=h.scale||"",m=k+l;b.data(a,"isoTransform",e),a.style[i]=m};b.cssNumber.scale=!0,b.cssHooks.scale={set:function(a,b){p(a,"scale",b)},get:function(a,c){var d=b.data(a,"isoTransform");return d&&d.scale?d.scale:1}},b.fx.step.scale=function(a){b.cssHooks.scale.set(a.elem,a.now+a.unit)},b.cssNumber.translate=!0,b.cssHooks.translate={set:function(a,b){p(a,"translate",b)},get:function(a,c){var d=b.data(a,"isoTransform");return d&&d.translate?d.translate:[0,0]}}}var q,r;e.csstransitions&&(q={WebkitTransitionProperty:"webkitTransitionEnd",MozTransitionProperty:"transitionend",OTransitionProperty:"oTransitionEnd otransitionend",transitionProperty:"transitionend"}[j],r=h("transitionDuration"));var s=b.event,t=b.event.handle?"handle":"dispatch",u;s.special.smartresize={setup:function(){b(this).bind("resize",s.special.smartresize.handler)},teardown:function(){b(this).unbind("resize",s.special.smartresize.handler)},handler:function(a,b){var c=this,d=arguments;a.type="smartresize",u&&clearTimeout(u),u=setTimeout(function(){s[t].apply(c,d)},b==="execAsap"?0:100)}},b.fn.smartresize=function(a){return a?this.bind("smartresize",a):this.trigger("smartresize",["execAsap"])},b.Isotope=function(a,c,d){this.element=b(c),this._create(a),this._init(d)};var v=["width","height"],w=b(a);b.Isotope.settings={resizable:!0,layoutMode:"masonry",containerClass:"isotope",itemClass:"isotope-item",hiddenClass:"isotope-hidden",hiddenStyle:{opacity:0,scale:.001},visibleStyle:{opacity:1,scale:1},containerStyle:{position:"relative",overflow:"hidden"},animationEngine:"best-available",animationOptions:{queue:!1,duration:800},sortBy:"original-order",sortAscending:!0,resizesContainer:!0,transformsEnabled:!0,itemPositionDataEnabled:!1},b.Isotope.prototype={_create:function(a){this.options=b.extend({},b.Isotope.settings,a),this.styleQueue=[],this.elemCount=0;var c=this.element[0].style;this.originalStyle={};var d=v.slice(0);for(var e in this.options.containerStyle)d.push(e);for(var f=0,g=d.length;f<g;f++)e=d[f],this.originalStyle[e]=c[e]||"";this.element.css(this.options.containerStyle),this._updateAnimationEngine(),this._updateUsingTransforms();var h={"original-order":function(a,b){return b.elemCount++,b.elemCount},random:function(){return Math.random()}};this.options.getSortData=b.extend(this.options.getSortData,h),this.reloadItems(),this.offset={left:parseInt(this.element.css("padding-left")||0,10),top:parseInt(this.element.css("padding-top")||0,10)};var i=this;setTimeout(function(){i.element.addClass(i.options.containerClass)},0),this.options.resizable&&w.bind("smartresize.isotope",function(){i.resize()}),this.element.delegate("."+this.options.hiddenClass,"click",function(){return!1})},_getAtoms:function(a){var b=this.options.itemSelector,c=b?a.filter(b).add(a.find(b)):a,d={position:"absolute"};return c=c.filter(function(a,b){return b.nodeType===1}),this.usingTransforms&&(d.left=0,d.top=0),c.css(d).addClass(this.options.itemClass),this.updateSortData(c,!0),c},_init:function(a){this.$filteredAtoms=this._filter(this.$allAtoms),this._sort(),this.reLayout(a)},option:function(a){if(b.isPlainObject(a)){this.options=b.extend(!0,this.options,a);var c;for(var d in a)c="_update"+f(d),this[c]&&this[c]()}},_updateAnimationEngine:function(){var a=this.options.animationEngine.toLowerCase().replace(/[ _\-]/g,""),b;switch(a){case"css":case"none":b=!1;break;case"jquery":b=!0;break;default:b=!e.csstransitions}this.isUsingJQueryAnimation=b,this._updateUsingTransforms()},_updateTransformsEnabled:function(){this._updateUsingTransforms()},_updateUsingTransforms:function(){var a=this.usingTransforms=this.options.transformsEnabled&&e.csstransforms&&e.csstransitions&&!this.isUsingJQueryAnimation;a||(delete this.options.hiddenStyle.scale,delete this.options.visibleStyle.scale),this.getPositionStyles=a?this._translate:this._positionAbs},_filter:function(a){var b=this.options.filter===""?"*":this.options.filter;if(!b)return a;var c=this.options.hiddenClass,d="."+c,e=a.filter(d),f=e;if(b!=="*"){f=e.filter(b);var g=a.not(d).not(b).addClass(c);this.styleQueue.push({$el:g,style:this.options.hiddenStyle})}return this.styleQueue.push({$el:f,style:this.options.visibleStyle}),f.removeClass(c),a.filter(b)},updateSortData:function(a,c){var d=this,e=this.options.getSortData,f,g;a.each(function(){f=b(this),g={};for(var a in e)!c&&a==="original-order"?g[a]=b.data(this,"isotope-sort-data")[a]:g[a]=e[a](f,d);b.data(this,"isotope-sort-data",g)})},_sort:function(){var a=this.options.sortBy,b=this._getSorter,c=this.options.sortAscending?1:-1,d=function(d,e){var f=b(d,a),g=b(e,a);return f===g&&a!=="original-order"&&(f=b(d,"original-order"),g=b(e,"original-order")),(f>g?1:f<g?-1:0)*c};this.$filteredAtoms.sort(d)},_getSorter:function(a,c){return b.data(a,"isotope-sort-data")[c]},_translate:function(a,b){return{translate:[a,b]}},_positionAbs:function(a,b){return{left:a,top:b}},_pushPosition:function(a,b,c){b=Math.round(b+this.offset.left),c=Math.round(c+this.offset.top);var d=this.getPositionStyles(b,c);this.styleQueue.push({$el:a,style:d}),this.options.itemPositionDataEnabled&&a.data("isotope-item-position",{x:b,y:c})},layout:function(a,b){var c=this.options.layoutMode;this["_"+c+"Layout"](a);if(this.options.resizesContainer){var d=this["_"+c+"GetContainerSize"]();this.styleQueue.push({$el:this.element,style:d})}this._processStyleQueue(a,b),this.isLaidOut=!0},_processStyleQueue:function(a,c){var d=this.isLaidOut?this.isUsingJQueryAnimation?"animate":"css":"css",f=this.options.animationOptions,g=this.options.onLayout,h,i,j,k;i=function(a,b){b.$el[d](b.style,f)};if(this._isInserting&&this.isUsingJQueryAnimation)i=function(a,b){h=b.$el.hasClass("no-transition")?"css":d,b.$el[h](b.style,f)};else if(c||g||f.complete){var l=!1,m=[c,g,f.complete],n=this;j=!0,k=function(){if(l)return;var b;for(var c=0,d=m.length;c<d;c++)b=m[c],typeof b=="function"&&b.call(n.element,a,n);l=!0};if(this.isUsingJQueryAnimation&&d==="animate")f.complete=k,j=!1;else if(e.csstransitions){var o=0,p=this.styleQueue[0],s=p&&p.$el,t;while(!s||!s.length){t=this.styleQueue[o++];if(!t)return;s=t.$el}var u=parseFloat(getComputedStyle(s[0])[r]);u>0&&(i=function(a,b){b.$el[d](b.style,f).one(q,k)},j=!1)}}b.each(this.styleQueue,i),j&&k(),this.styleQueue=[]},resize:function(){this["_"+this.options.layoutMode+"ResizeChanged"]()&&this.reLayout()},reLayout:function(a){this["_"+this.options.layoutMode+"Reset"](),this.layout(this.$filteredAtoms,a)},addItems:function(a,b){var c=this._getAtoms(a);this.$allAtoms=this.$allAtoms.add(c),b&&b(c)},insert:function(a,b){this.element.append(a);var c=this;this.addItems(a,function(a){var d=c._filter(a);c._addHideAppended(d),c._sort(),c.reLayout(),c._revealAppended(d,b)})},appended:function(a,b){var c=this;this.addItems(a,function(a){c._addHideAppended(a),c.layout(a),c._revealAppended(a,b)})},_addHideAppended:function(a){this.$filteredAtoms=this.$filteredAtoms.add(a),a.addClass("no-transition"),this._isInserting=!0,this.styleQueue.push({$el:a,style:this.options.hiddenStyle})},_revealAppended:function(a,b){var c=this;setTimeout(function(){a.removeClass("no-transition"),c.styleQueue.push({$el:a,style:c.options.visibleStyle}),c._isInserting=!1,c._processStyleQueue(a,b)},10)},reloadItems:function(){this.$allAtoms=this._getAtoms(this.element.children())},remove:function(a,b){this.$allAtoms=this.$allAtoms.not(a),this.$filteredAtoms=this.$filteredAtoms.not(a);var c=this,d=function(){a.remove(),b&&b.call(c.element)};a.filter(":not(."+this.options.hiddenClass+")").length?(this.styleQueue.push({$el:a,style:this.options.hiddenStyle}),this._sort(),this.reLayout(d)):d()},shuffle:function(a){this.updateSortData(this.$allAtoms),this.options.sortBy="random",this._sort(),this.reLayout(a)},destroy:function(){var a=this.usingTransforms,b=this.options;this.$allAtoms.removeClass(b.hiddenClass+" "+b.itemClass).each(function(){var b=this.style;b.position="",b.top="",b.left="",b.opacity="",a&&(b[i]="")});var c=this.element[0].style;for(var d in this.originalStyle)c[d]=this.originalStyle[d];this.element.unbind(".isotope").undelegate("."+b.hiddenClass,"click").removeClass(b.containerClass).removeData("isotope"),w.unbind(".isotope")},_getSegments:function(a){var b=this.options.layoutMode,c=a?"rowHeight":"columnWidth",d=a?"height":"width",e=a?"rows":"cols",g=this.element[d](),h,i=this.options[b]&&this.options[b][c]||this.$filteredAtoms["outer"+f(d)](!0)||g;h=Math.floor(g/i),h=Math.max(h,1),this[b][e]=h,this[b][c]=i},_checkIfSegmentsChanged:function(a){var b=this.options.layoutMode,c=a?"rows":"cols",d=this[b][c];return this._getSegments(a),this[b][c]!==d},_masonryReset:function(){this.masonry={},this._getSegments();var a=this.masonry.cols;this.masonry.colYs=[];while(a--)this.masonry.colYs.push(0)},_masonryLayout:function(a){var c=this,d=c.masonry;a.each(function(){var a=b(this),e=Math.ceil(a.outerWidth(!0)/d.columnWidth);e=Math.min(e,d.cols);if(e===1)c._masonryPlaceBrick(a,d.colYs);else{var f=d.cols+1-e,g=[],h,i;for(i=0;i<f;i++)h=d.colYs.slice(i,i+e),g[i]=Math.max.apply(Math,h);c._masonryPlaceBrick(a,g)}})},_masonryPlaceBrick:function(a,b){var c=Math.min.apply(Math,b),d=0;for(var e=0,f=b.length;e<f;e++)if(b[e]===c){d=e;break}var g=this.masonry.columnWidth*d,h=c;this._pushPosition(a,g,h);var i=c+a.outerHeight(!0),j=this.masonry.cols+1-f;for(e=0;e<j;e++)this.masonry.colYs[d+e]=i},_masonryGetContainerSize:function(){var a=Math.max.apply(Math,this.masonry.colYs);return{height:a}},_masonryResizeChanged:function(){return this._checkIfSegmentsChanged()},_fitRowsReset:function(){this.fitRows={x:0,y:0,height:0}},_fitRowsLayout:function(a){var c=this,d=this.element.width(),e=this.fitRows;a.each(function(){var a=b(this),f=a.outerWidth(!0),g=a.outerHeight(!0);e.x!==0&&f+e.x>d&&(e.x=0,e.y=e.height),c._pushPosition(a,e.x,e.y),e.height=Math.max(e.y+g,e.height),e.x+=f})},_fitRowsGetContainerSize:function(){return{height:this.fitRows.height}},_fitRowsResizeChanged:function(){return!0},_cellsByRowReset:function(){this.cellsByRow={index:0},this._getSegments(),this._getSegments(!0)},_cellsByRowLayout:function(a){var c=this,d=this.cellsByRow;a.each(function(){var a=b(this),e=d.index%d.cols,f=Math.floor(d.index/d.cols),g=(e+.5)*d.columnWidth-a.outerWidth(!0)/2,h=(f+.5)*d.rowHeight-a.outerHeight(!0)/2;c._pushPosition(a,g,h),d.index++})},_cellsByRowGetContainerSize:function(){return{height:Math.ceil(this.$filteredAtoms.length/this.cellsByRow.cols)*this.cellsByRow.rowHeight+this.offset.top}},_cellsByRowResizeChanged:function(){return this._checkIfSegmentsChanged()},_straightDownReset:function(){this.straightDown={y:0}},_straightDownLayout:function(a){var c=this;a.each(function(a){var d=b(this);c._pushPosition(d,0,c.straightDown.y),c.straightDown.y+=d.outerHeight(!0)})},_straightDownGetContainerSize:function(){return{height:this.straightDown.y}},_straightDownResizeChanged:function(){return!0},_masonryHorizontalReset:function(){this.masonryHorizontal={},this._getSegments(!0);var a=this.masonryHorizontal.rows;this.masonryHorizontal.rowXs=[];while(a--)this.masonryHorizontal.rowXs.push(0)},_masonryHorizontalLayout:function(a){var c=this,d=c.masonryHorizontal;a.each(function(){var a=b(this),e=Math.ceil(a.outerHeight(!0)/d.rowHeight);e=Math.min(e,d.rows);if(e===1)c._masonryHorizontalPlaceBrick(a,d.rowXs);else{var f=d.rows+1-e,g=[],h,i;for(i=0;i<f;i++)h=d.rowXs.slice(i,i+e),g[i]=Math.max.apply(Math,h);c._masonryHorizontalPlaceBrick(a,g)}})},_masonryHorizontalPlaceBrick:function(a,b){var c=Math.min.apply(Math,b),d=0;for(var e=0,f=b.length;e<f;e++)if(b[e]===c){d=e;break}var g=c,h=this.masonryHorizontal.rowHeight*d;this._pushPosition(a,g,h);var i=c+a.outerWidth(!0),j=this.masonryHorizontal.rows+1-f;for(e=0;e<j;e++)this.masonryHorizontal.rowXs[d+e]=i},_masonryHorizontalGetContainerSize:function(){var a=Math.max.apply(Math,this.masonryHorizontal.rowXs);return{width:a}},_masonryHorizontalResizeChanged:function(){return this._checkIfSegmentsChanged(!0)},_fitColumnsReset:function(){this.fitColumns={x:0,y:0,width:0}},_fitColumnsLayout:function(a){var c=this,d=this.element.height(),e=this.fitColumns;a.each(function(){var a=b(this),f=a.outerWidth(!0),g=a.outerHeight(!0);e.y!==0&&g+e.y>d&&(e.x=e.width,e.y=0),c._pushPosition(a,e.x,e.y),e.width=Math.max(e.x+f,e.width),e.y+=g})},_fitColumnsGetContainerSize:function(){return{width:this.fitColumns.width}},_fitColumnsResizeChanged:function(){return!0},_cellsByColumnReset:function(){this.cellsByColumn={index:0},this._getSegments(),this._getSegments(!0)},_cellsByColumnLayout:function(a){var c=this,d=this.cellsByColumn;a.each(function(){var a=b(this),e=Math.floor(d.index/d.rows),f=d.index%d.rows,g=(e+.5)*d.columnWidth-a.outerWidth(!0)/2,h=(f+.5)*d.rowHeight-a.outerHeight(!0)/2;c._pushPosition(a,g,h),d.index++})},_cellsByColumnGetContainerSize:function(){return{width:Math.ceil(this.$filteredAtoms.length/this.cellsByColumn.rows)*this.cellsByColumn.columnWidth}},_cellsByColumnResizeChanged:function(){return this._checkIfSegmentsChanged(!0)},_straightAcrossReset:function(){this.straightAcross={x:0}},_straightAcrossLayout:function(a){var c=this;a.each(function(a){var d=b(this);c._pushPosition(d,c.straightAcross.x,0),c.straightAcross.x+=d.outerWidth(!0)})},_straightAcrossGetContainerSize:function(){return{width:this.straightAcross.x}},_straightAcrossResizeChanged:function(){return!0}},b.fn.imagesLoaded=function(a){function h(){a.call(c,d)}function i(a){var c=a.target;c.src!==f&&b.inArray(c,g)===-1&&(g.push(c),--e<=0&&(setTimeout(h),d.unbind(".imagesLoaded",i)))}var c=this,d=c.find("img").add(c.filter("img")),e=d.length,f="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",g=[];return e||h(),d.bind("load.imagesLoaded error.imagesLoaded",i).each(function(){var a=this.src;this.src=f,this.src=a}),c};var x=function(b){a.console&&a.console.error(b)};b.fn.isotope=function(a,c){if(typeof a=="string"){var d=Array.prototype.slice.call(arguments,1);this.each(function(){var c=b.data(this,"isotope");if(!c){x("cannot call methods on isotope prior to initialization; attempted to call method '"+a+"'");return}if(!b.isFunction(c[a])||a.charAt(0)==="_"){x("no such method '"+a+"' for isotope instance");return}c[a].apply(c,d)})}else this.each(function(){var d=b.data(this,"isotope");d?(d.option(a),d._init(c)):b.data(this,"isotope",new b.Isotope(a,this,c))});return this}})(window,jQuery);
/*
* Swiper 1.9.4 - Mobile Touch Slider
* http://www.idangero.us/sliders/swiper/
*
* Copyright 2012-2013, Vladimir Kharlampidi
* The iDangero.us
* http://www.idangero.us/
*
* Licensed under GPL & MIT
*
* Updated on: May 23, 2013
*/
var Swiper = function (selector, params, callback) {
/*=========================
A little bit dirty but required part for IE8 and old FF support
===========================*/
if (!window.addEventListener) {
if (!window.Element)
Element = function () { };
Element.prototype.addEventListener = HTMLDocument.prototype.addEventListener = addEventListener = function (type, listener, useCapture) { this.attachEvent('on' + type, listener); }
Element.prototype.removeEventListener = HTMLDocument.prototype.removeEventListener = removeEventListener = function (type, listener, useCapture) { this.detachEvent('on' + type, listener); }
}
if (document.body.__defineGetter__) {
if (HTMLElement) {
var element = HTMLElement.prototype;
if (element.__defineGetter__)
element.__defineGetter__("outerHTML", function () { return new XMLSerializer().serializeToString(this); } );
}
}
if (!window.getComputedStyle) {
window.getComputedStyle = function (el, pseudo) {
this.el = el;
this.getPropertyValue = function (prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
/* End Of Polyfills*/
if(!(selector.nodeType))
if (!document.querySelectorAll||document.querySelectorAll(selector).length==0) return;
function dQ(s) {
return document.querySelectorAll(s)
}
var _this = this
_this.touches = {};
_this.positions = {
current : 0
};
_this.id = (new Date()).getTime();
_this.container = (selector.nodeType) ? selector : dQ(selector)[0];
_this.times = {};
_this.isTouched = false;
_this.realIndex = 0;
_this.activeSlide = 0;
_this.activeIndex = 0;
_this.previousSlide = null;
_this.previousIndex = null;
_this.langDirection = window.getComputedStyle(_this.container, null).getPropertyValue('direction')
/*=========================
New Support Object
===========================*/
_this.support = {
touch : _this.isSupportTouch(),
threeD : _this.isSupport3D(),
transitions : _this.isSupportTransitions()
}
//For fallback with older versions
_this.use3D = _this.support.threeD;
/*=========================
Default Parameters
===========================*/
var defaults = {
mode : 'horizontal',
ratio : 1,
speed : 300,
freeMode : false,
freeModeFluid : false,
slidesPerSlide : 1,
slidesPerGroup : 1,
simulateTouch : true,
followFinger : true,
shortSwipes : true,
moveStartThreshold:false,
autoPlay:false,
onlyExternal : false,
createPagination : true,
pagination : false,
resistance : true,
nopeek : false,
scrollContainer : false,
fluidContainerWidth: false,
preventLinks : true,
preventClassNoSwiping : true,
initialSlide: 0,
keyboardControl: false,
mousewheelControl : false,
resizeEvent : 'auto', //or 'resize' or 'orientationchange'
useCSS3Transforms : true,
queueStartCallbacks : false,
queueEndCallbacks : false,
//Namespace
slideElement : 'div',
slideClass : 'swiper-slide',
wrapperClass : 'swiper-wrapper',
paginationClass: 'swiper-pagination-switch' ,
paginationActiveClass : 'swiper-active-switch'
}
params = params || {};
for (var prop in defaults) {
if (! (prop in params)) {
params[prop] = defaults[prop]
}
}
_this.params = params;
if (params.scrollContainer) {
params.freeMode = true;
params.freeModeFluid = true;
}
var _widthFromCSS = false
if (params.slidesPerSlide=='auto') {
_widthFromCSS = true;
params.slidesPerSlide = 1;
}
//Default Vars
var wrapper, isHorizontal,
slideSize, numOfSlides, wrapperSize, direction, isScrolling, containerSize;
//Define wrapper
for (var i = _this.container.childNodes.length - 1; i >= 0; i--) {
if (_this.container.childNodes[i].className) {
var _wrapperClasses = _this.container.childNodes[i].className.split(' ')
for (var j = 0; j < _wrapperClasses.length; j++) {
if (_wrapperClasses[j]===params.wrapperClass) {
wrapper = _this.container.childNodes[i]
}
};
}
};
_this.wrapper = wrapper;
//Mode
isHorizontal = params.mode == 'horizontal';
//Define Touch Events
_this.touchEvents = {
touchStart : _this.support.touch || !params.simulateTouch ? 'touchstart' : (_this.ie10 ? 'MSPointerDown' : 'mousedown'),
touchMove : _this.support.touch || !params.simulateTouch ? 'touchmove' : (_this.ie10 ? 'MSPointerMove' : 'mousemove'),
touchEnd : _this.support.touch || !params.simulateTouch ? 'touchend' : (_this.ie10 ? 'MSPointerUp' : 'mouseup')
};
/*=========================
Slide API
===========================*/
_this._extendSwiperSlide = function (el) {
el.append = function () {
_this.wrapper.appendChild(el);
_this.reInit();
return el;
}
el.prepend = function () {
_this.wrapper.insertBefore(el, _this.wrapper.firstChild)
_this.reInit();
return el;
}
el.insertAfter = function (index) {
if(typeof index === 'undefined') return false;
var beforeSlide = _this.slides[index+1]
_this.wrapper.insertBefore(el, beforeSlide)
_this.reInit();
return el;
}
el.clone = function () {
return _this._extendSwiperSlide(el.cloneNode(true))
}
el.remove = function () {
_this.wrapper.removeChild(el);
_this.reInit()
}
el.html = function (html) {
if (typeof html === 'undefined') {
return el.innerHTML
}
else {
el.innerHTML = html;
return el;
}
}
el.index = function () {
var index
for (var i = _this.slides.length - 1; i >= 0; i--) {
if(el==_this.slides[i]) index = i
};
return index;
}
el.isActive = function () {
if (el.index() == _this.activeIndex) return true;
else return false;
}
if (!el.swiperSlideDataStorage) el.swiperSlideDataStorage={};
el.getData = function (name) {
return el.swiperSlideDataStorage[name]
}
el.setData = function (name, value) {
el.swiperSlideDataStorage[name] = value;
return el;
}
el.data = function (name, value) {
if (!value) {
return el.getAttribute('data-'+name);
}
else {
el.setAttribute('data-'+name,value);
return el;
}
}
return el;
}
//Calculate information about slides
_this._calcSlides = function () {
var oldNumber = _this.slides ? _this.slides.length : false;
_this.slides = []
for (var i = 0; i < _this.wrapper.childNodes.length; i++) {
if (_this.wrapper.childNodes[i].className) {
var _slideClasses = _this.wrapper.childNodes[i].className.split(' ')
for (var j = 0; j < _slideClasses.length; j++) {
if(_slideClasses[j]===params.slideClass) _this.slides.push(_this.wrapper.childNodes[i])
};
}
};
for (var i = _this.slides.length - 1; i >= 0; i--) {
_this._extendSwiperSlide(_this.slides[i]);
};
if (!oldNumber) return;
if(oldNumber!=_this.slides.length && _this.createPagination) {
// Number of slides has been changed
_this.createPagination();
_this.callPlugins('numberOfSlidesChanged')
}
/*
if (_this.langDirection=='rtl') {
for (var i = 0; i < _this.slides.length; i++) {
_this.slides[i].style.float="right"
};
}
*/
}
_this._calcSlides();
//Create Slide
_this.createSlide = function (html, slideClassList, el) {
var slideClassList = slideClassList || _this.params.slideClass;
var el = el||params.slideElement;
var newSlide = document.createElement(el)
newSlide.innerHTML = html||'';
newSlide.className = slideClassList;
return _this._extendSwiperSlide(newSlide);
}
//Append Slide
_this.appendSlide = function (html, slideClassList, el) {
if (!html) return;
if (html.nodeType) {
return _this._extendSwiperSlide(html).append()
}
else {
return _this.createSlide(html, slideClassList, el).append()
}
}
_this.prependSlide = function (html, slideClassList, el) {
if (!html) return;
if (html.nodeType) {
return _this._extendSwiperSlide(html).prepend()
}
else {
return _this.createSlide(html, slideClassList, el).prepend()
}
}
_this.insertSlideAfter = function (index, html, slideClassList, el) {
if (!index) return false;
if (html.nodeType) {
return _this._extendSwiperSlide(html).insertAfter(index)
}
else {
return _this.createSlide(html, slideClassList, el).insertAfter(index)
}
}
_this.removeSlide = function (index) {
if (_this.slides[index]) {
_this.slides[index].remove()
return true;
}
else return false;
}
_this.removeLastSlide = function () {
if (_this.slides.length>0) {
_this.slides[ (_this.slides.length-1) ].remove();
return true
}
else {
return false
}
}
_this.removeAllSlides = function () {
for (var i = _this.slides.length - 1; i >= 0; i--) {
_this.slides[i].remove()
};
}
_this.getSlide = function (index) {
return _this.slides[index]
}
_this.getLastSlide = function () {
return _this.slides[ _this.slides.length-1 ]
}
_this.getFirstSlide = function () {
return _this.slides[0]
}
//Currently Active Slide
_this.currentSlide = function () {
return _this.slides[_this.activeIndex]
}
/*=========================
Find All Plugins
!!! Plugins API is in beta !!!
===========================*/
var _plugins = [];
for (var plugin in _this.plugins) {
if (params[plugin]) {
var p = _this.plugins[plugin](_this, params[plugin])
if (p)
_plugins.push( p )
}
}
_this.callPlugins = function(method, args) {
if (!args) args = {}
for (var i=0; i<_plugins.length; i++) {
if (method in _plugins[i]) {
_plugins[i][method](args);
}
}
}
/*=========================
WP8 Fix
===========================*/
if (_this.ie10 && !params.onlyExternal) {
if (isHorizontal) _this.wrapper.classList.add('swiper-wp8-horizontal')
else _this.wrapper.classList.add('swiper-wp8-vertical')
}
/*=========================
Loop
===========================*/
if (params.loop) {
(function(){
numOfSlides = _this.slides.length;
if (_this.slides.length==0) return;
var slideFirstHTML = '';
var slideLastHTML = '';
//Grab First Slides
for (var i=0; i<params.slidesPerSlide; i++) {
slideFirstHTML+=_this.slides[i].outerHTML
}
//Grab Last Slides
for (var i=numOfSlides-params.slidesPerSlide; i<numOfSlides; i++) {
slideLastHTML+=_this.slides[i].outerHTML
}
wrapper.innerHTML = slideLastHTML + wrapper.innerHTML + slideFirstHTML;
_this._calcSlides()
_this.callPlugins('onCreateLoop');
})();
}
//Init Function
var firstInit = false;
//ReInitizize function. Good to use after dynamically changes of Swiper, like after add/remove slides
_this.reInit = function () {
_this.init(true)
}
_this.init = function(reInit) {
var _width = window.getComputedStyle(_this.container, null).getPropertyValue('width')
var _height = window.getComputedStyle(_this.container, null).getPropertyValue('height')
var newWidth = parseInt(_width,10);
var newHeight = parseInt(_height,10);
//IE8 Fixes
if(isNaN(newWidth) || _width.indexOf('%')>0) {
newWidth = _this.container.offsetWidth - parseInt(window.getComputedStyle(_this.container, null).getPropertyValue('padding-left'),10) - parseInt(window.getComputedStyle(_this.container, null).getPropertyValue('padding-right'),10)
}
if(isNaN(newHeight) || _height.indexOf('%')>0) {
newHeight = _this.container.offsetHeight - parseInt(window.getComputedStyle(_this.container, null).getPropertyValue('padding-top'),10) - parseInt(window.getComputedStyle(_this.container, null).getPropertyValue('padding-bottom'),10)
}
if (!reInit) {
if (_this.width==newWidth && _this.height==newHeight) return
}
if (reInit || firstInit) {
_this._calcSlides();
if (params.pagination) {
_this.updatePagination()
}
}
_this.width = newWidth;
_this.height = newHeight;
var dividerVertical = isHorizontal ? 1 : params.slidesPerSlide,
dividerHorizontal = isHorizontal ? params.slidesPerSlide : 1,
slideWidth, slideHeight, wrapperWidth, wrapperHeight;
numOfSlides = _this.slides.length
if (!params.scrollContainer) {
if (!_widthFromCSS) {
slideWidth = _this.width/dividerHorizontal;
slideHeight = _this.height/dividerVertical;
}
else {
slideWidth = _this.slides[0].offsetWidth;
slideHeight = _this.slides[0].offsetHeight;
}
containerSize = isHorizontal ? _this.width : _this.height;
slideSize = isHorizontal ? slideWidth : slideHeight;
wrapperWidth = isHorizontal ? numOfSlides * slideWidth : _this.width;
wrapperHeight = isHorizontal ? _this.height : numOfSlides*slideHeight;
if (_widthFromCSS) {
//Re-Calc sps for pagination
params.slidesPerSlide = Math.round(containerSize/slideSize)
}
}
else {
//Unset dimensions in vertical scroll container mode to recalculate slides
if (!isHorizontal) {
wrapper.style.width='';
wrapper.style.height='';
_this.slides[0].style.width='';
_this.slides[0].style.height='';
}
if (params.fluidContainerWidth && isHorizontal) {
slideWidth = 0;
slideHeight = 0;
for (var i=0; i<_this.slides[0].children.length; i++) {
slideWidth += _this.slides[0].children[i].offsetWidth;
if (_this.slides[0].children[i].offsetHeight > slideHeight) {
slideHeight = _this.slides[0].children[i].offsetHeight;
}
}
}
else {
slideWidth = _this.slides[0].offsetWidth;
slideHeight = _this.slides[0].offsetHeight;
}
containerSize = isHorizontal ? _this.width : _this.height;
slideSize = isHorizontal ? slideWidth : slideHeight;
wrapperWidth = slideWidth;
wrapperHeight = slideHeight;
}
wrapperSize = isHorizontal ? wrapperWidth : wrapperHeight;
for (var i=0; i<_this.slides.length; i++ ) {
var el = _this.slides[i];
if (!_widthFromCSS) {
el.style.width=slideWidth+"px"
el.style.height=slideHeight+"px"
}
if (params.onSlideInitialize) {
params.onSlideInitialize(_this, el);
}
}
wrapper.style.width = wrapperWidth+"px";
wrapper.style.height = wrapperHeight+"px";
// Set Initial Slide Position
if(params.initialSlide > 0 && params.initialSlide < numOfSlides && !firstInit) {
_this.realIndex = _this.activeIndex = params.initialSlide;
if (params.loop) {
_this.activeIndex = _this.realIndex-params.slidesPerSlide;
}
//Legacy
_this.activeSlide = _this.activeIndex;
//--
if (isHorizontal) {
_this.positions.current = -params.initialSlide * slideWidth;
_this.setTransform( _this.positions.current, 0, 0);
}
else {
_this.positions.current = -params.initialSlide * slideHeight;
_this.setTransform( 0, _this.positions.current, 0);
}
}
if (!firstInit) _this.callPlugins('onFirstInit');
else _this.callPlugins('onInit');
firstInit = true;
}
_this.init()
//Get Max And Min Positions
function maxPos() {
var a = (wrapperSize - containerSize);
if (params.loop) a = a - containerSize;
if (params.scrollContainer) {
a = slideSize - containerSize;
if (a<0) a = 0;
}
if (params.slidesPerSlide > _this.slides.length) a = 0;
return a;
}
function minPos() {
var a = 0;
if (params.loop) a = containerSize;
return a;
}
/*=========================
Pagination
===========================*/
_this.updatePagination = function() {
if (_this.slides.length<2) return;
var activeSwitch = dQ(params.pagination+' .'+params.paginationActiveClass)
if(!activeSwitch) return
for (var i=0; i < activeSwitch.length; i++) {
activeSwitch.item(i).className = params.paginationClass
}
var pagers = dQ(params.pagination+' .'+params.paginationClass).length;
var minPagerIndex = params.loop ? _this.realIndex-params.slidesPerSlide : _this.realIndex;
var maxPagerIndex = minPagerIndex + (params.slidesPerSlide-1);
for (var i = minPagerIndex; i <= maxPagerIndex; i++ ) {
var j = i;
if (j>=pagers) j=j-pagers;
if (j<0) j = pagers + j;
if (j<numOfSlides) {
dQ(params.pagination+' .'+params.paginationClass).item( j ).className = params.paginationClass+' '+params.paginationActiveClass
}
if (i==minPagerIndex) dQ(params.pagination+' .'+params.paginationClass).item( j ).className+=' swiper-activeslide-switch'
}
}
_this.createPagination = function () {
if (params.pagination && params.createPagination) {
var paginationHTML = "";
var numOfSlides = _this.slides.length;
var numOfButtons = params.loop ? numOfSlides - params.slidesPerSlide*2 : numOfSlides;
for (var i = 0; i < numOfButtons; i++) {
paginationHTML += '<span class="'+params.paginationClass+'"></span>'
}
dQ(params.pagination)[0].innerHTML = paginationHTML
_this.updatePagination()
_this.callPlugins('onCreatePagination');
}
}
_this.createPagination();
//Window Resize Re-init
_this.resizeEvent = params.resizeEvent==='auto'
? ('onorientationchange' in window) ? 'orientationchange' : 'resize'
: params.resizeEvent
_this.resizeFix = function(){
_this.callPlugins('beforeResizeFix');
_this.init()
//To fix translate value
if (!params.scrollContainer)
_this.swipeTo(_this.activeIndex, 0, false)
else {
var pos = isHorizontal ? _this.getTranslate('x') : _this.getTranslate('y')
if (pos < -maxPos()) {
var x = isHorizontal ? -maxPos() : 0;
var y = isHorizontal ? 0 : -maxPos();
_this.setTransition(0)
_this.setTransform(x,y,0)
}
}
_this.callPlugins('afterResizeFix');
}
if (!params.disableAutoResize) {
//Check for resize event
window.addEventListener(_this.resizeEvent, _this.resizeFix, false)
}
/*==========================================
Autoplay
============================================*/
var autoPlay
_this.startAutoPlay = function() {
if (params.autoPlay && !params.loop) {
autoPlay = setInterval(function(){
var newSlide = _this.realIndex + 1
if ( newSlide == numOfSlides) newSlide = 0
if ( newSlide == numOfSlides - params.slidesPerSlide + 1) newSlide=0;
_this.swipeTo(newSlide)
}, params.autoPlay)
}
else if (params.autoPlay && params.loop) {
autoPlay = setInterval(function(){
_this.fixLoop();
_this.swipeNext(true)
}, params.autoPlay)
}
_this.callPlugins('onAutoPlayStart');
}
_this.stopAutoPlay = function() {
if (autoPlay)
clearInterval(autoPlay)
_this.callPlugins('onAutoPlayStop');
}
if (params.autoPlay) {
_this.startAutoPlay()
}
/*==========================================
Event Listeners
============================================*/
if (!_this.ie10) {
if (_this.support.touch) {
wrapper.addEventListener('touchstart', onTouchStart, false);
wrapper.addEventListener('touchmove', onTouchMove, false);
wrapper.addEventListener('touchend', onTouchEnd, false);
}
if (params.simulateTouch) {
wrapper.addEventListener('mousedown', onTouchStart, false);
document.addEventListener('mousemove', onTouchMove, false);
document.addEventListener('mouseup', onTouchEnd, false);
}
}
else {
wrapper.addEventListener(_this.touchEvents.touchStart, onTouchStart, false);
document.addEventListener(_this.touchEvents.touchMove, onTouchMove, false);
document.addEventListener(_this.touchEvents.touchEnd, onTouchEnd, false);
}
//Remove Events
_this.destroy = function(removeResizeFix){
removeResizeFix = removeResizeFix===false ? removeResizeFix : removeResizeFix || true
if (removeResizeFix) {
window.removeEventListener(_this.resizeEvent, _this.resizeFix, false);
}
if (_this.ie10) {
wrapper.removeEventListener(_this.touchEvents.touchStart, onTouchStart, false);
document.removeEventListener(_this.touchEvents.touchMove, onTouchMove, false);
document.removeEventListener(_this.touchEvents.touchEnd, onTouchEnd, false);
}
else {
if (_this.support.touch) {
wrapper.removeEventListener('touchstart', onTouchStart, false);
wrapper.removeEventListener('touchmove', onTouchMove, false);
wrapper.removeEventListener('touchend', onTouchEnd, false);
}
wrapper.removeEventListener('mousedown', onTouchStart, false);
document.removeEventListener('mousemove', onTouchMove, false);
document.removeEventListener('mouseup', onTouchEnd, false);
}
if (params.keyboardControl) {
document.removeEventListener('keydown', handleKeyboardKeys, false);
}
if (params.mousewheelControl && _this._wheelEvent) {
_this.container.removeEventListener(_this._wheelEvent, handleMousewheel, false);
}
if (params.autoPlay) {
_this.stopAutoPlay()
}
_this.callPlugins('onDestroy');
}
/*=========================
Prevent Links
===========================*/
_this.allowLinks = true;
if (params.preventLinks) {
var links = _this.container.querySelectorAll('a')
for (var i=0; i<links.length; i++) {
links[i].addEventListener('click', preventClick, false)
}
}
function preventClick(e) {
if (!_this.allowLinks) (e.preventDefault) ? e.preventDefault() : e.returnValue = false;
}
/*==========================================
Keyboard Control
============================================*/
if (params.keyboardControl) {
function handleKeyboardKeys (e) {
var kc = e.keyCode || e.charCode;
if (isHorizontal) {
if (kc==37 || kc==39) e.preventDefault();
if (kc == 39) _this.swipeNext()
if (kc == 37) _this.swipePrev()
}
else {
if (kc==38 || kc==40) e.preventDefault();
if (kc == 40) _this.swipeNext()
if (kc == 38) _this.swipePrev()
}
}
document.addEventListener('keydown',handleKeyboardKeys, false);
}
/*==========================================
Mousewheel Control. Beta!
============================================*/
// detect available wheel event
_this._wheelEvent = false;
if (params.mousewheelControl) {
if ( document.onmousewheel !== undefined ) {
_this._wheelEvent = "mousewheel"
}
try {
WheelEvent("wheel");
_this._wheelEvent = "wheel";
} catch (e) {}
if ( !_this._wheelEvent ) {
_this._wheelEvent = "DOMMouseScroll";
}
function handleMousewheel (e) {
var we = _this._wheelEvent;
var delta;
//Opera & IE
if (e.detail) delta = -e.detail;
//WebKits
else if (we == 'mousewheel') delta = e.wheelDelta;
//Old FireFox
else if (we == 'DOMMouseScroll') delta = -e.detail;
//New FireFox
else if (we == 'wheel') {
delta = Math.abs(e.deltaX)>Math.abs(e.deltaY) ? - e.deltaX : - e.deltaY;
}
if (!params.freeMode) {
if(delta<0) _this.swipeNext()
else _this.swipePrev()
}
else {
//Freemode or scrollContainer:
var currentTransform =isHorizontal ? _this.getTranslate('x') : _this.getTranslate('y')
var x,y;
if (isHorizontal) {
x = _this.getTranslate('x') + delta;
y = _this.getTranslate('y');
if (x>0) x = 0;
if (x<-maxPos()) x = -maxPos();
}
else {
x = _this.getTranslate('x');
y = _this.getTranslate('y')+delta;
if (y>0) y = 0;
if (y<-maxPos()) y = -maxPos();
}
_this.setTransition(0)
_this.setTransform(x,y,0)
}
if(e.preventDefault) e.preventDefault();
else e.returnValue = false;
return false;
}
if (_this._wheelEvent) {
_this.container.addEventListener(_this._wheelEvent, handleMousewheel, false);
}
}
/*=========================
Grab Cursor
===========================*/
if (params.grabCursor) {
_this.container.style.cursor = 'move';
_this.container.style.cursor = 'grab';
_this.container.style.cursor = '-moz-grab';
_this.container.style.cursor = '-webkit-grab';
}
/*=========================
Handle Touches
===========================*/
//Detect event type for devices with both touch and mouse support
var isTouchEvent = false;
var allowThresholdMove;
function onTouchStart(event) {
//Exit if slider is already was touched
if (_this.isTouched || params.onlyExternal) {
return false
}
if (params.preventClassNoSwiping && event.target && event.target.className.indexOf('NoSwiping') > -1) return false;
//Check For Nested Swipers
_this.isTouched = true;
isTouchEvent = event.type=='touchstart';
if (!isTouchEvent || event.targetTouches.length == 1 ) {
_this.callPlugins('onTouchStartBegin');
if (params.loop) _this.fixLoop();
if(!isTouchEvent) {
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
}
var pageX = isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX)
var pageY = isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY)
//Start Touches to check the scrolling
_this.touches.startX = _this.touches.currentX = pageX;
_this.touches.startY = _this.touches.currentY = pageY;
_this.touches.start = _this.touches.current = isHorizontal ? _this.touches.startX : _this.touches.startY ;
//Set Transition Time to 0
_this.setTransition(0)
//Get Start Translate Position
_this.positions.start = _this.positions.current = isHorizontal ? _this.getTranslate('x') : _this.getTranslate('y');
//Set Transform
if (isHorizontal) {
_this.setTransform( _this.positions.start, 0, 0)
}
else {
_this.setTransform( 0, _this.positions.start, 0)
}
//TouchStartTime
var tst = new Date()
_this.times.start = tst.getTime()
//Unset Scrolling
isScrolling = undefined;
//Define Clicked Slide without additional event listeners
if (params.onSlideClick || params.onSlideTouch) {
;(function () {
var el = _this.container;
var box = el.getBoundingClientRect();
var body = document.body;
var clientTop = el.clientTop || body.clientTop || 0;
var clientLeft = el.clientLeft || body.clientLeft || 0;
var scrollTop = window.pageYOffset || el.scrollTop;
var scrollLeft = window.pageXOffset || el.scrollLeft;
var x = pageX - box.left + clientLeft - scrollLeft;
var y = pageY - box.top - clientTop - scrollTop;
var touchOffset = isHorizontal ? x : y;
var beforeSlides = -Math.round(_this.positions.current/slideSize)
var realClickedIndex = Math.floor(touchOffset/slideSize) + beforeSlides
var clickedIndex = realClickedIndex;
if (params.loop) {
var clickedIndex = realClickedIndex - params.slidesPerSlide;
if (clickedIndex<0) {
clickedIndex = _this.slides.length+clickedIndex-(params.slidesPerSlide*2);
}
}
_this.clickedSlideIndex = clickedIndex
_this.clickedSlide = _this.getSlide(realClickedIndex);
if (params.onSlideTouch) {
params.onSlideTouch(_this);
_this.callPlugins('onSlideTouch');
}
})();
}
//Set Treshold
if (params.moveStartThreshold>0) allowThresholdMove = false;
//CallBack
if (params.onTouchStart) params.onTouchStart(_this)
_this.callPlugins('onTouchStartEnd');
}
}
function onTouchMove(event) {
// If slider is not touched - exit
if (!_this.isTouched || params.onlyExternal) return;
if (isTouchEvent && event.type=='mousemove') return;
var pageX = isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX)
var pageY = isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY)
//check for scrolling
if ( typeof isScrolling === 'undefined' && isHorizontal) {
isScrolling = !!( isScrolling || Math.abs(pageY - _this.touches.startY) > Math.abs( pageX - _this.touches.startX ) )
}
if ( typeof isScrolling === 'undefined' && !isHorizontal) {
isScrolling = !!( isScrolling || Math.abs(pageY - _this.touches.startY) < Math.abs( pageX - _this.touches.startX ) )
}
if (isScrolling ) {
_this.isTouched = false;
return
}
//Check For Nested Swipers
if (event.assignedToSwiper) {
_this.isTouched = false;
return
}
event.assignedToSwiper = true;
//Block inner links
if (params.preventLinks) {
_this.allowLinks = false;
}
//Stop AutoPlay if exist
if (params.autoPlay) {
_this.stopAutoPlay()
}
if (!isTouchEvent || event.touches.length == 1) {
_this.callPlugins('onTouchMoveStart');
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
_this.touches.current = isHorizontal ? pageX : pageY ;
_this.positions.current = (_this.touches.current - _this.touches.start)*params.ratio + _this.positions.start
if (params.resistance) {
//Resistance for Negative-Back sliding
if(_this.positions.current > 0 && !(params.freeMode&&!params.freeModeFluid)) {
if (params.loop) {
var resistance = 1;
if (_this.positions.current>0) _this.positions.current = 0;
}
else {
var resistance = (containerSize*2-_this.positions.current)/containerSize/2;
}
if (resistance < 0.5)
_this.positions.current = (containerSize/2)
else
_this.positions.current = _this.positions.current * resistance
if (params.nopeek)
_this.positions.current = 0;
}
//Resistance for After-End Sliding
if ( (_this.positions.current) < -maxPos() && !(params.freeMode&&!params.freeModeFluid)) {
if (params.loop) {
var resistance = 1;
var newPos = _this.positions.current
var stopPos = -maxPos() - containerSize
}
else {
var diff = (_this.touches.current - _this.touches.start)*params.ratio + (maxPos()+_this.positions.start)
var resistance = (containerSize+diff)/(containerSize);
var newPos = _this.positions.current-diff*(1-resistance)/2
var stopPos = -maxPos() - containerSize/2;
}
if (params.nopeek) {
newPos = _this.positions.current-diff;
stopPos = -maxPos();
}
if (newPos < stopPos || resistance<=0)
_this.positions.current = stopPos;
else
_this.positions.current = newPos
}
}
//Move Slides
if (!params.followFinger) return
if (!params.moveStartThreshold) {
if (isHorizontal) _this.setTransform( _this.positions.current, 0, 0)
else _this.setTransform( 0, _this.positions.current, 0)
}
else {
if ( Math.abs(_this.touches.current - _this.touches.start)>params.moveStartThreshold || allowThresholdMove) {
allowThresholdMove = true;
if (isHorizontal) _this.setTransform( _this.positions.current, 0, 0)
else _this.setTransform( 0, _this.positions.current, 0)
}
else {
_this.positions.current = _this.positions.start
}
}
if (params.freeMode) {
_this.updateActiveSlide(_this.positions.current)
}
//Prevent onSlideClick Fallback if slide is moved
if (params.onSlideClick && _this.clickedSlide) {
_this.clickedSlide = false
}
//Grab Cursor
if (params.grabCursor) {
_this.container.style.cursor = 'move';
_this.container.style.cursor = 'grabbing';
_this.container.style.cursor = '-moz-grabbin';
_this.container.style.cursor = '-webkit-grabbing';
}
//Callbacks
_this.callPlugins('onTouchMoveEnd');
if (params.onTouchMove) params.onTouchMove(_this)
return false
}
}
function onTouchEnd(event) {
//Check For scrolling
if (isScrolling) _this.swipeReset();
// If slider is not touched exit
if ( params.onlyExternal || !_this.isTouched ) return
_this.isTouched = false
//Return Grab Cursor
if (params.grabCursor) {
_this.container.style.cursor = 'move';
_this.container.style.cursor = 'grab';
_this.container.style.cursor = '-moz-grab';
_this.container.style.cursor = '-webkit-grab';
}
//onSlideClick
if (params.onSlideClick && _this.clickedSlide) {
params.onSlideClick(_this);
_this.callPlugins('onSlideClick')
}
//Check for Current Position
if (!_this.positions.current && _this.positions.current!==0) {
_this.positions.current = _this.positions.start
}
//For case if slider touched but not moved
if (params.followFinger) {
if (isHorizontal) _this.setTransform( _this.positions.current, 0, 0)
else _this.setTransform( 0, _this.positions.current, 0)
}
//--
// TouchEndTime
var tet = new Date()
_this.times.end = tet.getTime();
//Difference
_this.touches.diff = _this.touches.current - _this.touches.start
_this.touches.abs = Math.abs(_this.touches.diff)
_this.positions.diff = _this.positions.current - _this.positions.start
_this.positions.abs = Math.abs(_this.positions.diff)
var diff = _this.positions.diff ;
var diffAbs =_this.positions.abs ;
if(diffAbs < 5 && (_this.times.end - _this.times.start) < 300 && _this.allowLinks == false) {
_this.swipeReset()
//Release inner links
if (params.preventLinks) {
_this.allowLinks = true;
}
}
var maxPosition = wrapperSize - containerSize;
if (params.scrollContainer) {
maxPosition = slideSize - containerSize
}
//Prevent Negative Back Sliding
if (_this.positions.current > 0) {
_this.swipeReset()
if (params.onTouchEnd) params.onTouchEnd(_this)
_this.callPlugins('onTouchEnd');
return
}
//Prevent After-End Sliding
if (_this.positions.current < -maxPosition) {
_this.swipeReset()
if (params.onTouchEnd) params.onTouchEnd(_this)
_this.callPlugins('onTouchEnd');
return
}
//Free Mode
if (params.freeMode) {
if ( (_this.times.end - _this.times.start) < 300 && params.freeModeFluid ) {
var newPosition = _this.positions.current + _this.touches.diff * 2 ;
if (newPosition < maxPosition*(-1)) newPosition = -maxPosition;
if (newPosition > 0) newPosition = 0;
if (isHorizontal)
_this.setTransform( newPosition, 0, 0)
else
_this.setTransform( 0, newPosition, 0)
_this.setTransition( (_this.times.end - _this.times.start)*2 )
_this.updateActiveSlide(newPosition)
}
if (!params.freeModeFluid || (_this.times.end - _this.times.start) >= 300) _this.updateActiveSlide(_this.positions.current)
if (params.onTouchEnd) params.onTouchEnd(_this)
_this.callPlugins('onTouchEnd');
return
}
//Direction
direction = diff < 0 ? "toNext" : "toPrev"
//Short Touches
if (direction=="toNext" && ( _this.times.end - _this.times.start <= 300 ) ) {
if (diffAbs < 30 || !params.shortSwipes) _this.swipeReset()
else _this.swipeNext(true);
}
if (direction=="toPrev" && ( _this.times.end - _this.times.start <= 300 ) ) {
if (diffAbs < 30 || !params.shortSwipes) _this.swipeReset()
else _this.swipePrev(true);
}
//Long Touches
var groupSize = slideSize * params.slidesPerGroup
if (direction=="toNext" && ( _this.times.end - _this.times.start > 300 ) ) {
if (diffAbs >= groupSize*0.5) {
_this.swipeNext(true)
}
else {
_this.swipeReset()
}
}
if (direction=="toPrev" && ( _this.times.end - _this.times.start > 300 ) ) {
if (diffAbs >= groupSize*0.5) {
_this.swipePrev(true);
}
else {
_this.swipeReset()
}
}
if (params.onTouchEnd) params.onTouchEnd(_this)
_this.callPlugins('onTouchEnd');
}
/*=========================
Swipe Functions
===========================*/
_this.swipeNext = function(internal) {
if (!internal && params.loop) _this.fixLoop();
if (!internal && params.autoPlay) _this.stopAutoPlay();
_this.callPlugins('onSwipeNext');
var getTranslate = isHorizontal ? _this.getTranslate('x') : _this.getTranslate('y');
var groupSize = slideSize * params.slidesPerGroup;
var newPosition = Math.floor(Math.abs(getTranslate)/Math.floor(groupSize))*groupSize + groupSize;
var curPos = Math.abs(getTranslate)
if (newPosition==wrapperSize) return;
if (curPos >= maxPos() && !params.loop) return;
if (newPosition > maxPos() && !params.loop) {
newPosition = maxPos()
};
if (params.loop) {
if (newPosition >= (maxPos()+containerSize)) newPosition = maxPos()+containerSize
}
if (isHorizontal) {
_this.setTransform(-newPosition,0,0)
}
else {
_this.setTransform(0,-newPosition,0)
}
_this.setTransition( params.speed)
//Update Active Slide
_this.updateActiveSlide(-newPosition)
//Run Callbacks
slideChangeCallbacks()
return true
}
_this.swipePrev = function(internal) {
if (!internal&¶ms.loop) _this.fixLoop();
if (!internal && params.autoPlay) _this.stopAutoPlay();
_this.callPlugins('onSwipePrev');
var getTranslate = Math.ceil( isHorizontal ? _this.getTranslate('x') : _this.getTranslate('y') );
var groupSize = slideSize * params.slidesPerGroup;
var newPosition = (Math.ceil(-getTranslate/groupSize)-1)*groupSize;
if (newPosition < 0) newPosition = 0;
if (isHorizontal) {
_this.setTransform(-newPosition,0,0)
}
else {
_this.setTransform(0,-newPosition,0)
}
_this.setTransition(params.speed)
//Update Active Slide
_this.updateActiveSlide(-newPosition)
//Run Callbacks
slideChangeCallbacks()
return true
}
_this.swipeReset = function(prevention) {
_this.callPlugins('onSwipeReset');
var getTranslate = isHorizontal ? _this.getTranslate('x') : _this.getTranslate('y');
var groupSize = slideSize * params.slidesPerGroup
var newPosition = getTranslate<0 ? Math.round(getTranslate/groupSize)*groupSize : 0
var maxPosition = -maxPos()
if (params.scrollContainer) {
newPosition = getTranslate<0 ? getTranslate : 0;
maxPosition = containerSize - slideSize;
}
if (newPosition <= maxPosition) {
newPosition = maxPosition
}
if (params.scrollContainer && (containerSize>slideSize)) {
newPosition = 0;
}
if (params.mode=='horizontal') {
_this.setTransform(newPosition,0,0)
}
else {
_this.setTransform(0,newPosition,0)
}
_this.setTransition( params.speed)
//Update Active Slide
_this.updateActiveSlide(newPosition)
//Reset Callback
if (params.onSlideReset) {
params.onSlideReset(_this)
}
return true
}
var firstTimeLoopPositioning = true;
_this.swipeTo = function (index, speed, runCallbacks) {
index = parseInt(index, 10); //type cast to int
_this.callPlugins('onSwipeTo', {index:index, speed:speed});
if (index > (numOfSlides-1)) return;
if (index<0 && !params.loop) return;
runCallbacks = runCallbacks===false ? false : runCallbacks || true
var speed = speed===0 ? speed : speed || params.speed;
if (params.loop) index = index + params.slidesPerSlide;
if (index > numOfSlides - params.slidesPerSlide) index = numOfSlides - params.slidesPerSlide;
var newPosition = -index*slideSize ;
if(firstTimeLoopPositioning && params.loop && params.initialSlide > 0 && params.initialSlide < numOfSlides){
newPosition = newPosition - params.initialSlide * slideSize;
firstTimeLoopPositioning = false;
}
if (isHorizontal) {
_this.setTransform(newPosition,0,0)
}
else {
_this.setTransform(0,newPosition,0)
}
_this.setTransition( speed )
_this.updateActiveSlide(newPosition)
//Run Callbacks
if (runCallbacks)
slideChangeCallbacks()
return true
}
//Prevent Multiple Callbacks
_this._queueStartCallbacks = false;
_this._queueEndCallbacks = false;
function slideChangeCallbacks() {
//Transition Start Callback
_this.callPlugins('onSlideChangeStart');
if (params.onSlideChangeStart) {
if (params.queueStartCallbacks && !_this._queueStartCallbacks) {
_this._queueStartCallbacks = true;
params.onSlideChangeStart(_this)
_this.transitionEnd(function(){
_this._queueStartCallbacks = false;
})
}
else if (!params.queueStartCallbacks) {
params.onSlideChangeStart(_this)
}
}
//Transition End Callback
if (params.onSlideChangeEnd) {
if (params.queueEndCallbacks && !_this.queueEndCallbacks) {
if(_this.support.transitions) {
_this._queueEndCallbacks = true;
_this.transitionEnd(params.onSlideChangeEnd)
}
else {
setTimeout(function(){
params.onSlideChangeEnd(_this)
},10)
}
}
else if (!params.queueEndCallbacks) {
if(_this.support.transitions) {
_this.transitionEnd(params.onSlideChangeEnd)
}
else {
setTimeout(function(){
params.onSlideChangeEnd(_this)
},10)
}
}
}
}
_this.updateActiveSlide = function(position) {
_this.previousIndex = _this.previousSlide = _this.realIndex
_this.realIndex = Math.round(-position/slideSize)
if (!params.loop) _this.activeIndex = _this.realIndex;
else {
_this.activeIndex = _this.realIndex-params.slidesPerSlide
if (_this.activeIndex>=numOfSlides-params.slidesPerSlide*2) {
_this.activeIndex = numOfSlides - params.slidesPerSlide*2 - _this.activeIndex
}
if (_this.activeIndex<0) {
_this.activeIndex = numOfSlides - params.slidesPerSlide*2 + _this.activeIndex
}
}
if (_this.realIndex==numOfSlides) _this.realIndex = numOfSlides-1
if (_this.realIndex<0) _this.realIndex = 0
//Legacy
_this.activeSlide = _this.activeIndex;
//Update Pagination
if (params.pagination) {
_this.updatePagination()
}
}
/*=========================
Loop Fixes
===========================*/
_this.fixLoop = function(){
//Fix For Negative Oversliding
if (_this.realIndex < params.slidesPerSlide) {
var newIndex = numOfSlides - params.slidesPerSlide*3 + _this.realIndex;
_this.swipeTo(newIndex,0, false)
}
//Fix For Positive Oversliding
if (_this.realIndex > numOfSlides - params.slidesPerSlide*2) {
var newIndex = -numOfSlides + _this.realIndex + params.slidesPerSlide
_this.swipeTo(newIndex,0, false)
}
}
if (params.loop) {
_this.swipeTo(0,0, false)
}
}
Swiper.prototype = {
plugins : {},
//Transition End
transitionEnd : function(callback, permanent) {
var a = this
var el = a.wrapper
var events = ['webkitTransitionEnd','transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'];
if (callback) {
function fireCallBack() {
callback(a)
a._queueEndCallbacks = false
if (!permanent) {
for (var i=0; i<events.length; i++) {
el.removeEventListener(events[i], fireCallBack, false)
}
}
}
for (var i=0; i<events.length; i++) {
el.addEventListener(events[i], fireCallBack, false)
}
}
},
//Touch Support
isSupportTouch : function() {
return ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch;
},
//Transition Support
isSupportTransitions : function(){
var div = document.createElement('div').style
return ('transition' in div) || ('WebkitTransition' in div) || ('MozTransition' in div) || ('msTransition' in div) || ('MsTransition' in div) || ('OTransition' in div);
},
// 3D Transforms Test
isSupport3D : function() {
var div = document.createElement('div');
div.id = 'test3d';
var s3d=false;
if("webkitPerspective" in div.style) s3d=true;
if("MozPerspective" in div.style) s3d=true;
if("OPerspective" in div.style) s3d=true;
if("MsPerspective" in div.style) s3d=true;
if("perspective" in div.style) s3d=true;
/* Test with Media query for Webkit to prevent FALSE positive*/
if(s3d && ("webkitPerspective" in div.style) ) {
var st = document.createElement('style');
st.textContent = '@media (-webkit-transform-3d), (transform-3d), (-moz-transform-3d), (-o-transform-3d), (-ms-transform-3d) {#test3d{height:5px}}'
document.getElementsByTagName('head')[0].appendChild(st);
document.body.appendChild(div);
s3d = div.offsetHeight === 5;
st.parentNode.removeChild(st);
div.parentNode.removeChild(div);
}
return s3d;
},
//GetTranslate
getTranslate : function(axis){
var el = this.wrapper
var matrix;
var curTransform;
if (window.WebKitCSSMatrix) {
var transformMatrix = new WebKitCSSMatrix(window.getComputedStyle(el, null).webkitTransform)
matrix = transformMatrix.toString().split(',');
}
else {
var transformMatrix = window.getComputedStyle(el, null).MozTransform || window.getComputedStyle(el, null).OTransform || window.getComputedStyle(el, null).MsTransform || window.getComputedStyle(el, null).msTransform || window.getComputedStyle(el, null).transform|| window.getComputedStyle(el, null).getPropertyValue("transform").replace("translate(", "matrix(1, 0, 0, 1,");
matrix = transformMatrix.toString().split(',');
}
if (this.params.useCSS3Transforms) {
if (axis=='x') {
//Crazy IE10 Matrix
if (matrix.length==16)
curTransform = parseFloat( matrix[12] )
//Latest Chrome and webkits Fix
else if (window.WebKitCSSMatrix)
curTransform = transformMatrix.m41
//Normal Browsers
else
curTransform = parseFloat( matrix[4] )
}
if (axis=='y') {
//Crazy IE10 Matrix
if (matrix.length==16)
curTransform = parseFloat( matrix[13] )
//Latest Chrome and webkits Fix
else if (window.WebKitCSSMatrix)
curTransform = transformMatrix.m42
//Normal Browsers
else
curTransform = parseFloat( matrix[5] )
}
}
else {
if (axis=='x') curTransform = parseFloat(el.style.left,10) || 0
if (axis=='y') curTransform = parseFloat(el.style.top,10) || 0
}
return curTransform;
},
//Set Transform
setTransform : function(x,y,z) {
var es = this.wrapper.style
x=x||0;
y=y||0;
z=z||0;
if (this.params.useCSS3Transforms) {
if (this.support.threeD) {
es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = 'translate3d('+x+'px, '+y+'px, '+z+'px)'
}
else {
es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = 'translate('+x+'px, '+y+'px)'
if (this.ie8) {
es.left = x+'px'
es.top = y+'px'
}
}
}
else {
es.left = x+'px';
es.top = y+'px';
}
this.callPlugins('onSetTransform', {x:x, y:y, z:z})
},
//Set Transition
setTransition : function(duration) {
var es = this.wrapper.style
es.webkitTransitionDuration = es.MsTransitionDuration = es.msTransitionDuration = es.MozTransitionDuration = es.OTransitionDuration = es.transitionDuration = duration/1000+'s';
this.callPlugins('onSetTransition', {duration: duration})
},
//Check for IE8
ie8: (function(){
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv != -1 && rv < 9;
})(),
ie10 : window.navigator.msPointerEnabled
}
/*=========================
jQuery & Zepto Plugins
===========================*/
if (window.jQuery||window.Zepto) {
(function($){
$.fn.swiper = function(params) {
var s = new Swiper($(this)[0], params)
$(this).data('swiper',s);
return s
}
})(window.jQuery||window.Zepto)
}
/**
* jquery.dlmenu.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
;( function( $, window, undefined ) {
// global
var Modernizr = window.Modernizr, $body = $( 'body' );
$.DLMenu = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.DLMenu.defaults = {
// classes for the animation effects
animationClasses : { animIn : 'dl-animate-in-2', animOut : 'dl-animate-out-2' }
};
$.DLMenu.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.DLMenu.defaults, options );
// cache some elements and initialize some variables
this._config();
var animEndEventNames = {
'WebkitAnimation' : 'webkitAnimationEnd',
'OAnimation' : 'oAnimationEnd',
'msAnimation' : 'MSAnimationEnd',
'animation' : 'animationend'
},
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
// animation end event name
this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu';
// transition end event name
this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu',
// support for css animations and css transitions
this.supportAnimations = Modernizr.cssanimations,
this.supportTransitions = Modernizr.csstransitions;
this._initEvents();
},
_config : function() {
this.open = false;
this.$trigger = this.$el.find( '#mobile-menu' );
/* ! !changed */
this.openCap = '<span class="wf-phone-visible"> </span><span class="wf-phone-hidden">'+this.$trigger.find( '.menu-open' ).html()+"</span>";
this.closeCap = '<span class="wf-phone-visible"> </span><span class="wf-phone-hidden">'+this.$trigger.find( '.menu-close' ).html()+"</span>";
/* !changed: end */
this.$menu = this.$el.find( 'ul.dl-menu' );
this.$menuitems = this.$menu.find( 'li:not(.dl-back)' );
this.$back = this.$menu.find( 'li.dl-back' );
},
_initEvents : function() {
var self = this;
this.$trigger.on( 'click.dlmenu', function() {
if( self.open ) {
self._closeMenu();
}
else {
self._openMenu();
// clicking somewhere else makes the menu close
$body.off( 'click' ).on( 'click.dlmenu', function() {
self._closeMenu() ;
} );
}
return false;
} );
this.$menuitems.on( 'click.dlmenu', function( event ) {
event.stopPropagation();
var $item = $(this),
$submenu = $item.children( 'ul.dl-submenu' );
if( $submenu.length > 0 ) {
$("html, body").animate({ scrollTop: self.$el.offset().top - 20 }, 150);
var $flyin = $submenu.clone().insertAfter( self.$menu ).addClass( self.options.animationClasses.animIn ),
onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.animOut ).addClass( 'dl-subview' );
$item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' );
$flyin.remove();
};
self.$menu.addClass( self.options.animationClasses.animOut );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
return false;
}
} );
this.$back.on( 'click.dlmenu', function( event ) {
$("html, body").animate({ scrollTop: self.$el.offset().top - 20 }, 150);
var $this = $( this ),
$submenu = $this.parents( 'ul.dl-submenu:first' ),
$item = $submenu.parent(),
$flyin = $submenu.clone().insertAfter( self.$menu ).addClass( self.options.animationClasses.animOut );
var onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.animIn );
$flyin.remove();
};
self.$menu.addClass( self.options.animationClasses.animIn );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
$item.removeClass( 'dl-subviewopen' );
var $subview = $this.parents( '.dl-subview:first' );
if( $subview.is( 'li' ) ) {
$subview.addClass( 'dl-subviewopen' );
}
$subview.removeClass( 'dl-subview' );
return false;
} );
},
_closeMenu : function() {
var self = this,
onTransitionEndFn = function() {
self.$menu.off( self.transEndEventName );
self._resetMenu();
};
this.$menu.removeClass( 'dl-menuopen' );
this.$menu.addClass( 'dl-menu-toggle' );
this.$trigger.removeClass( 'dl-active' ).html(this.openCap);
if( this.supportTransitions ) {
this.$menu.on( this.transEndEventName, onTransitionEndFn );
}
else {
onTransitionEndFn.call();
}
this.open = false;
/*
this.$el.css({
position : "fixed",
top : ""
});
*/
},
_openMenu : function() {
this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() {
$( this ).removeClass( 'dl-menu-toggle' );
} );
this.$trigger.addClass( 'dl-active' ).html(this.closeCap);
this.open = true;
$("html, body").animate({ scrollTop: this.$el.offset().top - 20 }, 150);
},
// resets the menu to its original state (first level of options)
_resetMenu : function() {
this.$menu.removeClass( 'dl-subview' );
this.$menuitems.removeClass( 'dl-subview dl-subviewopen' );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.dlmenu = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( !instance ) {
logError( "cannot call methods on dlmenu prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for dlmenu instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) );
}
});
}
return this;
};
} )( jQuery, window );
/****************************************************************************************************************************/
/* !- Tooltip*/
function simple_tooltip(target_items, name){
jQuery(target_items).each(function(i){
jQuery("body").append("<div class='"+name+"' id='"+name+i+"'>"+jQuery(this).find('span.tooltip-c').html()+"</div>");
var my_tooltip = jQuery("#"+name+i);
jQuery(this).removeAttr("title").mouseover(function(){
my_tooltip.css({opacity:1, display:"none"}).fadeIn(400);
}).mousemove(function(kmouse){
var border_top = jQuery(window).scrollTop();
var border_right = jQuery(window).width();
var left_pos;
var top_pos;
var offset = 15;
if(border_right - (offset *2) >= my_tooltip.width() + kmouse.pageX){
left_pos = kmouse.pageX+offset;
} else{
left_pos = border_right-my_tooltip.width()-offset;
}
if(border_top + (offset *2)>= kmouse.pageY - my_tooltip.height()){
top_pos = border_top +offset;
} else{
top_pos = kmouse.pageY-my_tooltip.height()-2.2*offset;
}
my_tooltip.css({left:left_pos, top:top_pos});
}).mouseout(function(){
my_tooltip.css({left:"-9999px"});
});
});
}
/********************************************************************************************************************************/
/* !- Accordion, Toggle*/
(function( window, $, undefined ) {
/*
* smartresize: debounced resize event for jQuery
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.smartresize.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*/
var $event = $.event, resizeTimeout;
var callClick = 0;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
$.Accordion = function( options, element ) {
this.$el = $( element );
// list items
this.$items = this.$el.children('ul').children('li');
// total number of items
this.itemsCount = this.$items.length;
// initialize accordion
this._init( options );
};
$.Accordion.defaults = {
// index of opened item. -1 means all are closed by default.
open : -1,
// if set to true, only one item can be opened. Once one item is opened, any other that is opened will be closed first
oneOpenedItem : false,
// speed of the open / close item animation
speed : 600,
// easing of the open / close item animation
easing : 'easeInOutExpo',
// speed of the scroll to action animation
scrollSpeed : 900,
// easing of the scroll to action animation
scrollEasing : 'easeInOutExpo'
};
$.Accordion.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Accordion.defaults, options );
// validate options
this._validate();
// current is the index of the opened item
this.current = this.options.open;
// hide the contents so we can fade it in afterwards
this.$items.find('div.st-content').hide();
// save original height and top of each item
this._saveDimValues();
// if we want a default opened item...
if( this.current != -1 )
this._toggleItem( this.$items.eq( this.current ) );
// initialize the events
this._initEvents();
},
_saveDimValues : function() {
this.$items.each( function() {
var $item = $(this);
$item.data({
originalHeight : $item.find('a:first').height(),
offsetTop : $item.offset().top
});
});
},
// validate options
_validate : function() {
// open must be between -1 and total number of items, otherwise we set it to -1
if( this.options.open < -1 || this.options.open > this.itemsCount - 1 )
this.options.open = -1;
},
_initEvents : function() {
var instance = this;
// open / close item
this.$items.find('a:first').bind('click.accordion', function( event ) {
var $item = $(this).parent();
// close any opened item if oneOpenedItem is true
if( instance.options.oneOpenedItem && instance._isOpened() && instance.current!== $item.index() ) {
instance._toggleItem( instance.$items.eq( instance.current ) );
}
// open / close item
instance._toggleItem( $item );
return false;
});
instance.$el.find('li').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ));
});
$(window).bind('smartresize.accordion', function( event ) {
// reset orinal item values
instance._saveDimValues();
// reset the content's height of any item that is currently opened
instance.$el.find('li').not('.st-open').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ));
});
instance.$el.find('li.st-open').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ) + $this.find('div.st-content').outerHeight( true ) );
});
});
},
// checks if there is any opened item
_isOpened : function() {
return ( this.$el.find('li.st-open').length > 0 );
},
// open / close item
_toggleItem : function( $item ) {
callClick++;
var instance = this;
var $content = $item.find('div.st-content');
( $item.hasClass( 'st-open' ) )
? ( this.current = -1, $content.stop(true, true).fadeOut( this.options.speed ), $item.removeClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' )
}, this.options.speed, this.options.easing, function(){
if(callClick > 1){
instance._scroll();
}
} ) )
: ( this.current = $item.index(), $content.stop(true, true).fadeIn( this.options.speed ), $item.addClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' ) + $content.outerHeight( true )
}, this.options.speed, this.options.easing, function(){
if(callClick > 1){
instance._scroll();
}
} ))
},
// scrolls to current item or last opened item if current is -1
//Ф-Я СКРОЛЛ
_scroll : function( instance ) {
var instance = instance || this, current;
( instance.current !== -1 ) ? current = instance.current : current = instance.$el.find('li.st-open:last').index();
if(window.innerWidth < 760){
$('html, body').stop().animate({
scrollTop : instance.$items.eq( current ).offset().top
}, instance.options.scrollSpeed, instance.options.scrollEasing );
}
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.accordion = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
logError( "cannot call methods on accordion prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for accordion instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'accordion' );
if ( !instance ) {
$.data( this, 'accordion', new $.Accordion( options, this ) );
}
});
}
return this;
};
})( window, jQuery );
(function( window, $, undefined ) {
/*
* smartresize: debounced resize event for jQuery
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.smartresize.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*/
var $event = $.event, resizeTimeout;
var callClick = 0;
$.Toggle = function( options, element ) {
this.$el = $( element );
// list items
this.$items = this.$el
// total number of items
this.itemsCount = this.$items.length;
// initialize accordion
this._init( options );
};
$.Toggle.defaults = {
// index of opened item. -1 means all are closed by default.
open : -1,
// if set to true, only one item can be opened. Once one item is opened, any other that is opened will be closed first
oneOpenedItem : false,
// speed of the open / close item animation
speed : 600,
// easing of the open / close item animation
easing : 'easeInOutExpo',
// speed of the scroll to action animation
scrollSpeed : 900,
// easing of the scroll to action animation
scrollEasing : 'easeInOutExpo'
};
$.Toggle.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Toggle.defaults, options );
// validate options
this._validate();
// current is the index of the opened item
this.current = this.options.open;
// hide the contents so we can fade it in afterwards
this.$items.find('div.st-toggle-content').hide();
// save original height and top of each item
this._saveDimValues();
// if we want a default opened item...
if( this.current != -1 )
this._toggleItem( this.$items.eq( this.current ) );
// initialize the events
this._initEvents();
},
_saveDimValues : function() {
this.$items.each( function() {
var $item = $(this);
$item.data({
originalHeight : $item.find('a:first').height(),
offsetTop : $item.offset().top
});
});
},
// validate options
_validate : function() {
// open must be between -1 and total number of items, otherwise we set it to -1
if( this.options.open < -1 || this.options.open > this.itemsCount - 1 )
this.options.open = -1;
},
_initEvents : function() {
var instance = this;
// open / close item
this.$items.find('a:first').bind('click.toggle', function( event ) {
var $item = $(this).parent();
// close any opened item if oneOpenedItem is true
if( instance.options.oneOpenedItem && instance._isOpened() && instance.current!== $item.index() ) {
instance._toggleItem( instance.$items.eq( instance.current ) );
}
// open / close item
instance._toggleItem( $item );
return false;
});
instance.$el.each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ));
});
$(window).bind('smartresize.toggle', function( event ) {
// reset orinal item values
instance._saveDimValues();
// reset the content's height of any item that is currently opened
instance.$el.not('.st-open').each( function() {
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ));
});
instance.$el.each( function() {
if($(this).hasClass('st-open')){
var $this = $(this);
$this.css( 'height', $this.data( 'originalHeight' ) + $this.find('div.st-toggle-content').outerHeight( true ) );
}
});
// scroll to current
});
},
// checks if there is any opened item
_isOpened : function() {
return ( this.$el.is('.st-toggle-open').length > 0 );
},
// open / close item
_toggleItem : function( $item ) {
callClick++;
var instance = this;
var $content = $item.find('div.st-toggle-content');
( $item.hasClass( 'st-open' ) )
? ( this.current = -1, $content.stop(true, true).fadeOut( this.options.speed ), $item.removeClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' )
}, this.options.speed, this.options.easing, function(){
if(callClick > 1){
instance._scroll();
}
} ) )
: ( this.current = $item.index(), $content.stop(true, true).fadeIn( this.options.speed ), $item.addClass( 'st-open' ).stop().animate({
height : $item.data( 'originalHeight' ) + $content.outerHeight( true )
}, this.options.speed, this.options.easing , function(){
if(callClick > 1){
instance._scroll();
}
} ) )
},
// scrolls to current item or last opened item if current is -1
_scroll : function( instance ) {
var instance = instance || this, current;
( instance.current !== -1 ) ? current = instance.current : current = instance.$el.find('li.st-open:last').index();
if(window.innerWidth < 760){
$('html, body').stop().animate({
scrollTop : instance.$items.eq( current ).offset().top
}, instance.options.scrollSpeed, instance.options.scrollEasing );
}
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.toggle = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'toggle' );
if ( !instance ) {
logError( "cannot call methods on toggle prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for toggle instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'toggle' );
if ( !instance ) {
$.data( this, 'toggle', new $.Toggle( options, this ) );
}
});
}
return this;
};
})( window, jQuery );
/*********************************************************************************************************************/
/* !- Tabs*/
jQuery(document).ready(function($) {
$.fn.goTabs = function (options) {
var defaults = {
heading: '.tab',
content: '.tab-content',
active: 'active-tab'
};
$('.tab-content .tab-inner-content').fadeOut();
$('.tab-content.active-tab-content .tab-inner-content').fadeIn();
var win = $(window)
options = $.extend(defaults, options);
return this.each(function () {
var container = $(this),
tab_titles = $('<div class="nav"></div>').prependTo(container),
tabs = $(options.heading, container),
content = $(options.content, container),
newtabs = false,
oldtabs = false;
newtabs = tabs.clone();
oldtabs = tabs.addClass('fullsize-tab');
tabs = newtabs;
tabs.prependTo(tab_titles).each(function (i) {
var tab = $(this),
the_oldtab = false;
if (newtabs) the_oldtab = oldtabs.filter(':eq(' + i + ')');
tab.addClass('tab-counter-' + i).bind('click', function () {
open_content(tab, i, the_oldtab);
return false;
});
if (newtabs) {
the_oldtab.bind('click', function () {
open_content(the_oldtab, i, tab);
return false;
});
}
});
trigger_default_open();
function open_content(tab, i, alternate_tab) {
if (!tab.is('.' + options.active)) {
var act_height = content.filter(':eq(' + i + ')').find('.tab-inner-content').outerHeight()/* + parseInt(content.filter(':eq(' + i + ')').find('.tab-inner-content').css('padding-top')) + parseInt(content.filter(':eq(' + i + ')').find('.tab-inner-content').css('padding-bottom'))*/;
$('.' + options.active, container).removeClass(options.active);
$('.' + options.active + '-content', container).removeClass(options.active + '-content')/*.css({'height': ""})*/.find('.tab-inner-content').css({'height': ""}).fadeOut(400, function(){
var active_t = tab.addClass(options.active);
var active_c = content.filter(':eq(' + i + ')').addClass(options.active + '-content')
active_c.find('.tab-inner-content').fadeIn(400);
if(window.innerWidth < 760){
$('html, body').stop().animate({
scrollTop : active_t.offset().top
}, 900, 'easeInOutExpo' );
}
});
var new_loc = tab.data('fake-id');
// if (typeof new_loc == 'string') location.replace(new_loc);
if (alternate_tab) alternate_tab.addClass(options.active);
}
}
function trigger_default_open() {
// if (!window.location.hash) return;
var open = tabs.filter('[data-fake-id=""]');
if (open.length) {
if (!open.is('.active-tab')) open.trigger('click');
}
}
});
};
});
/*********************************************************************************************************************************/
/*3D slideshow*/
jQuery(document).ready(function($){
if ( $('.three-d-slider').length > 0){
var GiveMoreSpace = 1.3;
if( $('#main-slideshow').hasClass('fixed') ){
var ratioFix = $('.three-d-slider').attr('data-height')/$('.three-d-slider').attr('data-width');
var thisH = $('.three-d-slider').css('height'),
main = $('.three-d-slider').css("height", $('.three-d-slider').width() * (ratioFix) ).addClass('slide-me');
//$('.three-d-slider-content').css("height", $('.three-d-slider').width() * (ratioFix) );
var fixW = $('.three-d-slider').width();
}else if( $('#main-slideshow').hasClass('fixed-height') ){
var ratioFix = $('.three-d-slider').attr('data-height')/$('.three-d-slider').attr('data-width');
var thisH = $('.three-d-slider').css('height'),
main = $('.three-d-slider').css("height", $('.three-d-slider').width() * (ratioFix) ).addClass('slide-me');
var fixW = $('.three-d-slider').width();
}else{
var boxedM = parseInt($('#page.boxed').css('margin-bottom'));
var main = $('.three-d-slider').css({'height': $(window).height() - $('#header').height() + $('#header.overlap').height() - $('#top-bar').height()}).addClass('slide-me');
}
var useJS = 1, //use JS to prevent mobile Safari crash
loading = main.children('#loading'),
windowH = main.height(),
windowW = main.width(),
ratio = windowW/windowH,
CellSize = 300,
Plane1 = $('#level1 img'),
Plane2 = $('#level2 img'),
Plane3 = $('#level3 img'),
scale = [0.14, 0.23, 0.35],
IEsc = [1,1,1], //consider scale if browser is IE
indexZ = [3, 6, 9],
speedZ = 1000,
$hovered,
$corner_w = 3,
$corner_l = 30,
corner_color = "#ffffff",
hover_color = "rgba(0, 0, 0, .35)",
layer_time = 700,
t0 = 850,
tscr = 500,
tdel = 100,
n = [],
m = [],
Plane = [Plane1,Plane2,Plane3],
length = Plane.length,
Container =[], // array of canvas containers
allowParallax = length,
useNavig = 0,
AnimDelay = 0,
AntiStumble = 0,
timer1,timer2,timer3,timer4,timer5,timer6,timer7,timer8,
isLightbox = 0,
loaded_imgs=0,
total = $('div.plane img').length, //parallax animation is initially allowed
isMobile = (/(Android|BlackBerry|iPhone|iPod|iPad|Palm|Symbian)/.test(navigator.userAgent)),
scrolling = false; // define whether you scroll or simply touch a display
if( $('#main-slideshow').hasClass('fixed') ){
var newWidth,
newHeight;
var fixedW = fixW;
$(window).on('resize', function(){
var asw = $('.three-d-slider').attr('data-width'),
ash = $('.three-d-slider').attr('data-height');
newWidth = $('.three-d-slider').width();
if(newWidth != fixedW) {
var main = $('.three-d-slider').css("height", newWidth * (ash / asw) ).addClass('slide-me');
newWidth = $('.three-d-slider').width();
}else{
main = $('.three-d-slider').css("height", $('.three-d-slider').width() * (ratioFix) ).addClass('slide-me');
}
});
}else if( $('#main-slideshow').hasClass('fixed-height') ){
var newWidth,
newHeight;
var fixedW = fixW;
$(window).on('resize', function(){
var asw = $('.three-d-slider').attr('data-width'),
ash = $('.three-d-slider').attr('data-height');
newWidth = $('.three-d-slider').width();
if(newWidth != fixedW) {
var main = $('.three-d-slider').css("height", newWidth * (ash / asw) ).addClass('slide-me');
newWidth = $('.three-d-slider').width();
}else{
main = $('.three-d-slider').css("height", $('.three-d-slider').width() * (ratioFix) ).addClass('slide-me');
}
});
}else{
$(window).on('resize', function(){
var boxedM = parseInt($('#page.boxed').css('margin-bottom'));
var main = $('.three-d-slider').css({'height': $(window).height() - $('#header').height() + $('#header.overlap').height() - boxedM - $('#wpadminbar').height() - boxedM - $('#top-bar').height()}).addClass('slide-me');
});
}
var main_left = main.offset().left,
main_top = main.offset().top;
//CSS3 transition depending on browser
var vP = ""; // What browser is being used
var transSupport =''; //To check whether CSS3 transitions are supported
if ($.browser.webkit) { // Find the transition prefix depending on browser
vP = "-webkit-";
transSupport = 'Webkit';
} else if ($.browser.msie) {
vP = "-ms-";
transSupport = 'ms';
} else if ($.browser.mozilla) {
vP = "-moz-";
transSupport = 'Moz';
} else if ($.browser.opera) {
vP = "-o-";
transSupport = 'O';
}
//CSS3 transition detection
function supportsTransforms() {
var b = document.body || document.documentElement;
var s = b.style;
var pp = 'transform';
if(typeof s[pp] == 'string') return true;
pp = pp.charAt(0).toUpperCase() + pp.substr(1);
if(typeof s[transSupport + pp] == 'string') return true;
return false;
}
function supportsTransitions() {
var b = document.body || document.documentElement;
var s = b.style;
var pp = 'transition';
if(typeof s[pp] == 'string') return true;
pp = pp.charAt(0).toUpperCase() + pp.substr(1);
if(typeof s[transSupport + pp] == 'string') return true;
return false;
}
var smart = supportsTransitions()*supportsTransforms(),
TrasitDur = vP+"transition-duration",
TrasitDel = vP+"transition-delay",
Transform = vP+"transform";
function coordinates(event) { //normalization of touch events
if (event.originalEvent.touches !== undefined && event.originalEvent.touches[0]) {
event.pageX = event.originalEvent.touches[0].pageX;
event.pageY = event.originalEvent.touches[0].pageY;
}
return event;
}
function EasyReposition(){ // reposition if window resize. Only image containers move.
windowH = main.height();
windowW = main.width();
ratio = windowW/windowH;
AnimateLayersBunch (0.5*windowW, 0.5*windowH);
}
function TotalReposition(){ // reposition if window resize. Both image containers and images move.
windowH = main.height();
windowW = main.width();
ratio = windowW/windowH;
ResizePlanes();
}
$.fn.loaded = function(callback, jointCallback, ensureCallback){ //image loader
var len = this.length;
if (len > 0) {
return this.each(function() {
var el = this,
$el = $(el),
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
$el.on("load.dt", function(event) {
$(this).off("load.dt");
if (typeof callback == "function") {
callback.call(this);
}
if (--len <= 0 && (typeof jointCallback == "function")){
jointCallback.call(this);
}
});
if (!el.complete || el.complete === undefined) {
el.src = el.src;
} else {
$el.trigger("load.dt")
}
});
} else if (ensureCallback) {
if (typeof jointCallback == "function") {
jointCallback.call(this);
}
return this;
}
};
function LoadProgress (){ //image load counter
timer7 = setTimeout(function(){
if (loaded_imgs>total*0.5) {
var fakeimgs = 0;
timer8 = setInterval(function() {
if (fakeimgs<total) {
loading.html((++fakeimgs)+'/'+total);
} else {
loading.html((total)+'/'+total);
if (loaded_imgs == total) {
clearInterval(timer8);
Launch();
}
}
},50);
} else {
timer8 = setInterval(function() {
loading.html((loaded_imgs)+'/'+total);
if (loaded_imgs == total) {
clearInterval(timer8);
Launch();
}
},100);
}
clearTimeout(timer7);
},150);
}
function createContainers(planes) { // create slider HTML
var CanvasArray ='<div class="close"></div><div class="dark-layer l2"></div><div class="dark-layer l1"></div><div class="img-caption"><p></p></div><div class="navig"><div class="act">1</div><div>2</div><div>3</div></div>',
corner;
for (var k=0; k<length; k++) {
//dealing with a single plane
CanvasArray += '<div class="container-'+(k+1)+' container" >';
var plane_lngth = planes[k].length;
for (var i=0; i<plane_lngth; i++) {
if ($('<canvas></canvas>')[0].getContext) {
var newImg = '<canvas class="photo"></canvas>';
} else {
var newImg = '<img class="photo" />';
}
CanvasArray += newImg;
}
CanvasArray +='<div class="dark-layer"></div>';
if (!isMobile) {
if (smart) {
corner = '<canvas class="corners"></canvas>';
} else {
corner = '<span class="top-l"></span><span class="top-r"></span><span class="bottom-l"></span><span class="bottom-r"></span>';
}
CanvasArray += corner;
}
CanvasArray +='</div>';
}
main.append(CanvasArray);
findInterfaceElems();
$(window).resize(function() {
main_left = main.offset().left;
main_top = main.offset().top;
navig.css('top',Math.round(0.5*(windowH-navig.height())));
if(!isLightbox) {
if (smart && !useJS){
TotalReposition();
return true;
}
EasyReposition();
}
});
$(document).on("scroll", function() {
$this = $(document);
scrollTop = $this.scrollTop();
scrollLeft = $this.scrollLeft();
});
return $('div.container');
}
function findInterfaceElems() {
closeX = main.children('.close');
dark_layer1 = main.children('.l1');
dark_layer2 = main.children('.l2');
caption = main.children('.img-caption');
caption_text = caption.children('p');
navig = main.children('.navig');
navig.css('top',Math.round(0.5*(windowH-navig.height())));
scrollTop = $(document).scrollTop();
scrollLeft = $(document).scrollLeft();
}
function ReadyCanavas(i) { // get all images from i-th Container
return $(Container[i]).children('.photo');
}
function drawCanvas (planes, container) { //draw canvas images
for (var k=0; k<length; k++) {
var ReadyImgs = ReadyCanavas(k);
//dealing with a single plane
var ReadyImgsLngth = ReadyImgs.length;
for (var i=0; i<ReadyImgsLngth; i++) {
var real_img = planes[k][i],
img_width = $(real_img).width(),
img_height = $(real_img).height();
ReadyImgs[i].width=img_width;
ReadyImgs[i].height=img_height;
if ($('<canvas></canvas>')[0].getContext) {
var context = ReadyImgs[i].getContext("2d");
context.drawImage(real_img,0,0,img_width,img_height);
} else {
$(ReadyImgs[i]).attr("src",$(real_img).attr("src"));
}
$(ReadyImgs[i]).attr("alt", real_img.alt);
$(ReadyImgs[i]).getCanvasSize();
}
}
}
$.fn.getCanvasSize = function () { // get number of cells across canvas image width and height
var $self=$(this),
w = Math.ceil($self.width()/CellSize),
h = Math.ceil($self.height()/CellSize);
$self.data({
"wCanvas" : w,
"hCanvas" : h,
"deviationX": Math.floor((w*CellSize-$self.width())*Math.random()), // devialtion of left position
"deviationY": Math.floor((h*CellSize-$self.height())*Math.random()) // deviation of top position
});
}
function ResizePlanes() {
for (var i=0;i<length;i++) {
var ReadyImgs = ReadyCanavas(i);
n[i] = PlaneSide(ReadyImgs,ratio).n;
m[i] = PlaneSide(ReadyImgs,ratio).m;
var newNM = PositionImage(ReadyImgs, CreateMatrix (0,m[i],0,n[i]), 0, 0, n[i], m[i]);
m[i] = newNM[0];
n[i] = newNM[1];
Container[i].ind = i; // set initial order of layers
var vertical = AddPaddings (n[i], windowH),
horizontal = AddPaddings (m[i], windowW),
ReadyImgsLng = ReadyImgs.length;
Container[i].Wo = horizontal[0];
Container[i].Ho = vertical[0];
for (var index=0;index<ReadyImgsLng;index++) {
var $img = $(ReadyImgs[index]),
top = parseFloat($img.css("top")),
left = parseFloat($img.css("left"));
$img.css({"top":top+vertical[1],"left":left+horizontal[1]});
}
Container[i].Scale = 1;
$(Container[i]).css({"width":Container[i].Wo, "height": Container[i].Ho});
if (!smart || useJS) {
IEsc[i] = scale[i]; //consider scale if browser is IE
Container[i] = ScaleIE(scale[i], Container[i], 0);
}
}
AnimateLayersBunch (0.5*windowW, 0.5*windowH); //center image containers
allowParallax = length;
return Container;
}
function PlaneSide(realImages, proportion) { // calculate number of cells across image plane width and height
var TotalImgArea = 0,
img_numb = realImages.length;
//Calculate the summ of images areas
for (var i=0;i<img_numb;i++){
TotalImgArea += realImages[i].width*realImages[i].height+2*CellSize*CellSize; // calculate required containner area
}
//approx container size when images are not scaled
var W0 = GiveMoreSpace*Math.sqrt(proportion*TotalImgArea), //required width
H0 = W0/proportion, // required height
//split container width hand height into integer number of cells. Enlarge Wo and Ho if required
m = Math.ceil(W0/CellSize),
n = Math.ceil(H0/CellSize);
return {"n":n,"m":m};
}
function CreateMatrix (Mo,M,No,N) { // create a matrix [Mo...M; No...N]
var Matrix = [];
for (var j=No;j<N;j++){
var row = [];
for (var i=Mo;i<M;i++){
row[i] = true; //the cell is ready for usage
}
Matrix[j] = row;
}
return Matrix;
}
function PositionImage (ImagesArray, uMatrix, Jo, Io, matrixN, matrixM){/*canvas positioning... God bless you */
/* ImagesArray - array of images to place
Jo, Io - where to start the search
matrixN, matrixM - number of cells in vertical and horizontal directions*/
var maxM = 0,
maxN = 0,
Ioo=Io;
var ImgArrLngth = ImagesArray.length;
for (var index=0;index<ImgArrLngth;index++){
Io=Ioo;
var $img = $(ImagesArray[index]);
widthCanvas = $img.data("wCanvas"),
heightCanvas = $img.data("hCanvas");
IamDone:
for (var j=Jo;j<(matrixN-heightCanvas);j++) {
MoveToNextCellinRow:
for (var i=Io;i<(matrixM-widthCanvas);i++) {
for (var r=j;r<(j+heightCanvas);r++) {
for (var s=i;s<(i+widthCanvas);s++) {
if (uMatrix[r][s] == false) {
if (j == (matrixN-heightCanvas-1) && i == (matrixM-widthCanvas-1)) { //the image is too large and does not fit the container
for (var q=0;q<matrixN;q++) { //add new column to container and try to position image again
uMatrix[q].push(true);
}
i = Io;
matrixM++; //adding new column
j=0;
}
continue MoveToNextCellinRow; //move to the next cell in row
}
}
}
for (var r=j;r<(j+heightCanvas+1);r++) {
for (var s=i;s<(i+widthCanvas+1);s++) {
uMatrix[r][s] = false;
}
}
if ((i+widthCanvas)> maxM) maxM = i+widthCanvas; //cut empty space on the right and in the bottom
if ((j+heightCanvas)> maxN) maxN = j+heightCanvas;
$img.css({"top":Math.floor(j*CellSize+$img.data("deviationY")), "left":Math.floor(i*CellSize+$img.data("deviationX"))});
break IamDone;
}
}
}
return [maxM, maxN];
}
function AddPaddings (n_m, H_W) { //add paddings between around image containers
if(CellSize*n_m*scale[length-1]<H_W) {
var newH_W = Math.round((H_W+0.5*CellSize)/scale[length -1]),
newPadding = Math.round(0.5*(newH_W-CellSize*n_m));
} else {
var newH_W = Math.round(CellSize*n_m+0.5*CellSize/scale[length -1]),
newPadding = Math.round(0.25*CellSize/scale[length -1]);
}
return [newH_W, newPadding];
}
//image container scroll animation. Very important
function AnimateLayersBunch (epageX, epageY) {
if (allowParallax < length) return false;//do not animate layers parallax while BringToTheFront is working
epageX -= main_left;
epageY -= main_top;
var RatioX = epageX/windowW,
RatioY = epageY/windowH,
k = length-1,
Left = (RatioX-0.5)*(1-scale[k]/IEsc[k])*Container[k].Wo-RatioX*(Container[k].Wo-windowW),
Top = (RatioY-0.5)*(1-scale[k]/IEsc[k])*Container[k].Ho-RatioY*(Container[k].Ho-windowH);
for (var s=0; s<k; s++) { //animate background image containers
var L = scale[s]/IEsc[k]*(Left+0.5*(IEsc[s]*Container[s].Wo-windowW))-0.5*(IEsc[s]*Container[s].Wo-windowW) ,
T = scale[s]/IEsc[k]*(Top+0.5*(IEsc[s]*Container[s].Ho-windowH))-0.5*(IEsc[s]*Container[s].Ho-windowH);
if (!AntiStumble) {
$(Container[s]).css({"left": Math.round(L), "top" : Math.round(T)});
} else {
allowParallax = 0;
$(Container[s]).animate({"left": Math.round(L), "top" : Math.round(T)},120, 'linear');
}
} // animate top image container
if (!AntiStumble) {
$(Container[k]).css({"left": Math.floor(Left), "top" : Math.floor(Top)});
} else {
$(Container[k]).animate({"left": Math.floor(Left), "top" : Math.floor(Top)}, 120, 'linear', function() {AntiStumble = 0; allowParallax = length});
}
}
function AnimateLayersMobile(){
var prevX = 0, prevY = 0,
startX = 0, endX = 0,
startY = 0, endY = 0,
d_X = 0, d_Y = 0, //where the previous touch stopped. Initially eq. zero
_delX, _delY,
is_move; // prevent touchend bubbling
main[0].ontouchmove = function(evdef){
evdef.preventDefault();
}
main.on('touchstart', function(evstart){
var start = coordinates(evstart);
scrolling = false;
startX = start.pageX - main_left;
startY = start.pageY - main_top;
d_X = prevX + (startX - 0.5*windowW);
d_Y = prevY + (startY - 0.5*windowH);
});
main.on('touchmove', function(evmove){
var move = coordinates(evmove),
moveX = move.pageX - main_left,
moveY = move.pageY - main_top,
X = moveX - d_X,
Y = moveY - d_Y,
desktopX, desktopY; // mobile coordinates -> argumets for desktop container scroll animation
_delX = moveX; // is required for detecting touchend coordinates
_delY = moveY;
//it is necessary to disallow scrolling out of the main:
desktopX = ((X>windowW)*(windowW+0.1)+(X<0)*0.1); // will return windowW or 0 if scroll to the boundary (0.1 is added since (X<0)*0 always = false)
desktopY = ((Y>windowH)*(windowH+0.1)+(Y<0)*0.1);
if (!desktopX) { // if one scrolls inside of the main
desktopX = X;
} else { // if one attempts to scroll out of the main. Boundary conditions:
desktopX = desktopX - 0.1; //remove the previously added 0.1
startX = windowW - desktopX - prevX; // amendment for correct boundary move animation
}
if (!desktopY) {
desktopY = Y;
} else {
desktopY = desktopY - 0.1;
startY = windowH - desktopY - prevY;
}
scrolling = true;
AnimateLayersBunch(windowW - desktopX + main_left , windowH - desktopY + main_top);
is_move = true;
});
main.on('touchend', function(ed){
if (is_move) {
prevX += startX - _delX; //calculate total distance
prevY += startY - _delY;
}
is_move = 0;
});
}
function DrawCorners (actimg) {
if (smart) { //roll-over size calculation
var $c_w = actimg.width()+2*$corner_w,
$c_h= actimg.height()+2*$corner_w,
$c_l = parseFloat(actimg.css("left"))-$corner_w,
$c_t = parseFloat(actimg.css("top"))-$corner_w,
corners = actimg.siblings(".corners").css({"left": $c_l, "top": $c_t});
//draw "corners" with help of canvas for smart browsers
corners[0].width=$c_w;
corners[0].height=$c_h;
var ctx=corners[0].getContext("2d");
ctx.clearRect(0, 0, $c_w, $c_h);
ctx.fillStyle = hover_color;
ctx.fillRect($corner_w, $corner_w, $c_w-2*$corner_w, $c_h-2*$corner_w);
ctx.beginPath();
ctx.strokeStyle = corner_color;
ctx.lineWidth = $corner_w;
ctx.lineCap = "square";
newCorner(ctx, 0.5*$corner_w,$corner_l, 0.5*$corner_w,0.5*$corner_w, $corner_l,0.5*$corner_w);
newCorner(ctx, $c_w-$corner_l,0.5*$corner_w, $c_w-0.5*$corner_w,0.5*$corner_w, $c_w-0.5*$corner_w,$corner_l);
newCorner(ctx, $c_w-0.5*$corner_w,$c_h-$corner_l, $c_w-0.5*$corner_w,$c_h-0.5*$corner_w, $c_w-$corner_l,$c_h-0.5*$corner_w);
ctx.stroke();
newCorner(ctx, $corner_l,$c_h-0.5*$corner_w, 0.5*$corner_w,$c_h-0.5*$corner_w, 0.5*$corner_w,$c_h-$corner_l);
ctx.stroke();
return false;
} else { //draw "corners" with help of spans for IE
var $span_t_l = actimg.siblings('span.top-l'),
$span_b_l = actimg.siblings('span.bottom-l'),
$span_t_r = actimg.siblings('span.top-r'),
$span_b_r = actimg.siblings('span.bottom-r'),
$l = parseFloat(actimg.css("left")),
$t = parseFloat(actimg.css("top")),
$w = actimg.width(),
$h = actimg.height();
$span_side = $corner_l - $corner_w;
$span_t_l.css({"opacity":0.7,"left":$l,"top":$t});
$span_b_l.css({"opacity":0.7,"left":$l,"top":$t+$h-$span_side});
$span_t_r.css({"opacity":0.7,"left":$l+$w-$span_side,"top":$t});
$span_b_r.css({"opacity":0.7,"left":$l+$w-$span_side,"top":$t+$h-$span_side});
actimg.on('mouseleave', function() {
$span_t_l.css("opacity",0);
$span_b_l.css("opacity",0);
$span_t_r.css("opacity",0);
$span_b_r.css("opacity",0);
});
}
}
function newCorner(brush, startX,startY, angleX,angleY, endX,endY) {
brush.moveTo(startX,startY);
brush.lineTo(angleX,angleY);
brush.lineTo(endX,endY);
}
function FindOnClickImage (planes, ev) {
var count = planes.length - 1,
el_below = ev.target;
SwitchDarkLayers();
while (!$(el_below).hasClass("photo") && (count != 0)){
var e = new jQuery.Event("click");
e.pageX = ev.pageX - scrollLeft; //calculate click coordinates considering document scroll correction
e.pageY = ev.pageY - scrollTop;
$(planes[count]).addClass("toBG");
el_below = document.elementFromPoint(e.pageX, e.pageY);
count--;
}
var planes_length = planes.length;
for (var pp=0;pp<planes_length;pp++) {
$(planes[pp]).removeClass("toBG");
}
SwitchDarkLayers();
if (!$(el_below).hasClass("photo")) el_below = false
return el_below;
}
function SwitchDarkLayers(){ // switch on/off dark layers when searching for an onclick target image
for (var i=0;i<DarkLayers.length;i++){
$(DarkLayers[i]).toggleClass('toBG');
}
return DarkLayers;
}
$.fn.BringToTheFront = function() { //bring chosen image container to the top
if (!useNavig) {
var $this = $(this),
$self = $this.parent('div.container');
navig.children('div.act').removeClass('act');
navig.children(':nth-child('+(length - $self.index('div.container'))+')').addClass('act');
ViewImg($this);
} else {
var $self = $(this);
AnimateLayersBunch(0.5*windowW,0.5*windowH);
}
allowParallax = 0;
var current = $self[0].ind,
dif = length - 1 - current,
reOrderCont = [];
main.addClass('scale-me').removeClass('slide-me');
for (var i=0;i<current+1;i++) {
var ind = (i+dif)%length,
duration = (ind - i)*layer_time;
reOrderCont[ind] = OnlyToFront(Container[i], scale[ind], indexZ[ind], duration);
reOrderCont[ind].ind = ind;
if (useNavig) {
timer2 = setTimeout(function() {
allowParallax++;
useNavig--;
}, 1.25*(duration-layer_time));
}
}
for (var ii=current+1;ii<length;ii++) {
var ind = (ii+dif)%length,
durBefore = (length - 1 - ii)*layer_time,
durAfter = (ind)*layer_time;
reOrderCont[ind] = ToFrontAndBack(Container[ii], scale[ind], indexZ[ind], durBefore, durAfter);
reOrderCont[ind].ind = ind;
if (useNavig) {
timer3 = setTimeout(function() {
allowParallax++;
useNavig--;
Math.floor(allowParallax/length)*main.removeClass('scale-me').addClass('slide-me');
}, durBefore+tscr+tdel+300+durAfter+t0);
}
}
return reOrderCont;
}
function OnlyToFront (el, scaling, Zindex, duration0){ // animate image container, which move to the front only
dark_layer1.removeClass('l1'); // disable dark layers when an image is coming to the front
dark_layer2.removeClass('l2');
if (smart && !useJS) {
$(el).css(TrasitDur,layer_time+"ms").css(TrasitDel,"0ms")
.css(Transform, "scale("+scaling+","+scaling+")");
} else {
el = ScaleIE(scaling, el, duration0);
}
timer4 = setTimeout(function() {
$(el).css({"zIndex": Zindex});
dark_layer1.addClass('l1');
dark_layer2.addClass('l2');
}, 1.25*(duration0-layer_time));
return el;
}
function ToFrontAndBack (el, scaling, Zindex, duration1, duration2) { // animate image container, which move to the front -> back -> target position
var ttt1=duration1+tscr; ttt2=0.5*duration1;
$(el).css("zIndex", 90*scaling); //the bigger is scale, the more z-index should be
if (smart && !useJS) {
$(el).css(TrasitDur,ttt1+"ms, "+tscr+"ms").css(TrasitDel," 0ms, "+ttt2+"ms")
.css(Transform, "scale(1,1)").css({"opacity":0});
} else {
el = ScaleIE(1, el, ttt1);
if (isMobile) $(el).css({"opacity":0}).css(TrasitDur,tscr+"ms").css(TrasitDel,ttt2+"ms");
}
timer5 = setTimeout(function() {
$(el).css({"zIndex": Zindex});
if (smart && !useJS) {
$(el).css(TrasitDur,"0ms").css(TrasitDel,"0ms").css(Transform, "scale(0.1,0.1)");
} else {
el = ScaleIE(0.1, el, 0);
if (!isMobile) $(el).css('visibility','hidden');
}
}, duration1+tscr+tdel);
var ttt3 = duration2+t0; ttt4 = 0.5*t0;
timer6 = setTimeout(function() {
if (smart && !useJS) {
$(el).css(TrasitDur,ttt3+"ms, "+ttt4+"ms").css(TrasitDel," 0ms")
.css(Transform, "scale("+scaling+","+scaling+")").css({"opacity":1});
} else {
$(el).css('visibility','visible');
el = ScaleIE(scaling, el, ttt3);
if (isMobile) {
$(el).css({"opacity":1}).css(TrasitDur,ttt4+"ms").css(TrasitDel," 0ms");
} else {$(el).css('visibility','visible');}
}
}, duration1+tscr+tdel+300);
return el;
}
function ScaleIE (scale, plane, time){ //scale planes for old IE with help of JS, since it does not undertsand CSS3
var newscale = scale/plane.Scale;
plane.Scale = scale;
var inContW = plane.Wo,
inContH = plane.Ho,
inContT = parseFloat($(plane).css("top")),
inContL = parseFloat($(plane).css("left")),
images = $(plane).children('.photo'),
ieW = Math.round(newscale*inContW),
ieH = Math.round(newscale*inContH);
$(plane).animate({
"width": ieW,
"height": ieH,
"top": Math.round(inContT+0.5*(1-newscale)*inContH),
"left": Math.round(inContL+0.5*(1-newscale)*inContW)
}, time);
//for correct AnimateLayersBunch functioning
plane.Wo = ieW;
plane.Ho = ieH;
var images_length = images.length;
for (var j=0;j<images_length;j++){
var inImW = parseFloat($(images[j]).css("width")), //.css('width') instead of .width() - to satisfy both IE8 and IE9
inImH = parseFloat($(images[j]).css("height")),
inImT = parseFloat($(images[j]).css("top")),
inImL = parseFloat($(images[j]).css("left"));
if (!$(images[j]).hasClass('show')) {
$(images[j]).animate({
"width": Math.round(newscale*inImW),
"height": Math.round(newscale*inImH),
"top": Math.round(newscale*inImT),
"left": Math.round(newscale*inImL)
}, time);
}
}
return plane;
}
function Launch() { // launch slider script
clearInterval(timer7); // clear the timer of image preloader
loading.css("display", "none");
Container = createContainers(Plane);
drawCanvas(Plane, Container);
if (useJS *= isMobile) main.addClass('useJS'); //use JS for mobile only
$('div.plane').remove();
//calculate size and scale for all planes
ResizePlanes();
DarkLayers=main.find('div.dark-layer');
if (!smart) {
closeX.css("display","none"); //to apply fadeIn then
caption.css("display","none")
} else {
$corner_w = Math.round($corner_w/scale[length-1]); //image roll-over width considering css3 scale();
$corner_l = Math.round($corner_l/scale[length-1]);//image roll-over height considering css3 scale();
}
//start animation only in case all containers are positioned
if ($(Container[length-1]).width())
{
/*animate the top container and position the rest of layers according to its position*/
main.on('click',function(ev){
if ((allowParallax == length)&& (!$(ev.target).hasClass("act"))) {
var targ = FindOnClickImage(Container, ev);
if (targ) {
Container = $(targ).BringToTheFront();
}
}
});
}
// launch container scroll animation for desktop
if (!isMobile){
main.on('mousemove',function(ex){
AnimateLayersBunch(ex.pageX, ex.pageY);
});
main.children('div.container').children('.photo').on('click', function() {
if ($(this).parent(".container")[0] == Container[length-1]) // necessary for IE: it has all layers clickable
ViewImg($(this));
});
main.children('div.container').children('canvas.corners').on('click touchend',function(){
ViewImg($hovered);
});
main.children('div.container').children('.photo').not('.top-slice').on('mouseenter', function(evnt) { // image "corners" roll-over
$hovered = $(evnt.target);
if(($hovered.parent(".container")[0] == Container[length-1])&&(!$hovered.hasClass('top-slice'))) { // necessary for IE: it has all layers clickable
DrawCorners($hovered);
}
});
// launch container scroll animation for mobile
} else {
AnimateLayersMobile();
main.children('div.container').children('.photo').on('touchend', function() {
if (!scrolling) // prevent click if touchmove, or if previous lightbox image animation is not finished yet
ViewImg($(this));
});
}
navig.children('div').on('click touchend',function(){
LayersNavig($(this));
});
}
function ViewImg($IMG) { // view a single image in a lightbox
if (!$IMG.hasClass('show') && (allowParallax == length)) { //first click - to open lightbox
isLightbox = 1;
allowParallax = 0;
inImW = $IMG.width();
inImH = $IMG.height();
inImT = parseFloat($IMG.css("top"));
inImL = parseFloat($IMG.css("left"));
$parent = $IMG.parent();
sc = scale[length-1];
inScale = scale[$parent[0].ind];
$dark_bg = $IMG.siblings('.dark-layer').addClass('l3');
main[0].ontouchstart = function(evdef){
evdef.preventDefault();
}
var parentT = parseFloat($parent.css("top")),
parentL = parseFloat($parent.css("left")),
parentW = $parent[0].Wo,
parentH = $parent[0].Ho,
parentTrasitDur = $parent.css(TrasitDur);
main.addClass('lightbox');
$IMG.addClass('show top-slice');/*.css(TrasitDur,parentTrasitDur)*/;
ImgFitScreen($IMG, inImW, inImH, sc, inScale, parentW, parentH, parentL, parentT, $dark_bg); //display the image in lightbox. If the image is too large, downscale
if (smart && !useJS) {
$dark_bg.css({"width":windowW, "height": windowH,
"left": Math.round((0.5*(parentW-windowW)*(inScale-1)-parentL)/inScale),
"top": Math.round((0.5*(parentH-windowH)*(inScale-1)-parentT)/inScale)
});
} else {
$IMG.siblings('span').css("opacity",0);
$dark_bg.css({"width":windowW, "height": windowH,
"left": Math.round(-parentL-0.5*(1-sc/inScale)*parentW),
"top": Math.round(-parentT-0.5*(1-sc/inScale)*parentH),
"display":"none"
});
}
$(window).resize(function() {
if (isLightbox && smart) {
main_left = main.offset().left;
main_top = main.offset().top;
EasyReposition();
parentT = parseFloat($parent.css("top"));
parentL = parseFloat($parent.css("left"));
ImgFitScreen(main.children('div.container').children('.show.top-slice'), inImW, inImH, sc, inScale, parentW, parentH, parentL, parentT, $dark_bg); //otherwise, it caches all IMGs
}
});
closeX.on('mouseover', function(){
closeX.addClass('hovered'); //remove delay of opacity animation
})
closeX.on('click touchend', function() { // 'close' button is pressed
ViewImg($IMG)
});
$(document).keyup(function(e) {
if (e.keyCode == 27) ViewImg($IMG); // ESC is pressed
});
return true;
} else if ($IMG.hasClass('show') && (Container.length == length) && (closeX[0].offsetWidth)) { //second click - to close lightbox
main[0].ontouchstart = function(evdef){
return true;
}
main.removeClass("lightbox");
closeX.removeClass('hovered'); // add delay of opacity animation
$IMG.siblings(".dark-layer").removeClass('l3');
/*put the image back to its initial position*/
if (smart && !useJS) {
$IMG.removeClass('show').css({"left": Math.round(inImL), "top": Math.round(inImT), "maxWidth": "none", "maxHeight": "none"});
} else {
$IMG.removeClass('show').animate({
"left": Math.round(sc*inImL/inScale), "top": Math.round(sc*inImT/inScale),
"width":Math.round(sc*inImW/inScale), "height":Math.round(sc*inImH/inScale)}, 400)
.css({"maxWidth": "none", "maxHeight": "none"});
closeX.fadeOut();
$dark_bg.fadeOut();
caption.fadeOut();
}
timer1 = setTimeout(function() {
$IMG.removeClass('top-slice');
allowParallax = length; // important. It is possible to unclick an image while container still are being reordered
isLightbox = 0;
AntiStumble = 1;
main.removeClass('scale-me').addClass('slide-me');
}, 400);
return true;
}
}
function ImgFitScreen($Img, InImW, InImH, sc, InScale, ParentW, ParentH, ParentL, ParentT, $darkbg) { //display the image in lightbox. If the image is too large, downscale
var $w, $h,
closeX_left = 30,
ifsmart=(smart*!useJS)+(!smart+useJS)*InScale;
if ((InImW/ifsmart>windowW)||(InImH/ifsmart>(windowH-110))) { //if image does not fit in the window
if ((InImW/InImH)>(windowW/windowH)) { // if image is wider than the window
var maxW = windowW-2*closeX.width(),
maxH = Math.round((windowW-2*closeX.width())*InImH/InImW);
closeX_left = 0.5*closeX.width();
} else {
var maxW = Math.round((windowH-110)*InImW/InImH),
maxH = windowH-110;
}
$Img.css({"maxHeight": maxH, "maxWidth": maxW});//do not use "auto" because of Opera
$w = maxW*ifsmart;
$h = maxH*ifsmart;
} else {
$w = InImW;
$h = InImH;
}
if (smart && !useJS) {
$Img.css({
"left": Math.round(0.5*(windowW-$w*sc-2*ParentL-ParentW*(1-sc))/sc),
"top": Math.round(0.5*(windowH-$h*sc-2*ParentT-ParentH*(1-sc))/sc)
});
} else {
$Img.animate({
"left": Math.round(-ParentL-0.5*(1-sc/InScale)*ParentW+0.5*(windowW-$w/InScale)),
"top": Math.round(-ParentT-0.5*(1-sc/InScale)*ParentH+0.5*(windowH-$h/InScale)),
"width": Math.round(($w/InScale)),
"height": Math.round(($h/InScale))
}, 850,function(){closeX.delay(700).fadeIn(400);
$darkbg.delay(700).fadeIn(400);
caption.delay(700).fadeIn(400);
});
}
caption.css("top",Math.round(0.5*(windowH+$h/((smart*!useJS)+(!smart+useJS)*InScale))));
caption_text.text($Img.attr('alt'));
closeX.css({"top":Math.round(0.5*(windowH-$h/((smart*!useJS)+(!smart+useJS)*InScale))),
"left": Math.round(0.5*$w/((smart*!useJS)+(!smart+useJS)*InScale)+closeX_left)
});
return $Img;
}
function LayersNavig($ths) { // navigation buttons
if ((allowParallax >= length) && (!$ths.hasClass('act'))) {
AnimateLayersMobile();
useNavig = length;
var actind = length - navig.children('.act').index(),
curind = length- $ths.index(),
difr = length-1-actind;
navig.children('.act').removeClass('act');
$ths.addClass('act');
Container = $(Container[(curind+difr)%length]).BringToTheFront();
}
}
$('div.plane img').loaded(function() {
++loaded_imgs;
});
LoadProgress();
function TotalDestroy () {
clearTimeout(timer1);
clearTimeout(timer2);
clearTimeout(timer3);
clearTimeout(timer4);
clearTimeout(timer5);
clearTimeout(timer6);
clearTimeout(timer7);
clearInterval(timer8);
main.children('div.container').children('.photo').off("click");
closeX.off("click");
main.off("click");
main.off("mousemove");
main.children('div.container').children('.photo').off('mouseenter');
main.children('div.container').children('.photo').off('mouseleave');
!isMobile*main.children('div.container').children('canvas.corners').off('click');
dark_layer1.remove();
dark_layer2.remove();
closeX.remove();
caption.remove();
Container.remove();
}
}
});
/***************************************************************************************/
jQuery(document).ready(function($) {
$.theScroller = function(el, options) {
var self = this,
$el = $(el);
$el.data("theScroller", self);
var isActive = false,
isScrolling = false,
threshold = 20,
contentX = 0,
contentCurX = 0,
offsetX, startX, lockX, offsetY, startY, lockY;
var elWidth = 0,
$content = $el.children(),
contentWidth = 0,
$slides = $content.children(),
slidesPosition = [],
csstransitions = ( typeof Modernizr != "undefined" ) ? Modernizr.csstransitions : false;
var tempStyle = document.createElement('div').style,
vendors = ['webkit','Moz','ms','O'],
vendor = '',
tempV;
for (i = 0; i < vendors.length; i++ ) {
tempV = vendors[i];
if (!vendor && (tempV + 'Transform') in tempStyle ) {
vendor = "-"+tempV.toLowerCase()+"-";
}
}
var tempCSS = {};
tempCSS[vendor+"user-select"] = "none";
tempCSS["user-select"] = "none";
$content.css(tempCSS);
$slides.each(function(i) {
slidesPosition[i] = -contentWidth;
contentWidth = $(this).width() + contentWidth;
});
$content.css({"width": contentWidth});
setUp();
if(options.prev) {
options.prev.on("click", function() {
if (!isScrolling) toPrev();
});
}
if(options.next) {
options.next.on("click", function() {
if (!isScrolling) toNext();
});
}
function transitionStart(coord) {
if (csstransitions) {
var tempCSS = {};
tempCSS["left"] = coord;
tempCSS[vendor+"transition"] = "left 150ms ease-out";
tempCSS["transition"] = "left 150ms ease-out";
$content.css(tempCSS);
}
else {
$content.animate({
"left": coord
}, 150, "linear");
};
};
function transitionStop() {
if (csstransitions) {
var tempCSS = {};
tempCSS[vendor+"transition"] = "none";
tempCSS["transition"] = "none";
$content.css(tempCSS);
};
};
function time() {
return (new Date()).getTime();
}
function unifiedEvent(event) {
if (event.originalEvent.touches !== undefined && event.originalEvent.touches[0]) {
event.pageX = event.originalEvent.touches[0].pageX;
event.pageY = event.originalEvent.touches[0].pageY;
}
return event;
}
function setNav() {
if (contentX <= -contentWidth + elWidth) {
rightMost();
notLeftMost();
}
else if (contentX >= 0) {
leftMost();
notRightMost();
}
else {
notRightMost();
notLeftMost();
};
}
function setUp() {
unbindEvents();
elWidth = $el.width();
if (elWidth > contentWidth) {
isActive = false;
$content.css({
left: (elWidth - contentWidth)/2
});
contentX = 0;
rightMost();
leftMost();
return false;
}
isActive = true;
if (contentX <= -contentWidth + elWidth) contentX = -contentWidth + elWidth;
setNav();
$content.css({
"left": contentX
});
bindEvents();
};
function onStart(event) {
if (!isScrolling) {
transitionStop();
isScrolling = true;
startX = event.pageX;
startY = event.pageY;
contentX = $content.position().left;
offsetX = 0;
offsetY = 0;
lockX = false;
lockY = false;
}
};
function onScroll(event) {
if (isScrolling) {
offsetX = event.pageX - startX;
offsetY = event.pageY - startY;
if ( (Math.abs(offsetX) >= threshold-1) && (Math.abs(offsetX) > Math.abs(offsetY)) && !lockX ) {
lockX = false;
lockY = true;
if (event.type == "touchmove") offsetY = 0;
} else if( (Math.abs(offsetY) >= threshold-1) && (Math.abs(offsetX) < Math.abs(offsetY)) && !lockY ) {
lockX = true;
lockY = false;
if (event.type == "touchmove") offsetX = 0;
};
if (lockX && event.type == "touchmove") offsetX = 0;
else if (lockY && event.type == "touchmove") offsetY = 0;
if (lockY) event.preventDefault();
contentCurX = contentX + offsetX;
if ( contentCurX < 0 && contentCurX > -contentWidth + elWidth) {
$content.css({
"left": contentCurX
});
}
else if (contentCurX >= 0) {
$content.css({
"left": contentCurX/4
});
}
else {
$content.css({
"left": (-contentWidth + elWidth) + ((contentWidth - elWidth + contentCurX) / 4)
});
};
};
};
function onStop(event) {
if (isScrolling) {
isScrolling = false;
if (contentCurX > 0) {
contentX = 0;
transitionStart(contentX);
}
else if ( contentCurX <= -contentWidth + elWidth ) {
contentX = -contentWidth + elWidth
transitionStart(contentX);
}
else {
$slides.each(function(i) {
if ( contentCurX > slidesPosition[i] ) {
if (offsetX < -threshold) {
contentX = !(slidesPosition[i] <= -contentWidth + elWidth) ? slidesPosition[i] : -contentWidth + elWidth;
}
else if(offsetX > threshold) {
contentX = slidesPosition[i-1]
}
else {
contentX = contentX;
}
transitionStart(contentX);
return false;
};
});
};
}
setNav();
return false;
};
function bindEvents() {
$content.on("mousedown.theScroller touchstart.theScroller", function(event) {
if (event.type != "touchstart") event.preventDefault();
onStart( unifiedEvent(event) );
$(document).on("mousemove.theScroller touchmove.theScroller", function(event) {
onScroll( unifiedEvent(event) );
});
$(document).on("mouseup.theScroller mouseleave.theScroller touchend.theScroller touchcancel.theScroller", function(event) {
$(document).off("mousemove.theScroller mouseup.theScroller mouseleave.theScroller touchmove.theScroller touchend.theScroller touchcancel.theScroller");
onStop( unifiedEvent(event) );
});
});
};
function unbindEvents() {
$content.off();
};
function rightMost() {
if(options.next) {
options.next.addClass("disabled");
}
};
function leftMost() {
if(options.prev) {
options.prev.addClass("disabled");
}
};
function notRightMost() {
if(options.next) {
options.next.removeClass("disabled");
}
};
function notLeftMost() {
if(options.prev) {
options.prev.removeClass("disabled");
}
};
function toNext() {
if (!isActive) return false;
isScrolling = true;
contentCurX = $content.position().left;
offsetX = - threshold - 1;
onStop();
};
function toPrev() {
if (!isActive) return false;
isScrolling = true;
contentCurX = $content.position().left + 1;
offsetX = threshold + 1;
onStop();
};
self.update = function() {
if(!isScrolling) setUp(); /* Fixes bug with "resize" event triggering in Safari 6 on iPhone; probably causes other bugs :P */
};
};
$.fn.theScroller = function(options) {
return this.each(function() {
( new $.theScroller(this, options) );
});
};
}); | JavaScript |
//console.log(Modernizr)
jQuery(document).ready(function($) {
if ($.browser.msie) $("html").removeClass("csstransforms3d");
var dtGlobals = {}; // Global storage
/* !Custom touch events */
/* !(we need to add swipe events here) */
dtGlobals.touches = {};
dtGlobals.touches.touching = false;
dtGlobals.touches.touch = false;
dtGlobals.touches.currX = 0;
dtGlobals.touches.currY = 0;
dtGlobals.touches.cachedX = 0;
dtGlobals.touches.cachedY = 0;
dtGlobals.touches.count = 0;
dtGlobals.resizeCounter = 0;
dtGlobals.isMobile = (/(Android|BlackBerry|iPhone|iPod|iPad|Palm|Symbian)/.test(navigator.userAgent));
dtGlobals.isAndroid = (/(Android)/.test(navigator.userAgent));
dtGlobals.isiOS = (/(iPhone|iPod|iPad)/.test(navigator.userAgent));
dtGlobals.isiPhone = (/(iPhone|iPod)/.test(navigator.userAgent));
dtGlobals.isiPad = (/(iPad)/.test(navigator.userAgent));
$(document).on('touchstart',function(e) {
if (e.originalEvent.touches.length == 1) {
dtGlobals.touches.touch = e.originalEvent.touches[0];
// caching the current x
dtGlobals.touches.cachedX = dtGlobals.touches.touch.pageX;
// caching the current y
dtGlobals.touches.cachedY = dtGlobals.touches.touch.pageY;
// a touch event is detected
dtGlobals.touches.touching = true;
// detecting if after 200ms the finger is still in the same position
setTimeout(function() {
dtGlobals.touches.currX = dtGlobals.touches.touch.pageX;
dtGlobals.touches.currY = dtGlobals.touches.touch.pageY;
if ((dtGlobals.touches.cachedX === dtGlobals.touches.currX) && !dtGlobals.touches.touching && (dtGlobals.touches.cachedY === dtGlobals.touches.currY)) {
// Here you get the Tap event
dtGlobals.touches.count++;
$(e.target).trigger("tap");
}
},200);
}
});
$(document).on('touchend touchcancel',function (e){
// here we can consider finished the touch event
dtGlobals.touches.touching = false;
});
$(document).on('touchmove',function (e){
dtGlobals.touches.touch = e.originalEvent.touches[0];
if(dtGlobals.touches.touching) {
// here you are swiping
}
});
$(document).on("tap", function(e) {
$(".dt-hovered").trigger("mouseout");
});
/* Custom touch events:end */
/* !Debounced resize event */
var dtResizeTimeout;
$(window).on("resize", function() {
clearTimeout(dtResizeTimeout);
dtResizeTimeout = setTimeout(function() {
$(window).trigger( "debouncedresize" );
}, 200);
});
/* Debounced resize event: end */
/* !jQuery extensions */
/* !- Check if element exists */
$.fn.exists = function() {
if ($(this).length > 0) {
return true;
} else {
return false;
}
}
/* !- Check if element is loaded */
$.fn.loaded = function(callback, jointCallback, ensureCallback){
var len = this.length;
if (len > 0) {
return this.each(function() {
var el = this,
$el = $(el),
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
$el.on("load.dt", function(event) {
$(this).off("load.dt");
if (typeof callback == "function") {
callback.call(this);
}
if (--len <= 0 && (typeof jointCallback == "function")){
jointCallback.call(this);
}
});
if (!el.complete || el.complete === undefined) {
el.src = el.src;
} else {
$el.trigger("load.dt")
}
});
} else if (ensureCallback) {
if (typeof jointCallback == "function") {
jointCallback.call(this);
}
return this;
}
};
/* jQuery extensions: end */
/* !Main navigation */
/* We need to fine-tune timings and do something about the usage of jQuery "animate" function */
$("#mobile-menu").wrap('<div id="dl-menu" class="dl-menuwrapper wf-mobile-visible" />');
var $mainNav = $("#main-nav");
$(".act", $mainNav).parents("li").addClass("act");
var $mobileNav = $mainNav.clone();
var backCap = $("#mobile-menu > .menu-back").html();
$mobileNav
.attr("id", "")
.attr("class", "dl-menu")
.find(".sub-nav")
.addClass("dl-submenu")
.removeClass("sub-nav")
.prepend('<li class="dl-back"><a href="#"><span>'+backCap+'</a></li>');
$mobileNav.appendTo("#dl-menu").wrap('<div class="dl-container" />');
if (!$("html").hasClass("old-ie")) $( '#dl-menu' ).dlmenu();
if ($mainNav.hasClass("fancy-rollovers") && $("html").hasClass("csstransforms3d")) {
$("> li > a", $mainNav).each(function() {
var $this = $(this).css("padding", 0),
tempHtml = $this.html();
tempHtml = '<span>'+tempHtml+'<span>'+tempHtml+'</span></span>';
$this.html(tempHtml);
});
}
$(".sub-nav", $mainNav).parent().each(function() {
var $this = $(this);
$this.find("> a").on("click", function(e) {
if (!$(this).hasClass("dt-clicked")) {
e.preventDefault();
$mainNav.find(".dt-clicked").removeClass("dt-clicked");
$(this).addClass("dt-clicked");
} else {
e.stopPropagation();
}
});
var menuTimeoutShow,
menuTimeoutHide;
$this.on("mouseenter tap", function(e) {
if(e.type == "tap") e.stopPropagation();
var $this = $(this);
$this.addClass("dt-hovered");
if ($("#page").width() - ($this.children('ul').offset().left - $("#page").offset().left) - 230 < 0) {
$this.children('ul').addClass("right-overflow");
}
clearTimeout(menuTimeoutShow);
clearTimeout(menuTimeoutHide);
menuTimeoutShow = setTimeout(function() {
if($this.hasClass("dt-hovered")){
$this.children('ul').stop().css("visibility", "visible").animate({
"opacity": 1
}, 200);
}
}, 350);
});
$this.on("mouseleave", function(e) {
var $this = $(this);
$this.removeClass("dt-hovered");
clearTimeout(menuTimeoutShow);
clearTimeout(menuTimeoutHide);
menuTimeoutHide = setTimeout(function() {
if(!$this.hasClass("dt-hovered")){
$this.children('ul').stop().animate({
"opacity": 0
}, 150, function() {
$(this).css("visibility", "hidden");
});
setTimeout(function() {
if(!$this.hasClass("dt-hovered")){
$this.children('ul').removeClass("right-overflow");
}
}, 400);
}
}, 200);
$this.find("> a").removeClass("dt-clicked");
});
});
/* Main navigation: end */
/* !Navigation widget */
$('.custom-nav > li > a').click(function(e){
$menuItem = $(this).parent();
if ($menuItem.hasClass("has-children")) e.preventDefault();
if ($(this).attr('class') != 'active'){
$('.custom-nav > li > ul').slideUp(400);
$(this).next().slideDown(500);
$('.custom-nav > li > a').removeClass('active');
$(this).addClass('active');
}
$menuItem.siblings().removeClass("act");
$menuItem.addClass("act");
});
$('.custom-nav > li > ul').each(function(){
$this = $(this);
$thisChildren = $this.find('li');
if($thisChildren.hasClass('act')){
$this.prev().addClass('active');
$this.parent().siblings().removeClass("act");
$this.parent().addClass('act');
$(this).slideDown(500);
}
});
/* Navigation widget: end */
$('.shortcode-tabs').goTabs().css('visibility', 'visible');
/* !Royal Slider */
if ($(".rsHomePorthole").exists()) {
var portholeSlider = {};
portholeSlider.container = $("#main-slideshow");
portholeSlider.width = portholeSlider.container.attr("data-width") ? parseInt(portholeSlider.container.attr("data-width")) : 1280;
portholeSlider.height = portholeSlider.container.attr("data-height") ? parseInt(portholeSlider.container.attr("data-height")) : 720;
portholeSlider.autoslide = portholeSlider.container.attr("data-autoslide") && parseInt(portholeSlider.container.attr("data-autoslide")) > 999 ? parseInt(portholeSlider.container.attr("data-autoslide")) : 5000;
portholeSlider.scale = portholeSlider.container.attr("data-scale") ? portholeSlider.container.attr("data-scale") : "fill";
portholeSlider.paused = portholeSlider.container.attr("data-paused") ? portholeSlider.container.attr("data-paused") : true;
portholeSlider.hendheld = $(window).width() < 740 && dtGlobals.isMobile ? true : false;
$("#main-slideshow-content").appendTo(portholeSlider.container);
portholeSlider.api = $(".rsHomePorthole").royalSlider({
autoScaleSlider: true,
autoScaleSliderWidth: portholeSlider.width,
autoScaleSliderHeight: portholeSlider.height,
autoPlay: {
enabled: !portholeSlider.hendheld,
stopAtAction: false,
pauseOnHover: false,
delay: portholeSlider.autoslide
},
imageScaleMode: portholeSlider.scale,
imageScalePadding: 0,
numImagesToPreload: 6,
slidesOrientation: "horizontal",
disableResponsiveness: false,
loopRewind: true,
arrowsNav: false,
globalCaption: true,
controlNavigation: !portholeSlider.hendheld ? 'porthole' : 'none',
thumbs: {
orientation: 'vertical',
drag: false,
touch: false,
spacing: 10,
firstMargin: false,
appendSpan: false
},
block: {
fadeEffect: true,
moveEffect: 'bottom',
moveOffset: 5
}
}).data("royalSlider");
if (portholeSlider.paused === "true" || portholeSlider.paused === true) portholeSlider.api.stopAutoPlay();
}
$(".slider-post").each(function(){
$(this).royalSlider({
autoScaleSlider: true,
imageScaleMode: "fit",
autoScaleSliderWidth: $(this).attr('data-width'),
autoScaleSliderHeight: $(this).attr('data-height'),
imageScalePadding: 0,
numImagesToPreload: 6,
slidesOrientation: "horizontal",
disableResponsiveness: false,
globalCaption:true
});
});
$(".slider-simple").each(function(){
$(this).royalSlider({
autoScaleSlider: true,
imageScaleMode: "fit",
autoScaleSliderWidth: $(this).attr('data-width'),
autoScaleSliderHeight: $(this).attr('data-height'),
imageScalePadding: 0,
numImagesToPreload: 6,
slidesOrientation: "horizontal",
disableResponsiveness: false,
globalCaption:true
});
});
$(".slider-content").each(function(){
var $this = $(this),
autoslide = $this.attr("data-autoslide") && parseInt($this.attr("data-autoslide")) > 999 ? parseInt($this.attr("data-autoslide")) : 5000;
hendheld = !($(window).width() < 740 && dtGlobals.isMobile) && $this.attr("data-autoslide") ? true : false;
$this.royalSlider({
autoPlay: {
enabled: hendheld,
stopAtAction: false,
pauseOnHover: false,
delay: autoslide
},
autoHeight: true,
controlsInside: false,
fadeinLoadedSlide: false,
controlNavigationSpacing: 0,
controlNavigation: 'bullets',
imageScaleMode: 'none',
imageAlignCenter:false,
loop: false,
loopRewind: true,
numImagesToPreload: 6,
keyboardNavEnabled: true
}).data('royalSlider');
});
/* Royal Slider: end */
//Full-width scroller
$(".fullwidth-slider").each(function() {
var $this = $(this),
scroller = $this.theScroller({
"prev": $this.parent().find('.prev'),
"next": $this.parent().find('.next')
}).data("theScroller");
});
//Instagram
function calcPics(maxitemwidth){
var $collection = $('.instagram-photos');
if ($collection.length < 1) return false;
//var maxitemwidth = maxitemwidth ? maxitemwidth : parseInt($collection.find('> a').css('max-width'));
$collection.each(function(){
/* $(this).find('a').css({ 'width': (100/(Math.ceil($(this).width()/maxitemwidth)))+'%' }); // Not optimized */
var maxitemwidth = maxitemwidth ? maxitemwidth : parseInt($(this).find('> a').css('max-width'));
// Cahce everything
var $container = $(this),
containerwidth = $container.width(),
itemperc = (100/(Math.ceil(containerwidth/maxitemwidth)));
$container.find('a').css({ 'width': itemperc+'%' });
});
};
function moveOffset(){
if( $(".map-container.full").length ){
var offset_map = $(".map-container.full").position().left;
$(".map-container.full").css({
width: $('#main').width(),
marginLeft: -offset_map
});
};
if( $(".slider-wrapper").length ){
$(".slider-wrapper.full").each(function(){
var offset_fs = $(this).position().left;
var $frame = $(this).children('.fullwidth-slider');
$(this).css({
width: $('#main').width(),
'margin-left': -offset_fs
});
var scroller = $(this).children().data("theScroller");
scroller.update();
});
};
};
/*calcPics();
moveOffset();*/
/* !Masonry layout: */
var $isoCollection = $(".iso-container");
var $gridCollection = $(".wf-container.grid-masonry");
// !- Columns width calculation
function calculateColumns(container) {
var $isoContainer = container,
containerWidth = $isoContainer.width(),
minCol = Math.floor(containerWidth / 12);
if (minCol*3 >= 200) {
$("> .iso-item", $isoContainer).each(function() {
var $this = $(this);
if ($this.hasClass("wf-1-4")) {
$this.css("width", minCol*3);
} else if ($this.hasClass("wf-2-4") || $this.hasClass("wf-1-2")) {
$this.css("width", minCol*6);
} else if ($this.hasClass("wf-1-3")) {
$this.css("width", minCol*4);
} else if ($this.hasClass("wf-2-3")) {
$this.css("width", minCol*8);
}
});
} else if ( minCol*3 < 200 && minCol*3 > 150) {
$("> .iso-item", $isoContainer).each(function() {
var $this = $(this);
if ($this.hasClass("wf-1-4")) {
$this.css("width", minCol*6);
} else if ($this.hasClass("wf-2-4") || $this.hasClass("wf-1-2")) {
$this.css("width", minCol*12);
} else if ($this.hasClass("wf-1-3")) {
$this.css("width", minCol*6);
} else if ($this.hasClass("wf-2-3")) {
$this.css("width", minCol*12);
}
});
} else if ( minCol*3 <= 150) {
$("> .iso-item", $isoContainer).each(function() {
$(this).css("width", minCol*12);
});
}
};
$isoCollection.each(function() {
var $isoContainer = $(this);
calculateColumns($isoContainer);
$(".preload-me", $isoContainer).loaded(null, function() {
// !- Slider initialization
$(".slider-masonry", $isoContainer).each(function(){
var $_this = $(this),
attrW = $_this.data('width'),
attrH = $_this.data('height');
$_this.royalSlider({
autoScaleSlider: true,
autoScaleSliderWidth: attrW,
autoScaleSliderHeight: attrH,
imageScaleMode: "fit",
imageScalePadding: 0,
slidesOrientation: "horizontal",
disableResponsiveness: true
});
});
// !- Masonry initialization
$isoContainer.isotope({
itemSelector : '.iso-item',
resizable: false,
layoutMode : 'masonry',
animationEngine: 'best-available',
masonry: { columnWidth: 1 },
getSortData : {
date : function( $elem ) {
return $elem.attr('data-date');
},
name : function( $elem ) {
return $elem.attr('data-name');
}
}
});
$(".iso-item", $isoContainer).css("visibility", "visible");
// !- Window resize event
$(window).on("debouncedresize", function () {
calculateColumns($isoContainer);
$(".royalSlider", $isoContainer).each(function() {
$(this).data('royalSlider').updateSliderSize();
});
$isoContainer.isotope('reLayout');
});
}, true);
});
/**/
function calculateGridColumns(container) {
var $gridContainer = container,
containerWidth = $gridContainer.width();
if( $('#main').hasClass('sidebar-none') ){
minCol = Math.floor(containerWidth / 248);
}else{
minCol = Math.floor(containerWidth / 186);
}
if ( minCol == 5) {
$("> .wf-cell", $gridContainer).each(function() {
var $this = $(this);
if ($this.hasClass("wf-1-4")) {
$(this).css("width", minCol*5 + "%");
}else if ($this.hasClass("wf-2-4") || $this.hasClass("wf-1-2")) {
$this.css("width", minCol*10 + "%");
} else if ($this.hasClass("wf-1-3")) {
$this.css("width", minCol*6.6666 + "%");
}
});
} else if ( minCol < 5 && minCol >= 4) {
$("> .wf-cell", $gridContainer).each(function() {
var $this = $(this);
if ($this.hasClass("wf-1-4")) {
$(this).css("width", minCol*6.25 + "%");
}else if ($this.hasClass("wf-2-4") || $this.hasClass("wf-1-2")) {
$this.css("width", minCol*12.5 + "%");
} else if ($this.hasClass("wf-1-3")) {
$this.css("width", minCol*8.333 + "%");
}
});
}else if ( minCol < 4 && minCol >=3 ) {
$("> .wf-cell", $gridContainer).each(function() {
var $this = $(this);
if ($this.hasClass("wf-1-4")) {
$this.css("width", minCol*11.111 + "%");
}else if ($this.hasClass("wf-2-4") || $this.hasClass("wf-1-2")) {
$this.css("width", minCol*16.667 + "%");
} else if ($this.hasClass("wf-1-3")) {
$this.css("width", minCol*11.111 + "%");
}
});
}
else if (minCol < 3 && minCol >=2) {
$("> .wf-cell", $gridContainer).each(function() {
var $this = $(this);
$this.css("width", minCol*25 + "%");
});
}
else if (minCol < 2 && minCol >=1) {
$("> .wf-cell", $gridContainer).each(function() {
var $this = $(this);
$this.css("width", minCol*50 + "%");
});
}
if (containerWidth < 360) {
$("> .wf-cell", $gridContainer).each(function() {
var $this = $(this);
$this.css("width", "100%");
});
}
};
$gridCollection.each(function() {
var $gridContainer = $(this);
calculateGridColumns($gridContainer);
$(window).on("debouncedresize", function () {
calculateGridColumns($gridCollection);
});
});
// !- Filter
$(".filter-categories > a").on("click", function(e) {
var $this = $(this);
if ( typeof arguments.callee.dtPreventD == 'undefined' ) {
arguments.callee.dtPreventD = !$this.parents('.filter').first().hasClass('without-isotope');
}
e.preventDefault();
$this.trigger("mouseleave");
if ($this.hasClass("act") && !$this.hasClass("show-all")) {
e.stopImmediatePropagation();
$this.removeClass("act");
$this.siblings("a.show-all").trigger('click');//.addClass("act");
} else {
$this.siblings().removeClass("act");
$this.addClass("act");
if ( !arguments.callee.dtPreventD ) {
window.location.href = $this.attr('href');
}
}
});
$(".filter-extras a").on("click", function(e) {
var $this = $(this);
if ( typeof arguments.callee.dtPreventD == 'undefined' ) {
arguments.callee.dtPreventD = !$this.parents('.filter').first().hasClass('without-isotope');
}
if ( arguments.callee.dtPreventD ) {
e.preventDefault();
}
$this.siblings().removeClass("act");
$this.addClass("act");
});
/* Masonry layout: end */
$('.full-boxed-pricing').each(function(){
$(this).find('.shortcode-pricing-table').last().addClass('last')
})
/* !Widgets: */
if(dtGlobals.isMobile){
$('.fs-navigation .prev, .fs-navigation .next').addClass('ar-hide');
}else{
};
$('img').on('dragstart', function(event) { event.preventDefault(); });
$('.fs-entry .show-content, .rollover-project .show-content').each(function(){
var $this = $(this);
$this.append('<i></i>')
});
$('.no-touch .fs-entry, .no-touch .swiper-slide').each(function() {
var ent = $(this);
ent.find('> .link').on('mousedown', function(e) {
var mouseDX = e.pageX,
mouseDY = e.pageY;
ent.find('> .link').one('mouseup', function(e) {
var mouseUX = e.pageX,
mouseUY = e.pageY;
if( Math.abs(mouseDX - mouseUX) < 5 ){
var $thisLink = $(this),
ent=jQuery(this).parents('.fs-entry, .swiper-slide'),
mi=ent.find('.fs-entry-content, > .swiper-caption');
$('.fs-entry .link, .swiper-slide > .link').removeClass('act');
$thisLink.addClass('act');
$('.fs-entry-content, .swiper-caption').not(mi).fadeOut(300);
mi.delay(300).fadeIn(400);
}
})
});
ent.find('.close-link').on('mousedown tap', function(e) {
var $this = $(this),
ent=jQuery(this).parents('.fs-entry, .swiper-slide'),
mi=ent.find('.fs-entry-content, > .swiper-caption');
mi.delay(100).fadeOut(300, function(){
ent.find('> .link').removeClass('act');
});
});
});
$('.touch .fs-entry, .rollover-project, .touch .swiper-slide').each(function() {
var ent=jQuery(this);
/*ent.find('>.link').on('tap', function() {
var $this = $(this),
ent=jQuery(this).parents('.fs-entry, .swiper-slide'),
mi=ent.find('.fs-entry-content, > .swiper-caption');
$('.fs-entry .link, .swiper-slide > .link').removeClass('act');
$this.addClass('act');
$('.fs-entry-content, .swiper-caption').not(mi).fadeOut(300);
//mi.fadeOut(300);
mi.delay(300).fadeIn(400);
});
ent.find('.close-link').on('tap', function() {
var $this = $(this),
ent=jQuery(this).parents('.fs-entry, .swiper-slide'),
mi=ent.find('.fs-entry-content, > .swiper-caption');
mi.delay(100).fadeOut(300, function(){
ent.find('> .link').removeClass('act');
});
});*/
ent.find('> .link').on('mousedown tap', function(e) {
var mouseDX = e.pageX,
mouseDY = e.pageY;
ent.find('> .link').one('mouseup tap', function(e) {
var mouseUX = e.pageX,
mouseUY = e.pageY;
if( Math.abs(mouseDX - mouseUX) < 5 ){
var $thisLink = $(this),
ent=jQuery(this).parents('.fs-entry, .swiper-slide'),
mi=ent.find('.fs-entry-content, > .swiper-caption');
$('.fs-entry-content, .swiper-caption').not(mi).fadeOut(200);
mi.delay(100).fadeIn(300);
}
})
});
ent.find('.close-link').on('mousedown tap', function(e) {
var $this = $(this),
ent=jQuery(this).parents('.fs-entry, .swiper-slide'),
mi=ent.find('.fs-entry-content, > .swiper-caption');
mi.delay(100).fadeOut(200, function(){
});
});
});
$('.touch .rollover-project').each(function() {
var ent = $(this);
ent.find('.link').on('tap', function() {
var $this = $(this),
ent = $(this).parents('.rollover-project'),
mi = ent.find('.rollover-content');
$('.rollover-project .link').removeClass('act');
$this.addClass('act');
$('.rollover-content').not(mi).fadeOut(300);
//mi.fadeOut(300);
mi.delay(150).fadeIn(200);
});
ent.find('.close-link').on('tap', function() {
var $this = $(this),
ent=jQuery(this).parents('.rollover-project'),
mi=ent.find('.rollover-content');
mi.delay(100).fadeOut(100, function(){
ent.find('.link').removeClass('act');
});
});
});
// Albums, exclude featured image from gallery post
$('.albums .ignore-feaured-image').on('click', function(e) {
e.preventDefault();
$(this).siblings('.dt-prettyphoto-gallery-container').first().find("a[rel^='prettyPhoto']").first().click();
return false;
});
// albums with rollover info
$('.albums .rollover-content, .media .rollover-content').on('click', function(e){
if ( $(e.target).is('a') ) return true;
$(this).siblings("a[rel^='prettyPhoto']").first().click();
});
// init prettyPhoto
$("a[rel^='prettyPhoto']").prettyPhoto();
//device rollovers
$('#parent-element a').live("touchstart",function(e){
var $link_id = $(this).attr('id');
if ($(this).parent().data('clicked') == $link_id) {
// element has been tapped (hovered), reset 'clicked' data flag on parent element and return true (activating the link)
$(this).parent().data('clicked', null);
return true;
} else {
$(this).trigger("mouseenter").siblings().trigger("mouseout"); //triggers the hover state on the tapped link (because preventDefault(); breaks this) and untriggers the hover state for all other links in the container.
// element has not been tapped (hovered) yet, set 'clicked' data flag on parent element to id of clicked link, and prevent click
e.preventDefault(); // return false; on the end of this else statement would do the same
$(this).parent().data('clicked', $link_id); //set this link's ID as the last tapped link ('clicked')
}
});
$('.skill-value').each(function(){
var $_this = $(this),
$this_data = $_this.data('width'),
current_percent = 0,
progress = null;
var progress = setInterval(function(){
if( current_percent >= $this_data ){
clearInterval(progress);
$_this.find('> span').delay(2000).fadeOut(200, function(){});
}else{
current_percent+=1
var skill_html = parseInt($_this.find('> span').html());
$_this.css({
width: current_percent + '%'
});
if( skill_html >= 99 ){
$_this.addClass('full');
}
//console.log(current_percent)
}
$_this.find('> span').text(current_percent + '%');
},10)
/*function run(){
if( current_percent >= $this_data ){
clearInterval(progress);
$_this.find('> span').delay(2000).fadeOut(200, function(){});
}else{
current_percent++;
$_this.css('width', current_percent +"%");
$_this.find('> span').text(current_percent+"%");
if(current_percent == 100){
clearInterval(progress);
//ex1running = false;
}
}
}
progress = setInterval(run, 50);*/
var fadeTimeout;
$_this.hover(function() {
clearTimeout(fadeTimeout);
fadeTimeout = setTimeout(function() {
$_this.find('> span').stop(true, true).fadeIn(200);
}, 200);
}, function(){
clearTimeout(fadeTimeout);
$_this.find('> span').fadeOut(200);
});
});
/* !- Grayscale */
simple_tooltip(".shortcode-tooltip","shortcode-tooltip-content");
// !- Accordion
$('.st-toggle').toggle();
$('.st-accordion').accordion({
open : 0,
oneOpenedItem : true
});
$(".filter-grayscale .slider-masonry").on("mouseenter tap", function(e) {
if(e.type == "tap") {
e.stopPropagation();
//e.preventDefault();
}
$(this).addClass("dt-hovered");
});
$(".filter-grayscale .slider-masonry").on("mouseleave", function(e) {
$(this).removeClass("dt-hovered");
});
/* Grayscale: end */
/* !- Fancy grid */
$.fn.fancyGrid = function(options) {
return this.each(function() {
var defaults = {
setWidth: true,
setHeight: false,
setLineHeight: false,
cellsSelector: "",
contentSelector: "",
borderBoxSelector: "",
maintainBorders: false,
maintainImages: false,
minColWidth: 150
},
settings = $.extend({}, defaults, options),
$gridContainer = $(this),
$cells = settings.cellsSelector ? $(settings.cellsSelector, $gridContainer) : $gridContainer.children();
if ($cells.length < 1) return false;
var calcWidth = function() {
var containerWidth = $gridContainer.width();
var $this = $($cells[0]),
curW = $this.width(),
basicW,
basicDenom = $gridContainer.data("basicDenom"),
basicCSS = $gridContainer.data("basicCSS"),
basicClass = $gridContainer.data("basicClass");
if (!basicDenom){
if ($this.hasClass("wf-1-6")) {
basicDenom = 6;
basicCSS = "16.6667%";
basicClass = "wf-1-6";
}
else if ($this.hasClass("wf-1-5")) {
basicDenom = 5;
basicCSS = "20%";
basicClass = "wf-1-5";
}
else if ($this.hasClass("wf-1-4")) {
basicDenom = 4;
basicCSS = "25%";
basicClass = "wf-1-4";
}
else if ($this.hasClass("wf-1-3")) {
basicDenom = 3;
basicCSS = "33.3333%";
basicClass = "wf-1-3";
}
else if ($this.hasClass("wf-2-4") || $this.hasClass("wf-1-2")) {
basicDenom = 2;
basicCSS = "50%";
basicClass = "wf-1-2";
}
else if ($this.hasClass("wf-1")) {
basicDenom = 1;
basicCSS = "100%";
basicClass = "wf-1";
};
};
$gridContainer.data("basicDenom", basicDenom);
$gridContainer.data("basicCSS", basicCSS);
$gridContainer.data("basicClass", basicClass);
basicW = containerWidth/basicDenom;
if (basicW < settings.minColWidth) {
$cells.css({ 'width': 100/Math.floor(containerWidth/settings.minColWidth)+'%' });
} else {
$cells.css("width", basicCSS);
}
/*
if (basicW < 150 && containerWidth/2 > 150) {
$cells.css("width", "50%");
}
else if (basicW < 150 && containerWidth/2 <= 150) {
$cells.css("width", "100%");
}
else {
$cells.css("width", basicCSS);
};
*/
};
var calcHeight = function() {
var topPosition = 0,
totalRows = 0,
currentRowStart = 0,
currentRow = -1,
rows = [],
tallest = [];
$cells.each(function() {
var $this = $(this),
currentHeight = settings.contentSelector ? $(settings.contentSelector, $this).outerHeight(true) : $this.children().outerHeight(true);
topPostion = $this.position().top;
if (currentRowStart != topPostion) {
// We just came to a new row
// Set the variables for the new row
currentRow++;
currentRowStart = topPostion;
tallest[currentRow] = currentHeight;
rows.push([]);
rows[currentRow].push($this);
} else {
// Another div on the current row. Add it to the list and check if it's taller
rows[currentRow].push($this);
tallest[currentRow] = (tallest[currentRow] < currentHeight) ? (currentHeight) : (tallest[currentRow]);
}
});
totalRows = rows.length;
for (i = 0; i < totalRows; i++) {
var inCurrentRow = rows[i].length;
for (j = 0; j < inCurrentRow; j++) {
settings.borderBoxSelector ? $(settings.borderBoxSelector, rows[i][j]).css("height", tallest[i]) : rows[i][j].css("height", tallest[i]);
if (settings.setLineHeight)
settings.borderBoxSelector ? $(settings.borderBoxSelector, rows[i][j]).css("line-height", tallest[i] + 'px') : rows[i][j].css("line-height", tallest[i] + 'px');
if (settings.maintainBorders && j == 0) {
rows[i][j].addClass("border-left-none");
} else {
rows[i][j].removeClass("border-left-none");
}
if (settings.maintainBorders && i == totalRows - 1) {
rows[i][j].addClass("border-bottom-none");
} else {
rows[i][j].removeClass("border-bottom-none");
}
}
}
}
if (settings.setWidth) calcWidth();
if (settings.setHeight || settings.setLineHeight) calcHeight();
if (settings.maintainImages) {
$("img", $cells).loaded(null, function() {
$gridContainer.addClass("grid-ready");
if (settings.setHeight || settings.setLineHeight) calcHeight();
}, true);
} else {
$gridContainer.addClass("grid-ready");
}
$(window).on("debouncedresize", function() { // ! needs to be !changed
if (settings.setWidth) calcWidth();
if (settings.setHeight || settings.setLineHeight) calcHeight();
});
});
}
$(".items-grid").fancyGrid({
setWidth: true,
setHeight: true,
maintainBorders: true,
contentSelector: "article",
borderBoxSelector: ".borders",
minColWidth: 180
});
$(".benefits-grid").fancyGrid({
setWidth: true,
setHeight: true,
maintainBorders: true,
maintainImages: true,
contentSelector: ".borders > div",
borderBoxSelector: ".borders",
minColWidth: 180
});
$(".logos-grid").fancyGrid({
setWidth: true,
setHeight: true,
setLineHeight: true,
maintainBorders: true,
maintainImages: true,
contentSelector: ".borders > a img",
borderBoxSelector: ".borders",
minColWidth: 130
});
/* Fancy grid: end */
/* !Sandbox */
/* !Fancy header*/
var fancyFeaderOverlap = $("#fancy-header.overlap").exists();
function fancyFeaderCalc() {
if (fancyFeaderOverlap) {
$("#fancy-header.overlap > .wf-wrap").css({
"padding-top" : $("#header").height()
});
}
}
fancyFeaderCalc();
/* Fancy header:end*/
/* !Rolovers*/
$('.rollover, .rollover-video, .post-rollover, .swiper-slide .link').each(function(){
var $this = $(this);
$this.append('<i></i>');
});
$('.rollover, .post-rollover').each(function(){
var $this = $(this);
if( $("html").hasClass("old-ie") ){
$(".rollover i, .post-rollover i, .rollover .rollover-thumbnails").fadeOut();
$this.hover(function(){
$("i, .rollover-thumbnails", this).css('display', 'block');
},function(){
$("i, .rollover-thumbnails", this).css('display', 'none');
});
}
});
$('.fs-entry, .rollover-project .link, .swiper-slide').each(function(){
var $this = $(this);
if( $("html").hasClass("old-ie") ){
$(".fs-entry .link, .rollover-project .link i, .swiper-slide .link").fadeOut();
$this.hover(function(){
$(" > .link, i", this).css('display', 'block');
},function(){
$(" > .link, i", this).css('display', 'none');
});
}
});
/* Rolovers:end*/
/* !Share links*/
$('.entry-share a').each(function(){
var caroufredselTimeout;
var $this = $(this);
$this.find('.share-content').css({
'margin-left': - $this.find('.share-content').width()/2
})
$this.hover(function() {
clearTimeout(caroufredselTimeout);
caroufredselTimeout = setTimeout(function() {
$this.find('.share-content').stop(true, true).fadeIn(200);
}, 200);
}, function(){
clearTimeout(caroufredselTimeout);
$this.find('.share-content').fadeOut(200);
});
});
/*Share links: end*/
var addSliderTimeout;
clearTimeout(addSliderTimeout);
//jQuery(".swiper-container").fadeOut();
addSliderTimeout = setTimeout(function() {
//var homeSliderH = jQuery(".swiper-container").height();
if( $(".swiper-container").length ){
var loading_label = jQuery("<div></div>").attr("id", "loading-label").addClass("loading-label").css("position" , "fixed").hide().appendTo("body");
loading_label.fadeIn(250);
jQuery(".swiper-container").animate({
//minHeight : homeSliderH + "px"
}, 500, function() {
//jQuery(".swiper-container > .swiper-wrapper").fadeIn();
loading_label.fadeOut(500);
});
};
}, 300);
/* !Metro slider*/
$(".swiper-container > .swiper-wrapper > .swiper-slide .preload-me").loaded(null, function() {
/* !Metro slider*/
if ($('.swiper-wrapper').length > 0) {
var swiperColH = 6;
var swiperN1 = $('.swiper-n1').swiper({
slidesPerSlide : swiperColH,
onTouchMove:function(){
var posX = swiperN1.getTranslate('x');
if( posX >= 0 ){
$('.swiper-n1 .arrow-right').removeClass('disable');
$('.swiper-n1 .arrow-left').addClass('disable');
}else if( posX <= -($('.swiper-n1 > .swiper-wrapper').width()-$('.swiper-n1').width()) ){
$('.swiper-n1 .arrow-right').addClass('disable');
$('.swiper-n1 .arrow-left').removeClass('disable');
}else{
$('.swiper-n1 .arrow-left').removeClass('disable');
$('.swiper-n1 .arrow-right').removeClass('disable');
}
},
onSlideChangeEnd :function(){
var posX = swiperN1.getTranslate('x');
if( posX >= 0 ){
$('.swiper-n1 .arrow-right').removeClass('disable');
$('.swiper-n1 .arrow-left').addClass('disable');
}else if( posX <= -($('.swiper-n1 > .swiper-wrapper').width()-$('.swiper-n1').width()) ){
$('.swiper-n1 .arrow-right').addClass('disable');
$('.swiper-n1 .arrow-left').removeClass('disable');
}
}
});
var swiperN1Length = swiperN1.slides.length;
$('.swiper-n1 .arrow-left').addClass('disable');
//Navigation arrows
$('.swiper-n1 .arrow-left').click(function(e) {
e.preventDefault();
swiperN1.swipePrev();
var swiperN1Index = swiperN1.activeIndex;
$('.swiper-n1 .arrow-right').removeClass('disable');
if( swiperN1Index == 0 ){
$(this).addClass('disable');
}else{
$(this).removeClass('disable');
}
});
$('.swiper-n1 .arrow-right').click(function(e) {
e.preventDefault();
swiperN1.swipeNext();
var swiperN1Index = swiperN1.activeIndex;
$('.swiper-n1 .arrow-left').removeClass('disable');
if( (swiperN1Index+swiperColH) >= swiperN1Length ){
$(this).addClass('disable');
}else{
$(this).removeClass('disable');
}
});
//Vertical
var swiperCol = 3;
var swiperN2 = $('.swiper-n2').swiper({
slidesPerSlide : swiperCol,
mode: 'vertical',
onTouchMove:function(){
var posY = swiperN2.getTranslate('y');
if( (posY) >= 0 ){
$('.swiper-n2 .arrow-bottom').removeClass('disable');
$('.swiper-n2 .arrow-top').addClass('disable');
}else if( (posY) <= -($('.swiper-n2 > .swiper-wrapper').height() - $('.swiper-n2').height()) ){
$('.swiper-n2 .arrow-bottom').addClass('disable');
$('.swiper-n2 .arrow-top').removeClass('disable');
}else{
$('.swiper-n2 .arrow-top').removeClass('disable');
$('.swiper-n2 .arrow-bottom').removeClass('disable');
}
},
onSlideChangeEnd :function(){
var posY = swiperN2.getTranslate('y');
if( posY >= 0 ){
$('.swiper-n2 .arrow-bottom').removeClass('disable');
$('.swiper-n2 .arrow-top').addClass('disable');
}else if( posY <= -($('.swiper-n2 > .swiper-wrapper').height()-$('.swiper-n2').height()) ){
$('.swiper-n2 .arrow-bottom').addClass('disable');
$('.swiper-n2 .arrow-top').removeClass('disable');
}
}
});
var swiperN2Length = swiperN2.slides.length;
$('.swiper-n2 .arrow-top').addClass('disable');
$('.swiper-n2 .arrow-top').click(function(e) {
e.preventDefault();
swiperN2.swipePrev();
var swiperN2Index = swiperN2.activeIndex;
$('.swiper-n2 .arrow-bottom').removeClass('disable');
if( swiperN2Index == 0 ){
$(this).addClass('disable');
}else{
$(this).removeClass('disable');
}
});
$('.swiper-n2 .arrow-bottom').click(function(e) {
e.preventDefault();
swiperN2.swipeNext();
var swiperN2Index = swiperN2.activeIndex;
$('.swiper-n2 .arrow-top').removeClass('disable');
if( (swiperN2Index+swiperCol) >= swiperN2Length ){
$(this).addClass('disable');
}else{
$(this).removeClass('disable');
}
});
var swiperN3 = $('.swiper-n3').swiper({
slidesPerSlide : swiperCol,
mode: 'vertical',
slidesPerSlide : swiperCol,
mode: 'vertical',
onTouchMove:function(){
var posY = swiperN3.getTranslate('y');
if( (posY) >= 0 ){
$('.swiper-n3 .arrow-bottom').removeClass('disable');
$('.swiper-n3 .arrow-top').addClass('disable');
}else if( (posY) <= -($('.swiper-n3 > .swiper-wrapper').height() - $('.swiper-n3').height()) ){
$('.swiper-n3 .arrow-bottom').addClass('disable');
$('.swiper-n3 .arrow-top').removeClass('disable');
}else{
$('.swiper-n3 .arrow-top').removeClass('disable');
$('.swiper-n3 .arrow-bottom').removeClass('disable');
}
},
onSlideChangeEnd :function(){
var posY = swiperN3.getTranslate('y');
if( posY >= 0 ){
$('.swiper-n3 .arrow-bottom').removeClass('disable');
$('.swiper-n3 .arrow-top').addClass('disable');
}else if( (posY-10) <= -($('.swiper-n3 > .swiper-wrapper').height()-$('.swiper-n3').height()) ){
$('.swiper-n3 .arrow-bottom').addClass('disable');
$('.swiper-n3 .arrow-top').removeClass('disable');
}
}
});
var swiperN3Length = swiperN3.slides.length;
$('.swiper-n3 .arrow-top').addClass('disable');
$('.swiper-n3 .arrow-top').click(function(e) {
e.preventDefault();
swiperN3.swipePrev();
var swiperN3Index = swiperN3.activeIndex;
$('.swiper-n3 .arrow-bottom').removeClass('disable');
if( swiperN3Index == 0 ){
$(this).addClass('disable');
}else{
$(this).removeClass('disable');
}
});
$('.swiper-n3 .arrow-bottom').click(function(e) {
e.preventDefault();
swiperN3.swipeNext();
var swiperN3Index = swiperN3.activeIndex;
$('.swiper-n3 .arrow-top').removeClass('disable');
if( (swiperN3Index+swiperCol) >= swiperN3Length ){
$(this).addClass('disable');
}else{
$(this).removeClass('disable');
}
});
$(window).resize(function(){
//Unset height
$('.swiper-container').css({height:''})
//Calc Height
$('.swiper-container').css({height: $('.swiper-container').find('img').height()});
swiperN1.reInit();
swiperN2.reInit();
swiperN3.reInit();
}).trigger('resize')
};
});
/* !Metro slider: end*/
$(window).on("debouncedresize", function( event ) {
dtGlobals.resizeCounter++;
calcPics();
moveOffset();
fancyFeaderCalc();
$(".slider-wrapper").not('.full').each(function(){
var scroller = $(this).children().data("theScroller");
scroller.update();
});
/*H1 max-width*/
$('h1.entry-title').css({
'max-width': $('.content').width() - $('.navigation-inner').width()
})
}).trigger( "debouncedresize" );
/* !Beautiful loading */
dtGlobals.imgLoaded = setTimeout(function() {
$("body").append('<style>img {opacity: 1}</style>');
}, 20000);
$("img").loaded(
function () {
$(this).css("opacity", 1);
},
function () {
clearTimeout(dtGlobals.imgLoaded);
},
true
);
/* !Beautiful loading: end */
/* Sandbox: end */
/* Old ie raw emulation */
//$("html").addClass("old-ie");
}); | JavaScript |
/* ------------------------------------------------------------------------
Class: prettyPhoto
Use: Lightbox clone for jQuery
Author: Stephane Caron (http://www.no-margin-for-errors.com)
Version: 3.1.5
------------------------------------------------------------------------- */
(function($) {
$.prettyPhoto = {version: '3.1.5'};
$.fn.prettyPhoto = function(pp_settings) {
pp_settings = jQuery.extend({
hook: 'rel', /* the attribute tag to use for prettyPhoto hooks. default: 'rel'. For HTML5, use "data-rel" or similar. */
animation_speed: 'fast', /* fast/slow/normal */
ajaxcallback: function() {},
slideshow: 5000, /* false OR interval time in ms */
autoplay_slideshow: false, /* true/false */
opacity: 0.80, /* Value between 0 and 1 */
show_title: true, /* true/false */
allow_resize: true, /* Resize the photos bigger than viewport. true/false */
allow_expand: true, /* Allow the user to expand a resized image. true/false */
default_width: 500,
default_height: 344,
counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
theme: 'dream-theme', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
horizontal_padding: 40, /* The padding on each side of the picture */
hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
wmode: 'opaque', /* Set the flash wmode attribute */
autoplay: true, /* Automatically start videos: True/False */
modal: false, /* If set to true, only the close button will close the window */
deeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */
overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
overlay_gallery_max: 30, /* Maximum number of pictures in the overlay gallery */
keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
callback: function(){}, /* Called when prettyPhoto is closed */
ie6_fallback: true,
markup: '<div class="pp_pic_holder"> \
<div class="pp_content_container"> \
<div class="pp_content"> \
<div class="pp_loaderIcon"></div> \
<div class="pp_fade"> \
<a class="pp_close" href="#">Close</a> \
<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
<div class="pp_hoverContainer"> \
<a class="pp_next" href="#">next</a> \
<a class="pp_previous" href="#">previous</a> \
</div> \
<div id="pp_full_res"></div> \
<div class="pp_details"> \
<div class="pp_nav"> \
<p class="currentTextHolder">0/0</p> \
<a href="#" class="pp_arrow_previous">Previous</a> \
<a href="#" class="pp_arrow_next">Next</a> \
</div> \
<p class="ppt"></p> \
<p class="pp_description"></p> \
<div class="pp_social">{pp_social}</div> \
</div> \
</div> \
</div> \
</div> \
</div> \
<div class="pp_overlay"></div>',
gallery_markup: '<div class="pp_gallery"> \
<a href="#" class="pp_arrow_previous">Previous</a> \
<div> \
<ul> \
{gallery} \
</ul> \
</div> \
<a href="#" class="pp_arrow_next">Next</a> \
</div>',
image_markup: '<img id="fullResImage" src="{path}" />',
flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
inline_markup: '<div class="pp_inline">{content}</div>',
custom_markup: '',
social_tools: '<div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="//www.facebook.com/plugins/like.php?locale=en_US&href={location_href}&layout=button_count&show_faces=true&width=500&action=like&font&colorscheme=light&height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div>', /* html or false to disable */
social_tools: false
}, pp_settings);
// Global variables accessible only by prettyPhoto
var matchedObjects = this, percentBased = false, pp_dimensions, pp_open,
// prettyPhoto container specific
pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth,
// Window size
windowHeight = $(window).height(), windowWidth = $(window).width(),
// Global elements
pp_slideshow;
doresize = true, scroll_pos = _get_scroll();
// Window/Keyboard events
$(window).unbind('resize.prettyphoto').bind('resize.prettyphoto',function(){ _center_overlay(); _resize_overlay(); });
if(pp_settings.keyboard_shortcuts) {
$(document).unbind('keydown.prettyphoto').bind('keydown.prettyphoto',function(e){
if(typeof $pp_pic_holder != 'undefined'){
if($pp_pic_holder.is(':visible')){
switch(e.keyCode){
case 37:
$.prettyPhoto.changePage('previous');
e.preventDefault();
break;
case 39:
$.prettyPhoto.changePage('next');
e.preventDefault();
break;
case 27:
if(!settings.modal)
$.prettyPhoto.close();
e.preventDefault();
break;
};
// return false;
};
};
});
};
/**
* Initialize prettyPhoto.
*/
$.prettyPhoto.initialize = function() {
settings = pp_settings;
if(settings.theme == 'pp_default') settings.horizontal_padding = 16;
// Find out if the picture is part of a set
theRel = $(this).attr(settings.hook);
galleryRegExp = /\[(?:.*)\]/;
isSet = (galleryRegExp.exec(theRel)) ? true : false;
// Put the SRCs, TITLEs, ALTs into an array.
pp_images = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr(settings.hook).indexOf(theRel) != -1) return $(n).attr('href'); }) : $.makeArray($(this).attr('href'));
pp_titles = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr(settings.hook).indexOf(theRel) != -1) return ($(n).find('img').attr('alt')) ? $(n).find('img').attr('alt') : ""; }) : $.makeArray($(this).find('img').attr('alt'));
pp_descriptions = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr(settings.hook).indexOf(theRel) != -1) return ($(n).attr('title')) ? $(n).attr('title') : ""; }) : $.makeArray($(this).attr('title'));
if(pp_images.length > settings.overlay_gallery_max) settings.overlay_gallery = false;
set_position = jQuery.inArray($(this).attr('href'), pp_images); // Define where in the array the clicked item is positionned
rel_index = (isSet) ? set_position : $("a["+settings.hook+"^='"+theRel+"']").index($(this));
_build_overlay(this); // Build the overlay {this} being the caller
if(settings.allow_resize)
$(window).bind('scroll.prettyphoto',function(){ _center_overlay(); });
$.prettyPhoto.open();
return false;
}
/**
* Opens the prettyPhoto modal box.
* @param image {String,Array} Full path to the image to be open, can also be an array containing full images paths.
* @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
* @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions.
*/
$.prettyPhoto.open = function(event) {
if(typeof settings == "undefined"){ // Means it's an API call, need to manually get the settings and set the variables
settings = pp_settings;
pp_images = $.makeArray(arguments[0]);
pp_titles = (arguments[1]) ? $.makeArray(arguments[1]) : $.makeArray("");
pp_descriptions = (arguments[2]) ? $.makeArray(arguments[2]) : $.makeArray("");
isSet = (pp_images.length > 1) ? true : false;
set_position = (arguments[3])? arguments[3]: 0;
_build_overlay(event.target); // Build the overlay {this} being the caller
}
if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','hidden'); // Hide the flash
_checkPosition($(pp_images).size()); // Hide the next/previous links if on first or last images.
$('.pp_loaderIcon').show();
if(settings.deeplinking)
setHashtag();
// Rebuild Facebook Like Button with updated href
if(settings.social_tools){
facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href));
$pp_pic_holder.find('.pp_social').html(facebook_like_link);
}
// Fade the content in
if($ppt.is(':hidden')) $ppt.css('opacity',0).show();
$pp_overlay.show().fadeTo(settings.animation_speed,settings.opacity);
// Display the current position
$pp_pic_holder.find('.currentTextHolder').text((set_position+1) + settings.counter_separator_label + $(pp_images).size());
// Set the description
if(typeof pp_descriptions[set_position] != 'undefined' && pp_descriptions[set_position] != ""){
$pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position]));
}else{
$pp_pic_holder.find('.pp_description').hide();
}
// Get the dimensions
movie_width = ( parseFloat(getParam('width',pp_images[set_position])) ) ? getParam('width',pp_images[set_position]) : settings.default_width.toString();
movie_height = ( parseFloat(getParam('height',pp_images[set_position])) ) ? getParam('height',pp_images[set_position]) : settings.default_height.toString();
// If the size is % based, calculate according to window dimensions
percentBased=false;
if(movie_height.indexOf('%') != -1) { movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 150); percentBased = true; }
if(movie_width.indexOf('%') != -1) { movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 150); percentBased = true; }
// Fade the holder
$pp_pic_holder.fadeIn(function(){
// Set the title
(settings.show_title && pp_titles[set_position] != "" && typeof pp_titles[set_position] != "undefined") ? $ppt.html(unescape(pp_titles[set_position])) : $ppt.html(' ');
imgPreloader = "";
skipInjection = false;
// Inject the proper content
switch(_getFileType(pp_images[set_position])){
case 'image':
imgPreloader = new Image();
// Preload the neighbour images
nextImage = new Image();
if(isSet && set_position < $(pp_images).size() -1) nextImage.src = pp_images[set_position + 1];
prevImage = new Image();
if(isSet && pp_images[set_position - 1]) prevImage.src = pp_images[set_position - 1];
$pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup.replace(/{path}/g,pp_images[set_position]);
imgPreloader.onload = function(){
// Fit item to viewport
pp_dimensions = _fitToViewport(imgPreloader.width,imgPreloader.height);
_showContent();
};
imgPreloader.onerror = function(){
alert('Image cannot be loaded. Make sure the path is correct and image exist.');
$.prettyPhoto.close();
};
imgPreloader.src = pp_images[set_position];
break;
case 'youtube':
pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
// Regular youtube link
movie_id = getParam('v',pp_images[set_position]);
// youtu.be link
if(movie_id == ""){
movie_id = pp_images[set_position].split('youtu.be/');
movie_id = movie_id[1];
if(movie_id.indexOf('?') > 0)
movie_id = movie_id.substr(0,movie_id.indexOf('?')); // Strip anything after the ?
if(movie_id.indexOf('&') > 0)
movie_id = movie_id.substr(0,movie_id.indexOf('&')); // Strip anything after the &
}
movie = 'http://www.youtube.com/embed/'+movie_id;
(getParam('rel',pp_images[set_position])) ? movie+="?rel="+getParam('rel',pp_images[set_position]) : movie+="?rel=1";
if(settings.autoplay) movie += "&autoplay=1";
toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie);
break;
case 'vimeo':
pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
movie_id = pp_images[set_position];
var regExp = /http(s?):\/\/(www\.)?vimeo.com\/(\d+)/;
var match = movie_id.match(regExp);
//movie = 'http://player.vimeo.com/video/'+ match[3] +'?title=0&byline=0&portrait=0';
movie = movie_id +'?title=0&byline=0&portrait=0';
if(settings.autoplay) movie += "&autoplay=1;";
vimeo_width = pp_dimensions['width'] + '/embed/?moog_width='+ pp_dimensions['width'];
toInject = settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,movie);
break;
case 'quicktime':
pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
pp_dimensions['height']+=15; pp_dimensions['contentHeight']+=15; pp_dimensions['containerHeight']+=15; // Add space for the control bar
toInject = settings.quicktime_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay);
break;
case 'flash':
pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
flash_vars = pp_images[set_position];
flash_vars = flash_vars.substring(pp_images[set_position].indexOf('flashvars') + 10,pp_images[set_position].length);
filename = pp_images[set_position];
filename = filename.substring(0,filename.indexOf('?'));
toInject = settings.flash_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);
break;
case 'iframe':
pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
frame_url = pp_images[set_position];
frame_url = frame_url.substr(0,frame_url.indexOf('iframe')-1);
toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,frame_url);
break;
case 'ajax':
doresize = false; // Make sure the dimensions are not resized.
pp_dimensions = _fitToViewport(movie_width,movie_height);
doresize = true; // Reset the dimensions
skipInjection = true;
$.get(pp_images[set_position],function(responseHTML){
toInject = settings.inline_markup.replace(/{content}/g,responseHTML);
$pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject;
_showContent();
});
break;
case 'custom':
pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport
toInject = settings.custom_markup;
break;
case 'inline':
// to get the item height clone it, apply default width, wrap it in the prettyPhoto containers , then delete
myClone = $(pp_images[set_position]).clone().append('<br clear="all" />').css({'width':settings.default_width}).wrapInner('<div id="pp_full_res"><div class="pp_inline"></div></div>').appendTo($('body')).show();
doresize = false; // Make sure the dimensions are not resized.
pp_dimensions = _fitToViewport($(myClone).width(),$(myClone).height());
doresize = true; // Reset the dimensions
$(myClone).remove();
toInject = settings.inline_markup.replace(/{content}/g,$(pp_images[set_position]).html());
break;
};
if(!imgPreloader && !skipInjection){
$pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject;
// Show content
_showContent();
};
});
return false;
};
/**
* Change page in the prettyPhoto modal box
* @param direction {String} Direction of the paging, previous or next.
*/
$.prettyPhoto.changePage = function(direction){
currentGalleryPage = 0;
if(direction == 'previous') {
set_position--;
if (set_position < 0) set_position = $(pp_images).size()-1;
}else if(direction == 'next'){
set_position++;
if(set_position > $(pp_images).size()-1) set_position = 0;
}else{
set_position=direction;
};
rel_index = set_position;
if(!doresize) doresize = true; // Allow the resizing of the images
if(settings.allow_expand) {
$('.pp_contract').removeClass('pp_contract').addClass('pp_expand');
}
_hideContent(function(){
$.prettyPhoto.open();
if (!(_getFileType(pp_images[set_position])=="image")) $pp_pic_holder.find('.pp_gallery').hide();
});
};
/**
* Change gallery page in the prettyPhoto modal box
* @param direction {String} Direction of the paging, previous or next.
*/
$.prettyPhoto.changeGalleryPage = function(direction){
if(direction=='next'){
currentGalleryPage ++;
if(currentGalleryPage > totalPage) currentGalleryPage = 0;
}else if(direction=='previous'){
currentGalleryPage --;
if(currentGalleryPage < 0) currentGalleryPage = totalPage;
}else{
currentGalleryPage = direction;
};
slide_speed = (direction == 'next' || direction == 'previous') ? settings.animation_speed : 0;
slide_to = currentGalleryPage * (itemsPerPage * itemWidth);
$pp_gallery.find('ul').animate({left:-slide_to},slide_speed);
};
/**
* Start the slideshow...
*/
$.prettyPhoto.startSlideshow = function(){
if(typeof pp_slideshow == 'undefined'){
$pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function(){
$.prettyPhoto.stopSlideshow();
return false;
});
pp_slideshow = setInterval($.prettyPhoto.startSlideshow,settings.slideshow);
}else{
$.prettyPhoto.changePage('next');
};
}
/**
* Stop the slideshow...
*/
$.prettyPhoto.stopSlideshow = function(){
$pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function(){
$.prettyPhoto.startSlideshow();
return false;
});
clearInterval(pp_slideshow);
pp_slideshow=undefined;
}
/**
* Closes prettyPhoto.
*/
$.prettyPhoto.close = function(){
if($pp_overlay.is(":animated")) return;
$.prettyPhoto.stopSlideshow();
$pp_pic_holder.stop().find('object,embed').css('visibility','hidden');
$('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){ $(this).remove(); });
$pp_overlay.fadeOut(settings.animation_speed, function(){
if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','visible'); // Show the flash
$(this).remove(); // No more need for the prettyPhoto markup
$(window).unbind('scroll.prettyphoto');
clearHashtag();
settings.callback();
doresize = true;
pp_open = false;
delete settings;
});
};
/**
* Set the proper sizes on the containers and animate the content in.
*/
function _showContent(){
$('.pp_loaderIcon').hide();
// Calculate the opened top position of the pic holder
projectedTop = scroll_pos['scrollTop'] + ((windowHeight/2) - (pp_dimensions['containerHeight']/2));
if(projectedTop < 0) projectedTop = 0;
$ppt.fadeTo(settings.animation_speed,1);
// Resize the content holder
$pp_pic_holder.find('.pp_content')
.animate({
height:pp_dimensions['contentHeight'],
width:pp_dimensions['contentWidth']
},settings.animation_speed);
// Resize picture the holder
$pp_pic_holder.animate({
'top': projectedTop,
'left': ((windowWidth/2) - (pp_dimensions['containerWidth']/2) < 0) ? 0 : (windowWidth/2) - (pp_dimensions['containerWidth']/2),
width:pp_dimensions['containerWidth']
},settings.animation_speed,function(){
$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(pp_dimensions['height']).width(pp_dimensions['width']);
$pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed); // Fade the new content
// Show the nav
if(isSet && _getFileType(pp_images[set_position])=="image") { $pp_pic_holder.find('.pp_hoverContainer').show(); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }
if(settings.allow_expand) {
if(pp_dimensions['resized']){ // Fade the resizing link if the image is resized
$('a.pp_expand,a.pp_contract').show();
}else{
$('a.pp_expand').hide();
}
}
if(settings.autoplay_slideshow && !pp_slideshow && !pp_open) $.prettyPhoto.startSlideshow();
settings.changepicturecallback(); // Callback!
pp_open = true;
});
_insert_gallery();
pp_settings.ajaxcallback();
};
/**
* Hide the content...DUH!
*/
function _hideContent(callback){
// Fade out the current picture
$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
$pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed,function(){
$('.pp_loaderIcon').show();
callback();
});
};
/**
* Check the item position in the gallery array, hide or show the navigation links
* @param setCount {integer} The total number of items in the set
*/
function _checkPosition(setCount){
(setCount > 1) ? $('.pp_nav').show() : $('.pp_nav').hide(); // Hide the bottom nav if it's not a set.
};
/**
* Resize the item dimensions if it's bigger than the viewport
* @param width {integer} Width of the item to be opened
* @param height {integer} Height of the item to be opened
* @return An array containin the "fitted" dimensions
*/
/* !_fitToViewport */
function _fitToViewport(width,height){
resized = false;
_getDimensions(width,height);
// Define them in case there's no resize needed
imageWidth = width, imageHeight = height;
if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allow_resize && !percentBased) {
resized = true, fitting = false;
while (!fitting){
if((pp_containerWidth > windowWidth)){
imageWidth = (windowWidth - 30 - settings.horizontal_padding);
imageHeight = (height/width) * imageWidth;
}else if((pp_containerHeight > windowHeight)){
imageHeight = (windowHeight - detailsHeight - 30);
imageWidth = (width/height) * imageHeight;
}else{
fitting = true;
};
pp_containerHeight = imageHeight, pp_containerWidth = imageWidth;
};
if((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)){
_fitToViewport(pp_containerWidth,pp_containerHeight)
};
_getDimensions(imageWidth,imageHeight);
};
return {
width:Math.floor(imageWidth),
height:Math.floor(imageHeight),
containerHeight:Math.floor(pp_containerHeight),
containerWidth:Math.floor(pp_containerWidth) + (settings.horizontal_padding),
contentHeight:Math.floor(pp_contentHeight),
contentWidth:Math.floor(pp_containerWidth) + (settings.horizontal_padding),
resized:resized
};
};
/**
* Get the containers dimensions according to the item size
* @param width {integer} Width of the item to be opened
* @param height {integer} Height of the item to be opened
*/
/* _getDimensions */
function _getDimensions(width,height){
width = parseFloat(width);
height = parseFloat(height);
// Get the details height, to do so, I need to clone it since it's invisible
$pp_details = $pp_pic_holder.find('.pp_details');
$pp_details.width(width);
detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom'));
$pp_details = $pp_details.clone().addClass(settings.theme).width(width).appendTo($('body')).css({
'position':'absolute',
'top':-10000
});
detailsHeight += $pp_details.height();
detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details
$pp_details.remove();
// Get the titles height, to do so, I need to clone it since it's invisible
/*
$pp_title = $pp_pic_holder.find('.ppt');
$pp_title.width(width);
titleHeight = parseFloat($pp_title.css('marginTop')) + parseFloat($pp_title.css('marginBottom'));
$pp_title = $pp_title.clone().appendTo($('body')).css({
'position':'absolute',
'top':-10000
});
titleHeight += $pp_title.height();
$pp_title.remove();
*/
// Get the container size, to resize the holder to the right dimensions
pp_contentHeight = height + detailsHeight;
pp_contentWidth = width;
pp_containerHeight = pp_contentHeight; // + titleHeight + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
pp_containerWidth = width;
}
function _getFileType(itemSrc){
if (itemSrc.match(/youtube\.com\/watch/i) || itemSrc.match(/youtu\.be/i)) {
return 'youtube';
}else if (itemSrc.match(/vimeo\.com/i)) {
return 'vimeo';
}else if(itemSrc.match(/\b.mov\b/i)){
return 'quicktime';
}else if(itemSrc.match(/\b.swf\b/i)){
return 'flash';
}else if(itemSrc.match(/\biframe=true\b/i)){
return 'iframe';
}else if(itemSrc.match(/\bajax=true\b/i)){
return 'ajax';
}else if(itemSrc.match(/\bcustom=true\b/i)){
return 'custom';
}else if(itemSrc.substr(0,1) == '#'){
return 'inline';
}else{
return 'image';
};
};
function _center_overlay(){
if(doresize && typeof $pp_pic_holder != 'undefined') {
scroll_pos = _get_scroll();
contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width();
projectedTop = (windowHeight/2) + scroll_pos['scrollTop'] - (contentHeight/2);
if(projectedTop < 0) projectedTop = 0;
if(contentHeight > windowHeight)
return;
$pp_pic_holder.css({
'top': projectedTop,
'left': (windowWidth/2) + scroll_pos['scrollLeft'] - (contentwidth/2)
});
};
};
function _get_scroll(){
if (self.pageYOffset) {
return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
} else if (document.body) {// all other Explorers
return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
};
};
function _resize_overlay() {
windowHeight = $(window).height(), windowWidth = $(window).width();
if(typeof $pp_overlay != "undefined") $pp_overlay.height($(document).height()).width(windowWidth);
};
function _insert_gallery(){
if(isSet && settings.overlay_gallery/* && _getFileType(pp_images[set_position])=="image" */) {
itemWidth = 80+5; // 100 beign the thumb width, 5 being the right margin.
navWidth = 22; // Define the arrow width
itemsPerPage = Math.floor((pp_dimensions['containerWidth'] - 100 - navWidth) / itemWidth);
itemsPerPage = (itemsPerPage < pp_images.length) ? itemsPerPage : pp_images.length;
totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1;
// Hide the nav in the case there's no need for links
if(totalPage == 0){
navWidth = 0; // No nav means no width!
$pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').hide();
}else{
$pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').show();
};
galleryWidth = itemsPerPage * itemWidth;
fullGalleryWidth = pp_images.length * itemWidth;
// Set the proper width to the gallery items
$pp_gallery
.css('margin-left',-((galleryWidth + navWidth*2 +5)/2 + settings.horizontal_padding/2))
.find('div:first').width(galleryWidth+5)
.find('ul').width(fullGalleryWidth)
.find('li.selected').removeClass('selected');
goToPage = (Math.floor(set_position/itemsPerPage) < totalPage) ? Math.floor(set_position/itemsPerPage) : totalPage;
$.prettyPhoto.changeGalleryPage(goToPage);
$pp_gallery_li.filter(':eq('+set_position+')').addClass('selected');
}else{
//$pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave');
// $pp_gallery.hide();
}
}
function _build_overlay(caller){
// Inject Social Tool markup into General markup
if(settings.social_tools)
facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href));
settings.markup = settings.markup.replace('{pp_social}','');
$('body').append(settings.markup); // Inject the markup
$pp_pic_holder = $('.pp_pic_holder') , $ppt = $('.ppt'), $pp_overlay = $('div.pp_overlay'); // Set my global selectors
// Inject the inline gallery!
if(isSet && settings.overlay_gallery) {
currentGalleryPage = 0;
toInject = "";
for (var i=0; i < pp_images.length; i++) {
if(!pp_images[i].match(/\b(jpg|jpeg|png|gif)\b/gi)){
classname = 'default';
img_src = '';
}else{
classname = '';
img_src = pp_images[i];
}
toInject += "<li class='"+classname+"'><a href='#'><img src='" + img_src + "' alt='' /></a></li>";
};
toInject = settings.gallery_markup.replace(/{gallery}/g,toInject);
$pp_pic_holder.find('#pp_full_res').after(toInject);
$pp_gallery = $('.pp_pic_holder .pp_gallery'), $pp_gallery_li = $pp_gallery.find('li'); // Set the gallery selectors
$pp_gallery.find('.pp_arrow_next').click(function(){
$.prettyPhoto.changeGalleryPage('next');
$.prettyPhoto.stopSlideshow();
return false;
});
$pp_gallery.find('.pp_arrow_previous').click(function(){
$.prettyPhoto.changeGalleryPage('previous');
$.prettyPhoto.stopSlideshow();
return false;
});
$pp_pic_holder.find('.pp_content').hover(
function(){
//$pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn();
if (_getFileType(pp_images[set_position])=="image") $pp_pic_holder.find('.pp_gallery').fadeIn();
},
function(){
//$pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut();
if (_getFileType(pp_images[set_position])=="image") $pp_pic_holder.find('.pp_gallery').fadeOut();
}
);
itemWidth = 80+5; // 80 beign the thumb width, 5 being the right margin.
$pp_gallery_li.each(function(i){
$(this)
.find('a')
.click(function(){
$.prettyPhoto.changePage(i);
$.prettyPhoto.stopSlideshow();
return false;
});
});
};
// Inject the play/pause if it's a slideshow
if(settings.slideshow){
$pp_pic_holder.find('.pp_nav .pp_arrow_previous').after('<a href="#" class="pp_play">Play</a>')
$pp_pic_holder.find('.pp_nav .pp_play').click(function(){
$.prettyPhoto.startSlideshow();
return false;
});
}
$pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme
$pp_overlay
.css({
'opacity':0,
'height':$(document).height(),
'width':$(window).width()
})
.bind('click',function(){
if(!settings.modal) $.prettyPhoto.close();
});
$('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; });
if(settings.allow_expand) {
$('a.pp_expand').bind('click',function(e){
// Expand the image
if($(this).hasClass('pp_expand')){
$(this).removeClass('pp_expand').addClass('pp_contract');
doresize = false;
}else{
$(this).removeClass('pp_contract').addClass('pp_expand');
doresize = true;
};
_hideContent(function(){ $.prettyPhoto.open(); });
return false;
});
}
$pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click',function(){
$.prettyPhoto.changePage('previous');
$.prettyPhoto.stopSlideshow();
return false;
});
$pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click',function(){
$.prettyPhoto.changePage('next');
$.prettyPhoto.stopSlideshow();
return false;
});
_center_overlay(); // Center it
};
if(!pp_alreadyInitialized && getHashtag()){
pp_alreadyInitialized = true;
// Grab the rel index to trigger the click on the correct element
hashIndex = getHashtag();
hashRel = hashIndex;
hashIndex = hashIndex.substring(hashIndex.indexOf('/')+1,hashIndex.length-1);
hashRel = hashRel.substring(0,hashRel.indexOf('/'));
// Little timeout to make sure all the prettyPhoto initialize scripts has been run.
// Useful in the event the page contain several init scripts.
setTimeout(function(){ $("a["+pp_settings.hook+"^='"+hashRel+"']:eq("+hashIndex+")").trigger('click'); },50);
}
return this.unbind('click.prettyphoto').bind('click.prettyphoto',$.prettyPhoto.initialize); // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
};
function getHashtag(){
var url = location.href;
hashtag = (url.indexOf('#prettyPhoto') !== -1) ? decodeURI(url.substring(url.indexOf('#prettyPhoto')+1,url.length)) : false;
return hashtag;
};
function setHashtag(){
if(typeof theRel == 'undefined') return; // theRel is set on normal calls, it's impossible to deeplink using the API
location.hash = theRel + '/'+rel_index+'/';
};
function clearHashtag(){
if ( location.href.indexOf('#prettyPhoto') !== -1 ) location.hash = "prettyPhoto";
}
function getParam(name,url){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return ( results == null ) ? "" : results[1];
}
})(jQuery);
var pp_alreadyInitialized = false; // Used for the deep linking to make sure not to call the same function several times.
| JavaScript |
/*
* RoyalSlider
*
* @version 9.4.8:
*
* Copyright 2011-2012, Dmitry Semenov
*
*/
(function($) {
if(!$.rsModules) {
$.rsModules = {uid:0};
}
function RoyalSlider(element, options) {
var i,
self = this,
ua = navigator.userAgent.toLowerCase();
self.uid = $.rsModules.uid++;
self.ns = '.rs' + self.uid; // unique namespace for events
// feature detection, some ideas taken from Modernizr
var tempStyle = document.createElement('div').style,
vendors = ['webkit','Moz','ms','O'],
vendor = '',
lastTime = 0,
tempV;
for (i = 0; i < vendors.length; i++ ) {
tempV = vendors[i];
if (!vendor && (tempV + 'Transform') in tempStyle ) {
vendor = tempV;
}
tempV = tempV.toLowerCase();
if(!window.requestAnimationFrame) {
window.requestAnimationFrame = window[tempV+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[tempV+'CancelAnimationFrame']
|| window[tempV+'CancelRequestAnimationFrame'];
}
}
// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) { clearTimeout(id); };
self.isIPAD = ua.match(/(ipad)/);
// browser UA sniffing, sadly still required
var uaMatch = function( ua ) {
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
var matched = uaMatch( ua );
var br = {};
if ( matched.browser ) {
br[ matched.browser ] = true;
br.version = matched.version;
}
if(br.chrome) { br.webkit = true; };
self._browser = br;
self.isAndroid = ua.indexOf("android") > -1;
self.slider = $(element); // DOM reference
self.ev = $(self); // event object
self._doc = $(document);
self.st = $.extend({}, $.fn.royalSlider.defaults, options);
self._currAnimSpeed = self.st.transitionSpeed;
self._minPosOffset = 0;
if(self.st.allowCSS3) {
if((!br.webkit || self.st.allowCSS3OnWebkit) ) {
var bT = vendor + (vendor ? 'T' : 't' );
self._useCSS3Transitions = ( (bT + 'ransform') in tempStyle ) && ( (bT + 'ransition') in tempStyle );
if(self._useCSS3Transitions) {
self._use3dTransform = (vendor + (vendor ? 'P' : 'p' ) + 'erspective') in tempStyle;
}
}
}
vendor = vendor.toLowerCase();
self._vendorPref = '-'+vendor+'-';
self._slidesHorizontal = (self.st.slidesOrientation === 'vertical') ? false : true;
self._reorderProp = self._slidesHorizontal ? 'left' : 'top';
self._sizeProp = self._slidesHorizontal ? 'width' : 'height';
self._prevNavItemId = -1;
self._isMove = (self.st.transitionType === 'fade') ? false : true;
if(!self._isMove) {
self.st.sliderDrag = false;
self._fadeZIndex = 10;
}
self._opacityCSS = 'z-index:0; display:none; opacity:0;';
self._newSlideId = 0;
self._sPosition = 0;
self._nextSlidePos = 0;
// init modules
$.each($.rsModules, function (helper, opts) {
if(helper !== 'uid')
opts.call(self);
});
// parse all slides
self.slides = [];
self._idCount = 0;
var returnVal;
var ts = self.st.slides ? $(self.st.slides) : self.slider.children().detach();
ts.each(function() {
self._parseNode(this, true);
});
if(self.st.randomizeSlides) {
self.slides.sort(function() { return 0.5 - Math.random() });
}
self.numSlides = self.slides.length;
self._refreshNumPreloadImages();
if(!self.st.startSlideId) {
self.st.startSlideId = 0;
} else if(self.st.startSlideId > self.numSlides - 1) {
self.st.startSlideId = self.numSlides - 1;
}
self._newSlideId = self.staticSlideId = self.currSlideId = self._realId = self.st.startSlideId;
self.currSlide = self.slides[self.currSlideId];
self._accelerationPos = 0;
self.msTouch = false;
self.slider.addClass( (self._slidesHorizontal ? 'rsHor' : 'rsVer') + (self._isMove ? '' : ' rsFade') );
var sliderHTML = '<div class="rsOverflow"><div class="rsContainer">';
self.slidesSpacing = self.st.slidesSpacing;
self._slideSize = ( self._slidesHorizontal ? self.slider.width() : self.slider.height() ) + self.st.slidesSpacing;
self._preload = Boolean(self._numPreloadImages > 0);
if(self.numSlides <= 1) {
self._loop = false;
}
var loopHelpers = (self._loop && self._isMove) ? ( self.numSlides === 2 ? 1 : 2) : 0;
self._loopHelpers = loopHelpers;
self._maxImages = self.numSlides < 6 ? self.numSlides : 6;
self._currBlockIndex = 0;
self._idOffset = 0;
self.slidesJQ = [];
for(i =0; i < self.numSlides; i++) {
self.slidesJQ.push( $(createItemHTML(i)) );
}
self._sliderOverflow = sliderHTML = $(sliderHTML + '</div></div>');
var addCursors = function() {
if(self.st.sliderDrag) {
self._hasDrag = true;
if (br.msie || br.opera) {
self._grabCursor = self._grabbingCursor = "move";
} else if(br.mozilla) {
self._grabCursor = "-moz-grab";
self._grabbingCursor = "-moz-grabbing";
} else if(br.webkit && (navigator.platform.indexOf("Mac")!=-1)) {
self._grabCursor = "-webkit-grab";
self._grabbingCursor = "-webkit-grabbing";
}
self._setGrabCursor();
}
};
var rsNS = self.ns;
var addEventNames = function(pref, down, move, up, cancel) {
self._downEvent = pref + down + rsNS;
self._moveEvent = pref + move + rsNS;
self._upEvent = pref + up + rsNS;
if(cancel)
self._cancelEvent = pref + cancel + rsNS;
};
// ie10
self.msEnabled = window.navigator.msPointerEnabled;
if(self.msEnabled) {
self.msTouch = Boolean(window.navigator.msMaxTouchPoints > 1);
self.hasTouch = false;
self._lastItemFriction = 0.2;
addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel');
} else {
addEventNames('mouse', 'down', 'move', 'up', 'up');
if('ontouchstart' in window || 'createTouch' in document) {
self.hasTouch = true;
self._downEvent += ' touchstart' + rsNS;
self._moveEvent += ' touchmove' + rsNS;
self._upEvent += ' touchend' + rsNS;
self._cancelEvent += ' touchcancel' + rsNS;
self._lastItemFriction = 0.5;
if(self.st.sliderTouch) {
self._hasDrag = true;
}
} else {
self.hasTouch = false;
self._lastItemFriction = 0.2;
}
}
addCursors();
self.slider.html(sliderHTML);
self._controlsContainer = self.st.controlsInside ? self._sliderOverflow : self.slider;
self._slidesContainer = self._sliderOverflow.children('.rsContainer');
if(self.msEnabled) {
self._slidesContainer.css('-ms-touch-action', self._slidesHorizontal ? 'pan-y' : 'pan-x');
}
self._preloader = $('<div class="rsPreloader"></div>');
var slides = self._slidesContainer.children('.rsSlide');
self._currHolder = self.slidesJQ[self.currSlideId]
self._selectedSlideHolder = 0;
function createItemHTML(i, className) {
return '<div style="'+ (self._isMove ? '' : (i !== self.currSlideId ? self._opacityCSS : 'z-index:0;') ) +'" class="rsSlide '+ (className || '')+'"></div>';
}
if(self._useCSS3Transitions) {
// some constants for CSS3
self._TP = 'transition-property';
self._TD = 'transition-duration';
self._TTF = 'transition-timing-function';
self._yProp = self._xProp = self._vendorPref +'transform';
if(self._use3dTransform) {
if(br.webkit && !br.chrome) {
self.slider.addClass('rsWebkit3d');
}
self._tPref1 = 'translate3d(';
self._tPref2 = 'px, ';
self._tPref3 = 'px, 0px)';
} else {
self._tPref1 = 'translate(';
self._tPref2 = 'px, ';
self._tPref3 = 'px)';
}
if(!self._isMove) {
var animObj = {};
animObj[(self._vendorPref + self._TP)] = 'opacity';
animObj[(self._vendorPref + self._TD)] = self.st.transitionSpeed + 'ms';
animObj[(self._vendorPref + self._TTF)] = self.st.css3easeInOut;
slides.css(animObj);
} else {
self._slidesContainer[(self._vendorPref + self._TP)] = (self._vendorPref + 'transform');
}
} else {
self._xProp = 'left';
self._yProp = 'top';
}
// !Responsiveness (on window resize)
if (!self.st.disableResponsiveness) {
var resizeTimer;
$(window).on('resize'+self.ns, function() {
if(resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function() { self.updateSliderSize(); }, 50);
});
}
self.ev.trigger('rsAfterPropsSetup'); // navigation (bullets, thumbs...) are created here
self.updateSliderSize();
// keyboard nav
if(self.st.keyboardNavEnabled) {
self._bindKeyboardNav();
}
if(self.st.arrowsNavHideOnTouch && (self.hasTouch || self.msTouch) ) {
self.st.arrowsNav = false;
}
//Direction navigation (arrows)
if(self.st.arrowsNav) {
var rArr = 'rsArrow',
container = self._controlsContainer;
$('<div class="'+rArr+' '+rArr+'Left"><div class="'+rArr+'Icn"></div></div><div class="'+rArr+' '+rArr+'Right"><div class="'+rArr+'Icn"></div></div>').appendTo(container);
self._arrowLeft = container.children('.'+rArr+'Left').click(function(e) {
e.preventDefault();
self.prev();
});
self._arrowRight = container.children('.'+rArr+'Right').click(function(e) {
e.preventDefault();
self.next();
});
if(self.st.arrowsNavAutoHide && !self.hasTouch) {
self._arrowLeft.addClass('rsHidden');
self._arrowRight.addClass('rsHidden');
var hoverEl = container;
hoverEl.one("mousemove.arrowshover",function() {
self._arrowLeft.removeClass('rsHidden');
self._arrowRight.removeClass('rsHidden');
});
hoverEl.hover(
function() {
if(!self._arrowsAutoHideLocked) {
self._arrowLeft.removeClass('rsHidden');
self._arrowRight.removeClass('rsHidden');
}
},
function() {
if(!self._arrowsAutoHideLocked) {
self._arrowLeft.addClass('rsHidden');
self._arrowRight.addClass('rsHidden');
}
}
);
}
self.ev.on('rsOnUpdateNav', function() {
self._updateArrowsNav();
});
self._updateArrowsNav();
}
if( self._hasDrag ) {
self._slidesContainer.on(self._downEvent, function(e) { self._onDragStart(e); });
} else {
self.dragSuccess = false;
}
var videoClasses = ['rsPlayBtnIcon', 'rsPlayBtn', 'rsCloseVideoBtn', 'rsCloseVideoIcn'];
self._slidesContainer.click(function(e) {
if(!self.dragSuccess) {
var t = $(e.target);
var tClass = t.attr('class');
if( $.inArray(tClass, videoClasses) !== -1) {
if( self.toggleVideo() ) {
return false;
}
}
if(self.st.navigateByClick && !self._blockActions) {
if($(e.target).closest('.rsNoDrag', self._currHolder).length) {
return true;
}
self._mouseNext(e);
}
self.ev.trigger('rsSlideClick');
}
}).on('click.rs', 'a', function(e) {
if(self.dragSuccess) {
return false;
} else {
self._blockActions = true;
//e.stopPropagation();
//e.stopImmediatePropagation();
setTimeout(function() {
self._blockActions = false;
}, 3);
}
});
self.ev.trigger('rsAfterInit');
} /* RoyalSlider Constructor End */
/**
*
* RoyalSlider Core Prototype
*
*/
RoyalSlider.prototype = {
constructor: RoyalSlider,
_mouseNext: function(e) {
var self = this,
relativePos = e[self._slidesHorizontal ? 'pageX' : 'pageY'] - self._sliderOffset;
if(relativePos >= self._nextSlidePos) {
self.next();
} else if(relativePos < 0) {
self.prev();
}
},
_refreshNumPreloadImages: function() {
var self = this,
n;
n = self.st.numImagesToPreload;
self._loop = self.st.loop;
if(self._loop) {
if(self.numSlides === 2) {
self._loop = false;
self.st.loopRewind = true;
} else if(self.numSlides < 2) {
self.st.loopRewind = self._loop = false;
}
}
if(self._loop && n > 0) {
if(self.numSlides <= 4) {
n = 1;
} else {
if(self.st.numImagesToPreload > (self.numSlides - 1) / 2 ) {
n = Math.floor( (self.numSlides - 1) / 2 );
}
}
}
self._numPreloadImages = n;
},
_parseNode: function(content, pushToSlides) {
var self = this,
hasImg,
isRoot,
hasCover,
obj = {},
tempEl,
first = true;
content = $(content);
self._currContent = content;
self.ev.trigger('rsBeforeParseNode', [content, obj]);
if(obj.stopParsing) {
return;
}
content = self._currContent;
obj.id = self._idCount;
obj.contentAdded = false;
self._idCount++;
obj.images = [];
obj.isBig = false;
if(!obj.hasCover) {
if(content.hasClass('rsImg')) {
tempEl = content;
hasImg = true;
} else {
tempEl = content.find('.rsImg');
if(tempEl.length) {
hasImg = true;
}
}
if(hasImg) {
obj.bigImage = tempEl.eq(0).attr('data-rsBigImg');
tempEl.each(function() {
var item = $(this);
if(item.is('a')) {
parseEl(item, 'href');
} else if(item.is('img')) {
parseEl(item, 'src');
} else {
parseEl(item);
}
});
} else if(content.is('img')) {
content.addClass('rsImg rsMainSlideImage');
parseEl(content, 'src');
}
}
tempEl = content.find('.rsCaption');
if(tempEl.length) {
obj.caption = tempEl.remove();
}
obj.content = content;
self.ev.trigger('rsAfterParseNode', [content, obj]);
function parseEl(el, s) {
if(s) {
obj.images.push( el.attr(s) );
} else {
obj.images.push( el.text() );
}
if(first) {
first = false;
obj.caption = (s === 'src') ? el.attr('alt') : el.contents();
obj.image = obj.images[0];
obj.videoURL = el.attr('data-rsVideo');
var wAtt = el.attr('data-rsw'),
hAtt = el.attr('data-rsh');
if (typeof wAtt !== 'undefined' && wAtt !== false && typeof hAtt !== 'undefined' && hAtt !== false ) {
obj.iW = parseInt(wAtt);
obj.iH = parseInt(hAtt);
} else if(self.st.imgWidth && self.st.imgHeight ) {
obj.iW = self.st.imgWidth;
obj.iH = self.st.imgHeight;
}
}
}
if(pushToSlides) {
self.slides.push(obj);
}
if(obj.images.length === 0) {
obj.isLoaded = true;
obj.isRendered = false;
obj.isLoading = false;
obj.images = null;
}
return obj;
},
_bindKeyboardNav: function() {
var self = this,
interval,
keyCode,
onKeyboardAction = function (keyCode) {
if (keyCode === 37) {
self.prev();
} else if (keyCode === 39) {
self.next();
}
};
self._doc.on('keydown' + self.ns, function(e) {
if(!self._isDragging) {
keyCode = e.keyCode;
if(keyCode === 37 || keyCode === 39) {
if(!interval) {
onKeyboardAction(keyCode);
interval = setInterval(function() {
onKeyboardAction(keyCode);
}, 700);
}
}
}
}).on('keyup' + self.ns, function(e) {
if(interval) {
clearInterval(interval);
interval = null;
}
});
},
goTo: function(id, notUserAction) {
var self = this;
if(id !== self.currSlideId) {
self._moveTo(id,self.st.transitionSpeed, true, !notUserAction);
}
},
destroy: function(remove) {
var self = this;
self.ev.trigger('rsBeforeDestroy');
self._doc.off('keydown' +self.ns+ ' keyup' + self.ns + ' ' + self._moveEvent +' '+ self._upEvent );
self._slidesContainer.off(self._downEvent + ' click');
self.slider.data('royalSlider', null);
$.removeData(self.slider, 'royalSlider');
$(window).off('resize' + self.ns);
if(remove) {
self.slider.remove();
}
self.slides = null;
self.slider = null;
self.ev = null;
},
_updateBlocksContent: function(beforeTransition, getId) {
var self = this,
item,
i,
n,
pref,
group,
groupId,
slideCode,
loop = self._loop,
numSlides = self.numSlides;
if(!isNaN(getId) ) {
return getCorrectLoopedId(getId);
}
var id = self.currSlideId;
var groupOffset;
var itemsOnSide = beforeTransition ? (Math.abs(self._prevSlideId - self.currSlideId) >= self.numSlides - 1 ? 0 : 1) : self._numPreloadImages;
var itemsToCheck = Math.min(2, itemsOnSide);
var updateAfter = false;
var updateBefore = false;
var tempId;
for(i = id; i < id + 1 + itemsToCheck; i++) {
tempId = getCorrectLoopedId(i);
item = self.slides[tempId];
if(item && (!item.isAdded || !item.positionSet) ) {
updateAfter = true;
break;
}
}
for(i = id - 1; i > id - 1 - itemsToCheck; i--) {
tempId = getCorrectLoopedId(i);
item = self.slides[tempId];
if(item && (!item.isAdded || !item.positionSet) ) {
updateBefore = true;
break;
}
}
if(updateAfter) {
for(i = id; i < id + itemsOnSide + 1; i++) {
tempId = getCorrectLoopedId(i);
groupOffset = Math.floor( (self._realId - (id - i)) / self.numSlides) * self.numSlides;
item = self.slides[tempId];
if(item) {
updateItem(item, tempId);
}
}
}
if(updateBefore) {
for(i = id - 1; i > id - 1 - itemsOnSide; i--) {
tempId = getCorrectLoopedId(i);
groupOffset = Math.floor( (self._realId - (id - i) ) / numSlides) * numSlides;
item = self.slides[tempId];
if(item) {
updateItem(item, tempId);
}
}
}
if(!beforeTransition) {
var start = id;
var distance = itemsOnSide;
var min = getCorrectLoopedId(id - itemsOnSide);
var max = getCorrectLoopedId(id + itemsOnSide);
var nmin = min > max ? 0 : min;
for (i = 0; i < numSlides; i++) {
if(min > max) {
if(i > min - 1) {
continue;
}
}
if(i < nmin || i > max) {
item = self.slides[i];
if(item && item.holder) {
//slideCode = self.slidesJQ[i];
//if(typeof slideCode !== "string") {
item.holder.detach();
item.isAdded = false;
//}
}
}
}
}
function updateItem(item , i, slideCode) {
if(!item.isAdded) {
if(!slideCode)
slideCode = self.slidesJQ[i];
if(!item.holder) {
slideCode = self.slidesJQ[i] = $(slideCode);
item.holder = slideCode;
} else {
slideCode = item.holder;
}
item.appendOnLoaded = false;
updatePos(i, item, slideCode);
addContent(i, item);
self._addBlockToContainer(item, slideCode, beforeTransition);
item.isAdded = true;
appended = true;
} else {
addContent(i, item);
updatePos(i, item);
}
}
function addContent(i, item) {
if(!item.contentAdded) {
self.setItemHtml(item, beforeTransition);
if(!beforeTransition) {
item.contentAdded = true;
}
}
}
function updatePos(i, item, slideCode) {
if(self._isMove) {
if(!slideCode) {
slideCode = self.slidesJQ[i];
}
slideCode.css(self._reorderProp, (i + self._idOffset + groupOffset) * self._slideSize);
}
}
function getCorrectLoopedId(index) {
var changed = false;
if(loop) {
if(index > numSlides - 1) {
return getCorrectLoopedId(index - numSlides);
} else if(index < 0) {
return getCorrectLoopedId(numSlides + index);
}
}
return index;
}
},
/**
* Sets or loads HTML for specified slide
* @param {Object} currSlideObject holds data about curr slide (read about rsAfterParseNode for more info)
* @param {Boolean} beforeTransition determines if setItemHTML method is called before or after transition
*/
setItemHtml: function(currSlideObject, beforeTransition) {
var self = this;
if(currSlideObject.isLoaded) {
appendContent();
return;
} else {
if(beforeTransition) {
waitForTransition();
} else {
parseDataAndLoad();
}
}
function parseDataAndLoad() {
if(!currSlideObject.images) {
currSlideObject.isRendered = true;
currSlideObject.isLoaded = true;
currSlideObject.isLoading = false;
appendContent(true);
return;
}
if(currSlideObject.isLoading) {
return;
}
var el,
isRoot;
if(currSlideObject.content.hasClass('rsImg') ) {
el = currSlideObject.content;
isRoot = true;
} else {
el = currSlideObject.content.find('.rsImg:not(img)')
}
if(el && !el.is('img')) {
el.each(function() {
var item = $(this),
newEl = '<img class="rsImg" src="'+ ( item.is('a') ? item.attr('href') : item.text() ) +'" />';
if(!isRoot) {
item.replaceWith( newEl );
} else {
currSlideObject.content = $(newEl);
}
});
}
el = isRoot ? currSlideObject.content : currSlideObject.content.find('img.rsImg');
setPreloader();
el.eq(0).addClass('rsMainSlideImage');
if(currSlideObject.iW && currSlideObject.iH) {
if(!currSlideObject.isLoaded) {
self._resizeImage( currSlideObject );
}
appendContent();
}
currSlideObject.isLoading = true;
var newEl;
if(currSlideObject.isBig) {
$('<img />').on('load.rs error.rs', function(e){
onLoad( [this], true );
}).attr('src', currSlideObject.image);
} else {
currSlideObject.loaded = [];
currSlideObject.imgLoaders = [];
for(var i = 0; i < currSlideObject.images.length; i++) {
var image = $('<img />');
currSlideObject.imgLoaders.push( this );
image.on('load.rs error.rs', function(e){
currSlideObject.loaded.push( this );
if(currSlideObject.loaded.length === currSlideObject.imgLoaders.length) {
onLoad( currSlideObject.loaded, false );
}
}).attr('src', currSlideObject.images[i]);
}
}
// old images loading
// el.imagesLoaded( function( $images, $proper, $broken ) {
// if($broken.length) {
// currSlideObject.isLoading = false;
// var img = $images[0],
// src = img.src;
// if(src && src.indexOf(currSlideObject.image) === -1 ) {
// return;
// }
// if(!currSlideObject.tryAgainCount) { currSlideObject.tryAgainCount = 0; }
// if(currSlideObject.tryAgainCount < 3) {
// currSlideObject.tryAgainCount++;
// self.setItemHtml(currSlideObject, beforeTransition);
// return;
// }
// }
// onLoad($images);
// });
}
function onLoad($images, isBig) {
if($images.length) {
var img = $images[0],
src = img.src;
if(isBig !== currSlideObject.isBig) {
var c = currSlideObject.holder.children();
if(c && c.length > 1) {
removePreloader();
}
return;
}
if(currSlideObject.iW && currSlideObject.iH) {
imageLoadingComplete();
return;
}
currSlideObject.iW = img.width;
currSlideObject.iH = img.height;
if(currSlideObject.iW && currSlideObject.iH) {
imageLoadingComplete();
return;
} else {
// if no size, try again
var loader = new Image();
loader.onload = function() {
if(loader.width) {
currSlideObject.iW = loader.width;
currSlideObject.iH = loader.height;
imageLoadingComplete();
} else {
setTimeout(function() {
if(loader.width) {
currSlideObject.iW = loader.width;
currSlideObject.iH = loader.height;
}
// failed to get size on last tier, just output image
imageLoadingComplete();
}, 1000);
}
};
loader.src = img.src;
}
} else {
imageLoadingComplete();
}
}
function imageLoadingComplete() {
currSlideObject.isLoaded = true;
currSlideObject.isLoading = false;
appendContent();
removePreloader();
triggerLoaded();
}
function waitForTransition() {
if(!self._isMove && currSlideObject.images && currSlideObject.iW && currSlideObject.iH) {
parseDataAndLoad();
return;
}
currSlideObject.holder.isWaiting = true;
setPreloader();
currSlideObject.holder.slideId = -99;
}
function appendContent() {
if(!currSlideObject.isAppended) {
var visibleNearby = self.st.visibleNearby,
bId = currSlideObject.id - self._newSlideId;
if(!beforeTransition && !currSlideObject.appendOnLoaded && self.st.fadeinLoadedSlide && ( bId === 0 || ( (visibleNearby || self._isAnimating || self._isDragging) && (bId === -1 || bId === 1) ) ) ) {
var css = {
visibility: 'visible',
opacity: 0
};
css[self._vendorPref + 'transition'] = 'opacity 400ms ease-in-out';
currSlideObject.content.css(css);
setTimeout(function() {
currSlideObject.content.css('opacity', 1);
}, 16);
}
if(currSlideObject.holder.find('.rsPreloader').length) {
currSlideObject.holder.append( currSlideObject.content );
} else {
currSlideObject.holder.html( currSlideObject.content );
}
currSlideObject.isAppended = true;
if(currSlideObject.isLoaded) {
self._resizeImage(currSlideObject);
triggerLoaded();
}
if(!currSlideObject.sizeReady) {
currSlideObject.sizeReady = true;
setTimeout(function() {
// triggers after content is added, usually is true when page is refreshed from cache
self.ev.trigger('rsMaybeSizeReady', currSlideObject);
}, 100);
}
}
}
function triggerLoaded() {
if(!currSlideObject.loadedTriggered) {
currSlideObject.isLoaded = currSlideObject.loadedTriggered = true;
currSlideObject.holder.trigger('rsAfterContentSet');
self.ev.trigger('rsAfterContentSet', currSlideObject);
}
}
function setPreloader() {
if(self.st.usePreloader)
currSlideObject.holder.html(self._preloader.clone());
}
function removePreloader(now) {
if(self.st.usePreloader) {
var preloader = currSlideObject.holder.find('.rsPreloader');
if(preloader.length) {
preloader.remove();
}
}
}
},
_addBlockToContainer: function(slideObject, content, dontFade) {
var self = this;
var holder = slideObject.holder;
var bId = slideObject.id - self._newSlideId;
var visibleNearby = false;
// if(self._isMove && !dontFade && self.st.fadeinLoadedSlide && ( bId === 0 || ( (visibleNearby || self._isAnimating || self._isDragging) && (bId === -1 || bId === 1) ) ) ) {
// var content = slideObject.content;
// content.css(self._vendorPref + 'transition', 'opacity 400ms ease-in-out').css({visibility: 'visible', opacity: 0});
// //holder.css('opacity', 0);
// self._slidesContainer.append(holder);
// setTimeout(function() {
// content.css('opacity', 1);
// //self.ev.trigger('rsAfterContentSet', holder);
// }, 6);
// } else {
self._slidesContainer.append(holder);
//}
slideObject.appendOnLoaded = false;
},
_onDragStart:function(e, isThumbs) {
var self = this,
point,
wasAnimating,
isTouch = (e.type === 'touchstart');
self._isTouchGesture = isTouch;
self.ev.trigger('rsDragStart');
if($(e.target).closest('.rsNoDrag', self._currHolder).length) {
self.dragSuccess = false;
return true;
}
if(!isThumbs) {
if(self._isAnimating) {
self._wasAnimating = true;
self._stopAnimation();
}
}
self.dragSuccess = false;
if(self._isDragging) {
if(isTouch) {
self._multipleTouches = true;
}
return;
} else {
if(isTouch) {
self._multipleTouches = false;
}
}
self._setGrabbingCursor();
if(isTouch) {
//parsing touch event
var touches = e.originalEvent.touches;
if(touches && touches.length > 0) {
point = touches[0];
if(touches.length > 1) {
self._multipleTouches = true;
}
}
else {
return;
}
} else {
e.preventDefault();
point = e;
if(self.msEnabled) point = point.originalEvent;
}
self._isDragging = true;
self._doc.on(self._moveEvent, function(e) { self._onDragMove(e, isThumbs); })
.on(self._upEvent, function(e) { self._onDragRelease(e, isThumbs); });
self._currMoveAxis = '';
self._hasMoved = false;
self._pageX = point.pageX;
self._pageY = point.pageY;
self._startPagePos = self._accelerationPos = (!isThumbs ? self._slidesHorizontal : self._thumbsHorizontal) ? point.pageX : point.pageY;
self._horDir = 0;
self._verDir = 0;
self._currRenderPosition = !isThumbs ? self._sPosition : self._thumbsPosition;
self._startTime = new Date().getTime();
if(isTouch) {
self._sliderOverflow.on(self._cancelEvent, function(e) { self._onDragRelease(e, isThumbs); });
}
},
_renderMovement:function(point, isThumbs) {
var self = this;
if(self._checkedAxis) {
var timeStamp = self._renderMoveTime,
deltaX = point.pageX - self._pageX,
deltaY = point.pageY - self._pageY,
newX = self._currRenderPosition + deltaX,
newY = self._currRenderPosition + deltaY,
isHorizontal = (!isThumbs ? self._slidesHorizontal : self._thumbsHorizontal),
newPos = isHorizontal ? newX : newY,
mAxis = self._currMoveAxis;
self._hasMoved = true;
self._pageX = point.pageX;
self._pageY = point.pageY;
if(mAxis === 'x' && deltaX !== 0) {
self._horDir = deltaX > 0 ? 1 : -1;
} else if(mAxis === 'y' && deltaY !== 0) {
self._verDir = deltaY > 0 ? 1 : -1;
}
var pointPos = isHorizontal ? self._pageX : self._pageY,
deltaPos = isHorizontal ? deltaX : deltaY;
if(!isThumbs) {
if(!self._loop) {
if(self.currSlideId <= 0) {
if(pointPos - self._startPagePos > 0) {
newPos = self._currRenderPosition + deltaPos * self._lastItemFriction;
}
}
if(self.currSlideId >= self.numSlides - 1) {
if(pointPos - self._startPagePos < 0) {
newPos = self._currRenderPosition + deltaPos * self._lastItemFriction ;
}
}
}
} else {
if(newPos > self._thumbsMinPosition) {
newPos = self._currRenderPosition + deltaPos * self._lastItemFriction;
} else if(newPos < self._thumbsMaxPosition) {
newPos = self._currRenderPosition + deltaPos * self._lastItemFriction ;
}
}
self._currRenderPosition = newPos;
if (timeStamp - self._startTime > 200) {
self._startTime = timeStamp;
self._accelerationPos = pointPos;
}
if(!isThumbs) {
if(self._isMove) {
self._setPosition(self._currRenderPosition);
}
} else {
self._setThumbsPosition(self._currRenderPosition);
}
}
},
_onDragMove:function(e, isThumbs) {
var self = this,
point,
isTouch = (e.type === 'touchmove');
if(self._isTouchGesture && !isTouch) {
return;
}
if(isTouch) {
if(self._lockAxis) {
return;
}
var touches = e.originalEvent.touches;
if(touches) {
if(touches.length > 1) {
return;
} else {
point = touches[0];
}
} else {
return;
}
} else {
point = e;
if(self.msEnabled) point = point.originalEvent;
}
if(!self._hasMoved) {
if(self._useCSS3Transitions) {
(!isThumbs ? self._slidesContainer : self._thumbsContainer).css((self._vendorPref + self._TD), '0s');
}
(function animloop(){
if(self._isDragging) {
self._animFrame = requestAnimationFrame(animloop);
if(self._renderMoveEvent)
self._renderMovement(self._renderMoveEvent, isThumbs);
}
})();
}
if(!self._checkedAxis) {
var dir = (!isThumbs ? self._slidesHorizontal : self._thumbsHorizontal),
diff = (Math.abs(point.pageX - self._pageX) - Math.abs(point.pageY - self._pageY) ) - (dir ? -7 : 7);
if(diff > 7) {
// hor movement
if(dir) {
e.preventDefault();
self._currMoveAxis = 'x';
} else if(isTouch) {
self._completeGesture();
return;
}
self._checkedAxis = true;
} else if(diff < -7) {
// ver movement
if(!dir) {
e.preventDefault();
self._currMoveAxis = 'y';
} else if(isTouch) {
self._completeGesture();
return;
}
self._checkedAxis = true;
}
return;
}
e.preventDefault();
self._renderMoveTime = new Date().getTime();
self._renderMoveEvent = point;
},
_completeGesture: function() {
var self = this;
self._lockAxis = true;
self._hasMoved = self._isDragging = false;
self._onDragRelease();
},
_onDragRelease:function(e, isThumbs) {
var self = this,
totalMoveDist,
accDist,
duration,
v0,
newPos,
newDist,
newDuration,
blockLink,
isTouch = (e.type === 'touchend' || e.type === 'touchcancel');
if(self._isTouchGesture && !isTouch) {
return;
}
self._isTouchGesture = false;
self.ev.trigger('rsDragRelease');
self._renderMoveEvent = null;
self._isDragging = false;
self._lockAxis = false;
self._checkedAxis = false;
self._renderMoveTime = 0;
cancelAnimationFrame(self._animFrame);
if(self._hasMoved) {
if(!isThumbs) {
if(self._isMove) {
self._setPosition(self._currRenderPosition);
}
} else {
self._setThumbsPosition(self._currRenderPosition);
}
}
self._doc.off(self._moveEvent).off(self._upEvent);
if(isTouch) {
self._sliderOverflow.off(self._cancelEvent);
}
self._setGrabCursor();
if (!self._hasMoved && !self._multipleTouches) {
if(isThumbs && self._thumbsEnabled) {
var item = $(e.target).closest('.rsNavItem');
if(item.length) {
self.goTo(item.index());
}
return;
}
}
var orient = (!isThumbs ? self._slidesHorizontal : self._thumbsHorizontal);
if(!self._hasMoved || (self._currMoveAxis === 'y' && orient) || (self._currMoveAxis === 'x' && !orient) ) {
if(!isThumbs && self._wasAnimating) {
self._wasAnimating = false;
if(!self.st.navigateByClick) {
self.dragSuccess = true;
} else {
self._mouseNext( (self.msEnabled ? e.originalEvent : e) );
self.dragSuccess = true;
return;
}
} else {
self._wasAnimating = false;
self.dragSuccess = false;
return;
}
} else {
self.dragSuccess = true;
}
self._wasAnimating = false;
self._currMoveAxis = '';
function getCorrectSpeed(newSpeed) {
if(newSpeed < 100) {
return 100;
} else if(newSpeed > 500) {
return 500;
}
return newSpeed;
}
function returnToCurrent(isSlow, v0) {
if(self._isMove || isThumbs) {
newPos = (-self._realId - self._idOffset) * self._slideSize;
newDist = Math.abs(self._sPosition - newPos);
self._currAnimSpeed = newDist / v0;
if(isSlow) {
self._currAnimSpeed += 250;
}
self._currAnimSpeed = getCorrectSpeed(self._currAnimSpeed);
self._animateTo(newPos, false);
}
}
var snapDist = self.st.minSlideOffset,
point = isTouch ? e.originalEvent.changedTouches[0] : (self.msEnabled ? e.originalEvent : e),
pPos = orient ? point.pageX : point.pageY,
sPos = self._startPagePos,
axPos = self._accelerationPos,
axCurrItem = self.currSlideId,
axNumItems = self.numSlides,
dir = orient ? self._horDir : self._verDir,
loop = self._loop,
changeHash = false,
distOffset = 0;
totalMoveDist = Math.abs(pPos - sPos);
accDist = pPos - axPos;
duration = (new Date().getTime()) - self._startTime;
v0 = Math.abs(accDist) / duration;
if(dir === 0 || axNumItems <= 1) {
returnToCurrent(true, v0);
return;
}
if(!loop && !isThumbs) {
if(axCurrItem <= 0) {
if(dir > 0) {
returnToCurrent(true, v0);
return;
}
} else if(axCurrItem >= axNumItems - 1) {
if(dir < 0) {
returnToCurrent(true, v0);
return;
}
}
}
if(!isThumbs) {
if(sPos + snapDist < pPos) {
if(dir < 0) {
returnToCurrent(false, v0);
return;
}
self._moveTo('prev', getCorrectSpeed(Math.abs(self._sPosition - (-self._realId - self._idOffset + 1) * self._slideSize) / v0), changeHash, true, true);
} else if(sPos - snapDist > pPos) {
if(dir > 0) {
returnToCurrent(false, v0);
return;
}
self._moveTo('next', getCorrectSpeed(Math.abs(self._sPosition - (-self._realId - self._idOffset - 1) * self._slideSize) / v0), changeHash, true, true);
} else {
returnToCurrent(false, v0);
}
} else {
var newPos = self._thumbsPosition;
var transitionSpeed;
if(newPos > self._thumbsMinPosition) {
newPos = self._thumbsMinPosition;
} else if(newPos < self._thumbsMaxPosition) {
newPos = self._thumbsMaxPosition;
} else {
var friction = 0.003,
S = (v0 * v0) / (friction * 2),
minXDist = -self._thumbsPosition,
maxXDist = self._thumbsContainerSize - self._thumbsViewportSize + self._thumbsPosition;
if (accDist > 0 && S > minXDist) {
minXDist = minXDist + self._thumbsViewportSize / (15 / (S / v0 * friction));
v0 = v0 * minXDist / S;
S = minXDist;
} else if (accDist < 0 && S > maxXDist) {
maxXDist = maxXDist + self._thumbsViewportSize / (15 / (S / v0 * friction));
v0 = v0 * maxXDist / S;
S = maxXDist;
}
transitionSpeed = Math.max(Math.round(v0 / friction), 50);
newPos = newPos + S * (accDist < 0 ? -1 : 1);
if(newPos > self._thumbsMinPosition) {
self._animateThumbsTo(newPos, transitionSpeed, true, self._thumbsMinPosition, 200);
return;
} else if(newPos < self._thumbsMaxPosition) {
self._animateThumbsTo( newPos, transitionSpeed, true, self._thumbsMaxPosition, 200);
return;
}
}
self._animateThumbsTo(newPos, transitionSpeed, true);
}
},
_setPosition: function(pos) {
var self = this;
pos = self._sPosition = pos;
if(self._useCSS3Transitions) {
self._slidesContainer.css(self._xProp, self._tPref1 + ( self._slidesHorizontal ? (pos + self._tPref2 + 0) : (0 + self._tPref2 + pos) ) + self._tPref3 );
} else {
self._slidesContainer.css(self._slidesHorizontal ? self._xProp : self._yProp, pos);
}
},
updateSliderSize: function(force) {
var self = this,
newWidth,
newHeight;
if(self.st.autoScaleSlider) {
var asw = self.st.autoScaleSliderWidth,
ash = self.st.autoScaleSliderHeight;
if(self.st.autoScaleHeight) {
newWidth = self.slider.width();
if(newWidth != self.width) {
self.slider.css("height", newWidth * (ash / asw) );
newWidth = self.slider.width();
}
newHeight = self.slider.height();
} else {
newHeight = self.slider.height();
if(newHeight != self.height) {
self.slider.css("width", newHeight * (asw / ash));
newHeight = self.slider.height();
}
newWidth = self.slider.width();
}
} else {
newWidth = self.slider.width();
newHeight = self.slider.height();
}
if(force || newWidth != self.width || newHeight != self.height) {
self.width = newWidth;
self.height = newHeight;
self._wrapWidth = newWidth;
self._wrapHeight = newHeight;
self.ev.trigger('rsBeforeSizeSet');
self.ev.trigger('rsAfterSizePropSet');
self._sliderOverflow.css({
width: self._wrapWidth,
height: self._wrapHeight
});
self._slideSize = (self._slidesHorizontal ? self._wrapWidth : self._wrapHeight) + self.st.slidesSpacing;
self._imagePadding = self.st.imageScalePadding;
var item,
slideItem,
i,
img;
for(i = 0; i < self.slides.length; i++) {
item = self.slides[i];
item.positionSet = false;
if(item && item.images && item.isLoaded) {
item.isRendered = false;
self._resizeImage(item);
}
}
if(self._cloneHolders) {
for(i = 0; i < self._cloneHolders.length; i++) {
item = self._cloneHolders[i];
item.holder.css(self._reorderProp, (item.id + self._idOffset) * self._slideSize);
}
}
self._updateBlocksContent();
if(self._isMove) {
if(self._useCSS3Transitions) {
self._slidesContainer.css(self._vendorPref + 'transition-duration', '0s');
}
self._setPosition( (-self._realId - self._idOffset) * self._slideSize);
}
self.ev.trigger('rsOnUpdateNav');
}
self._sliderOffset = self._sliderOverflow.offset();
self._sliderOffset = self._sliderOffset[self._reorderProp];
},
//setSlidesOrientation: function(orient) {
// TODO
// var self = this,
// newHor = Boolean(orient === 'horizontal');
// if(self._slidesHorizontal !== newHor) {
// self._setPosition(0);
// if(self._isMove) {
// for(var i = 0; i < self._slideHolders.length; i++) {
// self._slideHolders[i].block.css(self._reorderProp, '');
// }
// }
// self.slider.removeClass(self._slidesHorizontal ? 'rsHor' : 'rsVer').addClass(newHor ? 'rsHor' : 'rsVer');
// self._slidesHorizontal = newHor;
// self._reorderProp = newHor ? 'left' : 'top';
// self.updateSliderSize(true);
// }
//},
/**
* Adds slide
* @param {jQuery object or raw HTML} htmltext
* @param {int} index (optional) Index where item should be added (last item is removed of not specified)
*/
appendSlide: function(htmltext, index) {
var self = this,
parsedSlide = self._parseNode(htmltext);
if(isNaN(index) || index > self.numSlides) {
index = self.numSlides;
}
self.slides.splice(index, 0, parsedSlide);
self.slidesJQ.splice(index, 0, '<div style="'+ (self._isMove ? 'position:absolute;' : self._opacityCSS ) +'" class="rsSlide"></div>');
if(index < self.currSlideId) {
self.currSlideId++;
}
self.ev.trigger('rsOnAppendSlide', [parsedSlide, index]);
self._refreshSlides(index);
if(index === self.currSlideId) {
self.ev.trigger('rsAfterSlideChange');
}
},
/**
* Removes slide
* @param {int} Index of item that should be removed
*/
removeSlide: function(index) {
var self = this,
slideToRemove = self.slides[index];
if(slideToRemove) {
if(slideToRemove.holder) {
slideToRemove.holder.remove();
}
if(index < self.currSlideId) {
self.currSlideId--;
}
self.slides.splice(index, 1);
self.slidesJQ.splice(index, 1);
self.ev.trigger('rsOnRemoveSlide', [index]);
self._refreshSlides(index);
if(index === self.currSlideId) {
self.ev.trigger('rsAfterSlideChange');
}
}
},
_refreshSlides: function(refreshIndex) {
// todo: optimize this stuff
var self = this;
var oldNumSlides = self.numSlides;
var numLoops = self._realId <= 0 ? 0 : Math.floor(self._realId / oldNumSlides);
self.numSlides = self.slides.length;
if(self.numSlides === 0) {
self.currSlideId = self._idOffset = self._realId = 0;
self.currSlide = self._oldHolder = null;
} else {
self._realId = numLoops * self.numSlides + self.currSlideId;
}
for(var i = 0; i < self.numSlides; i++) {
self.slides[i].id = i;
}
self.currSlide = self.slides[self.currSlideId];
self._currHolder = self.slidesJQ[self.currSlideId];
if(self.currSlideId >= self.numSlides) {
self.goTo(self.numSlides - 1);
} else if(self.currSlideId < 0) {
self.goTo(0);
}
self._refreshNumPreloadImages();
if(self._isMove && self._loop) {
self._slidesContainer.css((self._vendorPref + self._TD), '0ms');
}
if(self._refreshSlidesTimeout) {
clearTimeout(self._refreshSlidesTimeout);
}
self._refreshSlidesTimeout = setTimeout(function() {
if(self._isMove) {
self._setPosition( (-self._realId - self._idOffset) * self._slideSize);
}
self._updateBlocksContent();
if(!self._isMove) {
self._currHolder.css({
display: 'block',
opacity: 1
});
}
}, 14);
self.ev.trigger('rsOnUpdateNav');
},
_setGrabCursor:function() {
var self = this;
if(self._hasDrag && self._isMove) {
if(self._grabCursor) {
self._sliderOverflow.css('cursor', self._grabCursor);
} else {
self._sliderOverflow.removeClass('grabbing-cursor');
self._sliderOverflow.addClass('grab-cursor');
}
}
},
_setGrabbingCursor:function() {
var self = this;
if(self._hasDrag && self._isMove) {
if(self._grabbingCursor) {
self._sliderOverflow.css('cursor', self._grabbingCursor);
} else {
self._sliderOverflow.removeClass('grab-cursor');
self._sliderOverflow.addClass('grabbing-cursor');
}
}
},
next: function(notUserAction) {
var self = this;
self._moveTo('next', self.st.transitionSpeed, true, !notUserAction);
},
prev: function(notUserAction) {
var self = this;
self._moveTo('prev', self.st.transitionSpeed, true, !notUserAction);
},
_moveTo:function(type, speed, inOutEasing, userAction, fromSwipe) {
var self = this,
newPos,
difference,
i;
self.ev.trigger('rsBeforeMove', [type, userAction]);
if(type === 'next') {
newItemId = self.currSlideId+1;
} else if(type === 'prev') {
newItemId = self.currSlideId-1;
} else {
newItemId = type = parseInt(type, 10);
}
if(!self._loop) {
if(newItemId < 0) {
self._doBackAndForthAnim('left', !userAction);
return;
} else if(newItemId >= self.numSlides ) {
self._doBackAndForthAnim('right', !userAction);
return;
}
}
if(self._isAnimating) {
self._stopAnimation(true);
inOutEasing = false;
}
difference = newItemId - self.currSlideId;
self._prevSlideId = self.currSlideId;
var prevId = self.currSlideId;
var id = self.currSlideId + difference;
var realId = self._realId;
var temp;
var delayed;
if(self._loop) {
id = self._updateBlocksContent(false, id);
realId += difference;
} else {
realId = id;
}
self._newSlideId = id;
self._oldHolder = self.slidesJQ[self.currSlideId];
self._realId = realId;
self.currSlideId = self._newSlideId;
self.currSlide = self.slides[self.currSlideId];
self._currHolder = self.slidesJQ[self.currSlideId];
var checkDist = self.st.slidesDiff;
var next = Boolean(difference > 0);
var absDiff = Math.abs(difference);
var g1 = Math.floor( prevId / self._numPreloadImages);
var g2 = Math.floor( ( prevId + (next ? checkDist : -checkDist ) ) / self._numPreloadImages);
var biggest = next ? Math.max(g1,g2) : Math.min(g1,g2);
var biggestId = biggest * self._numPreloadImages + ( next ? (self._numPreloadImages - 1) : 0 );
if(biggestId > self.numSlides - 1) {
biggestId = self.numSlides - 1;
} else if(biggestId < 0) {
biggestId = 0;
}
var toLast = next ? (biggestId - prevId) : (prevId - biggestId);
if(toLast > self._numPreloadImages) {
toLast = self._numPreloadImages;
}
if(absDiff > toLast + checkDist) {
self._idOffset += ( absDiff - (toLast + checkDist) ) * ( next ? -1 : 1 );
speed = speed * 1.4;
for(i = 0; i < self.numSlides; i++) {
self.slides[i].positionSet = false;
}
}
self._currAnimSpeed = speed;
self._updateBlocksContent(true);
if(!fromSwipe) {
delayed = true;
}
newPos = (-realId - self._idOffset) * self._slideSize;
if(delayed) {
setTimeout(function() {
self._isWorking = false;
self._animateTo(newPos, type, false, inOutEasing);
self.ev.trigger('rsOnUpdateNav');
}, 0);
} else {
self._animateTo(newPos, type, false, inOutEasing);
self.ev.trigger('rsOnUpdateNav');
}
function isSetToCurrent(testId) {
if(testId < 0) {
testId = self.numSlides + testId;
} else if(testId > self.numSlides - 1) {
testId = testId - self.numSlides;
}
if(testId !== self.currSlideId) {
return false;
}
return true;
}
},
_updateArrowsNav: function() {
var self = this,
arrDisClass = 'rsArrowDisabled';
if(self.st.arrowsNav) {
if(self.numSlides <= 1) {
self._arrowLeft.css('display', 'none');
self._arrowRight.css('display', 'none');
return;
} else {
self._arrowLeft.css('display', 'block');
self._arrowRight.css('display', 'block');
}
if(!self._loop && !self.st.loopRewind) {
if(self.currSlideId === 0) {
self._arrowLeft.addClass(arrDisClass);
} else {
self._arrowLeft.removeClass(arrDisClass);
}
if(self.currSlideId === self.numSlides - 1) {
self._arrowRight.addClass(arrDisClass);
} else {
self._arrowRight.removeClass(arrDisClass);
}
}
}
},
_animateTo:function(pos, dir, loadAll, inOutEasing, customComplete) {
var self = this,
moveProp,
oldBlock,
animBlock;
var animObj = {};
if(isNaN(self._currAnimSpeed)) {
self._currAnimSpeed = 400;
}
self._sPosition = self._currRenderPosition = pos;
self.ev.trigger('rsBeforeAnimStart');
if(!self._useCSS3Transitions) {
if(self._isMove) {
animObj[self._slidesHorizontal ? self._xProp : self._yProp] = pos + 'px';
self._slidesContainer.animate(animObj, self._currAnimSpeed, /*'easeOutQuart'*/ inOutEasing ? self.st.easeInOut : self.st.easeOut);
} else {
oldBlock = self._oldHolder;
animBlock = self._currHolder;
animBlock.stop(true, true).css({
opacity: 0,
display: 'block',
zIndex: self._fadeZIndex
});
self._currAnimSpeed = self.st.transitionSpeed;
animBlock.animate({opacity: 1}, self._currAnimSpeed, self.st.easeInOut);
clearTimeouts();
if(oldBlock) {
oldBlock.data('rsTimeout', setTimeout(function() {
oldBlock.stop(true, true).css({
opacity: 0,
display: 'none',
zIndex: 0
});
}, self._currAnimSpeed + 60) );
}
}
} else {
if(self._isMove) {
self._currAnimSpeed = parseInt(self._currAnimSpeed);
var td = self._vendorPref + self._TD;
var ttf = self._vendorPref + self._TTF;
animObj[td] = self._currAnimSpeed+'ms';
animObj[ttf] = inOutEasing ? $.rsCSS3Easing[self.st.easeInOut] : $.rsCSS3Easing[self.st.easeOut];
self._slidesContainer.css(animObj);
if(inOutEasing || !self.hasTouch) {
setTimeout(function() {
self._setPosition(pos);
}, 5);
} else {
self._setPosition(pos);
}
} else {
//self._currAnimSpeed = 10
self._currAnimSpeed = self.st.transitionSpeed;
oldBlock = self._oldHolder;
animBlock = self._currHolder;
if(animBlock.data('rsTimeout')) {
animBlock.css('opacity', 0);
}
clearTimeouts();
if(oldBlock) {
//if(oldBlock)
oldBlock.data('rsTimeout', setTimeout(function() {
animObj[self._vendorPref + self._TD] = '0ms';
animObj.zIndex = 0;
animObj.display = 'none';
oldBlock.data('rsTimeout', '');
oldBlock.css(animObj);
setTimeout(function() {
oldBlock.css('opacity', 0);
}, 16);
}, self._currAnimSpeed + 60) );
}
animObj.display = 'block';
animObj.zIndex = self._fadeZIndex;
animObj.opacity = 0;
animObj[self._vendorPref + self._TD] = '0ms';
animObj[self._vendorPref + self._TTF] = $.rsCSS3Easing[self.st.easeInOut];
animBlock.css(animObj);
animBlock.data('rsTimeout', setTimeout(function() {
//animBlock.css('opacity', 0);
animBlock.css(self._vendorPref + self._TD, self._currAnimSpeed+'ms');
//oldBlock.css(self._vendorPref + self._TD, '0ms');
animBlock.data('rsTimeout', setTimeout(function() {
animBlock.css('opacity', 1);
animBlock.data('rsTimeout', '');
}, 20) );
}, 20) );
}
}
self._isAnimating = true;
if(self.loadingTimeout) {
clearTimeout(self.loadingTimeout);
}
if(customComplete) {
self.loadingTimeout = setTimeout(function() {
self.loadingTimeout = null;
customComplete.call();
}, self._currAnimSpeed + 60);
} else {
self.loadingTimeout = setTimeout(function() {
self.loadingTimeout = null;
self._animationComplete(dir);
}, self._currAnimSpeed + 60);
}
function clearTimeouts() {
var t;
if(oldBlock) {
t = oldBlock.data('rsTimeout');
if(t) {
if(oldBlock !== animBlock) {
oldBlock.css({
opacity: 0,
display: 'none',
zIndex: 0
});
}
clearTimeout(t);
oldBlock.data('rsTimeout', '');
}
}
t = animBlock.data('rsTimeout');
if(t) {
clearTimeout(t);
animBlock.data('rsTimeout', '');
}
}
},
_stopAnimation: function(noCSS3) {
var self = this;
self._isAnimating = false;
clearTimeout(self.loadingTimeout);
if(self._isMove) {
if(!self._useCSS3Transitions) {
self._slidesContainer.stop(true);
self._sPosition = parseInt(self._slidesContainer.css(self._xProp), 10);
} else if (!noCSS3) {
var oldPos = self._sPosition;
var newPos = self._currRenderPosition = self._getTransformProp();
self._slidesContainer.css((self._vendorPref + self._TD), '0ms');
if(oldPos !==newPos) {
self._setPosition(newPos);
}
}
} else {
// kung fu
if(self._fadeZIndex > 20) {
self._fadeZIndex = 10;
} else {
self._fadeZIndex++;
}
}
},
// Thanks to @benpbarnett
_getTransformProp:function(){
var self = this,
transform = window.getComputedStyle(self._slidesContainer.get(0), null).getPropertyValue(self._vendorPref + 'transform'),
explodedMatrix = transform.replace(/^matrix\(/i, '').split(/, |\)$/g),
isMatrix3d = (explodedMatrix[0].indexOf('matrix3d') === 0);
return parseInt(explodedMatrix[(self._slidesHorizontal ? (isMatrix3d ? 12 : 4) : (isMatrix3d ? 13 : 5) )], 10);
},
_getCSS3Prop: function(pos, hor) {
var self = this;
return self._useCSS3Transitions ? self._tPref1 + ( hor ? (pos + self._tPref2 + 0) : (0 + self._tPref2 + pos) ) + self._tPref3 : pos;
},
_animationComplete: function(dir) {
var self = this;
if(!self._isMove) {
self._currHolder.css('z-index', 0);
self._fadeZIndex = 10;
}
self._isAnimating = false;
self.staticSlideId = self.currSlideId;
self._updateBlocksContent();
self._slidesMoved = false;
self.ev.trigger('rsAfterSlideChange');
},
_doBackAndForthAnim:function(type, userAction) {
var self = this,
newPos = (-self._realId - self._idOffset) * self._slideSize;
if(self.numSlides === 0 || self._isAnimating) {
return;
}
if(self.st.loopRewind) {
self.goTo(type === 'left' ? self.numSlides - 1 : 0, userAction);
return;
}
if(self._isMove) {
self._currAnimSpeed = 200;
function allAnimComplete() {
self._isAnimating = false;
}
function firstAnimComplete() {
self._isAnimating = false;
self._animateTo(newPos, '', false, true, allAnimComplete);
}
self._animateTo(newPos + (type === 'left' ? 30 : -30),'', false, true, firstAnimComplete);
}
},
_resizeImage:function(slideObject, useClone) {
var isRoot = true;
if(slideObject.isRendered) {
return;
}
var img = slideObject.content;
var classToFind = 'rsMainSlideImage';
var isVideo;
var self = this,
imgAlignCenter = self.st.imageAlignCenter,
imgScaleMode = self.st.imageScaleMode,
tempEl;
if(slideObject.videoURL) {
classToFind = 'rsVideoContainer';
if(imgScaleMode !== 'fill') {
isVideo = true;
} else {
tempEl = img;
if(!tempEl.hasClass(classToFind)) {
tempEl = tempEl.find('.'+classToFind);
}
tempEl.css({width:'100%',height: '100%'});
classToFind = 'rsMainSlideImage';
}
}
if(!img.hasClass(classToFind)) {
isRoot = false;
img = img.find('.'+classToFind);
}
if(!img) {
return;
}
var baseImageWidth = slideObject.iW,
baseImageHeight = slideObject.iH;
slideObject.isRendered = true;
if(imgScaleMode === 'none' && !imgAlignCenter) {
return;
}
if(imgScaleMode !== 'fill') {
bMargin = self._imagePadding;
} else {
bMargin = 0;
}
//var block = img.parent('.block-inside').css('margin', bMargin);
var containerWidth = self._wrapWidth - bMargin * 2,
containerHeight = self._wrapHeight - bMargin * 2,
hRatio,
vRatio,
ratio,
nWidth,
nHeight,
cssObj = {};
if(imgScaleMode === 'fit-if-smaller') {
if(baseImageWidth > containerWidth || baseImageHeight > containerHeight) {
imgScaleMode = 'fit';
}
}
if(imgScaleMode === 'fill' || imgScaleMode === 'fit') {
hRatio = containerWidth / baseImageWidth;
vRatio = containerHeight / baseImageHeight;
if (imgScaleMode == "fill") {
ratio = hRatio > vRatio ? hRatio : vRatio;
} else if (imgScaleMode == "fit") {
ratio = hRatio < vRatio ? hRatio : vRatio;
} else {
ratio = 1;
}
nWidth = Math.ceil(baseImageWidth * ratio, 10);
nHeight = Math.ceil(baseImageHeight * ratio, 10);
} else {
nWidth = baseImageWidth;
nHeight = baseImageHeight;
}
if(imgScaleMode !== 'none') {
cssObj.width = nWidth;
cssObj.height = nHeight;
if(isVideo) {
img.find('.rsImg').css({width: '100%', height:'100%'});
}
}
if (imgAlignCenter) {
cssObj.marginLeft = Math.floor((containerWidth - nWidth) / 2) + bMargin;
cssObj.marginTop = Math.floor((containerHeight - nHeight) / 2) + bMargin;
}
img.css(cssObj);
}
}; /* RoyalSlider core prototype end */
$.rsProto = RoyalSlider.prototype;
$.fn.royalSlider = function(options) {
var args = arguments;
return this.each(function(){
var self = $(this);
if (typeof options === "object" || !options) {
if( !self.data('royalSlider') ) {
self.data('royalSlider', new RoyalSlider(self, options));
}
} else {
var royalSlider = self.data('royalSlider');
if (royalSlider && royalSlider[options]) {
return royalSlider[options].apply(royalSlider, Array.prototype.slice.call(args, 1));
}
}
});
};
$.fn.royalSlider.defaults = {
slidesSpacing: 8,
startSlideId: 0,
loop: false,
loopRewind: false,
numImagesToPreload: 4,
fadeinLoadedSlide: true,
slidesOrientation: 'horizontal',
transitionType: 'move',
transitionSpeed: 600,
controlNavigation: 'bullets',
controlsInside: true,
arrowsNav: true,
arrowsNavAutoHide: true,
navigateByClick: true,
randomizeSlides: false,
sliderDrag: true,
sliderTouch: true,
keyboardNavEnabled: false,
fadeInAfterLoaded: true,
allowCSS3: true,
allowCSS3OnWebkit: true,
addActiveClass: false,
autoHeight: false,
easeOut: 'easeOutSine',
easeInOut: 'easeInOutSine',
minSlideOffset: 10,
imageScaleMode:"fit-if-smaller",
imageAlignCenter:true,
imageScalePadding: 4,
usePreloader: true,
autoScaleSlider: false,
autoScaleSliderWidth: 800,
autoScaleSliderHeight: 400,
autoScaleHeight: true,
arrowsNavHideOnTouch: false,
globalCaption: false,
slidesDiff: 2,
disableResponsiveness: false // !disable responsiveness option
}; /* default options end */
$.rsCSS3Easing = {
easeOutSine: 'cubic-bezier(0.390, 0.575, 0.565, 1.000)',
easeInOutSine: 'cubic-bezier(0.445, 0.050, 0.550, 0.950)'
};
$.extend(jQuery.easing, {
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
}
});
/****************************************************************************************************************/
/**
*
* RoyalSlider fullscreen module
* @version 1.0.5:
*
* 1.0.1:
* - Added rsEnterFullscreen and rsExitFullscreen events
*
* 1.0.2
* - Added window scroll detection
*
* 1.0.3
* - Fullscreen button now is added to _controlsContainer element
*
* 1.0.4
* - Fixed issue that could cause small image be loaded in fullscreen
*
* 1.0.5
* - Fix "false" native fullscreen on Android
*
*/
$.extend($.rsProto, {
_initFullscreen: function() {
var self = this;
self._fullscreenDefaults = {
enabled: false,
keyboardNav: true,
buttonFS: true,
nativeFS: false,
doubleTap: true
};
self.st.fullscreen = $.extend({}, self._fullscreenDefaults, self.st.fullscreen);
if(self.st.fullscreen.enabled) {
self.ev.one('rsBeforeSizeSet', function() {
self._setupFullscreen();
});
}
},
_setupFullscreen: function() {
var self = this;
self._fsKeyboard = (!self.st.keyboardNavEnabled && self.st.fullscreen.keyboardNav);
if(self.st.fullscreen.nativeFS) {
// Thanks to John Dyer http://j.hn/
self._fullScreenApi = {
supportsFullScreen: false,
isFullScreen: function() { return false; },
requestFullScreen: function() {},
cancelFullScreen: function() {},
fullScreenEventName: '',
prefix: ''
};
var browserPrefixes = 'webkit moz o ms khtml'.split(' ');
// check for native support
if(!self.isAndroid) {
if (typeof document.cancelFullScreen != 'undefined') {
self._fullScreenApi.supportsFullScreen = true;
} else {
// check for fullscreen support by vendor prefix
for (var i = 0; i < browserPrefixes.length; i++ ) {
self._fullScreenApi.prefix = browserPrefixes[i];
if (typeof document[ self._fullScreenApi.prefix + 'CancelFullScreen' ] != 'undefined' ) {
self._fullScreenApi.supportsFullScreen = true;
break;
}
}
}
}
// update methods to do something useful
if ( self._fullScreenApi.supportsFullScreen) {
self.nativeFS = true;
self._fullScreenApi.fullScreenEventName = self._fullScreenApi.prefix + 'fullscreenchange' + self.ns;
self._fullScreenApi.isFullScreen = function() {
switch (this.prefix) {
case '':
return document.fullScreen;
case 'webkit':
return document.webkitIsFullScreen;
default:
return document[this.prefix + 'FullScreen'];
}
};
self._fullScreenApi.requestFullScreen = function(el) {
return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']();
};
self._fullScreenApi.cancelFullScreen = function(el) {
return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + 'CancelFullScreen']();
};
} else {
self._fullScreenApi = false;
}
}
if(self.st.fullscreen.buttonFS) {
self._fsBtn = $('<div class="rsFullscreenBtn"><div class="rsFullscreenIcn"></div></div>')
.appendTo(self._controlsContainer)
.on('click.rs', function() {
if(self.isFullscreen) {
self.exitFullscreen();
} else {
self.enterFullscreen();
}
});
}
},
enterFullscreen: function(preventNative) {
var self = this;
if( self._fullScreenApi ) {
if(!preventNative) {
self._doc.on( self._fullScreenApi.fullScreenEventName, function(e) {
if(!self._fullScreenApi.isFullScreen()) {
self.exitFullscreen(true);
} else {
self.enterFullscreen(true);
}
});
self._fullScreenApi.requestFullScreen($('html')[0]);
return;
} else {
self._fullScreenApi.requestFullScreen($('html')[0]);
}
}
if(self._isFullscreenUpdating) {
return;
}
self._isFullscreenUpdating = true;
self._doc.on('keyup' + self.ns + 'fullscreen', function(e) {
if(e.keyCode === 27) {
self.exitFullscreen();
}
});
if(self._fsKeyboard) {
self._bindKeyboardNav();
}
var win = $(window);
self._fsScrollTopOnEnter = win.scrollTop();
self._fsScrollLeftOnEnter = win.scrollLeft();
self._htmlStyle = $('html').attr('style');
self._bodyStyle = $('body').attr('style');
self._sliderStyle = self.slider.attr('style');
$('body, html').css({
overflow: 'hidden',
height: '100%',
width: '100%',
margin: '0',
padding: '0'
});
self.slider.addClass('rsFullscreen');
var item,
i;
for(i = 0; i < self.numSlides; i++) {
item = self.slides[i];
item.isRendered = false;
if(item.bigImage) {
item.isBig = true;
item.isMedLoaded = item.isLoaded;
item.isMedLoading = item.isLoading;
item.medImage = item.image;
item.medIW = item.iW;
item.medIH = item.iH;
item.slideId = -99;
if(item.bigImage !== item.medImage) {
item.sizeType = 'big';
}
item.isLoaded = item.isBigLoaded;
item.isLoading = false;
item.image = item.bigImage;
item.images[0] = item.bigImage;
item.iW = item.bigIW;
item.iH = item.bigIH;
item.isAppended = item.contentAdded = false;
self._updateItemSrc(item);
}
}
self.isFullscreen = true;
self._isFullscreenUpdating = false;
self.updateSliderSize();
self.ev.trigger('rsEnterFullscreen');
},
exitFullscreen: function(preventNative) {
var self = this;
if( self._fullScreenApi ) {
if(!preventNative) {
self._fullScreenApi.cancelFullScreen($('html')[0]);
return;
}
self._doc.off( self._fullScreenApi.fullScreenEventName );
}
if(self._isFullscreenUpdating) {
return;
}
self._isFullscreenUpdating = true;
self._doc.off('keyup' + self.ns + 'fullscreen');
if(self._fsKeyboard) {
self._doc.off('keydown' + self.ns);
}
$('html').attr('style', self._htmlStyle || '');
$('body').attr('style', self._bodyStyle || '');
var item,
i;
for(i = 0; i < self.numSlides; i++) {
item = self.slides[i];
item.isRendered = false;
if(item.bigImage) {
item.isBig = false;
item.slideId = -99;
item.isBigLoaded = item.isLoaded;
item.isBigLoading = item.isLoading;
item.bigImage = item.image;
item.bigIW = item.iW;
item.bigIH = item.iH;
item.isLoaded = item.isMedLoaded;
item.isLoading = false;
item.image = item.medImage;
item.images[0] = item.medImage;
item.iW = item.medIW;
item.iH = item.medIH;
item.isAppended = item.contentAdded = false;
self._updateItemSrc(item, true);
if(item.bigImage !== item.medImage) {
item.sizeType = 'med';
}
}
}
self.isFullscreen = false;
var win = $(window);
win.scrollTop( self._fsScrollTopOnEnter );
win.scrollLeft( self._fsScrollLeftOnEnter );
self._isFullscreenUpdating = false;
self.slider.removeClass('rsFullscreen');
self.updateSliderSize();
// fix overflow bug
setTimeout(function() {
self.updateSliderSize();
},1);
self.ev.trigger('rsExitFullscreen');
},
_updateItemSrc: function(item, exit) {
var newHTML = (!item.isLoaded && !item.isLoading) ? '<a class="rsImg rsMainSlideImage" href="'+item.image+'"></a>' : '<img class="rsImg rsMainSlideImage" src="'+item.image+'"/>';
if(item.content.hasClass('rsImg')) {
item.content = $(newHTML);
} else {
item.content.find('.rsImg').eq(0).replaceWith(newHTML);
}
if(!item.isLoaded && !item.isLoading && item.holder) {
item.holder.html(item.content);
}
}
});
$.rsModules.fullscreen = $.rsProto._initFullscreen;
/****************************************************************************************************************/
/**
*
* RoyalSlider bullets module
* @version 1.0.1:
*
* 1.0.1
* - Minor optimizations
*
*/
$.extend($.rsProto, {
_initBullets: function() {
var self = this;
if(self.st.controlNavigation === 'bullets') {
var itemHTML = '<div class="rsNavItem rsBullet"><span></span></div>';
self.ev.one('rsAfterPropsSetup', function() {
self._controlNavEnabled = true;
self.slider.addClass('rsWithBullets');
var out = '<div class="rsNav rsBullets">';
for(var i = 0; i < self.numSlides; i++) {
out += itemHTML;
}
self._controlNav = out = $(out + '</div>');
self._controlNavItems = out.appendTo(self.slider).children();
self._controlNav.on('click.rs','.rsNavItem',function(e) {
if(!self._thumbsDrag ) {
self.goTo( $(this).index() );
}
});
});
self.ev.on('rsOnAppendSlide', function(e, parsedSlide, index) {
if(index >= self.numSlides) {
self._controlNav.append(itemHTML);
} else {
self._controlNavItems.eq(index).before(itemHTML);
}
self._controlNavItems = self._controlNav.children();
});
self.ev.on('rsOnRemoveSlide', function(e, index) {
var itemToRemove = self._controlNavItems.eq(index);
if(itemToRemove && itemToRemove.length) {
itemToRemove.remove();
self._controlNavItems = self._controlNav.children();
}
});
self.ev.on('rsOnUpdateNav', function() {
var id = self.currSlideId,
currItem,
prevItem;
if(self._prevNavItem) {
self._prevNavItem.removeClass('rsNavSelected');
}
currItem = self._controlNavItems.eq(id);
currItem.addClass('rsNavSelected');
self._prevNavItem = currItem;
});
}
}
});
$.rsModules.bullets = $.rsProto._initBullets;
/****************************************************************************************************************/
/**
*
* RoyalSlider auto height module
* @version 1.0.2:
*
* 1.0.2
* - Changed "on" to "one" in afterInit event listener
* - Removed id="clear"
*/
$.extend($.rsProto, {
_initAutoHeight: function() {
var self = this;
if(self.st.autoHeight) {
var holder,
tH,
currSlide,
currHeight,
updHeight = function(animate) {
currSlide = self.slides[self.currSlideId];
holder = currSlide.holder;
if(holder) {
tH = holder.height();
if(tH && tH !== currHeight) {
self._wrapHeight = tH;
if(self._useCSS3Transitions || !animate) {
self._sliderOverflow.css('height', tH);
} else {
self._sliderOverflow.stop(true,true).animate({height: tH}, self.st.transitionSpeed);
}
}
}
};
self.ev.on('rsMaybeSizeReady.rsAutoHeight', function(e, slideObject) {
if(currSlide === slideObject) {
updHeight();
}
});
self.ev.on('rsAfterContentSet.rsAutoHeight', function(e, slideObject) {
if(currSlide === slideObject) {
updHeight();
}
});
self.slider.addClass('rsAutoHeight');
self.ev.one('rsAfterInit', function() {
setTimeout(function() {
updHeight(false);
setTimeout(function() {
self.slider.append('<div style="clear:both; float: none;"></div>');
if(self._useCSS3Transitions) {
self._sliderOverflow.css(self._vendorPref + 'transition', 'height ' + self.st.transitionSpeed + 'ms ease-in-out');
}
}, 16);
}, 16);
});
self.ev.on('rsBeforeAnimStart', function() {
updHeight(true);
});
self.ev.on('rsBeforeSizeSet' , function() {
setTimeout(function() {
updHeight(false);
}, 16);
});
}
}
});
$.rsModules.autoHeight = $.rsProto._initAutoHeight;
/****************************************************************************************************************/
/**
*
* RoyalSlider video module
* @version 1.1.0:
*
* 1.0.3:
* - Added rsOnDestroyVideoElement event
*
* 1.0.4:
* - Added wmode=transparent to default YouTube video embed code
*
* 1.0.5
* - Fixed bug: HTMl5 YouTube player sometimes keeps playing in ie9 after closing
*
* 1.0.6
* - A bit lightened Vimeo and YouTube regex
*
* 1.0.7
* - Minor optimizations
* - Added autoHideCaption option
*
* 1.0.9
* - Fixed error that could appear if updateSliderSize method is called directly after video close
*
* 1.1.0
* - Video is now removed in rsAfterSlideChange event to avoid transition lag
* - Fixed bug that could cause appearing of arrows with auto-hide
*/
$.extend($.rsProto, {
_initVideo: function() {
var self = this;
self._videoDefaults = {
autoHideArrows: true,
autoHideControlNav: false,
autoHideBlocks: false,
autoHideCaption: false,
youTubeCode: '<iframe src="http://www.youtube.com/embed/%id%?rel=1&autoplay=1&showinfo=0&autoplay=1&wmode=transparent" frameborder="no"></iframe>',
vimeoCode: '<iframe src="http://player.vimeo.com/video/%id%?byline=0&portrait=0&autoplay=1" frameborder="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
};
self.st.video = $.extend({}, self._videoDefaults, self.st.video);
self.ev.on('rsBeforeSizeSet', function() {
if(self._isVideoPlaying) {
setTimeout(function() {
var content = self._currHolder;
content = content.hasClass('rsVideoContainer') ? content : content.find('.rsVideoContainer');
if(self._videoFrameHolder) {
self._videoFrameHolder.css({
width: content.width(),
height: content.height()
});
}
}, 32);
}
});
var isFF = self._browser.mozilla;
self.ev.on('rsAfterParseNode', function(e, content, obj) {
var jqcontent = $(content),
tempEl,
hasVideo;
if(obj.videoURL) {
if(!hasVideo && isFF) {
hasVideo = true;
self._useCSS3Transitions = self._use3dTransform = false;
}
var wrap = $('<div class="rsVideoContainer"></div>'),
playBtn = $('<div class="rsBtnCenterer"><div class="rsPlayBtn"><div class="rsPlayBtnIcon"></div></div></div>');
if(jqcontent.hasClass('rsImg')) {
obj.content = wrap.append(jqcontent).append(playBtn);
} else {
obj.content.find('.rsImg').wrap(wrap).after(playBtn);
}
}
});
self.ev.on('rsAfterSlideChange', function() {
self.stopVideo();
});
},
toggleVideo: function() {
var self = this;
if(!self._isVideoPlaying) {
return self.playVideo();
} else {
return self.stopVideo();
}
},
playVideo: function() {
var self = this;
if(!self._isVideoPlaying) {
var currSlide = self.currSlide;
if(!currSlide.videoURL) {
return false;
}
var content = self._currVideoContent = currSlide.content;
var url = currSlide.videoURL,
videoId,
regExp,
match;
if( url.match(/youtu\.be/i) || url.match(/youtube\.com/i) ) {
regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
match = url.match(regExp);
if (match && match[7].length==11){
videoId = match[7];
}
if(videoId !== undefined) {
self._videoFrameHolder = self.st.video.youTubeCode.replace("%id%", videoId);
}
} else if(url.match(/vimeo\.com/i)) {
regExp = /(www\.)?vimeo.com\/(\d+)($|\/)/;
match = url.match(regExp);
if(match) {
videoId = match[2];
}
if(videoId !== undefined) {
self._videoFrameHolder = self.st.video.vimeoCode.replace("%id%", videoId);
}
}
self.videoObj = $(self._videoFrameHolder);
self.ev.trigger('rsOnCreateVideoElement', [url]);
if(self.videoObj.length) {
self._videoFrameHolder = $('<div class="rsVideoFrameHolder"><div class="rsPreloader"></div><div class="rsCloseVideoBtn"><div class="rsCloseVideoIcn"></div></div></div>');
self._videoFrameHolder.find('.rsPreloader').after(self.videoObj);
content = content.hasClass('rsVideoContainer') ? content : content.find('.rsVideoContainer');
self._videoFrameHolder.css({
width: content.width(),
height: content.height()
}).find('.rsCloseVideoBtn').off('click.rsv').on('click.rsv', function(e) {
self.stopVideo();
e.preventDefault();
e.stopPropagation();
return false;
});
content.append(self._videoFrameHolder);
if(self.isIPAD) {
content.addClass('rsIOSVideo');
}
self._toggleHiddenClass(false);
setTimeout(function() {
self._videoFrameHolder.addClass('rsVideoActive');
}, 10);
self.ev.trigger('rsVideoPlay');
self._isVideoPlaying = true;
}
return true;
}
return false;
},
stopVideo: function() {
var self = this;
if(self._isVideoPlaying) {
if(self.isIPAD) {
self.slider.find('.rsCloseVideoBtn').remove();
}
self._toggleHiddenClass(true);
setTimeout(function() {
self.ev.trigger('rsOnDestroyVideoElement', [self.videoObj]);
var ifr = self._videoFrameHolder.find('iframe');
if(ifr.length) {
try {
ifr.attr('src', "");
} catch(ex) { }
}
self._videoFrameHolder.remove();
self._videoFrameHolder = null;
}, 16);
self.ev.trigger('rsVideoStop');
self._isVideoPlaying = false;
return true;
}
return false;
},
_toggleHiddenClass: function(remove) {
var arr = [],
self = this,
vst = self.st.video;
if(vst.autoHideArrows) {
if(self._arrowLeft) {
arr.push(self._arrowLeft, self._arrowRight);
self._arrowsAutoHideLocked = !remove;
}
if(self._fsBtn) {
arr.push(self._fsBtn);
}
}
if(vst.autoHideControlNav && self._controlNav) {
arr.push(self._controlNav);
}
if(vst.autoHideBlocks && self.currSlide.animBlocks) {
arr.push(self.currSlide.animBlocks);
}
if(vst.autoHideCaption && self.globalCaption) {
arr.push(self.globalCaption);
}
if(arr.length) {
for(var i = 0; i < arr.length; i++) {
if(!remove) {
arr[i].addClass('rsHidden');
} else {
arr[i].removeClass('rsHidden');
}
}
}
}
});
$.rsModules.video = $.rsProto._initVideo;
/****************************************************************************************************************/
/**
*
* RoyalSlider auto play module
* @version 1.0.5:
*
* 1.0.3:
* - added support for 'autoplay' property name.
*
* 1.0.4
* - added toggleAutoPlay public method
*
* 1.0.5
* - Fixed issue when autoPlay may not pause when switching browser tabs
*/
$.extend($.rsProto, {
_initAutoplay: function() {
var self = this,
del;
self._autoPlayDefaults = {
enabled: false,
stopAtAction: true,
pauseOnHover: true,
delay: 2000
};
// fix deprecated name
if(!self.st.autoPlay && self.st.autoplay) {
self.st.autoPlay = self.st.autoplay;
}
self.st.autoPlay = $.extend({}, self._autoPlayDefaults, self.st.autoPlay);
if(self.st.autoPlay.enabled) {
self.ev.on('rsBeforeParseNode', function(e, content, obj) {
content = $(content);
del = content.attr('data-rsDelay');
if(del) {
obj.customDelay = parseInt(del, 10);
}
});
self.ev.one('rsAfterInit', function() {
self._setupAutoPlay();
});
self.ev.on('rsBeforeDestroy', function() {
self.stopAutoPlay();
$(window).off('blur'+self.ns + ' focus' + self.ns);
});
}
},
_setupAutoPlay: function() {
var self = this;
self.startAutoPlay();
self.ev.on('rsAfterContentSet', function(e, slideObject) {
if(!self._isDragging && !self._isAnimating && self._autoPlayEnabled && slideObject === self.currSlide ) {
self._play();
}
});
self.ev.on('rsDragRelease', function() {
if(self._autoPlayEnabled && self._autoPlayPaused) {
self._autoPlayPaused = false;
self._play();
}
});
self.ev.on('rsAfterSlideChange', function() {
if(self._autoPlayEnabled) {
if(self._autoPlayPaused) {
self._autoPlayPaused = false;
if(self.currSlide.isLoaded) {
self._play();
}
}
}
});
self.ev.on('rsDragStart', function() {
if(self._autoPlayEnabled) {
if(self.st.autoPlay.stopAtAction) {
self.stopAutoPlay();
} else {
self._autoPlayPaused = true;
self._pause();
}
}
});
self.ev.on('rsBeforeMove', function(e, type, userAction) {
if(self._autoPlayEnabled) {
if(userAction && self.st.autoPlay.stopAtAction) {
self.stopAutoPlay();
} else {
self._autoPlayPaused = true;
self._pause();
}
}
});
self._pausedByVideo = false;
self.ev.on('rsVideoStop', function() {
if(self._autoPlayEnabled) {
self._pausedByVideo = false;
self._play();
}
});
self.ev.on('rsVideoPlay', function() {
if(self._autoPlayEnabled) {
self._autoPlayPaused = false;
self._pause();
self._pausedByVideo = true;
}
});
$(window).on('blur'+self.ns, function(){
if(self._autoPlayEnabled) {
self._autoPlayPaused = true;
self._pause();
}
}).on('focus'+self.ns, function(){
if(self._autoPlayEnabled && self._autoPlayPaused) {
self._autoPlayPaused = false;
self._play();
}
});
if(self.st.autoPlay.pauseOnHover) {
self._pausedByHover = false;
self.slider.hover(
function() {
if(self._autoPlayEnabled) {
self._autoPlayPaused = false;
self._pause();
self._pausedByHover = true;
}
},
function() {
if(self._autoPlayEnabled) {
self._pausedByHover = false;
self._play();
}
}
);
}
},
toggleAutoPlay: function() {
var self = this;
if(self._autoPlayEnabled) {
self.stopAutoPlay();
} else {
self.startAutoPlay();
}
},
startAutoPlay: function() {
var self = this;
self._autoPlayEnabled = true;
if(self.currSlide.isLoaded) {
self._play();
}
},
stopAutoPlay: function() {
var self = this;
self._pausedByVideo = self._pausedByHover = self._autoPlayPaused = self._autoPlayEnabled = false;
self._pause();
},
_play: function() {
var self = this;
self.ev.trigger('autoPlayPlay');
if(!self._pausedByHover && !self._pausedByVideo) {
self._autoPlayRunning = true;
if(self._autoPlayTimeout) {
clearTimeout(self._autoPlayTimeout);
}
self._autoPlayTimeout = setTimeout(function() {
var changed;
if(!self._loop && !self.st.loopRewind) {
changed = true;
self.st.loopRewind = true;
}
self.next(true);
if(changed) {
changed = false;
self.st.loopRewind = false;
}
}, !self.currSlide.customDelay ? self.st.autoPlay.delay : self.currSlide.customDelay);
}
},
_pause: function() {
var self = this;
self.ev.trigger('autoPlayPause');
if(!self._pausedByHover && !self._pausedByVideo) {
self._autoPlayRunning = false;
if(self._autoPlayTimeout) {
clearTimeout(self._autoPlayTimeout);
self._autoPlayTimeout = null;
}
}
}
});
$.rsModules.autoplay = $.rsProto._initAutoplay;
/****************************************************************************************************************/
/**
*
* RoyalSlider animated blocks module
* @version 1.0.6:
*
* 1.0.2:
* - Fixed mistake from prev fix :/
*
* 1.0.3:
* - Fixed animated block appearing in Firefox
*
* 1.0.4
* - Fixed bug that could cause incorrect block when randomizeSlides is enabled
*
* 1.0.5
* - moveEffect:none' bug
*
* 1.0.6
* - Fixed issue that could cause incorrect position of blocks in IE
*/
$.extend($.rsProto, {
_initAnimatedBlocks: function() {
var self = this,
i;
self._blockDefaults = {
fadeEffect: true,
moveEffect: 'top',
moveOffset:20,
speed:400,
easing:'easeOutSine',
delay:200
};
self.st.block = $.extend({}, self._blockDefaults, self.st.block);
self._blockAnimProps = [];
self._animatedBlockTimeouts = [];
self.ev.on('rsAfterInit', function() {
runBlocks();
});
self.ev.on('rsBeforeParseNode', function(e, content, obj) {
content = $(content);
obj.animBlocks = content.find('.rsABlock').css('display', 'none');
if(!obj.animBlocks.length) {
if(content.hasClass('rsABlock')) {
obj.animBlocks = content.css('display', 'none');
} else {
obj.animBlocks = false;
}
}
});
self.ev.on('rsAfterContentSet', function(e, slideObject) {
var currId = self.slides[self.currSlideId].id;
if(slideObject.id === currId) {
setTimeout(function() {
runBlocks();
}, self.st.fadeinLoadedSlide ? 300 : 0);
}
});
self.ev.on('rsAfterSlideChange', function() {
runBlocks();
});
function runBlocks() {
var slide = self.currSlide;
if(!self.currSlide || !self.currSlide.isLoaded) {
return;
}
// clear previous animations
if(self._slideWithBlocks !== slide) {
if(self._animatedBlockTimeouts.length > 0) {
for(i = 0; i < self._animatedBlockTimeouts.length; i++) {
clearTimeout(self._animatedBlockTimeouts[i]);
}
self._animatedBlockTimeouts = [];
}
if(self._blockAnimProps.length > 0) {
var cItemTemp;
for(i = 0; i < self._blockAnimProps.length; i++) {
cItemTemp = self._blockAnimProps[i];
if(cItemTemp) {
if(!self._useCSS3Transitions) {
// if(cItemTemp.running) {
// cItemTemp.block.stop(true, true);
// } else {
cItemTemp.block.stop(true).css(cItemTemp.css);
//}
} else {
cItemTemp.block.css(self._vendorPref + self._TD, '0s');
cItemTemp.block.css(cItemTemp.css);
}
self._slideWithBlocks = null;
slide.animBlocksDisplayed = false;
}
}
self._blockAnimProps = [];
}
if(slide.animBlocks) {
slide.animBlocksDisplayed = true;
self._slideWithBlocks = slide;
self._animateBlocks(slide.animBlocks);
}
}
}
},
_updateAnimBlockProps: function(obj, props) {
setTimeout(function() {
obj.css(props);
}, 6);
},
_animateBlocks: function(animBlocks) {
var self = this,
item,
animObj,
newPropObj,
transitionData;
var currItem,
fadeEnabled,
moveEnabled,
effectName,
effectsObject,
moveEffectProperty,
currEffects,
newEffectObj,
moveOffset,
delay,
speed,
easing,
moveProp,
i;
self._animatedBlockTimeouts = [];
animBlocks.each(function(index) {
item = $(this);
animObj = {};
newPropObj = {};
transitionData = null;
var moveOffset = item.data('move-offset');
if(isNaN(moveOffset)) {
moveOffset = self.st.block.moveOffset;
}
if(moveOffset > 0) {
var moveEffect = item.data('move-effect');
if(moveEffect) {
moveEffect = moveEffect.toLowerCase();
if(moveEffect === 'none') {
moveEffect = false;
} else if(moveEffect !== 'left' && moveEffect !== 'top' && moveEffect !== 'bottom' && moveEffect !== 'right') {
moveEffect = self.st.block.moveEffect;
if(moveEffect === 'none') {
moveEffect = false;
}
}
} else {
moveEffect = self.st.block.moveEffect;
}
if(moveEffect && moveEffect !== 'none') {
var moveHorizontal;
if(moveEffect === 'right' || moveEffect === 'left') {
moveHorizontal = true;
} else {
moveHorizontal = false;
}
var currPos,
moveProp,
startPos;
isOppositeProp = false;
if(self._useCSS3Transitions) {
currPos = 0;
moveProp = self._xProp;
} else {
if(moveHorizontal) {
if( !isNaN( parseInt(item.css('right'), 10) ) ) {
moveProp = 'right';
isOppositeProp = true;
} else {
moveProp = 'left';
}
} else {
if( !isNaN( parseInt(item.css('bottom'), 10) ) ) {
moveProp = 'bottom';
isOppositeProp = true;
} else {
moveProp = 'top';
}
}
moveProp = 'margin-'+moveProp;
if(isOppositeProp) {
moveOffset = -moveOffset;
}
if(!self._useCSS3Transitions) {
currPos = item.data('rs-start-move-prop');
if( currPos === undefined ) {
currPos = parseInt(item.css(moveProp), 10);
item.data('rs-start-move-prop', currPos);
}
} else {
currPos = parseInt(item.css(moveProp), 10);
}
}
if(moveEffect === 'top' || moveEffect === 'left') {
startPos = currPos - moveOffset;
} else {
startPos = currPos + moveOffset;
}
newPropObj[moveProp] = self._getCSS3Prop(startPos, moveHorizontal);
animObj[moveProp] = self._getCSS3Prop(currPos, moveHorizontal);
}
}
var fadeEffect = item.attr('data-fade-effect');
if(!fadeEffect) {
fadeEffect = self.st.block.fadeEffect;
} else if(fadeEffect.toLowerCase() === 'none' || fadeEffect.toLowerCase() === 'false') {
fadeEffect = false;
}
if(fadeEffect) {
newPropObj.opacity = 0;
animObj.opacity = 1;
}
if(fadeEffect || moveEffect) {
transitionData = {};
transitionData.hasFade = Boolean(fadeEffect);
if(Boolean(moveEffect)) {
transitionData.moveProp = moveProp;
transitionData.hasMove = true;
}
transitionData.speed = item.data('speed');
if(isNaN(transitionData.speed)) {
transitionData.speed = self.st.block.speed;
}
transitionData.easing = item.data('easing');
if(!transitionData.easing) {
transitionData.easing = self.st.block.easing;
}
transitionData.css3Easing = $.rsCSS3Easing[transitionData.easing];
transitionData.delay = item.data('delay');
if(isNaN(transitionData.delay)) {
transitionData.delay = self.st.block.delay * index;
}
}
var blockPropsObj = {};
if(self._useCSS3Transitions) {
blockPropsObj[(self._vendorPref + self._TD)] = '0ms';
}
blockPropsObj.moveProp = animObj.moveProp;
blockPropsObj.opacity = animObj.opacity;
blockPropsObj.display = 'none';
self._blockAnimProps.push({block:item, css:blockPropsObj});
self._updateAnimBlockProps(item, newPropObj);
// animate caption
self._animatedBlockTimeouts.push(setTimeout((function (cItem, animateData, transitionData, index) {
return function() {
cItem.css('display', 'block');
if(transitionData) {
var animObj = {};
if(!self._useCSS3Transitions) {
setTimeout(function() {
cItem.animate(animateData, transitionData.speed, transitionData.easing);
}, 16);
} else {
var prop = '';
if(transitionData.hasMove) {
prop += transitionData.moveProp;
}
if(transitionData.hasFade) {
if(transitionData.hasMove) {
prop += ', ';
}
prop += 'opacity';
}
animObj[(self._vendorPref + self._TP)] = prop;
animObj[(self._vendorPref + self._TD)] = transitionData.speed + 'ms';
animObj[(self._vendorPref + self._TTF)] = transitionData.css3Easing;
cItem.css(animObj);
setTimeout(function() {
cItem.css(animateData);
}, 24);
}
}
delete self._animatedBlockTimeouts[index];
};
})(item, animObj, transitionData, index), transitionData.delay <= 6 ? 12 : transitionData.delay));
//}
});
}
});
$.rsModules.animatedBlocks = $.rsProto._initAnimatedBlocks;
/****************************************************************************************************************/
/**
*
* RoyalSlider porthole-thumbnails module by Miroslav Varsky (from Dream-Theme.com)
* @version 1.0.b:
*
*/
$.extend($.rsProto, {
_initThumbs: function() {
var self = this;
if(self.st.controlNavigation === 'porthole') {
self._thumbsDefaults = {
drag: false,
touch: false,
orientation: 'vertical',
navigation: true,
spacing: 10,
appendSpan: false,
transitionSpeed:600,
autoCenter: true,
fitInViewport: true,
firstMargin: true,
paddingTop: 0,
paddingBottom: 0
};
self.st.thumbs = $.extend({}, self._thumbsDefaults, self.st.thumbs);
self._firstThumbMoved = true;
if(self.st.thumbs.firstMargin === false) { self.st.thumbs.firstMargin = 0; }
else if(self.st.thumbs.firstMargin === true) { self.st.thumbs.firstMargin = self.st.thumbs.spacing; }
self.ev.on('rsBeforeParseNode', function(e, content, obj) {
content = $(content);
obj.thumbnail = content.find('.rsTmb').remove();
if(!obj.thumbnail.length) {
obj.thumbnail = content.attr('data-rsTmb');
if(!obj.thumbnail) {
obj.thumbnail = content.find('.rsImg').attr('data-rsTmb');
}
if(!obj.thumbnail) {
obj.thumbnail = '';
} else {
obj.thumbnail = '<img src="'+obj.thumbnail+'"/>';
}
} else {
obj.thumbnail = $(document.createElement('div')).append(obj.thumbnail).html();
}
});
self.ev.one('rsAfterPropsSetup', function() {
self._createThumbs();
});
self._prevNavItem = null;
self.ev.on('rsOnUpdateNav', function() {
//self._controlNavItems.attr('class', 'rsNavItem rsThumb');
var currItem = $(self._controlNavItems[self.currSlideId]);
if(currItem === self._prevNavItem) {
return;
}
if(self._prevNavItem) {
self._prevNavItem = null;
}
if(self._thumbsNavigation) {
self._setCurrentThumb(self.currSlideId);
}
self._prevNavItem = currItem;
self._controlNavItems.each(function() {
if (self._prevNavItem[0]===this) {
$(this).attr('class', 'rsNavItem rsThumb rsNavSelected');
}
else if (self._prevNavItem.prev().prev()[0]===this || self._prevNavItem.next().next()[0]===this) {
$(this).attr('class', 'rsNavItem rsThumb rsNavVis');
}
else if (self._prevNavItem.prev()[0]===this) {
$(this).attr('class', 'rsNavItem rsThumb rsNavPrev');
}
else if (self._prevNavItem.next()[0]===this) {
$(this).attr('class', 'rsNavItem rsThumb rsNavNext');
}
else {
$(this).attr('class', 'rsNavItem rsThumb');
}
});
});
self.ev.on('rsOnAppendSlide', function(e, parsedSlide, index) {
var html = '<div'+self._thumbsMargin+' class="rsNavItem rsThumb">'+self._addThumbHTML+parsedSlide.thumbnail+'</div>';
if(index >= self.numSlides) {
self._thumbsContainer.append(html);
} else {
self._controlNavItems.eq(index).before(html);
}
self._controlNavItems = self._thumbsContainer.children();
self.updateThumbsSize();
});
self.ev.on('rsOnRemoveSlide', function(e, index) {
var itemToRemove = self._controlNavItems.eq(index);
if(itemToRemove) {
itemToRemove.remove();
self._controlNavItems = self._thumbsContainer.children();
self.updateThumbsSize();
}
});
}
},
_createThumbs: function() {
var self = this,
tText = 'rsThumbs',
thumbSt = self.st.thumbs,
out = '',
style,
item,
spacing = thumbSt.spacing;
self._controlNavEnabled = true;
self._thumbsHorizontal = (thumbSt.orientation === 'vertical') ? false : true;
self._thumbsMargin = style = spacing ? ' style="margin-' + (self._thumbsHorizontal ? 'right' : 'bottom') + ':'+ spacing+'px;"' : '';
self._thumbsPosition = 0;
self._isThumbsAnimating = false;
self._thumbsDrag = false;
self._thumbsNavigation = false;
var pl = (self._thumbsHorizontal ? 'Hor' : 'Ver');
self.slider.addClass('rsWithThumbs' + ' rsWithThumbs'+ pl );
out += '<div class="rsNav rsThumbs rsThumbs'+pl +'"><div class="'+tText+'Container">';
self._addThumbHTML = thumbSt.appendSpan ? '<span class="thumbIco"></span>' : '';
for(var i = 0; i < self.numSlides; i++) {
item = self.slides[i];
out += '<div'+style+' class="rsNavItem rsThumb">'+item.thumbnail+self._addThumbHTML+'</div>';
}
out = $(out +'</div></div>');
var o = {};
if(thumbSt.paddingTop) {
o[self._thumbsHorizontal ? 'paddingTop' : 'paddingLeft'] = thumbSt.paddingTop;
}
if(thumbSt.paddingBottom) {
o[self._thumbsHorizontal ? 'paddingBottom' : 'paddingRight'] = thumbSt.paddingBottom;
}
out.css(o);
self._thumbsContainer = $(out).find('.' + tText + 'Container');
self._controlNav = out;
self._controlNavItems = self._thumbsContainer.children();
if(self.msEnabled && self.st.thumbs.navigation) {
self._thumbsContainer.css('-ms-touch-action', self._thumbsHorizontal ? 'pan-y' : 'pan-x');
}
self.slider.append(out);
self._thumbsEnabled = true;
self._thumbsSpacing = spacing;
if(thumbSt.navigation) {
if(self._useCSS3Transitions) {
self._thumbsContainer.css(self._vendorPref + 'transition-property', self._vendorPref + 'transform');
}
}
self._controlNav.on('click.rs','.rsNavItem',function(e) {
if(!self._thumbsDrag ) {
self.goTo( $(this).index() );
}
});
self.ev.off('rsBeforeSizeSet.thumbs').on('rsBeforeSizeSet.thumbs', function() {
self._realWrapSize = self._thumbsHorizontal ? self._wrapHeight : self._wrapWidth;
self.updateThumbsSize(true);
});
// fix deprecated name
if(!self.st.autoPlay && self.st.autoplay) {
self.st.autoPlay = self.st.autoplay;
}
if (self.st.autoPlay.enabled) {
self._thumbsContainer.after('<div class="progress-wrapper"><div class="progress-controls"></div></div>');
self.progressWrap = self._thumbsContainer.next();
self.progressHtml = '<div class="progress-mask"><div class="progress-spinner-left" style="'+self._vendorPref+'animation-duration: '+self.st.autoPlay.delay+'ms;"></div></div><div class="progress-mask"><div class="progress-spinner-right" style="'+self._vendorPref+'animation-duration: '+self.st.autoPlay.delay+'ms;"></div></div>';
self.ev.on("autoPlayPlay", function() {
if (self.progressWrap.find(".progress-mask").length < 1) {
self.progressWrap.prepend(self.progressHtml);
}
self.progressWrap.removeClass("paused");
});
self.ev.on("autoPlayPause", function() {
self.progressWrap.find(".progress-mask").remove();
if (!self._autoPlayEnabled) {
self.progressWrap.addClass("paused");
}
});
self.ev.on('rsAfterSlideChange', function() {
self.progressWrap.removeClass("blurred");
});
self.ev.on('rsBeforeAnimStart', function() {
self.progressWrap.addClass("blurred");
});
self.ev.on('rsVideoPlay', function() {
$("body").addClass("hide-thumbnails");
if (!self.slider.parent().hasClass("fixed")) $("body").addClass("video-playing");
});
self.ev.on('rsVideoStop', function() {
$("body").removeClass("video-playing").removeClass("hide-thumbnails");
});
self.progressWrap.on("click", function() {
self.toggleAutoPlay();
});
}
},
updateThumbsSize: function(isResize) {
var self = this,
firstThumb = self._controlNavItems.first(),
cssObj = {};
var numItems = self._controlNavItems.length;
self._thumbSize = ( self._thumbsHorizontal ? firstThumb.outerWidth() : firstThumb.outerHeight() ) + self._thumbsSpacing;
self._thumbsContainerSize = self._thumbsContainer.outerHeight(); // numItems * self._thumbSize - self._thumbsSpacing;
//cssObj[self._thumbsHorizontal ? 'width' : 'height'] = self._thumbsContainerSize + self._thumbsSpacing;
self._thumbsViewportSize = self._thumbsHorizontal ? self._controlNav.width() : self._controlNav.height();
self._thumbsMaxPosition = -(self._thumbsContainerSize - self._thumbsViewportSize) - (self.st.thumbs.firstMargin);
self._thumbsMinPosition = self.st.thumbs.firstMargin;
self._visibleThumbsPerView = Math.floor(self._thumbsViewportSize / self._thumbSize); // 1;
if(self.st.thumbs.navigation && !self._thumbsNavigation) {
self._thumbsNavigation = true;
if( (!self.hasTouch && self.st.thumbs.drag) || (self.hasTouch && self.st.thumbs.touch)) {
self._thumbsDrag = true;
self._controlNav.on(self._downEvent, function(e) { self._onDragStart(e, true); });
}
}
if(self._useCSS3Transitions) {
cssObj[(self._vendorPref + 'transition-duration')] = '0ms';
}
self._thumbsContainer.css(cssObj);
},
setThumbsOrientation: function(newPlacement, dontUpdateSize) {
var self = this;
if(self._thumbsEnabled) {
self.st.thumbs.orientation = newPlacement;
self._controlNav.remove();
self.slider.removeClass('rsWithThumbsHor rsWithThumbsVer');
self._createThumbs();
self._controlNav.off(self._downEvent);
if(!dontUpdateSize) {
self.updateSliderSize(true);
}
}
},
_setThumbsPosition: function(pos) {
var self = this;
self._thumbsPosition = pos;
if(self._useCSS3Transitions) {
self._thumbsContainer.css(self._xProp, self._tPref1 + ( self._thumbsHorizontal ? (pos + self._tPref2 + 0) : (0 + self._tPref2 + pos) ) + self._tPref3 );
} else {
self._thumbsContainer.css(self._thumbsHorizontal ? self._xProp : self._yProp, pos);
}
},
_animateThumbsTo: function(pos, speed, outEasing, bounceAnimPosition, bounceAnimSpeed) {
var self = this;
if(!self._thumbsNavigation) {
return;
}
if(!speed) {
speed = self.st.thumbs.transitionSpeed;
}
self._thumbsPosition = pos;
if(self._thumbsAnimTimeout) {
clearTimeout(self._thumbsAnimTimeout);
}
if(self._isThumbsAnimating) {
if(!self._useCSS3Transitions) {
self._thumbsContainer.stop();
}
outEasing = true;
}
var animObj = {};
self._isThumbsAnimating = true;
if(!self._useCSS3Transitions) {
animObj[self._thumbsHorizontal ? self._xProp : self._yProp] = pos + 'px';
self._thumbsContainer.animate(animObj, speed, outEasing ? 'easeOutCubic' : self.st.easeInOut);
} else {
animObj[(self._vendorPref + 'transition-duration')] = speed+'ms';
animObj[(self._vendorPref + 'transition-timing-function')] = outEasing ? $.rsCSS3Easing[self.st.easeOut] : $.rsCSS3Easing[self.st.easeInOut];
self._thumbsContainer.css(animObj);
self._setThumbsPosition(pos);
}
if(bounceAnimPosition) {
self._thumbsPosition = bounceAnimPosition;
}
self._thumbsAnimTimeout = setTimeout(function() {
self._isThumbsAnimating = false;
if(bounceAnimSpeed) {
self._animateThumbsTo(bounceAnimPosition, bounceAnimSpeed, true);
bounceAnimSpeed = null;
}
}, speed);
},
_setCurrentThumb: function(id, justSet) {
var self = this,
newPos = -id * 40;
if (newPos == 0) {
newPos = 20;
}
if(!self._thumbsNavigation) {
return;
}
if(self._firstThumbMoved) {
justSet = true;
self._firstThumbMoved = false;
}
if(newPos !== self._thumbsPosition) {
if(!justSet) {
self._animateThumbsTo(newPos);
} else {
self._setThumbsPosition(newPos);
}
}
if ($("#header").hasClass("overlap") && !$("#main-slideshow").hasClass("fixed")) {
self._controlNav.css({
"margin-top": -185 + $("#header").outerHeight() / 2
})
} else if ($("#header").hasClass("overlap") && $("#main-slideshow").hasClass("fixed")) {
self.slider.css({
"margin-top": $("#header").outerHeight()
});
}
}
});
$.rsModules.thumbnails = $.rsProto._initThumbs;
})(jQuery, window); | JavaScript |
/*
Bootstrap - File Input
======================
This is meant to convert all file input tags into a set of elements that displays consistently in all browsers.
Converts all
<input type="file">
into Bootstrap buttons
<a class="btn">Browse</a>
*/
$(function() {
$.fn.bootstrapFileInput = function() {
this.each(function(i,elem){
var $elem = $(elem);
// Maybe some fields don't need to be standardized.
if (typeof $elem.attr('data-bfi-disabled') != 'undefined') {
return;
}
// Set the word to be displayed on the button
var buttonWord = 'Browse';
if (typeof $elem.attr('title') != 'undefined') {
buttonWord = $elem.attr('title');
}
// Start by getting the HTML of the input element.
// Thanks for the tip http://stackoverflow.com/a/1299069
var input = $('<div>').append( $elem.eq(0).clone() ).html();
var className = '';
if (!!$elem.attr('class')) {
className = ' ' + $elem.attr('class');
}
// Now we're going to replace that input field with a Bootstrap button.
// The input will actually still be there, it will just be float above and transparent (done with the CSS).
$elem.replaceWith('<a class="file-input-wrapper btn' + className + '">'+buttonWord+input+'</a>');
})
// After we have found all of the file inputs let's apply a listener for tracking the mouse movement.
// This is important because the in order to give the illusion that this is a button in FF we actually need to move the button from the file input under the cursor. Ugh.
.promise().done( function(){
// As the cursor moves over our new Bootstrap button we need to adjust the position of the invisible file input Browse button to be under the cursor.
// This gives us the pointer cursor that FF denies us
$('.file-input-wrapper').mousemove(function(cursor) {
var input, wrapper,
wrapperX, wrapperY,
inputWidth, inputHeight,
cursorX, cursorY;
// This wrapper element (the button surround this file input)
wrapper = $(this);
// The invisible file input element
input = wrapper.find("input");
// The left-most position of the wrapper
wrapperX = wrapper.offset().left;
// The top-most position of the wrapper
wrapperY = wrapper.offset().top;
// The with of the browsers input field
inputWidth= input.width();
// The height of the browsers input field
inputHeight= input.height();
//The position of the cursor in the wrapper
cursorX = cursor.pageX;
cursorY = cursor.pageY;
//The positions we are to move the invisible file input
// The 20 at the end is an arbitrary number of pixels that we can shift the input such that cursor is not pointing at the end of the Browse button but somewhere nearer the middle
moveInputX = cursorX - wrapperX - inputWidth + 20;
// Slides the invisible input Browse button to be positioned middle under the cursor
moveInputY = cursorY- wrapperY - (inputHeight/2);
// Apply the positioning styles to actually move the invisible file input
input.css({
left:moveInputX,
top:moveInputY
});
});
$('.file-input-wrapper input[type=file]').change(function(){
var fileName;
fileName = $(this).val();
// Remove any previous file names
$(this).parent().next('.file-input-name').remove();
if (!!$(this).prop('files') && $(this).prop('files').length > 1) {
fileName = $(this)[0].files.length+' files';
//$(this).parent().after('<span class="file-input-name">'+$(this)[0].files.length+' files</span>');
}
else {
// var fakepath = 'C:\\fakepath\\';
// fileName = $(this).val().replace('C:\\fakepath\\','');
fileName = fileName.substring(fileName.lastIndexOf('\\')+1,fileName.length);
}
$(this).parent().after('<span class="file-input-name">'+fileName+'</span>');
});
});
};
// Add the styles before the first stylesheet
// This ensures they can be easily overridden with developer styles
var cssHtml = '<style>'+
'.file-input-wrapper { overflow: hidden; position: relative; cursor: pointer; z-index: 1; }'+
'.file-input-wrapper input[type=file], .file-input-wrapper input[type=file]:focus, .file-input-wrapper input[type=file]:hover { position: absolute; top: 0; left: 0; cursor: pointer; opacity: 0; filter: alpha(opacity=0); z-index: 99; outline: 0; }'+
'.file-input-name { margin-left: 8px; }'+
'</style>';
$('link[rel=stylesheet]').eq(0).before(cssHtml);
}); | JavaScript |
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
!function ($) {
$(function(){
// Disable certain links in docs
$('section [href^=#]').click(function (e) {
e.preventDefault()
})
// 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')
})
// position static twipsies for components page
if ($(".twipsies a").length) {
$(window).on('load resize', function () {
$(".twipsies a").each(function () {
$(this)
.tooltip({
placement: $(this).attr('title')
, trigger: 'manual'
})
.tooltip('show')
})
})
}
// add tipsies to grid for scaffolding
if ($('#grid-system').length) {
$('#grid-system').tooltip({
selector: '.show-grid > div'
, title: function () { return $(this).width() + 'px' }
})
}
// fix sub nav on scroll
var $win = $(window)
, $nav = $('.subnav')
, navTop = $('.subnav').length && $('.subnav').offset().top - 40
, isFixed = 0
processScroll()
$win.on('scroll', processScroll)
function processScroll() {
var i, scrollTop = $win.scrollTop()
if (scrollTop >= navTop && !isFixed) {
isFixed = 1
$nav.addClass('subnav-fixed')
} else if (scrollTop <= navTop && isFixed) {
isFixed = 0
$nav.removeClass('subnav-fixed')
}
}
// tooltip demo
$('.tooltip-demo.well').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').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: '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 |
(function($) {
$.fn.countdown = function(options, callback) {
//custom 'this' selector
thisEl = $(this);
//array of custom settings
var settings = {
'date': null,
'format': null
};
//append the settings array to options
if(options) {
$.extend(settings, options);
}
//main countdown function
function countdown_proc() {
eventDate = Date.parse(settings['date']) / 1000;
currentDate = Math.floor($.now() / 1000);
if(eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
//conditional Ss
if (days == 1) { thisEl.find(".timeRefDays").text("day"); } else { thisEl.find(".timeRefDays").text("days"); }
if (hours == 1) { thisEl.find(".timeRefHours").text("hour"); } else { thisEl.find(".timeRefHours").text("hours"); }
if (minutes == 1) { thisEl.find(".timeRefMinutes").text("minute"); } else { thisEl.find(".timeRefMinutes").text("minutes"); }
if (seconds == 1) { thisEl.find(".timeRefSeconds").text("second"); } else { thisEl.find(".timeRefSeconds").text("seconds"); }
//logic for the two_digits ON setting
if(settings['format'] == "on") {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}
//update the countdown's html values.
if(!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds);
} else {
alert("Invalid date. Here's an example: 12 Tuesday 2012 17:30:00");
clearInterval(interval);
}
}
//run the function
countdown_proc();
//loop the function
interval = setInterval(countdown_proc, 1000);
}
}) (jQuery); | JavaScript |
/*
Quicksand 1.2.2
Reorder and filter items with a nice shuffling animation.
Copyright (c) 2010 Jacek Galanciak (razorjack.net) and agilope.com
Big thanks for Piotr Petrus (riddle.pl) for deep code review and wonderful docs & demos.
Dual licensed under the MIT and GPL version 2 licenses.
http://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt
http://github.com/jquery/jquery/blob/master/GPL-LICENSE.txt
Project site: http://razorjack.net/quicksand
Github site: http://github.com/razorjack/quicksand
*/
(function ($) {
$.fn.quicksand = function (collection, customOptions) {
var options = {
duration: 750,
easing: 'swing',
attribute: 'data-id', // attribute to recognize same items within source and dest
adjustHeight: 'auto', // 'dynamic' animates height during shuffling (slow), 'auto' adjusts it before or after the animation, false leaves height constant
useScaling: true, // disable it if you're not using scaling effect or want to improve performance
enhancement: function(c) {}, // Visual enhacement (eg. font replacement) function for cloned elements
selector: '> *',
dx: 0,
dy: 0
};
$.extend(options, customOptions);
if ($.browser.msie || (typeof($.fn.scale) == 'undefined')) {
// Got IE and want scaling effect? Kiss my ass.
options.useScaling = false;
}
var callbackFunction;
if (typeof(arguments[1]) == 'function') {
var callbackFunction = arguments[1];
} else if (typeof(arguments[2] == 'function')) {
var callbackFunction = arguments[2];
}
return this.each(function (i) {
var val;
var animationQueue = []; // used to store all the animation params before starting the animation; solves initial animation slowdowns
var $collection = $(collection).clone(); // destination (target) collection
var $sourceParent = $(this); // source, the visible container of source collection
var sourceHeight = $(this).css('height'); // used to keep height and document flow during the animation
var destHeight;
var adjustHeightOnCallback = false;
var offset = $($sourceParent).offset(); // offset of visible container, used in animation calculations
var offsets = []; // coordinates of every source collection item
var $source = $(this).find(options.selector); // source collection items
// Replace the collection and quit if IE6
if ($.browser.msie && $.browser.version.substr(0,1)<7) {
$sourceParent.html('').append($collection);
return;
}
// Gets called when any animation is finished
var postCallbackPerformed = 0; // prevents the function from being called more than one time
var postCallback = function () {
if (!postCallbackPerformed) {
postCallbackPerformed = 1;
// hack:
// used to be: $sourceParent.html($dest.html()); // put target HTML into visible source container
// but new webkit builds cause flickering when replacing the collections
$toDelete = $sourceParent.find('> *');
$sourceParent.prepend($dest.find('> *'));
$toDelete.remove();
if (adjustHeightOnCallback) {
$sourceParent.css('height', destHeight);
}
options.enhancement($sourceParent); // Perform custom visual enhancements on a newly replaced collection
if (typeof callbackFunction == 'function') {
callbackFunction.call(this);
}
}
};
// Position: relative situations
var $correctionParent = $sourceParent.offsetParent();
var correctionOffset = $correctionParent.offset();
if ($correctionParent.css('position') == 'relative') {
if ($correctionParent.get(0).nodeName.toLowerCase() == 'body') {
} else {
correctionOffset.top += (parseFloat($correctionParent.css('border-top-width')) || 0);
correctionOffset.left +=( parseFloat($correctionParent.css('border-left-width')) || 0);
}
} else {
correctionOffset.top -= (parseFloat($correctionParent.css('border-top-width')) || 0);
correctionOffset.left -= (parseFloat($correctionParent.css('border-left-width')) || 0);
correctionOffset.top -= (parseFloat($correctionParent.css('margin-top')) || 0);
correctionOffset.left -= (parseFloat($correctionParent.css('margin-left')) || 0);
}
// perform custom corrections from options (use when Quicksand fails to detect proper correction)
if (isNaN(correctionOffset.left)) {
correctionOffset.left = 0;
}
if (isNaN(correctionOffset.top)) {
correctionOffset.top = 0;
}
correctionOffset.left -= options.dx;
correctionOffset.top -= options.dy;
// keeps nodes after source container, holding their position
$sourceParent.css('height', $(this).height());
// get positions of source collections
$source.each(function (i) {
offsets[i] = $(this).offset();
});
// stops previous animations on source container
$(this).stop();
var dx = 0; var dy = 0;
$source.each(function (i) {
$(this).stop(); // stop animation of collection items
var rawObj = $(this).get(0);
if (rawObj.style.position == 'absolute') {
dx = -options.dx;
dy = -options.dy;
} else {
dx = options.dx;
dy = options.dy;
}
rawObj.style.position = 'absolute';
rawObj.style.margin = '0';
rawObj.style.top = (offsets[i].top - parseFloat(rawObj.style.marginTop) - correctionOffset.top + dy) + 'px';
rawObj.style.left = (offsets[i].left - parseFloat(rawObj.style.marginLeft) - correctionOffset.left + dx) + 'px';
});
// create temporary container with destination collection
var $dest = $($sourceParent).clone();
var rawDest = $dest.get(0);
rawDest.innerHTML = '';
rawDest.setAttribute('id', '');
rawDest.style.height = 'auto';
rawDest.style.width = $sourceParent.width() + 'px';
$dest.append($collection);
// insert node into HTML
// Note that the node is under visible source container in the exactly same position
// The browser render all the items without showing them (opacity: 0.0)
// No offset calculations are needed, the browser just extracts position from underlayered destination items
// and sets animation to destination positions.
$dest.insertBefore($sourceParent);
$dest.css('opacity', 0.0);
rawDest.style.zIndex = -1;
rawDest.style.margin = '0';
rawDest.style.position = 'absolute';
rawDest.style.top = offset.top - correctionOffset.top + 'px';
rawDest.style.left = offset.left - correctionOffset.left + 'px';
if (options.adjustHeight === 'dynamic') {
// If destination container has different height than source container
// the height can be animated, adjusting it to destination height
$sourceParent.animate({height: $dest.height()}, options.duration, options.easing);
} else if (options.adjustHeight === 'auto') {
destHeight = $dest.height();
if (parseFloat(sourceHeight) < parseFloat(destHeight)) {
// Adjust the height now so that the items don't move out of the container
$sourceParent.css('height', destHeight);
} else {
// Adjust later, on callback
adjustHeightOnCallback = true;
}
}
// Now it's time to do shuffling animation
// First of all, we need to identify same elements within source and destination collections
$source.each(function (i) {
var destElement = [];
if (typeof(options.attribute) == 'function') {
val = options.attribute($(this));
$collection.each(function() {
if (options.attribute(this) == val) {
destElement = $(this);
return false;
}
});
} else {
destElement = $collection.filter('[' + options.attribute + '=' + $(this).attr(options.attribute) + ']');
}
if (destElement.length) {
// The item is both in source and destination collections
// It it's under different position, let's move it
if (!options.useScaling) {
animationQueue.push(
{
element: $(this),
animation:
{top: destElement.offset().top - correctionOffset.top,
left: destElement.offset().left - correctionOffset.left,
opacity: 1.0
}
});
} else {
animationQueue.push({
element: $(this),
animation: {top: destElement.offset().top - correctionOffset.top,
left: destElement.offset().left - correctionOffset.left,
opacity: 1.0,
scale: '1.0'
}
});
}
} else {
// The item from source collection is not present in destination collections
// Let's remove it
if (!options.useScaling) {
animationQueue.push({element: $(this),
animation: {opacity: '0.0'}});
} else {
animationQueue.push({element: $(this), animation: {opacity: '0.0',
scale: '0.0'}});
}
}
});
$collection.each(function (i) {
// Grab all items from target collection not present in visible source collection
var sourceElement = [];
var destElement = [];
if (typeof(options.attribute) == 'function') {
val = options.attribute($(this));
$source.each(function() {
if (options.attribute(this) == val) {
sourceElement = $(this);
return false;
}
});
$collection.each(function() {
if (options.attribute(this) == val) {
destElement = $(this);
return false;
}
});
} else {
sourceElement = $source.filter('[' + options.attribute + '=' + $(this).attr(options.attribute) + ']');
destElement = $collection.filter('[' + options.attribute + '=' + $(this).attr(options.attribute) + ']');
}
var animationOptions;
if (sourceElement.length === 0) {
// No such element in source collection...
if (!options.useScaling) {
animationOptions = {
opacity: '1.0'
};
} else {
animationOptions = {
opacity: '1.0',
scale: '1.0'
};
}
// Let's create it
d = destElement.clone();
var rawDestElement = d.get(0);
rawDestElement.style.position = 'absolute';
rawDestElement.style.margin = '0';
rawDestElement.style.top = destElement.offset().top - correctionOffset.top + 'px';
rawDestElement.style.left = destElement.offset().left - correctionOffset.left + 'px';
d.css('opacity', 0.0); // IE
if (options.useScaling) {
d.css('transform', 'scale(0.0)');
}
d.appendTo($sourceParent);
animationQueue.push({element: $(d),
animation: animationOptions});
}
});
$dest.remove();
options.enhancement($sourceParent); // Perform custom visual enhancements during the animation
for (i = 0; i < animationQueue.length; i++) {
animationQueue[i].element.animate(animationQueue[i].animation, options.duration, options.easing, postCallback);
}
});
};
})(jQuery); | JavaScript |
/*!
* jQuery Form Plugin
* version: 3.50.0-2014.02.05
* Requires jQuery v1.5 or later
* Copyright (c) 2013 M. Alsup
* Examples and documentation at: http://malsup.com/jquery/form/
* Project repository: https://github.com/malsup/form
* Dual licensed under the MIT and GPL licenses.
* https://github.com/malsup/form#copyright-and-license
*/
/*global ActiveXObject */
// AMD support
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// using AMD; register as anon module
define(['jquery'], factory);
} else {
// no AMD; invoke directly
factory((typeof (jQuery) != 'undefined') ? jQuery : window.Zepto);
}
}
(function ($) {
"use strict";
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:
$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
var hasProp = !!$.fn.prop;
// attr2 uses prop when it can but checks the return type for
// an expected string. this accounts for the case where a form
// contains inputs with names like "action" or "method"; in those
// cases "prop" returns the element
$.fn.attr2 = function () {
if (!hasProp) {
return this.attr.apply(this, arguments);
}
var val = this.prop.apply(this, arguments);
if ((val && val.jquery) || typeof val === 'string') {
return val;
}
return this.attr.apply(this, arguments);
};
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function (options) {
/*jshint scripturl:true */
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
else if (options === undefined) {
options = {};
}
method = options.type || this.attr2('method');
action = options.url || this.attr2('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/) || [])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || $.ajaxSettings.type,
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if (traditional === undefined) {
traditional = $.ajaxSettings.traditional;
}
var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = (q ? (q + '&' + qx) : qx);
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function () { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function () { $form.clearForm(options.includeHidden); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function () { };
callbacks.push(function (data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function (data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this; // jQuery 1.4+ supports scope context
for (var i = 0, max = callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
if (options.error) {
var oldError = options.error;
options.error = function (xhr, status, error) {
var context = options.context || this;
oldError.apply(context, [xhr, status, error, $form]);
};
}
if (options.complete) {
var oldComplete = options.complete;
options.complete = function (xhr, status) {
var context = options.context || this;
oldComplete.apply(context, [xhr, status, $form]);
};
}
// are there files to upload?
// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
var fileInputs = $('input[type=file]:enabled', this).filter(function () { return $(this).val() !== ''; });
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
var jqxhr;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function () {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}
$form.removeData('jqxhr').data('jqxhr', jqxhr);
// clear element array
for (var k = 0; k < elements.length; k++) {
elements[k] = null;
}
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// utility fn for deep serialization
function deepSerialize(extraData) {
var serialized = $.param(extraData, options.traditional).split('&');
var len = serialized.length;
var result = [];
var i, part;
for (i = 0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g, ' ');
part = serialized[i].split('=');
// #278; use array instead of object storage, favoring array serializations
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i = 0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i = 0; i < serializedData.length; i++) {
if (serializedData[i]) {
formdata.append(serializedData[i][0], serializedData[i][1]);
}
}
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function () {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function (xhr, o) {
//Send FormData() provided by user
if (options.formData) {
o.data = options.formData;
}
else {
o.data = formdata;
}
if (beforeSend) {
beforeSend.call(this, xhr, o);
}
};
return $.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var deferred = $.Deferred();
// #341
deferred.abort = function (status) {
xhr.abort(status);
};
if (a) {
// ensure that every serialized input is still enabled
for (i = 0; i < elements.length; i++) {
el = $(elements[i]);
if (hasProp) {
el.prop('disabled', false);
}
else {
el.removeAttr('disabled');
}
}
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr2('name');
if (!n) {
$io.attr2('name', id);
}
else {
id = n;
}
}
else {
$io = $('<iframe name="' + id + '" src="' + s.iframeSrc + '" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function () { },
getResponseHeader: function () { },
setRequestHeader: function () { },
abort: function (status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch (ignore) { }
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error) {
s.error.call(s.context, xhr, e, status);
}
if (g) {
$.event.trigger("ajaxError", [xhr, s, e]);
}
if (s.complete) {
s.complete.call(s.context, xhr, e);
}
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n + '.x'] = form.clk_x;
s.extraData[n + '.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
/* it looks like contentWindow or contentDocument do not
* carry the protocol property in ie8, when running under ssl
* frame.document is the only valid response document, since
* the protocol is know but not on the other two objects. strange?
* "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
*/
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch (err) {
// IE8 access denied under ssl & missing protocol
log('cannot get iframe.contentWindow document: ' + err);
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch (err) {
// last attempt
log('cannot get iframe.contentDocument: ' + err);
doc = frame.document;
}
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr2('target'),
a = $form.attr2('action'),
mp = 'multipart/form-data',
et = $form.attr('enctype') || $form.attr('encoding') || mp;
// update form attrs in IE friendly way
form.setAttribute('target', id);
if (!method || /post/i.test(method)) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (!s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function () { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized') {
setTimeout(checkState, 50);
}
}
catch (e) {
log('Server abort: ', e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if ($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="' + s.extraData[n].name + '">').val(s.extraData[n].value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="' + n + '">').val(s.extraData[n])
.appendTo(form)[0]);
}
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
}
if (io.attachEvent) {
io.attachEvent('onload', cb);
}
else {
io.addEventListener('load', cb, false);
}
setTimeout(checkState, 15);
try {
form.submit();
} catch (err) {
// just in case form has element with name/id of 'submit'
var submitFn = document.createElement('form').submit;
submitFn.apply(form);
}
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action', a);
form.setAttribute('enctype', et); // #380
if (t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
doc = getDoc(io);
if (!doc) {
log('cannot access response document');
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut) {
return;
}
}
if (io.detachEvent) {
io.detachEvent('onload', cb);
}
else {
io.removeEventListener('load', cb, false);
}
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml=' + isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml) {
s.dataType = 'xml';
}
xhr.getResponseHeader = function (header) {
var headers = { 'content-type': s.dataType };
return headers[header.toLowerCase()];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number(docRoot.getAttribute('status')) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number(ta.getAttribute('status')) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (err) {
status = 'parsererror';
xhr.error = errMsg = (err || status);
}
}
catch (err) {
log('error caught: ', err);
status = 'error';
xhr.error = errMsg = (err || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success) {
s.success.call(s.context, data, 'success', xhr);
}
deferred.resolve(xhr.responseText, 'success', xhr);
if (g) {
$.event.trigger("ajaxSuccess", [xhr, s]);
}
}
else if (status) {
if (errMsg === undefined) {
errMsg = xhr.statusText;
}
if (s.error) {
s.error.call(s.context, xhr, status, errMsg);
}
deferred.reject(xhr, 'error', errMsg);
if (g) {
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}
}
if (g) {
$.event.trigger("ajaxComplete", [xhr, s]);
}
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete) {
s.complete.call(s.context, xhr, status);
}
callbackProcessed = true;
if (s.timeout) {
clearTimeout(timeoutHandle);
}
// clean up
setTimeout(function () {
if (!s.iframeTarget) {
$io.remove();
}
else { //adding else to clean up existing iframe response.
$io.attr('src', s.iframeSrc);
}
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function (s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function (s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};
var httpData = function (xhr, type, s) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error) {
$.error('parsererror');
}
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
return deferred;
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function (options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function () {
$(o.s, o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if (options.delegation) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};
// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(e.target).ajaxSubmit(options); // #365
}
}
function captureSubmittingElement(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function () { form.clk = form.clk_x = form.clk_y = null; }, 100);
}
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function () {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function (semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var formId = this.attr('id');
var els = semantic ? form.getElementsByTagName('*') : form.elements;
var els2;
if (els && !/MSIE [678]/.test(navigator.userAgent)) { // #390
els = $(els).get(); // convert to standard array
}
// #386; account for inputs outside the form which use the 'form' attribute
if (formId) {
els2 = $(':input[form=' + formId + ']').get();
if (els2.length) {
els = (els || []).concat(els2);
}
}
if (!els || !els.length) {
return a;
}
var i, j, n, v, el, max, jmax;
for (i = 0, max = els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n || el.disabled) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if (form.clk == el) {
a.push({ name: n, value: $(el).val(), type: el.type });
a.push({ name: n + '.x', value: form.clk_x }, { name: n + '.y', value: form.clk_y });
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements) {
elements.push(el);
}
for (j = 0, jmax = v.length; j < jmax; j++) {
a.push({ name: n, value: v[j] });
}
}
else if (feature.fileapi && el.type == 'file') {
if (elements) {
elements.push(el);
}
var files = el.files;
if (files.length) {
for (j = 0; j < files.length; j++) {
a.push({ name: n, value: files[j], type: el.type });
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements) {
elements.push(el);
}
a.push({ name: n, value: v, type: el.type, required: el.required });
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({ name: n, value: $input.val() });
a.push({ name: n + '.x', value: form.clk_x }, { name: n + '.y', value: form.clk_y });
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function (semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function (successful) {
var a = [];
this.each(function () {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i = 0, max = v.length; i < max; i++) {
a.push({ name: n, value: v[i] });
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({ name: this.name, value: v });
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $('input[type=text]').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $('input[type=checkbox]').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $('input[type=radio]').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function (successful) {
for (var val = [], i = 0, max = this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array) {
$.merge(val, v);
}
else {
val.push(v);
}
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function (el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index + 1 : ops.length);
for (var i = (one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function (includeHidden) {
return this.each(function () {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function (includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function () {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ((includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden))) {
this.value = '';
}
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function () {
return this.each(function () {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function (b) {
if (b === undefined) {
b = true;
}
return this.each(function () {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function (select) {
if (select === undefined) {
select = true;
}
return this.each(function () {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug) {
return;
}
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments, '');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
}));
| 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})$" //身份证
}
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
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 |
//QQ客服弹出对话框
var online= new Array();
var urlroot = "http://gdp.istudy.com.cn/";
var tOut = -1;
var drag = false;
var g_safeNode = null;
lastScrollY = 0;
var kfguin;
var ws;
var companyname;
var welcomeword;
var type;
var wpadomain;
var eid;
var Browser = {
ie:/msie/.test(window.navigator.userAgent.toLowerCase()),
moz:/gecko/.test(window.navigator.userAgent.toLowerCase()),
opera:/opera/.test(window.navigator.userAgent.toLowerCase()),
safari:/safari/.test(window.navigator.userAgent.toLowerCase())
};
if(kfguin)
{
//_Ten_rightDivHtml = '<div id="_Ten_rightDiv" style="position:absolute; top:160px; right:1px; display:none;">';
//_Ten_rightDivHtml += kf_getPopup_Ten_rightDivHtml(kfguin,ws,wpadomain);
//_Ten_rightDivHtml += '</div>';
//document.write(_Ten_rightDivHtml);
if(type==1 && kf_getCookie('hasshown')==0)
{
companyname = companyname.substr(0,15);
welcomeword = kf_processWelcomeword(welcomeword);
kfguin = kf_getSafeHTML(kfguin);
companyname = kf_getSafeHTML(companyname);
welcomeword = welcomeword.replace(/<br>/g,'\r\n');
welcomeword = kf_getSafeHTML(welcomeword);
welcomeword = welcomeword.replace(/\r/g, "").replace(/\n/g, "<BR>");
window.setTimeout("kf_sleepShow()",200);
}
window.setTimeout("kf_moveWithScroll()",1);
}
function kf_getSafeHTML(s)
{
var html = "";
var safeNode = g_safeNode;
if(!safeNode){
safeNode = document.createElement("TEXTAREA");
}
if(safeNode){
if(Browser.moz){
safeNode.textContent = s;
}
else{
safeNode.innerText = s;
}
html = safeNode.innerHTML;
if(Browser.moz){
safeNode.textContent = "";
}
else{
safeNode.innerText = "";
}
g_safeNode = safeNode;
}
return html;
}
function kf_moveWithScroll()
{
if(typeof window.pageYOffset != 'undefined') {
nowY = window.pageYOffset;
}
else if(typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
nowY = document.documentElement.scrollTop;
}
else if(typeof document.body != 'undefined') {
nowY = document.body.scrollTop;
}
percent = .1*(nowY - lastScrollY);
if(percent > 0)
{
percent=Math.ceil(percent);
}
else
{
percent=Math.floor(percent);
}
//document.getElementById("_Ten_rightDiv").style.top = parseInt(document.getElementById("_Ten_rightDiv").style.top) + percent+"px";
if(document.getElementById("kfpopupDiv"))
{
document.getElementById("kfpopupDiv").style.top = parseInt(document.getElementById("kfpopupDiv").style.top) + percent+"px";
}
lastScrollY = lastScrollY + percent;
tOut = window.setTimeout("kf_moveWithScroll()",1);
}
function kf_hide()
{
if(tOut!=-1)
{
clearTimeout(tOut);
tOut=-1;
}
//document.getElementById("_Ten_rightDiv").style.visibility = "hidden";
//document.getElementById("_Ten_rightDiv").style.display = "none";
kf_setCookie('hasshown', 1, '', '/', wpadomain);
}
function kf_hidekfpopup()
{
if(tOut!=-1)
{
clearTimeout(tOut);
tOut=-1;
}
document.getElementById("kfpopupDiv").style.visibility = "hidden";
document.getElementById("kfpopupDiv").style.display = "none";
tOut=window.setTimeout("kf_moveWithScroll()",1);
kf_setCookie('hasshown', 1, '', '/', wpadomain);
}
function kf_getPopupDivHtml(kfguin,reference,companyname,welcomeword, wpadomain)
{
var temp = '';
temp += '<span class="zixun0704_x"><a href="javascript:void(0);" onclick="kf_hidekfpopup();return false;"><!--关闭--></a></span>';
temp += '<img src="'+urlroot+'web/pic_zixun0704_nv.jpg" class="zixun0704_img" />';
temp += '<p class="zixun0704_font">'+welcomeword+'</p>';
temp += '<div class="zixun0704_button"><a href="javascript:void(0);" onclick="kf_openChatWindow(1,\'b\',\''+kfguin+'\')"><img src="'+urlroot+'web/pic_zixun0704QQ.jpg" /></a> <a href="javascript:void(0);" onclick="kf_hidekfpopup();return false;"><img src="'+urlroot+'web/pic_zixun0704_later.jpg" /></a></div>';
return temp;
}
//function kf_getPopup_Ten_rightDivHtml(kfguin,reference, wpadomain)
//{
// var temp = "";
//
// temp += '<div style="width:90px; height:150px;">';
// temp += '<div style="width:8px; height:150px; float:left; background:url('+urlroot+'bg_1.gif);"></div>';
// temp += '<div style="float:left; width:74px; height:150px; background:url('+urlroot+'middle.jpg); background-position: center;">';
// temp += '<div ><h1 style="line-height:17px; font-size:14px; color:#FFFFFF; margin:0px; padding:10px 0 13px 8px; display:block; background:none; border:none; float:none; position:static;"> </h1></div>';
// temp += '<div style="height:83px; padding:0 0 0 2px; clear:both;"><div style="width:70px; height:70px; float:left; background:url('+urlroot+'face.jpg);"></div></div>';
// temp += '<div style="clear:both;"><a href="#" onclick="kf_openChatWindow(0,\''+wpadomain+'\',\''+kfguin+'\')" style="width:69px; height:21px; background:url('+urlroot+'btn_2.gif); margin:0 0 0 2px; display:block;"></a></div></div>';
// temp += '<div style="width:8px; height:150px; float:left; background:url('+urlroot+'bg_1.gif) right;"></div></div>';
//
// return temp;
//}
//added by simon 2008-11-04
function kf_openChatWindow(flag, wpadomain, kfguin)
{
window.open('http://b.qq.com/webc.htm?new=0&sid='+kfguin+'&eid='+eid+'&o=&q=7', '_blank', 'height=544, width=644,toolbar=no,scrollbars=no,menubar=no,status=no');
if(flag==1)
{
kf_hidekfpopup();
}
return false;
}
//added by simon 2008-11-04 end
function kf_validateWelcomeword(word)
{
var count = 0;
for(var i=0;i<word.length;i++)
{
if(word.charAt(i)=='\n')
{
count++;
}
if(count>2)
{
return 2;
}
}
if(word.length > 57+2*count)
{
return 1;
}
count = 0;
var temp = word.indexOf('\n');
while(temp!=-1)
{
word = word.substr(temp+1);
if(temp-1<=19)
{
count += 19;
}
else if(temp-1<=38)
{
count += 38;
}
else if(temp-1<=57)
{
count += 57;
}
temp = word.indexOf('\n');
}
count+=word.length;
if(count>57)
{
return 3;
}
return 0;
}
function kf_processWelcomeword(word)
{
word = word.substr(0,57+10);
var result = '';
var count = 0;
var temp = word.indexOf('<br>');
while(count<57 && temp!=-1)
{
if(temp<=19)
{
count += 19;
if(count<=57)
{
result += word.substr(0,temp+5);
}
else
{
result += word.substr(0,57-count>word.length?word.length:57-count);
}
}
else if(temp<=38)
{
count += 38;
if(count<=57)
{
result += word.substr(0,temp+5);
}
else
{
result += word.substr(0,57-count>word.length?word.length:57-count);
}
}
else if(temp<=57)
{
count += 57;
if(count<=57)
{
result += word.substr(0,temp+5);
}
else
{
result += word.substr(0,57-count>word.length?word.length:57-count);
}
}
word = word.substr(temp+5);
temp = word.indexOf('<br>');
}
if(count<57)
{
result += word.substr(0,57-count>word.length?word.length:57-count);
}
return result;
}
function kf_setCookie(name, value, exp, path, domain)
{
var nv = name + "=" + escape(value) + ";";
var d = null;
if(typeof(exp) == "object")
{
d = exp;
}
else if(typeof(exp) == "number")
{
d = new Date();
d = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes() + exp, d.getSeconds(), d.getMilliseconds());
}
if(d)
{
nv += "expires=" + d.toGMTString() + ";";
}
if(!path)
{
nv += "path=/;";
}
else if(typeof(path) == "string" && path != "")
{
nv += "path=" + path + ";";
}
if(!domain && typeof(VS_COOKIEDM) != "undefined")
{
domain = VS_COOKIEDM;
}
if(typeof(domain) == "string" && domain != "")
{
nv += "domain=" + domain + ";";
}
document.cookie = nv;
}
function kf_getCookie(name)
{
var value = "";
var cookies = document.cookie.split("; ");
var nv;
var i;
for(i = 0; i < cookies.length; i++)
{
nv = cookies[i].split("=");
if(nv && nv.length >= 2 && name == kf_rTrim(kf_lTrim(nv[0])))
{
value = unescape(nv[1]);
}
}
return value;
}
function kf_sleepShow()
{
kf_setCookie('hasshown', 0, '', '/', wpadomain);
var position_1 = (document.documentElement.clientWidth-381)/2+document.body.scrollLeft;
var position_2 = (document.documentElement.clientHeight-159)/2+document.body.scrollTop;
popupDivHtml = '<div class="zixun0704" id="kfpopupDiv" onmousedown="MyMove.Move(\'kfpopupDiv\',event,1);" style="z-index:10000; position: absolute; top: '+position_2+'px; left: '+position_1+'px;color:#000;font-size: 12px;cursor:move;height: 159px;width: 381px;">';
popupDivHtml += kf_getPopupDivHtml(kfguin,ws,companyname,welcomeword, wpadomain);
popupDivHtml += '</div>';
if(document.body.insertAdjacentHTML)
{
document.body.insertAdjacentHTML("beforeEnd",popupDivHtml);
}
else
{
$("#footer").before(popupDivHtml);
// sWhere="beforeEnd";
// sHTML=popupDivHtml;
// alert(HTMLElement.prototype.insertAdjacentHTML);
// HTMLElement.prototype.insertAdjacentHTML = function(sWhere, sHTML){
// var df = null,r = this.ownerDocument.createRange();
// switch (String(sWhere).toLowerCase()) {
// case "beforebegin":
// r.setStartBefore(this);
// df = r.createContextualFragment(sHTML);
// this.parentNode.insertBefore(df, this);
// break;
// case "afterbegin":
// r.selectNodeContents(this);
// r.collapse(true);
// df = r.createContextualFragment(sHTML);
// this.insertBefore(df, this.firstChild);
// break;
// case "beforeend":
// r.selectNodeContents(this);
// r.collapse(false);
// df = r.createContextualFragment(sHTML);
// this.appendChild(df);
// break;
// case "afterend":
// r.setStartAfter(this);
// df = r.createContextualFragment(sHTML);
// this.parentNode.insertBefore(df, this.nextSibling);
// break;
// }
// };
}
}
function kf_dealErrors()
{
kf_hide();
return true;
}
function kf_lTrim(str)
{
while (str.charAt(0) == " ")
{
str = str.slice(1);
}
return str;
}
function kf_rTrim(str)
{
var iLength = str.length;
while (str.charAt(iLength - 1) == " ")
{
str = str.slice(0, iLength - 1);
iLength--;
}
return str;
}
window.onerror = kf_dealErrors;
var MyMove = new Tong_MoveDiv();
function Tong_MoveDiv()
{
this.Move=function(Id,Evt,T)
{
if(Id == "")
{
return;
}
var o = document.getElementById(Id);
if(!o)
{
return;
}
evt = Evt ? Evt : window.event;
o.style.position = "absolute";
o.style.zIndex = 9999;
var obj = evt.srcElement ? evt.srcElement : evt.target;
var w = o.offsetWidth;
var h = o.offsetHeight;
var l = o.offsetLeft;
var t = o.offsetTop;
var div = document.createElement("DIV");
document.body.appendChild(div);
div.style.cssText = "filter:alpha(Opacity=10,style=0);opacity:0.2;width:"+w+"px;height:"+h+"px;top:"+t+"px;left:"+l+"px;position:absolute;background:#000";
div.setAttribute("id", Id +"temp");
this.Move_OnlyMove(Id,evt,T);
}
this.Move_OnlyMove = function(Id,Evt,T)
{
var o = document.getElementById(Id+"temp");
if(!o)
{
return;
}
evt = Evt?Evt:window.event;
var relLeft = evt.clientX - o.offsetLeft;
var relTop = evt.clientY - o.offsetTop;
if(!window.captureEvents)
{
o.setCapture();
}
else
{
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
}
document.onmousemove = function(e)
{
if(!o)
{
return;
}
e = e ? e : window.event;
var bh = Math.max(document.body.scrollHeight,document.body.clientHeight,document.body.offsetHeight,
document.documentElement.scrollHeight,document.documentElement.clientHeight,document.documentElement.offsetHeight);
var bw = Math.max(document.body.scrollWidth,document.body.clientWidth,document.body.offsetWidth,
document.documentElement.scrollWidth,document.documentElement.clientWidth,document.documentElement.offsetWidth);
var sbw = 0;
if(document.body.scrollWidth < bw)
sbw = document.body.scrollWidth;
if(document.body.clientWidth < bw && sbw < document.body.clientWidth)
sbw = document.body.clientWidth;
if(document.body.offsetWidth < bw && sbw < document.body.offsetWidth)
sbw = document.body.offsetWidth;
if(document.documentElement.scrollWidth < bw && sbw < document.documentElement.scrollWidth)
sbw = document.documentElement.scrollWidth;
if(document.documentElement.clientWidth < bw && sbw < document.documentElement.clientWidth)
sbw = document.documentElement.clientWidth;
if(document.documentElement.offsetWidth < bw && sbw < document.documentElement.offsetWidth)
sbw = document.documentElement.offsetWidth;
if(e.clientX - relLeft <= 0)
{
o.style.left = 0 +"px";
}
else if(e.clientX - relLeft >= bw - o.offsetWidth - 2)
{
o.style.left = (sbw - o.offsetWidth - 2) +"px";
}
else
{
o.style.left = e.clientX - relLeft +"px";
}
if(e.clientY - relTop <= 1)
{
o.style.top = 1 +"px";
}
else if(e.clientY - relTop >= bh - o.offsetHeight - 30)
{
o.style.top = (bh - o.offsetHeight) +"px";
}
else
{
o.style.top = e.clientY - relTop +"px";
}
}
document.onmouseup = function()
{
if(!o) return;
if(!window.captureEvents)
{
o.releaseCapture();
}
else
{
window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP);
}
var o1 = document.getElementById(Id);
if(!o1)
{
return;
}
var l0 = o.offsetLeft;
var t0 = o.offsetTop;
var l = o1.offsetLeft;
var t = o1.offsetTop;
//alert(l0 + " " + t0 +" "+ l +" "+t);
MyMove.Move_e(Id, l0 , t0, l, t,T);
document.body.removeChild(o);
o = null;
}
}
this.Move_e = function(Id, l0 , t0, l, t,T)
{
if(typeof(window["ct"+ Id]) != "undefined")
{
clearTimeout(window["ct"+ Id]);
}
var o = document.getElementById(Id);
if(!o) return;
var sl = st = 8;
var s_l = Math.abs(l0 - l);
var s_t = Math.abs(t0 - t);
if(s_l - s_t > 0)
{
if(s_t)
{
sl = Math.round(s_l / s_t) > 8 ? 8 : Math.round(s_l / s_t) * 6;
}
else
{
sl = 0;
}
}
else
{
if(s_l)
{
st = Math.round(s_t / s_l) > 8 ? 8 : Math.round(s_t / s_l) * 6;
}
else
{
st = 0;
}
}
if(l0 - l < 0)
{
sl *= -1;
}
if(t0 - t < 0)
{
st *= -1;
}
if(Math.abs(l + sl - l0) < 52 && sl)
{
sl = sl > 0 ? 2 : -2;
}
if(Math.abs(t + st - t0) < 52 && st)
{
st = st > 0 ? 2 : -2;
}
if(Math.abs(l + sl - l0) < 16 && sl)
{
sl = sl > 0 ? 1 : -1;
}
if(Math.abs(t + st - t0) < 16 && st)
{
st = st > 0 ? 1 : -1;
}
if(s_l == 0 && s_t == 0)
{
return;
}
if(T)
{
o.style.left = l0 +"px";
o.style.top = t0 +"px";
return;
}
else
{
if(Math.abs(l + sl - l0) < 2)
{
o.style.left = l0 +"px";
}
else
{
o.style.left = l + sl +"px";
}
if(Math.abs(t + st - t0) < 2)
{
o.style.top = t0 +"px";
}
else
{
o.style.top = t + st +"px";
}
window["ct"+ Id] = window.setTimeout("MyMove.Move_e('"+ Id +"', "+ l0 +" , "+ t0 +", "+ (l + sl) +", "+ (t + st) +","+T+")", 1);
}
}
}
function wpa_count()
{
var body = document.getElementsByTagName('body').item(0);
var img = document.createElement('img');
var now = new Date();
img.src = "http://"+wpadomain+".qq.com/cgi/wpac?kfguin=" + kfguin + "&ext=0" + "&time=" + now.getTime() + "ip=172.23.30.15&";
img.style.display = "none";
body.appendChild(img);
} | JavaScript |
function getUrlParas() {
var hash = location.hash,
para = {},
tParas = hash.substr(1).split("&");
for (var p in tParas) {
if (tParas.hasOwnProperty(p)) {
var obj = tParas[p].split("=");
para[obj[0]] = obj[1];
}
}
return para;
}
var para = getUrlParas(),
center = para.address ? decodeURIComponent(para.address) : "百度大厦",
city = para.city ? decodeURIComponent(para.city) : "北京市";
document.getElementById("keyword").value = center;
var marker_trick = false;
var map = new BMap.Map("map_container");
map.enableScrollWheelZoom();
var marker = new BMap.Marker(new BMap.Point(116.404, 39.915), {
enableMassClear: false,
raiseOnDrag: true
});
marker.enableDragging();
map.addOverlay(marker);
map.addEventListener("click", function (e) {
if (!(e.overlay)) {
map.clearOverlays();
marker.show();
marker.setPosition(e.point);
setResult(e.point.lng, e.point.lat);
}
});
marker.addEventListener("dragend", function (e) {
setResult(e.point.lng, e.point.lat);
});
var local = new BMap.LocalSearch(map, {
renderOptions: { map: map },
pageCapacity: 1
});
local.setSearchCompleteCallback(function (results) {
if (local.getStatus() !== BMAP_STATUS_SUCCESS) {
local.search('百度大厦');
} else {
marker.hide();
}
});
local.setMarkersSetCallback(function (pois) {
for (var i = pois.length; i--; ) {
var marker = pois[i].marker;
marker.addEventListener("click", function (e) {
marker_trick = true;
var pos = this.getPosition();
setResult(pos.lng, pos.lat);
});
}
});
function a() {
document.getElementById("float_search_bar").style.display = "none";
}
/*
* setResult : 定义得到标注经纬度后的操作
* 请修改此函数以满足您的需求
* lng: 标注的经度
* lat: 标注的纬度
*/
function setResult(lng, lat) {
document.getElementById("result").innerHTML = lng + ", " + lat;
} | JavaScript |
/**
* @license Copyright (c) 2003-2013, 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 complete reference see:
// // http://docs.ckeditor.com/#!/api/CKEDITOR.config
// // The toolbar groups arrangement, optimized for two toolbar rows.
// config.toolbarGroups = [
// { name: 'clipboard', groups: ['clipboard', 'undo'] },
// { name: 'editing', groups: ['find', 'selection', 'spellchecker'] },
// { name: 'links' },
// { name: 'insert' },
// { name: 'forms' },
// { name: 'tools' },
// { name: 'document', groups: ['mode', 'document', 'doctools'] },
// { name: 'others' },
// '/',
// { name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
// { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi'] },
// { name: 'styles' },
// { name: 'colors' },
// { name: 'about' }
// ];
// // Remove some buttons provided by the standard plugins, which are
// // not needed in the Standard(s) toolbar.
// config.removeButtons = 'Underline,Subscript,Superscript';
// // Set the most common block elements.
// config.format_tags = 'p;h1;h2;h3;pre';
// // Simplify the dialog windows.
// config.removeDialogTabs = 'image:advanced;link:advanced';
//};
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here.
// For complete reference see:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: ['clipboard', 'undo'] },
{ name: 'editing', groups: ['find', 'selection', 'spellchecker'] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: ['mode', 'document', 'doctools'] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
{ name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi'] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
var ckfinderPath = "/ckfinder";
config.filebrowserBrowseUrl = ckfinderPath + '/ckfinder/ckfinder.html';
config.filebrowserImageBrowseUrl = ckfinderPath + '/ckfinder/ckfinder.html?type=Images';
config.filebrowserFlashBrowseUrl = ckfinderPath + '/ckfinder/ckfinder.html?type=Flashs';
config.filebrowserUploadUrl = ckfinderPath + '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&Type=Files';
config.filebrowserImageUploadUrl = ckfinderPath + '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&Type=Images';
config.filebrowserFlashUploadUrl = ckfinderPath + '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&Type=Flash';
}; | JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, 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-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
(function () {
//Section 1 : 按下自定义按钮时执行的代码
var a = {
exec: function (editor) {
show();
}
},
b = 'addpic';
CKEDITOR.plugins.add(b, {
init: function (editor) {
editor.addCommand(b, a);
editor.ui.addButton('addpic', {
label: '添加图片',
icon: this.path + 'addpic.JPG',
command: b
});
}
});
})(); | JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
function checkWord(a){
fibdn = new Array ("@" ,"#", "$", "%", "&", "(",")","'");
i=fibdn.length;
j=a.length;
for (ii=0;ii<i;ii++){
for (jj=0;jj<j;jj++){
temp1=a.charAt(jj);
temp2=fibdn[ii];
if (temp1==temp2){
return false;
}
}
}
return true;
}
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2013 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @website http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
* @version 4.1.10 (2013-11-23)
*******************************************************************************/
(function (window, undefined) {
if (window.KindEditor) {
return;
}
if (!window.console) {
window.console = {};
}
if (!console.log) {
console.log = function () { };
}
var _VERSION = '4.1.10 (2013-11-23)',
_ua = navigator.userAgent.toLowerCase(),
_IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
_NEWIE = _ua.indexOf('msie') == -1 && _ua.indexOf('trident') > -1,
_GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
_WEBKIT = _ua.indexOf('applewebkit') > -1,
_OPERA = _ua.indexOf('opera') > -1,
_MOBILE = _ua.indexOf('mobile') > -1,
_IOS = /ipad|iphone|ipod/.test(_ua),
_QUIRKS = document.compatMode != 'CSS1Compat',
_IERANGE = !window.getSelection,
_matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
_V = _matches ? _matches[1] : '0',
_TIME = new Date().getTime();
function _isArray(val) {
if (!val) {
return false;
}
return Object.prototype.toString.call(val) === '[object Array]';
}
function _isFunction(val) {
if (!val) {
return false;
}
return Object.prototype.toString.call(val) === '[object Function]';
}
function _inArray(val, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (val === arr[i]) {
return i;
}
}
return -1;
}
function _each(obj, fn) {
if (_isArray(obj)) {
for (var i = 0, len = obj.length; i < len; i++) {
if (fn.call(obj[i], i, obj[i]) === false) {
break;
}
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (fn.call(obj[key], key, obj[key]) === false) {
break;
}
}
}
}
}
function _trim(str) {
return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
}
function _inString(val, str, delimiter) {
delimiter = delimiter === undefined ? ',' : delimiter;
return (delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
}
function _addUnit(val, unit) {
unit = unit || 'px';
return val && /^\d+$/.test(val) ? val + unit : val;
}
function _removeUnit(val) {
var match;
return val && (match = /(\d+)/.exec(val)) ? parseInt(match[1], 10) : 0;
}
function _escape(val) {
return val.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function _unescape(val) {
return val.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
}
function _toCamel(str) {
var arr = str.split('-');
str = '';
_each(arr, function (key, val) {
str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
});
return str;
}
function _toHex(val) {
function hex(d) {
var s = parseInt(d, 10).toString(16).toUpperCase();
return s.length > 1 ? s : '0' + s;
}
return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
function ($0, $1, $2, $3) {
return '#' + hex($1) + hex($2) + hex($3);
}
);
}
function _toMap(val, delimiter) {
delimiter = delimiter === undefined ? ',' : delimiter;
var map = {}, arr = _isArray(val) ? val : val.split(delimiter), match;
_each(arr, function (key, val) {
if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
for (var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
map[i.toString()] = true;
}
} else {
map[val] = true;
}
});
return map;
}
function _toArray(obj, offset) {
return Array.prototype.slice.call(obj, offset || 0);
}
function _undef(val, defaultVal) {
return val === undefined ? defaultVal : val;
}
function _invalidUrl(url) {
return !url || /[<>"]/.test(url);
}
function _addParam(url, param) {
return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
}
function _extend(child, parent, proto) {
if (!proto) {
proto = parent;
parent = null;
}
var childProto;
if (parent) {
var fn = function () { };
fn.prototype = parent.prototype;
childProto = new fn();
_each(proto, function (key, val) {
childProto[key] = val;
});
} else {
childProto = proto;
}
childProto.constructor = child;
child.prototype = childProto;
child.parent = parent ? parent.prototype : null;
}
function _json(text) {
var match;
if ((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
text = match[0];
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
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, ''))) {
return eval('(' + text + ')');
}
throw 'JSON parse error';
}
var _round = Math.round;
var K = {
DEBUG: false,
VERSION: _VERSION,
IE: _IE,
GECKO: _GECKO,
WEBKIT: _WEBKIT,
OPERA: _OPERA,
V: _V,
TIME: _TIME,
each: _each,
isArray: _isArray,
isFunction: _isFunction,
inArray: _inArray,
inString: _inString,
trim: _trim,
addUnit: _addUnit,
removeUnit: _removeUnit,
escape: _escape,
unescape: _unescape,
toCamel: _toCamel,
toHex: _toHex,
toMap: _toMap,
toArray: _toArray,
undef: _undef,
invalidUrl: _invalidUrl,
addParam: _addParam,
extend: _extend,
json: _json
};
var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
_BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
_SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
_STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
_CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
_PRE_TAG_MAP = _toMap('pre,style,script'),
_NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
_AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
_FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
_VALUE_TAG_MAP = _toMap('input,button,textarea,select');
function _getBasePath() {
var els = document.getElementsByTagName('script'), src;
for (var i = 0, len = els.length; i < len; i++) {
src = els[i].src || '';
if (/kindeditor[\w\-\.]*\.js/.test(src)) {
return src.substring(0, src.lastIndexOf('/') + 1);
}
}
return '';
}
K.basePath = _getBasePath();
K.options = {
designMode: true,
fullscreenMode: false,
filterMode: true,
wellFormatMode: true,
shadowMode: true,
loadStyleMode: true,
basePath: K.basePath,
themesPath: K.basePath + 'themes/',
langPath: K.basePath + 'lang/',
pluginsPath: K.basePath,
themeType: 'default',
langType: 'zh_CN',
urlType: '',
newlineTag: 'p',
resizeType: 2,
syncType: 'form',
pasteType: 2,
dialogAlignType: 'page',
useContextmenu: true,
fullscreenShortcut: false,
bodyClass: 'ke-content',
indentChar: '\t',
cssPath: '',
cssData: '',
minWidth: 650,
minHeight: 100,
minChangeSize: 50,
zIndex: 811213,
items: [
'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
'anchor', 'link', 'unlink', '|', 'about'
],
noDisableItems: ['source', 'fullscreen'],
colorTable: [
['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
],
fontSizeTable: ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
htmlTags: {
font: ['id', 'class', 'color', 'size', 'face', '.background-color'],
span: [
'id', 'class', '.color', '.background-color', '.font-size', '.font-family', '.background',
'.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
],
div: [
'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color',
'.background-color', '.font-size', '.font-family', '.font-weight', '.background',
'.font-style', '.text-decoration', '.vertical-align', '.margin-left'
],
table: [
'id', 'class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
'.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
'.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
'.width', '.height', '.border-collapse'
],
'td,th': [
'id', 'class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
'.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
'.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
],
a: ['id', 'class', 'href', 'target', 'name'],
embed: ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
img: ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': [
'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
'.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
],
pre: ['id', 'class'],
hr: ['id', 'class', '.page-break-after'],
'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del': ['id', 'class'],
iframe: ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height']
},
layout: '<div class="container"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
};
var _useCapture = false;
var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
var _CURSORMOVE_KEY_MAP = _toMap('33..40');
var _CHANGE_KEY_MAP = {};
_each(_INPUT_KEY_MAP, function (key, val) {
_CHANGE_KEY_MAP[key] = val;
});
_each(_CURSORMOVE_KEY_MAP, function (key, val) {
_CHANGE_KEY_MAP[key] = val;
});
function _bindEvent(el, type, fn) {
if (el.addEventListener) {
el.addEventListener(type, fn, _useCapture);
} else if (el.attachEvent) {
el.attachEvent('on' + type, fn);
}
}
function _unbindEvent(el, type, fn) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, _useCapture);
} else if (el.detachEvent) {
el.detachEvent('on' + type, fn);
}
}
var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
'data,detail,eventPhase,fromElement,handler,keyCode,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
function KEvent(el, event) {
this.init(el, event);
}
_extend(KEvent, {
init: function (el, event) {
var self = this, doc = el.ownerDocument || el.document || el;
self.event = event;
_each(_EVENT_PROPS, function (key, val) {
self[val] = event[val];
});
if (!self.target) {
self.target = self.srcElement || doc;
}
if (self.target.nodeType === 3) {
self.target = self.target.parentNode;
}
if (!self.relatedTarget && self.fromElement) {
self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
}
if (self.pageX == null && self.clientX != null) {
var d = doc.documentElement, body = doc.body;
self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
}
if (!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
self.which = self.charCode || self.keyCode;
}
if (!self.metaKey && self.ctrlKey) {
self.metaKey = self.ctrlKey;
}
if (!self.which && self.button !== undefined) {
self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
}
switch (self.which) {
case 186:
self.which = 59;
break;
case 187:
case 107:
case 43:
self.which = 61;
break;
case 189:
case 45:
self.which = 109;
break;
case 42:
self.which = 106;
break;
case 47:
self.which = 111;
break;
case 78:
self.which = 110;
break;
}
if (self.which >= 96 && self.which <= 105) {
self.which -= 48;
}
},
preventDefault: function () {
var ev = this.event;
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
},
stopPropagation: function () {
var ev = this.event;
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
},
stop: function () {
this.preventDefault();
this.stopPropagation();
}
});
var _eventExpendo = 'kindeditor_' + _TIME, _eventId = 0, _eventData = {};
function _getId(el) {
return el[_eventExpendo] || null;
}
function _setId(el) {
el[_eventExpendo] = ++_eventId;
return _eventId;
}
function _removeId(el) {
try {
delete el[_eventExpendo];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(_eventExpendo);
}
}
}
function _bind(el, type, fn) {
if (type.indexOf(',') >= 0) {
_each(type.split(','), function () {
_bind(el, this, fn);
});
return;
}
var id = _getId(el);
if (!id) {
id = _setId(el);
}
if (_eventData[id] === undefined) {
_eventData[id] = {};
}
var events = _eventData[id][type];
if (events && events.length > 0) {
_unbindEvent(el, type, events[0]);
} else {
_eventData[id][type] = [];
_eventData[id].el = el;
}
events = _eventData[id][type];
if (events.length === 0) {
events[0] = function (e) {
var kevent = e ? new KEvent(el, e) : undefined;
_each(events, function (i, event) {
if (i > 0 && event) {
event.call(el, kevent);
}
});
};
}
if (_inArray(fn, events) < 0) {
events.push(fn);
}
_bindEvent(el, type, events[0]);
}
function _unbind(el, type, fn) {
if (type && type.indexOf(',') >= 0) {
_each(type.split(','), function () {
_unbind(el, this, fn);
});
return;
}
var id = _getId(el);
if (!id) {
return;
}
if (type === undefined) {
if (id in _eventData) {
_each(_eventData[id], function (key, events) {
if (key != 'el' && events.length > 0) {
_unbindEvent(el, key, events[0]);
}
});
delete _eventData[id];
_removeId(el);
}
return;
}
if (!_eventData[id]) {
return;
}
var events = _eventData[id][type];
if (events && events.length > 0) {
if (fn === undefined) {
_unbindEvent(el, type, events[0]);
delete _eventData[id][type];
} else {
_each(events, function (i, event) {
if (i > 0 && event === fn) {
events.splice(i, 1);
}
});
if (events.length == 1) {
_unbindEvent(el, type, events[0]);
delete _eventData[id][type];
}
}
var count = 0;
_each(_eventData[id], function () {
count++;
});
if (count < 2) {
delete _eventData[id];
_removeId(el);
}
}
}
function _fire(el, type) {
if (type.indexOf(',') >= 0) {
_each(type.split(','), function () {
_fire(el, this);
});
return;
}
var id = _getId(el);
if (!id) {
return;
}
var events = _eventData[id][type];
if (_eventData[id] && events && events.length > 0) {
events[0]();
}
}
function _ctrl(el, key, fn) {
var self = this;
key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
_bind(el, 'keydown', function (e) {
if (e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
fn.call(el);
e.stop();
}
});
}
var _readyFinished = false;
function _ready(fn) {
if (_readyFinished) {
fn(KindEditor);
return;
}
var loaded = false;
function readyFunc() {
if (!loaded) {
loaded = true;
fn(KindEditor);
_readyFinished = true;
}
}
function ieReadyFunc() {
if (!loaded) {
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(ieReadyFunc, 100);
return;
}
readyFunc();
}
}
function ieReadyStateFunc() {
if (document.readyState === 'complete') {
readyFunc();
}
}
if (document.addEventListener) {
_bind(document, 'DOMContentLoaded', readyFunc);
} else if (document.attachEvent) {
_bind(document, 'readystatechange', ieReadyStateFunc);
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch (e) { }
if (document.documentElement.doScroll && toplevel) {
ieReadyFunc();
}
}
_bind(window, 'load', readyFunc);
}
if (_IE) {
window.attachEvent('onunload', function () {
_each(_eventData, function (key, events) {
if (events.el) {
_unbind(events.el);
}
});
});
}
K.ctrl = _ctrl;
K.ready = _ready;
function _getCssList(css) {
var list = {},
reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
match;
while ((match = reg.exec(css))) {
var key = _trim(match[1].toLowerCase()),
val = _trim(_toHex(match[2]));
list[key] = val;
}
return list;
}
function _getAttrList(tag) {
var list = {},
reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
match;
while ((match = reg.exec(tag))) {
var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || '';
list[key] = val;
}
return list;
}
function _addClassToTag(tag, className) {
if (/\s+class\s*=/.test(tag)) {
tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function ($0, $1, $2, $3) {
if ((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
} else {
return $0;
}
});
} else {
tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
}
return tag;
}
function _formatCss(css) {
var str = '';
_each(_getCssList(css), function (key, val) {
str += key + ':' + val + ';';
});
return str;
}
function _formatUrl(url, mode, host, pathname) {
mode = _undef(mode, '').toLowerCase();
if (url.substr(0, 5) != 'data:') {
url = url.replace(/([^:])\/\//g, '$1/');
}
if (_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
return url;
}
host = host || location.protocol + '//' + location.host;
if (pathname === undefined) {
var m = location.pathname.match(/^(\/.*)\//);
pathname = m ? m[1] : '';
}
var match;
if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
if (match[1] !== host) {
return url;
}
} else if (/^\w+:/.test(url)) {
return url;
}
function getRealPath(path) {
var parts = path.split('/'), paths = [];
for (var i = 0, len = parts.length; i < len; i++) {
var part = parts[i];
if (part == '..') {
if (paths.length > 0) {
paths.pop();
}
} else if (part !== '' && part != '.') {
paths.push(part);
}
}
return '/' + paths.join('/');
}
if (/^\//.test(url)) {
url = host + getRealPath(url.substr(1));
} else if (!/^\w+:\/\//.test(url)) {
url = host + getRealPath(pathname + '/' + url);
}
function getRelativePath(path, depth) {
if (url.substr(0, path.length) === path) {
var arr = [];
for (var i = 0; i < depth; i++) {
arr.push('..');
}
var prefix = '.';
if (arr.length > 0) {
prefix += '/' + arr.join('/');
}
if (pathname == '/') {
prefix += '/';
}
return prefix + url.substr(path.length);
} else {
if ((match = /^(.*)\//.exec(path))) {
return getRelativePath(match[1], ++depth);
}
}
}
if (mode === 'relative') {
url = getRelativePath(host + pathname, 0).substr(2);
} else if (mode === 'absolute') {
if (url.substr(0, host.length) === host) {
url = url.substr(host.length);
}
}
return url;
}
function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
if (html == null) {
html = '';
}
urlType = urlType || '';
wellFormatted = _undef(wellFormatted, false);
indentChar = _undef(indentChar, '\t');
var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function ($0, $1, $2, $3) {
return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
});
html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
html = html.replace(/\u200B/g, '');
html = html.replace(/\u00A9/g, '©');
html = html.replace(/\u00AE/g, '®');
html = html.replace(/<[^>]+/g, function ($0) {
return $0.replace(/\s+/g, ' ');
});
var htmlTagMap = {};
if (htmlTags) {
_each(htmlTags, function (key, val) {
var arr = key.split(',');
for (var i = 0, len = arr.length; i < len; i++) {
htmlTagMap[arr[i]] = _toMap(val);
}
});
if (!htmlTagMap.script) {
html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
}
if (!htmlTagMap.style) {
html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
}
}
var re = /(\s*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>(\s*)/g;
var tagStack = [];
html = html.replace(re, function ($0, $1, $2, $3, $4, $5, $6) {
var full = $0,
startNewline = $1 || '',
startSlash = $2 || '',
tagName = $3.toLowerCase(),
attr = $4 || '',
endSlash = $5 ? ' ' + $5 : '',
endNewline = $6 || '';
if (htmlTags && !htmlTagMap[tagName]) {
return '';
}
if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
endSlash = ' /';
}
if (_INLINE_TAG_MAP[tagName]) {
if (startNewline) {
startNewline = ' ';
}
if (endNewline) {
endNewline = ' ';
}
}
if (_PRE_TAG_MAP[tagName]) {
if (startSlash) {
endNewline = '\n';
} else {
startNewline = '\n';
}
}
if (wellFormatted && tagName == 'br') {
endNewline = '\n';
}
if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
if (wellFormatted) {
if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
tagStack.pop();
} else {
tagStack.push(tagName);
}
startNewline = '\n';
endNewline = '\n';
for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
startNewline += indentChar;
if (!startSlash) {
endNewline += indentChar;
}
}
if (endSlash) {
tagStack.pop();
} else if (!startSlash) {
endNewline += indentChar;
}
} else {
startNewline = endNewline = '';
}
}
if (attr !== '') {
var attrMap = _getAttrList(full);
if (tagName === 'font') {
var fontStyleMap = {}, fontStyle = '';
_each(attrMap, function (key, val) {
if (key === 'color') {
fontStyleMap.color = val;
delete attrMap[key];
}
if (key === 'size') {
fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
delete attrMap[key];
}
if (key === 'face') {
fontStyleMap['font-family'] = val;
delete attrMap[key];
}
if (key === 'style') {
fontStyle = val;
}
});
if (fontStyle && !/;$/.test(fontStyle)) {
fontStyle += ';';
}
_each(fontStyleMap, function (key, val) {
if (val === '') {
return;
}
if (/\s/.test(val)) {
val = "'" + val + "'";
}
fontStyle += key + ':' + val + ';';
});
attrMap.style = fontStyle;
}
_each(attrMap, function (key, val) {
if (_FILL_ATTR_MAP[key]) {
attrMap[key] = key;
}
if (_inArray(key, ['src', 'href']) >= 0) {
attrMap[key] = _formatUrl(val, urlType);
}
if (htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
tagName === 'body' && key === 'contenteditable' ||
/^kindeditor_\d+$/.test(key)) {
delete attrMap[key];
}
if (key === 'style' && val !== '') {
var styleMap = _getCssList(val);
_each(styleMap, function (k, v) {
if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
delete styleMap[k];
}
});
var style = '';
_each(styleMap, function (k, v) {
style += k + ':' + v + ';';
});
attrMap.style = style;
}
});
attr = '';
_each(attrMap, function (key, val) {
if (key === 'style' && val === '') {
return;
}
val = val.replace(/"/g, '"');
attr += ' ' + key + '="' + val + '"';
});
}
if (tagName === 'font') {
tagName = 'span';
}
return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
});
html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function ($0, $1, $2, $3) {
return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
});
html = html.replace(/\n\s*\n/g, '\n');
html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
return _trim(html);
}
function _clearMsWord(html, htmlTags) {
html = html.replace(/<meta[\s\S]*?>/ig, '')
.replace(/<![\s\S]*?>/ig, '')
.replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
.replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
.replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
.replace(/<(?:table|td)[^>]*>/ig, function (full) {
return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
});
return _formatHtml(html, htmlTags);
}
function _mediaType(src) {
if (/\.(rm|rmvb)(\?|$)/i.test(src)) {
return 'audio/x-pn-realaudio-plugin';
}
if (/\.(swf|flv)(\?|$)/i.test(src)) {
return 'application/x-shockwave-flash';
}
return 'video/x-ms-asf-plugin';
}
function _mediaClass(type) {
if (/realaudio/i.test(type)) {
return 'ke-rm';
}
if (/flash/i.test(type)) {
return 'ke-flash';
}
return 'ke-media';
}
function _mediaAttrs(srcTag) {
return _getAttrList(unescape(srcTag));
}
function _mediaEmbed(attrs) {
var html = '<embed ';
_each(attrs, function (key, val) {
html += key + '="' + val + '" ';
});
html += '/>';
return html;
}
function _mediaImg(blankPath, attrs) {
var width = attrs.width,
height = attrs.height,
type = attrs.type || _mediaType(attrs.src),
srcTag = _mediaEmbed(attrs),
style = '';
if (/\D/.test(width)) {
style += 'width:' + width + ';';
} else if (width > 0) {
style += 'width:' + width + 'px;';
}
if (/\D/.test(height)) {
style += 'height:' + height + ';';
} else if (height > 0) {
style += 'height:' + height + 'px;';
}
var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
if (style !== '') {
html += 'style="' + style + '" ';
}
html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
return html;
}
function _tmpl(str, data) {
var fn = new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
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('');");
return data ? fn(data) : fn;
}
K.formatUrl = _formatUrl;
K.formatHtml = _formatHtml;
K.getCssList = _getCssList;
K.getAttrList = _getAttrList;
K.mediaType = _mediaType;
K.mediaAttrs = _mediaAttrs;
K.mediaEmbed = _mediaEmbed;
K.mediaImg = _mediaImg;
K.clearMsWord = _clearMsWord;
K.tmpl = _tmpl;
function _contains(nodeA, nodeB) {
if (nodeA.nodeType == 9 && nodeB.nodeType != 9) {
return true;
}
while ((nodeB = nodeB.parentNode)) {
if (nodeB == nodeA) {
return true;
}
}
return false;
}
var _getSetAttrDiv = document.createElement('div');
_getSetAttrDiv.setAttribute('className', 't');
var _GET_SET_ATTRIBUTE = _getSetAttrDiv.className !== 't';
function _getAttr(el, key) {
key = key.toLowerCase();
var val = null;
if (!_GET_SET_ATTRIBUTE && el.nodeName.toLowerCase() != 'script') {
var div = el.ownerDocument.createElement('div');
div.appendChild(el.cloneNode(false));
var list = _getAttrList(_unescape(div.innerHTML));
if (key in list) {
val = list[key];
}
} else {
try {
val = el.getAttribute(key, 2);
} catch (e) {
val = el.getAttribute(key, 1);
}
}
if (key === 'style' && val !== null) {
val = _formatCss(val);
}
return val;
}
function _queryAll(expr, root) {
var exprList = expr.split(',');
if (exprList.length > 1) {
var mergedResults = [];
_each(exprList, function () {
_each(_queryAll(this, root), function () {
if (_inArray(this, mergedResults) < 0) {
mergedResults.push(this);
}
});
});
return mergedResults;
}
root = root || document;
function escape(str) {
if (typeof str != 'string') {
return str;
}
return str.replace(/([^\w\-])/g, '\\$1');
}
function stripslashes(str) {
return str.replace(/\\/g, '');
}
function cmpTag(tagA, tagB) {
return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
}
function byId(id, tag, root) {
var arr = [],
doc = root.ownerDocument || root,
el = doc.getElementById(stripslashes(id));
if (el) {
if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
arr.push(el);
}
}
return arr;
}
function byClass(className, tag, root) {
var doc = root.ownerDocument || root, arr = [], els, i, len, el;
if (root.getElementsByClassName) {
els = root.getElementsByClassName(stripslashes(className));
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (cmpTag(tag, el.nodeName)) {
arr.push(el);
}
}
} else if (doc.querySelectorAll) {
els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (_contains(root, el)) {
arr.push(el);
}
}
} else {
els = root.getElementsByTagName(tag);
className = ' ' + className + ' ';
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
var cls = el.className;
if (cls && (' ' + cls + ' ').indexOf(className) > -1) {
arr.push(el);
}
}
}
}
return arr;
}
function byName(name, tag, root) {
var arr = [], doc = root.ownerDocument || root,
els = doc.getElementsByName(stripslashes(name)), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
if (el.getAttribute('name') !== null) {
arr.push(el);
}
}
}
return arr;
}
function byAttr(key, val, tag, root) {
var arr = [], els = root.getElementsByTagName(tag), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
if (val === null) {
if (_getAttr(el, key) !== null) {
arr.push(el);
}
} else {
if (val === escape(_getAttr(el, key))) {
arr.push(el);
}
}
}
}
return arr;
}
function select(expr, root) {
var arr = [], matches;
matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
var tag = matches ? matches[1] : '*';
if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
arr = byId(matches[1], tag, root);
} else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
arr = byClass(matches[1], tag, root);
} else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
arr = byAttr(matches[1].toLowerCase(), null, tag, root);
} else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
var key = matches[1].toLowerCase(), val = matches[2];
if (key === 'id') {
arr = byId(val, tag, root);
} else if (key === 'class') {
arr = byClass(val, tag, root);
} else if (key === 'name') {
arr = byName(val, tag, root);
} else {
arr = byAttr(key, val, tag, root);
}
} else {
var els = root.getElementsByTagName(tag), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
arr.push(el);
}
}
}
return arr;
}
var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
while ((arr = re.exec(expr))) {
if (arr[1] !== ' ') {
parts.push(arr[1]);
}
}
var results = [];
if (parts.length == 1) {
return select(parts[0], root);
}
var isChild = false, part, els, subResults, val, v, i, j, k, length, len, l;
for (i = 0, lenth = parts.length; i < lenth; i++) {
part = parts[i];
if (part === '>') {
isChild = true;
continue;
}
if (i > 0) {
els = [];
for (j = 0, len = results.length; j < len; j++) {
val = results[j];
subResults = select(part, val);
for (k = 0, l = subResults.length; k < l; k++) {
v = subResults[k];
if (isChild) {
if (val === v.parentNode) {
els.push(v);
}
} else {
els.push(v);
}
}
}
results = els;
} else {
results = select(part, root);
}
if (results.length === 0) {
return [];
}
}
return results;
}
function _query(expr, root) {
var arr = _queryAll(expr, root);
return arr.length > 0 ? arr[0] : null;
}
K.query = _query;
K.queryAll = _queryAll;
function _get(val) {
return K(val)[0];
}
function _getDoc(node) {
if (!node) {
return document;
}
return node.ownerDocument || node.document || node;
}
function _getWin(node) {
if (!node) {
return window;
}
var doc = _getDoc(node);
return doc.parentWindow || doc.defaultView;
}
function _setHtml(el, html) {
if (el.nodeType != 1) {
return;
}
var doc = _getDoc(el);
try {
el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
var temp = doc.getElementById('__kindeditor_temp_tag__');
temp.parentNode.removeChild(temp);
} catch (e) {
K(el).empty();
K('@' + html, doc).each(function () {
el.appendChild(this);
});
}
}
function _hasClass(el, cls) {
return _inString(cls, el.className, ' ');
}
function _setAttr(el, key, val) {
if (_IE && _V < 8 && key.toLowerCase() == 'class') {
key = 'className';
}
el.setAttribute(key, '' + val);
}
function _removeAttr(el, key) {
if (_IE && _V < 8 && key.toLowerCase() == 'class') {
key = 'className';
}
_setAttr(el, key, '');
el.removeAttribute(key);
}
function _getNodeName(node) {
if (!node || !node.nodeName) {
return '';
}
return node.nodeName.toLowerCase();
}
function _computedCss(el, key) {
var self = this, win = _getWin(el), camelKey = _toCamel(key), val = '';
if (win.getComputedStyle) {
var style = win.getComputedStyle(el, null);
val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
} else if (el.currentStyle) {
val = el.currentStyle[camelKey] || el.style[camelKey];
}
return val;
}
function _hasVal(node) {
return !!_VALUE_TAG_MAP[_getNodeName(node)];
}
function _docElement(doc) {
doc = doc || document;
return _QUIRKS ? doc.body : doc.documentElement;
}
function _docHeight(doc) {
var el = _docElement(doc);
return Math.max(el.scrollHeight, el.clientHeight);
}
function _docWidth(doc) {
var el = _docElement(doc);
return Math.max(el.scrollWidth, el.clientWidth);
}
function _getScrollPos(doc) {
doc = doc || document;
var x, y;
if (_IE || _NEWIE || _OPERA) {
x = _docElement(doc).scrollLeft;
y = _docElement(doc).scrollTop;
} else {
x = _getWin(doc).scrollX;
y = _getWin(doc).scrollY;
}
return { x: x, y: y };
}
function KNode(node) {
this.init(node);
}
_extend(KNode, {
init: function (node) {
var self = this;
node = _isArray(node) ? node : [node];
var length = 0;
for (var i = 0, len = node.length; i < len; i++) {
if (node[i]) {
self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
length++;
}
}
self.length = length;
self.doc = _getDoc(self[0]);
self.name = _getNodeName(self[0]);
self.type = self.length > 0 ? self[0].nodeType : null;
self.win = _getWin(self[0]);
},
each: function (fn) {
var self = this;
for (var i = 0; i < self.length; i++) {
if (fn.call(self[i], i, self[i]) === false) {
return self;
}
}
return self;
},
bind: function (type, fn) {
this.each(function () {
_bind(this, type, fn);
});
return this;
},
unbind: function (type, fn) {
this.each(function () {
_unbind(this, type, fn);
});
return this;
},
fire: function (type) {
if (this.length < 1) {
return this;
}
_fire(this[0], type);
return this;
},
hasAttr: function (key) {
if (this.length < 1) {
return false;
}
return !!_getAttr(this[0], key);
},
attr: function (key, val) {
var self = this;
if (key === undefined) {
return _getAttrList(self.outer());
}
if (typeof key === 'object') {
_each(key, function (k, v) {
self.attr(k, v);
});
return self;
}
if (val === undefined) {
val = self.length < 1 ? null : _getAttr(self[0], key);
return val === null ? '' : val;
}
self.each(function () {
_setAttr(this, key, val);
});
return self;
},
removeAttr: function (key) {
this.each(function () {
_removeAttr(this, key);
});
return this;
},
get: function (i) {
if (this.length < 1) {
return null;
}
return this[i || 0];
},
eq: function (i) {
if (this.length < 1) {
return null;
}
return this[i] ? new KNode(this[i]) : null;
},
hasClass: function (cls) {
if (this.length < 1) {
return false;
}
return _hasClass(this[0], cls);
},
addClass: function (cls) {
this.each(function () {
if (!_hasClass(this, cls)) {
this.className = _trim(this.className + ' ' + cls);
}
});
return this;
},
removeClass: function (cls) {
this.each(function () {
if (_hasClass(this, cls)) {
this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
}
});
return this;
},
html: function (val) {
var self = this;
if (val === undefined) {
if (self.length < 1 || self.type != 1) {
return '';
}
return _formatHtml(self[0].innerHTML);
}
self.each(function () {
_setHtml(this, val);
});
return self;
},
text: function () {
var self = this;
if (self.length < 1) {
return '';
}
return _IE ? self[0].innerText : self[0].textContent;
},
hasVal: function () {
if (this.length < 1) {
return false;
}
return _hasVal(this[0]);
},
val: function (val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return '';
}
return self.hasVal() ? self[0].value : self.attr('value');
} else {
self.each(function () {
if (_hasVal(this)) {
this.value = val;
} else {
_setAttr(this, 'value', val);
}
});
return self;
}
},
css: function (key, val) {
var self = this;
if (key === undefined) {
return _getCssList(self.attr('style'));
}
if (typeof key === 'object') {
_each(key, function (k, v) {
self.css(k, v);
});
return self;
}
if (val === undefined) {
if (self.length < 1) {
return '';
}
return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
}
self.each(function () {
this.style[_toCamel(key)] = val;
});
return self;
},
width: function (val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return 0;
}
return self[0].offsetWidth;
}
return self.css('width', _addUnit(val));
},
height: function (val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return 0;
}
return self[0].offsetHeight;
}
return self.css('height', _addUnit(val));
},
opacity: function (val) {
this.each(function () {
if (this.style.opacity === undefined) {
this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
} else {
this.style.opacity = val == 1 ? '' : val;
}
});
return this;
},
data: function (key, val) {
var self = this;
key = 'kindeditor_data_' + key;
if (val === undefined) {
if (self.length < 1) {
return null;
}
return self[0][key];
}
this.each(function () {
this[key] = val;
});
return self;
},
pos: function () {
var self = this, node = self[0], x = 0, y = 0;
if (node) {
if (node.getBoundingClientRect) {
var box = node.getBoundingClientRect(),
pos = _getScrollPos(self.doc);
x = box.left + pos.x;
y = box.top + pos.y;
} else {
while (node) {
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
}
}
return { x: _round(x), y: _round(y) };
},
clone: function (bool) {
if (this.length < 1) {
return new KNode([]);
}
return new KNode(this[0].cloneNode(bool));
},
append: function (expr) {
this.each(function () {
if (this.appendChild) {
this.appendChild(_get(expr));
}
});
return this;
},
appendTo: function (expr) {
this.each(function () {
_get(expr).appendChild(this);
});
return this;
},
before: function (expr) {
this.each(function () {
this.parentNode.insertBefore(_get(expr), this);
});
return this;
},
after: function (expr) {
this.each(function () {
if (this.nextSibling) {
this.parentNode.insertBefore(_get(expr), this.nextSibling);
} else {
this.parentNode.appendChild(_get(expr));
}
});
return this;
},
replaceWith: function (expr) {
var nodes = [];
this.each(function (i, node) {
_unbind(node);
var newNode = _get(expr);
node.parentNode.replaceChild(newNode, node);
nodes.push(newNode);
});
return K(nodes);
},
empty: function () {
var self = this;
self.each(function (i, node) {
var child = node.firstChild;
while (child) {
if (!node.parentNode) {
return;
}
var next = child.nextSibling;
child.parentNode.removeChild(child);
child = next;
}
});
return self;
},
remove: function (keepChilds) {
var self = this;
self.each(function (i, node) {
if (!node.parentNode) {
return;
}
_unbind(node);
if (keepChilds) {
var child = node.firstChild;
while (child) {
var next = child.nextSibling;
node.parentNode.insertBefore(child, node);
child = next;
}
}
node.parentNode.removeChild(node);
delete self[i];
});
self.length = 0;
return self;
},
show: function (val) {
var self = this;
if (val === undefined) {
val = self._originDisplay || '';
}
if (self.css('display') != 'none') {
return self;
}
return self.css('display', val);
},
hide: function () {
var self = this;
if (self.length < 1) {
return self;
}
self._originDisplay = self[0].style.display;
return self.css('display', 'none');
},
outer: function () {
var self = this;
if (self.length < 1) {
return '';
}
var div = self.doc.createElement('div'), html;
div.appendChild(self[0].cloneNode(true));
html = _formatHtml(div.innerHTML);
div = null;
return html;
},
isSingle: function () {
return !!_SINGLE_TAG_MAP[this.name];
},
isInline: function () {
return !!_INLINE_TAG_MAP[this.name];
},
isBlock: function () {
return !!_BLOCK_TAG_MAP[this.name];
},
isStyle: function () {
return !!_STYLE_TAG_MAP[this.name];
},
isControl: function () {
return !!_CONTROL_TAG_MAP[this.name];
},
contains: function (otherNode) {
if (this.length < 1) {
return false;
}
return _contains(this[0], _get(otherNode));
},
parent: function () {
if (this.length < 1) {
return null;
}
var node = this[0].parentNode;
return node ? new KNode(node) : null;
},
children: function () {
if (this.length < 1) {
return new KNode([]);
}
var list = [], child = this[0].firstChild;
while (child) {
if (child.nodeType != 3 || _trim(child.nodeValue) !== '') {
list.push(child);
}
child = child.nextSibling;
}
return new KNode(list);
},
first: function () {
var list = this.children();
return list.length > 0 ? list.eq(0) : null;
},
last: function () {
var list = this.children();
return list.length > 0 ? list.eq(list.length - 1) : null;
},
index: function () {
if (this.length < 1) {
return -1;
}
var i = -1, sibling = this[0];
while (sibling) {
i++;
sibling = sibling.previousSibling;
}
return i;
},
prev: function () {
if (this.length < 1) {
return null;
}
var node = this[0].previousSibling;
return node ? new KNode(node) : null;
},
next: function () {
if (this.length < 1) {
return null;
}
var node = this[0].nextSibling;
return node ? new KNode(node) : null;
},
scan: function (fn, order) {
if (this.length < 1) {
return;
}
order = (order === undefined) ? true : order;
function walk(node) {
var n = order ? node.firstChild : node.lastChild;
while (n) {
var next = order ? n.nextSibling : n.previousSibling;
if (fn(n) === false) {
return false;
}
if (walk(n) === false) {
return false;
}
n = next;
}
}
walk(this[0]);
return this;
}
});
_each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function (i, type) {
KNode.prototype[type] = function (fn) {
return fn ? this.bind(type, fn) : this.fire(type);
};
});
var _K = K;
K = function (expr, root) {
if (expr === undefined || expr === null) {
return;
}
function newNode(node) {
if (!node[0]) {
node = [];
}
return new KNode(node);
}
if (typeof expr === 'string') {
if (root) {
root = _get(root);
}
var length = expr.length;
if (expr.charAt(0) === '@') {
expr = expr.substr(1);
}
if (expr.length !== length || /<.+>/.test(expr)) {
var doc = root ? root.ownerDocument || root : document,
div = doc.createElement('div'), list = [];
div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
for (var i = 0, len = div.childNodes.length; i < len; i++) {
var child = div.childNodes[i];
if (child.id == '__kindeditor_temp_tag__') {
continue;
}
list.push(child);
}
return newNode(list);
}
return newNode(_queryAll(expr, root));
}
if (expr && expr.constructor === KNode) {
return expr;
}
if (expr.toArray) {
expr = expr.toArray();
}
if (_isArray(expr)) {
return newNode(expr);
}
return newNode(_toArray(arguments));
};
_each(_K, function (key, val) {
K[key] = val;
});
K.NodeClass = KNode;
window.KindEditor = K;
var _START_TO_START = 0,
_START_TO_END = 1,
_END_TO_END = 2,
_END_TO_START = 3,
_BOOKMARK_ID = 0;
function _updateCollapsed(range) {
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
return range;
}
function _copyAndDelete(range, isCopy, isDelete) {
var doc = range.doc, nodeList = [];
function splitTextNode(node, startOffset, endOffset) {
var length = node.nodeValue.length, centerNode;
if (isCopy) {
var cloneNode = node.cloneNode(true);
if (startOffset > 0) {
centerNode = cloneNode.splitText(startOffset);
} else {
centerNode = cloneNode;
}
if (endOffset < length) {
centerNode.splitText(endOffset - startOffset);
}
}
if (isDelete) {
var center = node;
if (startOffset > 0) {
center = node.splitText(startOffset);
range.setStart(node, startOffset);
}
if (endOffset < length) {
var right = center.splitText(endOffset - startOffset);
range.setEnd(right, 0);
}
nodeList.push(center);
}
return centerNode;
}
function removeNodes() {
if (isDelete) {
range.up().collapse(true);
}
for (var i = 0, len = nodeList.length; i < len; i++) {
var node = nodeList[i];
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
}
var copyRange = range.cloneRange().down();
var start = -1, incStart = -1, incEnd = -1, end = -1,
ancestor = range.commonAncestor(), frag = doc.createDocumentFragment();
if (ancestor.nodeType == 3) {
var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
if (isCopy) {
frag.appendChild(textNode);
}
removeNodes();
return isCopy ? frag : range;
}
function extractNodes(parent, frag) {
var node = parent.firstChild, nextNode;
while (node) {
var testRange = new KRange(doc).selectNode(node);
start = testRange.compareBoundaryPoints(_START_TO_END, range);
if (start >= 0 && incStart <= 0) {
incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
}
if (incStart >= 0 && incEnd <= 0) {
incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
}
if (incEnd >= 0 && end <= 0) {
end = testRange.compareBoundaryPoints(_END_TO_START, range);
}
if (end >= 0) {
return false;
}
nextNode = node.nextSibling;
if (start > 0) {
if (node.nodeType == 1) {
if (incStart >= 0 && incEnd <= 0) {
if (isCopy) {
frag.appendChild(node.cloneNode(true));
}
if (isDelete) {
nodeList.push(node);
}
} else {
var childFlag;
if (isCopy) {
childFlag = node.cloneNode(false);
frag.appendChild(childFlag);
}
if (extractNodes(node, childFlag) === false) {
return false;
}
}
} else if (node.nodeType == 3) {
var textNode;
if (node == copyRange.startContainer) {
textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
} else if (node == copyRange.endContainer) {
textNode = splitTextNode(node, 0, copyRange.endOffset);
} else {
textNode = splitTextNode(node, 0, node.nodeValue.length);
}
if (isCopy) {
try {
frag.appendChild(textNode);
} catch (e) { }
}
}
}
node = nextNode;
}
}
extractNodes(ancestor, frag);
if (isDelete) {
range.up().collapse(true);
}
for (var i = 0, len = nodeList.length; i < len; i++) {
var node = nodeList[i];
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
return isCopy ? frag : range;
}
function _moveToElementText(range, el) {
var node = el;
while (node) {
var knode = K(node);
if (knode.name == 'marquee' || knode.name == 'select') {
return;
}
node = node.parentNode;
}
try {
range.moveToElementText(el);
} catch (e) { }
}
function _getStartEnd(rng, isStart) {
var doc = rng.parentElement().ownerDocument,
pointRange = rng.duplicate();
pointRange.collapse(isStart);
var parent = pointRange.parentElement(),
nodes = parent.childNodes;
if (nodes.length === 0) {
return { node: parent.parentNode, offset: K(parent).index() };
}
var startNode = doc, startPos = 0, cmp = -1;
var testRange = rng.duplicate();
_moveToElementText(testRange, parent);
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
cmp = testRange.compareEndPoints('StartToStart', pointRange);
if (cmp === 0) {
return { node: node.parentNode, offset: i };
}
if (node.nodeType == 1) {
var nodeRange = rng.duplicate(), dummy, knode = K(node), newNode = node;
if (knode.isControl()) {
dummy = doc.createElement('span');
knode.after(dummy);
newNode = dummy;
startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
}
_moveToElementText(nodeRange, newNode);
testRange.setEndPoint('StartToEnd', nodeRange);
if (cmp > 0) {
startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
} else {
startPos = 0;
}
if (dummy) {
K(dummy).remove();
}
} else if (node.nodeType == 3) {
testRange.moveStart('character', node.nodeValue.length);
startPos += node.nodeValue.length;
}
if (cmp < 0) {
startNode = node;
}
}
if (cmp < 0 && startNode.nodeType == 1) {
return { node: parent, offset: K(parent.lastChild).index() + 1 };
}
if (cmp > 0) {
while (startNode.nextSibling && startNode.nodeType == 1) {
startNode = startNode.nextSibling;
}
}
testRange = rng.duplicate();
_moveToElementText(testRange, parent);
testRange.setEndPoint('StartToEnd', pointRange);
startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
if (cmp > 0 && startNode.nodeType == 3) {
var prevNode = startNode.previousSibling;
while (prevNode && prevNode.nodeType == 3) {
startPos -= prevNode.nodeValue.length;
prevNode = prevNode.previousSibling;
}
}
return { node: startNode, offset: startPos };
}
function _getEndRange(node, offset) {
var doc = node.ownerDocument || node,
range = doc.body.createTextRange();
if (doc == node) {
range.collapse(true);
return range;
}
if (node.nodeType == 1 && node.childNodes.length > 0) {
var children = node.childNodes, isStart, child;
if (offset === 0) {
child = children[0];
isStart = true;
} else {
child = children[offset - 1];
isStart = false;
}
if (!child) {
return range;
}
if (K(child).name === 'head') {
if (offset === 1) {
isStart = true;
}
if (offset === 2) {
isStart = false;
}
range.collapse(isStart);
return range;
}
if (child.nodeType == 1) {
var kchild = K(child), span;
if (kchild.isControl()) {
span = doc.createElement('span');
if (isStart) {
kchild.before(span);
} else {
kchild.after(span);
}
child = span;
}
_moveToElementText(range, child);
range.collapse(isStart);
if (span) {
K(span).remove();
}
return range;
}
node = child;
offset = isStart ? 0 : child.nodeValue.length;
}
var dummy = doc.createElement('span');
K(node).before(dummy);
_moveToElementText(range, dummy);
range.moveStart('character', offset);
K(dummy).remove();
return range;
}
function _toRange(rng) {
var doc, range;
function tr2td(start) {
if (K(start.node).name == 'tr') {
start.node = start.node.cells[start.offset];
start.offset = 0;
}
}
if (_IERANGE) {
if (rng.item) {
doc = _getDoc(rng.item(0));
range = new KRange(doc);
range.selectNode(rng.item(0));
return range;
}
doc = rng.parentElement().ownerDocument;
var start = _getStartEnd(rng, true),
end = _getStartEnd(rng, false);
tr2td(start);
tr2td(end);
range = new KRange(doc);
range.setStart(start.node, start.offset);
range.setEnd(end.node, end.offset);
return range;
}
var startContainer = rng.startContainer;
doc = startContainer.ownerDocument || startContainer;
range = new KRange(doc);
range.setStart(startContainer, rng.startOffset);
range.setEnd(rng.endContainer, rng.endOffset);
return range;
}
function KRange(doc) {
this.init(doc);
}
_extend(KRange, {
init: function (doc) {
var self = this;
self.startContainer = doc;
self.startOffset = 0;
self.endContainer = doc;
self.endOffset = 0;
self.collapsed = true;
self.doc = doc;
},
commonAncestor: function () {
function getParents(node) {
var parents = [];
while (node) {
parents.push(node);
node = node.parentNode;
}
return parents;
}
var parentsA = getParents(this.startContainer),
parentsB = getParents(this.endContainer),
i = 0, lenA = parentsA.length, lenB = parentsB.length, parentA, parentB;
while (++i) {
parentA = parentsA[lenA - i];
parentB = parentsB[lenB - i];
if (!parentA || !parentB || parentA !== parentB) {
break;
}
}
return parentsA[lenA - i + 1];
},
setStart: function (node, offset) {
var self = this, doc = self.doc;
self.startContainer = node;
self.startOffset = offset;
if (self.endContainer === doc) {
self.endContainer = node;
self.endOffset = offset;
}
return _updateCollapsed(this);
},
setEnd: function (node, offset) {
var self = this, doc = self.doc;
self.endContainer = node;
self.endOffset = offset;
if (self.startContainer === doc) {
self.startContainer = node;
self.startOffset = offset;
}
return _updateCollapsed(this);
},
setStartBefore: function (node) {
return this.setStart(node.parentNode || this.doc, K(node).index());
},
setStartAfter: function (node) {
return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
},
setEndBefore: function (node) {
return this.setEnd(node.parentNode || this.doc, K(node).index());
},
setEndAfter: function (node) {
return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
},
selectNode: function (node) {
return this.setStartBefore(node).setEndAfter(node);
},
selectNodeContents: function (node) {
var knode = K(node);
if (knode.type == 3 || knode.isSingle()) {
return this.selectNode(node);
}
var children = knode.children();
if (children.length > 0) {
return this.setStartBefore(children[0]).setEndAfter(children[children.length - 1]);
}
return this.setStart(node, 0).setEnd(node, 0);
},
collapse: function (toStart) {
if (toStart) {
return this.setEnd(this.startContainer, this.startOffset);
}
return this.setStart(this.endContainer, this.endOffset);
},
compareBoundaryPoints: function (how, range) {
var rangeA = this.get(), rangeB = range.get();
if (_IERANGE) {
var arr = {};
arr[_START_TO_START] = 'StartToStart';
arr[_START_TO_END] = 'EndToStart';
arr[_END_TO_END] = 'EndToEnd';
arr[_END_TO_START] = 'StartToEnd';
var cmp = rangeA.compareEndPoints(arr[how], rangeB);
if (cmp !== 0) {
return cmp;
}
var nodeA, nodeB, nodeC, posA, posB;
if (how === _START_TO_START || how === _END_TO_START) {
nodeA = this.startContainer;
posA = this.startOffset;
}
if (how === _START_TO_END || how === _END_TO_END) {
nodeA = this.endContainer;
posA = this.endOffset;
}
if (how === _START_TO_START || how === _START_TO_END) {
nodeB = range.startContainer;
posB = range.startOffset;
}
if (how === _END_TO_END || how === _END_TO_START) {
nodeB = range.endContainer;
posB = range.endOffset;
}
if (nodeA === nodeB) {
var diff = posA - posB;
return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
}
nodeC = nodeB;
while (nodeC && nodeC.parentNode !== nodeA) {
nodeC = nodeC.parentNode;
}
if (nodeC) {
return K(nodeC).index() >= posA ? -1 : 1;
}
nodeC = nodeA;
while (nodeC && nodeC.parentNode !== nodeB) {
nodeC = nodeC.parentNode;
}
if (nodeC) {
return K(nodeC).index() >= posB ? 1 : -1;
}
nodeC = K(nodeB).next();
if (nodeC && nodeC.contains(nodeA)) {
return 1;
}
nodeC = K(nodeA).next();
if (nodeC && nodeC.contains(nodeB)) {
return -1;
}
} else {
return rangeA.compareBoundaryPoints(how, rangeB);
}
},
cloneRange: function () {
return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
},
toString: function () {
var rng = this.get(), str = _IERANGE ? rng.text : rng.toString();
return str.replace(/\r\n|\n|\r/g, '');
},
cloneContents: function () {
return _copyAndDelete(this, true, false);
},
deleteContents: function () {
return _copyAndDelete(this, false, true);
},
extractContents: function () {
return _copyAndDelete(this, true, true);
},
insertNode: function (node) {
var self = this,
sc = self.startContainer, so = self.startOffset,
ec = self.endContainer, eo = self.endOffset,
firstChild, lastChild, c, nodeCount = 1;
if (node.nodeName.toLowerCase() === '#document-fragment') {
firstChild = node.firstChild;
lastChild = node.lastChild;
nodeCount = node.childNodes.length;
}
if (sc.nodeType == 1) {
c = sc.childNodes[so];
if (c) {
sc.insertBefore(node, c);
if (sc === ec) {
eo += nodeCount;
}
} else {
sc.appendChild(node);
}
} else if (sc.nodeType == 3) {
if (so === 0) {
sc.parentNode.insertBefore(node, sc);
if (sc.parentNode === ec) {
eo += nodeCount;
}
} else if (so >= sc.nodeValue.length) {
if (sc.nextSibling) {
sc.parentNode.insertBefore(node, sc.nextSibling);
} else {
sc.parentNode.appendChild(node);
}
} else {
if (so > 0) {
c = sc.splitText(so);
} else {
c = sc;
}
sc.parentNode.insertBefore(node, c);
if (sc === ec) {
ec = c;
eo -= so;
}
}
}
if (firstChild) {
self.setStartBefore(firstChild).setEndAfter(lastChild);
} else {
self.selectNode(node);
}
if (self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
return self;
}
return self.setEnd(ec, eo);
},
surroundContents: function (node) {
node.appendChild(this.extractContents());
return this.insertNode(node).selectNode(node);
},
isControl: function () {
var self = this,
sc = self.startContainer, so = self.startOffset,
ec = self.endContainer, eo = self.endOffset, rng;
return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
},
get: function (hasControlRange) {
var self = this, doc = self.doc, node, rng;
if (!_IERANGE) {
rng = doc.createRange();
try {
rng.setStart(self.startContainer, self.startOffset);
rng.setEnd(self.endContainer, self.endOffset);
} catch (e) { }
return rng;
}
if (hasControlRange && self.isControl()) {
rng = doc.body.createControlRange();
rng.addElement(self.startContainer.childNodes[self.startOffset]);
return rng;
}
var range = self.cloneRange().down();
rng = doc.body.createTextRange();
rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
return rng;
},
html: function () {
return K(this.cloneContents()).outer();
},
down: function () {
var self = this;
function downPos(node, pos, isStart) {
if (node.nodeType != 1) {
return;
}
var children = K(node).children();
if (children.length === 0) {
return;
}
var left, right, child, offset;
if (pos > 0) {
left = children.eq(pos - 1);
}
if (pos < children.length) {
right = children.eq(pos);
}
if (left && left.type == 3) {
child = left[0];
offset = child.nodeValue.length;
}
if (right && right.type == 3) {
child = right[0];
offset = 0;
}
if (!child) {
return;
}
if (isStart) {
self.setStart(child, offset);
} else {
self.setEnd(child, offset);
}
}
downPos(self.startContainer, self.startOffset, true);
downPos(self.endContainer, self.endOffset, false);
return self;
},
up: function () {
var self = this;
function upPos(node, pos, isStart) {
if (node.nodeType != 3) {
return;
}
if (pos === 0) {
if (isStart) {
self.setStartBefore(node);
} else {
self.setEndBefore(node);
}
} else if (pos == node.nodeValue.length) {
if (isStart) {
self.setStartAfter(node);
} else {
self.setEndAfter(node);
}
}
}
upPos(self.startContainer, self.startOffset, true);
upPos(self.endContainer, self.endOffset, false);
return self;
},
enlarge: function (toBlock) {
var self = this;
self.up();
function enlargePos(node, pos, isStart) {
var knode = K(node), parent;
if (knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
return;
}
if (pos === 0) {
while (!knode.prev()) {
parent = knode.parent();
if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
break;
}
knode = parent;
}
if (isStart) {
self.setStartBefore(knode[0]);
} else {
self.setEndBefore(knode[0]);
}
} else if (pos == knode.children().length) {
while (!knode.next()) {
parent = knode.parent();
if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
break;
}
knode = parent;
}
if (isStart) {
self.setStartAfter(knode[0]);
} else {
self.setEndAfter(knode[0]);
}
}
}
enlargePos(self.startContainer, self.startOffset, true);
enlargePos(self.endContainer, self.endOffset, false);
return self;
},
shrink: function () {
var self = this, child, collapsed = self.collapsed;
while (self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
self.setStart(child, 0);
}
if (collapsed) {
return self.collapse(collapsed);
}
while (self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
self.setEnd(child, child.childNodes.length);
}
return self;
},
createBookmark: function (serialize) {
var self = this, doc = self.doc, endNode,
startNode = K('<span style="display:none;"></span>', doc)[0];
startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
if (!self.collapsed) {
endNode = startNode.cloneNode(true);
endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
}
if (endNode) {
self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
}
self.insertNode(startNode).setStartAfter(startNode);
return {
start: serialize ? '#' + startNode.id : startNode,
end: endNode ? (serialize ? '#' + endNode.id : endNode) : null
};
},
moveToBookmark: function (bookmark) {
var self = this, doc = self.doc,
start = K(bookmark.start, doc), end = bookmark.end ? K(bookmark.end, doc) : null;
if (!start || start.length < 1) {
return self;
}
self.setStartBefore(start[0]);
start.remove();
if (end && end.length > 0) {
self.setEndBefore(end[0]);
end.remove();
} else {
self.collapse(true);
}
return self;
},
dump: function () {
console.log('--------------------');
console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
}
});
function _range(mixed) {
if (!mixed.nodeName) {
return mixed.constructor === KRange ? mixed : _toRange(mixed);
}
return new KRange(mixed);
}
K.RangeClass = KRange;
K.range = _range;
K.START_TO_START = _START_TO_START;
K.START_TO_END = _START_TO_END;
K.END_TO_END = _END_TO_END;
K.END_TO_START = _END_TO_START;
function _nativeCommand(doc, key, val) {
try {
doc.execCommand(key, false, val);
} catch (e) { }
}
function _nativeCommandValue(doc, key) {
var val = '';
try {
val = doc.queryCommandValue(key);
} catch (e) { }
if (typeof val !== 'string') {
val = '';
}
return val;
}
function _getSel(doc) {
var win = _getWin(doc);
return _IERANGE ? doc.selection : win.getSelection();
}
function _getRng(doc) {
var sel = _getSel(doc), rng;
try {
if (sel.rangeCount > 0) {
rng = sel.getRangeAt(0);
} else {
rng = sel.createRange();
}
} catch (e) { }
if (_IERANGE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
return null;
}
return rng;
}
function _singleKeyMap(map) {
var newMap = {}, arr, v;
_each(map, function (key, val) {
arr = key.split(',');
for (var i = 0, len = arr.length; i < len; i++) {
v = arr[i];
newMap[v] = val;
}
});
return newMap;
}
function _hasAttrOrCss(knode, map) {
return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
}
function _hasAttrOrCssByKey(knode, map, mapKey) {
mapKey = mapKey || knode.name;
if (knode.type !== 1) {
return false;
}
var newMap = _singleKeyMap(map);
if (!newMap[mapKey]) {
return false;
}
var arr = newMap[mapKey].split(',');
for (var i = 0, len = arr.length; i < len; i++) {
var key = arr[i];
if (key === '*') {
return true;
}
var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
var method = match[1] ? 'css' : 'attr';
key = match[2];
var val = match[3] || '';
if (val === '' && knode[method](key) !== '') {
return true;
}
if (val !== '' && knode[method](key) === val) {
return true;
}
}
return false;
}
function _removeAttrOrCss(knode, map) {
if (knode.type != 1) {
return;
}
_removeAttrOrCssByKey(knode, map, '*');
_removeAttrOrCssByKey(knode, map);
}
function _removeAttrOrCssByKey(knode, map, mapKey) {
mapKey = mapKey || knode.name;
if (knode.type !== 1) {
return;
}
var newMap = _singleKeyMap(map);
if (!newMap[mapKey]) {
return;
}
var arr = newMap[mapKey].split(','), allFlag = false;
for (var i = 0, len = arr.length; i < len; i++) {
var key = arr[i];
if (key === '*') {
allFlag = true;
break;
}
var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
key = match[2];
if (match[1]) {
key = _toCamel(key);
if (knode[0].style[key]) {
knode[0].style[key] = '';
}
} else {
knode.removeAttr(key);
}
}
if (allFlag) {
knode.remove(true);
}
}
function _getInnerNode(knode) {
var inner = knode;
while (inner.first()) {
inner = inner.first();
}
return inner;
}
function _isEmptyNode(knode) {
if (knode.type != 1 || knode.isSingle()) {
return false;
}
return knode.html().replace(/<[^>]+>/g, '') === '';
}
function _mergeWrapper(a, b) {
a = a.clone(true);
var lastA = _getInnerNode(a), childA = a, merged = false;
while (b) {
while (childA) {
if (childA.name === b.name) {
_mergeAttrs(childA, b.attr(), b.css());
merged = true;
}
childA = childA.first();
}
if (!merged) {
lastA.append(b.clone(false));
}
merged = false;
b = b.first();
}
return a;
}
function _wrapNode(knode, wrapper) {
wrapper = wrapper.clone(true);
if (knode.type == 3) {
_getInnerNode(wrapper).append(knode.clone(false));
knode.replaceWith(wrapper);
return wrapper;
}
var nodeWrapper = knode, child;
while ((child = knode.first()) && child.children().length == 1) {
knode = child;
}
child = knode.first();
var frag = knode.doc.createDocumentFragment();
while (child) {
frag.appendChild(child[0]);
child = child.next();
}
wrapper = _mergeWrapper(nodeWrapper, wrapper);
if (frag.firstChild) {
_getInnerNode(wrapper).append(frag);
}
nodeWrapper.replaceWith(wrapper);
return wrapper;
}
function _mergeAttrs(knode, attrs, styles) {
_each(attrs, function (key, val) {
if (key !== 'style') {
knode.attr(key, val);
}
});
_each(styles, function (key, val) {
knode.css(key, val);
});
}
function _inPreElement(knode) {
while (knode && knode.name != 'body') {
if (_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
return true;
}
knode = knode.parent();
}
return false;
}
function KCmd(range) {
this.init(range);
}
_extend(KCmd, {
init: function (range) {
var self = this, doc = range.doc;
self.doc = doc;
self.win = _getWin(doc);
self.sel = _getSel(doc);
self.range = range;
},
selection: function (forceReset) {
var self = this, doc = self.doc, rng = _getRng(doc);
self.sel = _getSel(doc);
if (rng) {
self.range = _range(rng);
if (K(self.range.startContainer).name == 'html') {
self.range.selectNodeContents(doc.body).collapse(false);
}
return self;
}
if (forceReset) {
self.range.selectNodeContents(doc.body).collapse(false);
}
return self;
},
select: function (hasDummy) {
hasDummy = _undef(hasDummy, true);
var self = this, sel = self.sel, range = self.range.cloneRange().shrink(),
sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset,
doc = _getDoc(sc), win = self.win, rng, hasU200b = false;
if (hasDummy && sc.nodeType == 1 && range.collapsed) {
if (_IERANGE) {
var dummy = K('<span> </span>', doc);
range.insertNode(dummy[0]);
rng = doc.body.createTextRange();
try {
rng.moveToElementText(dummy[0]);
} catch (ex) { }
rng.collapse(false);
rng.select();
dummy.remove();
win.focus();
return self;
}
if (_WEBKIT) {
var children = sc.childNodes;
if (K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
range.insertNode(doc.createTextNode('\u200B'));
hasU200b = true;
}
}
}
if (_IERANGE) {
try {
rng = range.get(true);
rng.select();
} catch (e) { }
} else {
if (hasU200b) {
range.collapse(false);
}
rng = range.get(true);
sel.removeAllRanges();
sel.addRange(rng);
if (doc !== document) {
var pos = K(rng.endContainer).pos();
win.scrollTo(pos.x, pos.y);
}
}
win.focus();
return self;
},
wrap: function (val) {
var self = this, doc = self.doc, range = self.range, wrapper;
wrapper = K(val, doc);
if (range.collapsed) {
range.shrink();
range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
return self;
}
if (wrapper.isBlock()) {
var copyWrapper = wrapper.clone(true), child = copyWrapper;
while (child.first()) {
child = child.first();
}
child.append(range.extractContents());
range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
return self;
}
range.enlarge();
var bookmark = range.createBookmark(), ancestor = range.commonAncestor(), isStart = false;
K(ancestor).scan(function (node) {
if (!isStart && node == bookmark.start) {
isStart = true;
return;
}
if (isStart) {
if (node == bookmark.end) {
return false;
}
var knode = K(node);
if (_inPreElement(knode)) {
return;
}
if (knode.type == 3 && _trim(node.nodeValue).length > 0) {
var parent;
while ((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
knode = parent;
}
_wrapNode(knode, wrapper);
}
}
});
range.moveToBookmark(bookmark);
return self;
},
split: function (isStart, map) {
var range = this.range, doc = range.doc;
var tempRange = range.cloneRange().collapse(isStart);
var node = tempRange.startContainer, pos = tempRange.startOffset,
parent = node.nodeType == 3 ? node.parentNode : node,
needSplit = false, knode;
while (parent && parent.parentNode) {
knode = K(parent);
if (map) {
if (!knode.isStyle()) {
break;
}
if (!_hasAttrOrCss(knode, map)) {
break;
}
} else {
if (_NOSPLIT_TAG_MAP[knode.name]) {
break;
}
}
needSplit = true;
parent = parent.parentNode;
}
if (needSplit) {
var dummy = doc.createElement('span');
range.cloneRange().collapse(!isStart).insertNode(dummy);
if (isStart) {
tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
} else {
tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
}
var frag = tempRange.extractContents(),
first = frag.firstChild, last = frag.lastChild;
if (isStart) {
tempRange.insertNode(frag);
range.setStartAfter(last).setEndBefore(dummy);
} else {
parent.appendChild(frag);
range.setStartBefore(dummy).setEndBefore(first);
}
var dummyParent = dummy.parentNode;
if (dummyParent == range.endContainer) {
var prev = K(dummy).prev(), next = K(dummy).next();
if (prev && next && prev.type == 3 && next.type == 3) {
range.setEnd(prev[0], prev[0].nodeValue.length);
} else if (!isStart) {
range.setEnd(range.endContainer, range.endOffset - 1);
}
}
dummyParent.removeChild(dummy);
}
return this;
},
remove: function (map) {
var self = this, doc = self.doc, range = self.range;
range.enlarge();
if (range.startOffset === 0) {
var ksc = K(range.startContainer), parent;
while ((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
ksc = parent;
}
range.setStart(ksc[0], 0);
ksc = K(range.startContainer);
if (ksc.isBlock()) {
_removeAttrOrCss(ksc, map);
}
var kscp = ksc.parent();
if (kscp && kscp.isBlock()) {
_removeAttrOrCss(kscp, map);
}
}
var sc, so;
if (range.collapsed) {
self.split(true, map);
sc = range.startContainer;
so = range.startOffset;
if (so > 0) {
var sb = K(sc.childNodes[so - 1]);
if (sb && _isEmptyNode(sb)) {
sb.remove();
range.setStart(sc, so - 1);
}
}
var sa = K(sc.childNodes[so]);
if (sa && _isEmptyNode(sa)) {
sa.remove();
}
if (_isEmptyNode(sc)) {
range.startBefore(sc);
sc.remove();
}
range.collapse(true);
return self;
}
self.split(true, map);
self.split(false, map);
var startDummy = doc.createElement('span'), endDummy = doc.createElement('span');
range.cloneRange().collapse(false).insertNode(endDummy);
range.cloneRange().collapse(true).insertNode(startDummy);
var nodeList = [], cmpStart = false;
K(range.commonAncestor()).scan(function (node) {
if (!cmpStart && node == startDummy) {
cmpStart = true;
return;
}
if (node == endDummy) {
return false;
}
if (cmpStart) {
nodeList.push(node);
}
});
K(startDummy).remove();
K(endDummy).remove();
sc = range.startContainer;
so = range.startOffset;
var ec = range.endContainer, eo = range.endOffset;
if (so > 0) {
var startBefore = K(sc.childNodes[so - 1]);
if (startBefore && _isEmptyNode(startBefore)) {
startBefore.remove();
range.setStart(sc, so - 1);
if (sc == ec) {
range.setEnd(ec, eo - 1);
}
}
var startAfter = K(sc.childNodes[so]);
if (startAfter && _isEmptyNode(startAfter)) {
startAfter.remove();
if (sc == ec) {
range.setEnd(ec, eo - 1);
}
}
}
var endAfter = K(ec.childNodes[range.endOffset]);
if (endAfter && _isEmptyNode(endAfter)) {
endAfter.remove();
}
var bookmark = range.createBookmark(true);
_each(nodeList, function (i, node) {
_removeAttrOrCss(K(node), map);
});
range.moveToBookmark(bookmark);
return self;
},
commonNode: function (map) {
var range = this.range;
var ec = range.endContainer, eo = range.endOffset,
node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
function find(node) {
var child = node, parent = node;
while (parent) {
if (_hasAttrOrCss(K(parent), map)) {
return K(parent);
}
parent = parent.parentNode;
}
while (child && (child = child.lastChild)) {
if (_hasAttrOrCss(K(child), map)) {
return K(child);
}
}
return null;
}
var cNode = find(node);
if (cNode) {
return cNode;
}
if (node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
var prev = K(node).prev();
if (prev) {
return find(prev);
}
}
return null;
},
commonAncestor: function (tagName) {
var range = this.range,
sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset,
startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
function find(node) {
while (node) {
if (node.nodeType == 1) {
if (node.tagName.toLowerCase() === tagName) {
return node;
}
}
node = node.parentNode;
}
return null;
}
var start = find(startNode), end = find(endNode);
if (start && end && start === end) {
return K(start);
}
return null;
},
state: function (key) {
var self = this, doc = self.doc, bool = false;
try {
bool = doc.queryCommandState(key);
} catch (e) { }
return bool;
},
val: function (key) {
var self = this, doc = self.doc, range = self.range;
function lc(val) {
return val.toLowerCase();
}
key = lc(key);
var val = '', knode;
if (key === 'fontfamily' || key === 'fontname') {
val = _nativeCommandValue(doc, 'fontname');
val = val.replace(/['"]/g, '');
return lc(val);
}
if (key === 'formatblock') {
val = _nativeCommandValue(doc, key);
if (val === '') {
knode = self.commonNode({ 'h1,h2,h3,h4,h5,h6,p,div,pre,address': '*' });
if (knode) {
val = knode.name;
}
}
if (val === 'Normal') {
val = 'p';
}
return lc(val);
}
if (key === 'fontsize') {
knode = self.commonNode({ '*': '.font-size' });
if (knode) {
val = knode.css('font-size');
}
return lc(val);
}
if (key === 'forecolor') {
knode = self.commonNode({ '*': '.color' });
if (knode) {
val = knode.css('color');
}
val = _toHex(val);
if (val === '') {
val = 'default';
}
return lc(val);
}
if (key === 'hilitecolor') {
knode = self.commonNode({ '*': '.background-color' });
if (knode) {
val = knode.css('background-color');
}
val = _toHex(val);
if (val === '') {
val = 'default';
}
return lc(val);
}
return val;
},
toggle: function (wrapper, map) {
var self = this;
if (self.commonNode(map)) {
self.remove(map);
} else {
self.wrap(wrapper);
}
return self.select();
},
bold: function () {
return this.toggle('<strong></strong>', {
span: '.font-weight=bold',
strong: '*',
b: '*'
});
},
italic: function () {
return this.toggle('<em></em>', {
span: '.font-style=italic',
em: '*',
i: '*'
});
},
underline: function () {
return this.toggle('<u></u>', {
span: '.text-decoration=underline',
u: '*'
});
},
strikethrough: function () {
return this.toggle('<s></s>', {
span: '.text-decoration=line-through',
s: '*'
});
},
forecolor: function (val) {
return this.wrap('<span style="color:' + val + ';"></span>').select();
},
hilitecolor: function (val) {
return this.wrap('<span style="background-color:' + val + ';"></span>').select();
},
fontsize: function (val) {
return this.wrap('<span style="font-size:' + val + ';"></span>').select();
},
fontname: function (val) {
return this.fontfamily(val);
},
fontfamily: function (val) {
return this.wrap('<span style="font-family:' + val + ';"></span>').select();
},
removeformat: function () {
var map = {
'*': '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
},
tags = _STYLE_TAG_MAP;
_each(tags, function (key, val) {
map[key] = '*';
});
this.remove(map);
return this.select();
},
inserthtml: function (val, quickMode) {
var self = this, range = self.range;
if (val === '') {
return self;
}
function pasteHtml(range, val) {
val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
var rng = range.get();
if (rng.item) {
rng.item(0).outerHTML = val;
} else {
rng.pasteHTML(val);
}
var temp = range.doc.getElementById('__kindeditor_temp_tag__');
temp.parentNode.removeChild(temp);
var newRange = _toRange(rng);
range.setEnd(newRange.endContainer, newRange.endOffset);
range.collapse(false);
self.select(false);
}
function insertHtml(range, val) {
var doc = range.doc,
frag = doc.createDocumentFragment();
K('@' + val, doc).each(function () {
frag.appendChild(this);
});
range.deleteContents();
range.insertNode(frag);
range.collapse(false);
self.select(false);
}
if (_IERANGE && quickMode) {
try {
pasteHtml(range, val);
} catch (e) {
insertHtml(range, val);
}
return self;
}
insertHtml(range, val);
return self;
},
hr: function () {
return this.inserthtml('<hr />');
},
print: function () {
this.win.print();
return this;
},
insertimage: function (url, title, width, height, border, align) {
title = _undef(title, '');
border = _undef(border, 0);
var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
if (width) {
html += 'width="' + _escape(width) + '" ';
}
if (height) {
html += 'height="' + _escape(height) + '" ';
}
if (title) {
html += 'title="' + _escape(title) + '" ';
}
if (align) {
html += 'align="' + _escape(align) + '" ';
}
html += 'alt="' + _escape(title) + '" ';
html += '/>';
return this.inserthtml(html);
},
createlink: function (url, type) {
var self = this, doc = self.doc, range = self.range;
self.select();
var a = self.commonNode({ a: '*' });
if (a && !range.isControl()) {
range.selectNode(a.get());
self.select();
}
var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
if (type) {
html += ' target="' + _escape(type) + '"';
}
if (range.collapsed) {
html += '>' + _escape(url) + '</a>';
return self.inserthtml(html);
}
if (range.isControl()) {
var node = K(range.startContainer.childNodes[range.startOffset]);
html += '></a>';
node.after(K(html, doc));
node.next().append(node);
range.selectNode(node[0]);
return self.select();
}
function setAttr(node, url, type) {
K(node).attr('href', url).attr('data-ke-src', url);
if (type) {
K(node).attr('target', type);
} else {
K(node).removeAttr('target');
}
}
var sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset;
if (sc.nodeType == 1 && sc === ec && so + 1 === eo) {
var child = sc.childNodes[so];
if (child.nodeName.toLowerCase() == 'a') {
setAttr(child, url, type);
return self;
}
}
_nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
K('a[href="__kindeditor_temp_url__"]', doc).each(function () {
setAttr(this, url, type);
});
return self;
},
unlink: function () {
var self = this, doc = self.doc, range = self.range;
self.select();
if (range.collapsed) {
var a = self.commonNode({ a: '*' });
if (a) {
range.selectNode(a.get());
self.select();
}
_nativeCommand(doc, 'unlink', null);
if (_WEBKIT && K(range.startContainer).name === 'img') {
var parent = K(range.startContainer).parent();
if (parent.name === 'a') {
parent.remove(true);
}
}
} else {
_nativeCommand(doc, 'unlink', null);
}
return self;
}
});
_each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function (i, name) {
KCmd.prototype[name] = function (val) {
var self = this;
self.select();
_nativeCommand(self.doc, name, val);
if (_IERANGE && _inArray(name, 'justifyleft,justifycenter,justifyright,justifyfull'.split(',')) >= 0) {
self.selection();
}
if (!_IERANGE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
self.selection();
}
return self;
};
});
_each('cut,copy,paste'.split(','), function (i, name) {
KCmd.prototype[name] = function () {
var self = this;
if (!self.doc.queryCommandSupported(name)) {
throw 'not supported';
}
self.select();
_nativeCommand(self.doc, name, null);
return self;
};
});
function _cmd(mixed) {
if (mixed.nodeName) {
var doc = _getDoc(mixed);
mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
}
return new KCmd(mixed);
}
K.CmdClass = KCmd;
K.cmd = _cmd;
function _drag(options) {
var moveEl = options.moveEl,
moveFn = options.moveFn,
clickEl = options.clickEl || moveEl,
beforeDrag = options.beforeDrag,
iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
var docs = [document];
if (iframeFix) {
K('iframe').each(function () {
var src = _formatUrl(this.src || '', 'absolute');
if (/^https?:\/\//.test(src)) {
return;
}
var doc;
try {
doc = _iframeDoc(this);
} catch (e) { }
if (doc) {
var pos = K(this).pos();
K(doc).data('pos-x', pos.x);
K(doc).data('pos-y', pos.y);
docs.push(doc);
}
});
}
clickEl.mousedown(function (e) {
e.stopPropagation();
var self = clickEl.get(),
x = _removeUnit(moveEl.css('left')),
y = _removeUnit(moveEl.css('top')),
width = moveEl.width(),
height = moveEl.height(),
pageX = e.pageX,
pageY = e.pageY;
if (beforeDrag) {
beforeDrag();
}
function moveListener(e) {
e.preventDefault();
var kdoc = K(_getDoc(e.target));
var diffX = _round((kdoc.data('pos-x') || 0) + e.pageX - pageX);
var diffY = _round((kdoc.data('pos-y') || 0) + e.pageY - pageY);
moveFn.call(clickEl, x, y, width, height, diffX, diffY);
}
function selectListener(e) {
e.preventDefault();
}
function upListener(e) {
e.preventDefault();
K(docs).unbind('mousemove', moveListener)
.unbind('mouseup', upListener)
.unbind('selectstart', selectListener);
if (self.releaseCapture) {
self.releaseCapture();
}
}
K(docs).mousemove(moveListener)
.mouseup(upListener)
.bind('selectstart', selectListener);
if (self.setCapture) {
self.setCapture();
}
});
}
function KWidget(options) {
this.init(options);
}
_extend(KWidget, {
init: function (options) {
var self = this;
self.name = options.name || '';
self.doc = options.doc || document;
self.win = _getWin(self.doc);
self.x = _addUnit(options.x);
self.y = _addUnit(options.y);
self.z = options.z;
self.width = _addUnit(options.width);
self.height = _addUnit(options.height);
self.div = K('<div style="display:block;"></div>');
self.options = options;
self._alignEl = options.alignEl;
if (self.width) {
self.div.css('width', self.width);
}
if (self.height) {
self.div.css('height', self.height);
}
if (self.z) {
self.div.css({
position: 'absolute',
left: self.x,
top: self.y,
'z-index': self.z
});
}
if (self.z && (self.x === undefined || self.y === undefined)) {
self.autoPos(self.width, self.height);
}
if (options.cls) {
self.div.addClass(options.cls);
}
if (options.shadowMode) {
self.div.addClass('ke-shadow');
}
if (options.css) {
self.div.css(options.css);
}
if (options.src) {
K(options.src).replaceWith(self.div);
} else {
K(self.doc.body).append(self.div);
}
if (options.html) {
self.div.html(options.html);
}
if (options.autoScroll) {
if (_IE && _V < 7 || _QUIRKS) {
var scrollPos = _getScrollPos();
K(self.win).bind('scroll', function (e) {
var pos = _getScrollPos(),
diffX = pos.x - scrollPos.x,
diffY = pos.y - scrollPos.y;
self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
});
} else {
self.div.css('position', 'fixed');
}
}
},
pos: function (x, y, updateProp) {
var self = this;
updateProp = _undef(updateProp, true);
if (x !== null) {
x = x < 0 ? 0 : _addUnit(x);
self.div.css('left', x);
if (updateProp) {
self.x = x;
}
}
if (y !== null) {
y = y < 0 ? 0 : _addUnit(y);
self.div.css('top', y);
if (updateProp) {
self.y = y;
}
}
return self;
},
autoPos: function (width, height) {
var self = this,
w = _removeUnit(width) || 0,
h = _removeUnit(height) || 0,
scrollPos = _getScrollPos();
if (self._alignEl) {
var knode = K(self._alignEl),
pos = knode.pos(),
diffX = _round(knode[0].clientWidth / 2 - w / 2),
diffY = _round(knode[0].clientHeight / 2 - h / 2);
x = diffX < 0 ? pos.x : pos.x + diffX;
y = diffY < 0 ? pos.y : pos.y + diffY;
} else {
var docEl = _docElement(self.doc);
x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
}
if (!(_IE && _V < 7 || _QUIRKS)) {
x -= scrollPos.x;
y -= scrollPos.y;
}
return self.pos(x, y);
},
remove: function () {
var self = this;
if (_IE && _V < 7 || _QUIRKS) {
K(self.win).unbind('scroll');
}
self.div.remove();
_each(self, function (i) {
self[i] = null;
});
return this;
},
show: function () {
this.div.show();
return this;
},
hide: function () {
this.div.hide();
return this;
},
draggable: function (options) {
var self = this;
options = options || {};
options.moveEl = self.div;
options.moveFn = function (x, y, width, height, diffX, diffY) {
if ((x = x + diffX) < 0) {
x = 0;
}
if ((y = y + diffY) < 0) {
y = 0;
}
self.pos(x, y);
};
_drag(options);
return self;
}
});
function _widget(options) {
return new KWidget(options);
}
K.WidgetClass = KWidget;
K.widget = _widget;
function _iframeDoc(iframe) {
iframe = _get(iframe);
return iframe.contentDocument || iframe.contentWindow.document;
}
var html, _direction = '';
if ((html = document.getElementsByTagName('html'))) {
_direction = html[0].dir;
}
function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
var arr = [
(_direction === '' ? '<html>' : '<html dir="' + _direction + '">'),
'<head><meta charset="utf-8" /><title></title>',
'<style>',
'html {margin:0;padding:0;}',
'body {margin:0;padding:5px;}',
'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
'body, p, div {word-wrap: break-word;}',
'p {margin:5px 0;}',
'table {border-collapse:collapse;}',
'img {border:0;}',
'noscript {display:none;}',
'table.ke-zeroborder td {border:1px dotted #AAA;}',
'img.ke-flash {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/flash.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-rm {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/rm.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-media {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/media.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-anchor {',
' border:1px dashed #666;',
' width:16px;',
' height:16px;',
'}',
'.ke-script, .ke-noscript, .ke-display-none {',
' display:none;',
' font-size:0;',
' width:0;',
' height:0;',
'}',
'.ke-pagebreak {',
' border:1px dotted #AAA;',
' font-size:0;',
' height:2px;',
'}',
'</style>'
];
if (!_isArray(cssPath)) {
cssPath = [cssPath];
}
_each(cssPath, function (i, path) {
if (path) {
arr.push('<link href="' + path + '" rel="stylesheet" />');
}
});
if (cssData) {
arr.push('<style>' + cssData + '</style>');
}
arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
return arr.join('\n');
}
function _elementVal(knode, val) {
if (knode.hasVal()) {
if (val === undefined) {
var html = knode.val();
html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
return html;
}
return knode.val(val);
}
return knode.html(val);
}
function KEdit(options) {
this.init(options);
}
_extend(KEdit, KWidget, {
init: function (options) {
var self = this;
KEdit.parent.init.call(self, options);
self.srcElement = K(options.srcElement);
self.div.addClass('ke-edit');
self.designMode = _undef(options.designMode, true);
self.beforeGetHtml = options.beforeGetHtml;
self.beforeSetHtml = options.beforeSetHtml;
self.afterSetHtml = options.afterSetHtml;
var themesPath = _undef(options.themesPath, ''),
bodyClass = options.bodyClass,
cssPath = options.cssPath,
cssData = options.cssData,
isDocumentDomain = location.protocol != 'res:' && location.host.replace(/:\d+/, '') !== document.domain,
srcScript = ('document.open();' +
(isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
'document.close();'),
iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
self.tabIndex = isNaN(parseInt(options.tabIndex, 10)) ? self.srcElement.attr('tabindex') : parseInt(options.tabIndex, 10);
self.iframe.attr('tabindex', self.tabIndex);
self.textarea.attr('tabindex', self.tabIndex);
if (self.width) {
self.setWidth(self.width);
}
if (self.height) {
self.setHeight(self.height);
}
if (self.designMode) {
self.textarea.hide();
} else {
self.iframe.hide();
}
function ready() {
var doc = _iframeDoc(self.iframe);
doc.open();
if (isDocumentDomain) {
doc.domain = document.domain;
}
doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
doc.close();
self.win = self.iframe[0].contentWindow;
self.doc = doc;
var cmd = _cmd(doc);
self.afterChange(function (e) {
cmd.selection();
});
if (_WEBKIT) {
K(doc).click(function (e) {
if (K(e.target).name === 'img') {
cmd.selection(true);
cmd.range.selectNode(e.target);
cmd.select();
}
});
}
if (_IE) {
self._mousedownHandler = function () {
var newRange = cmd.range.cloneRange();
newRange.shrink();
if (newRange.isControl()) {
self.blur();
}
};
K(document).mousedown(self._mousedownHandler);
K(doc).keydown(function (e) {
if (e.which == 8) {
cmd.selection();
var rng = cmd.range;
if (rng.isControl()) {
rng.collapse(true);
K(rng.startContainer.childNodes[rng.startOffset]).remove();
e.preventDefault();
}
}
});
}
self.cmd = cmd;
self.html(_elementVal(self.srcElement));
if (_IE) {
doc.body.disabled = true;
doc.body.contentEditable = true;
doc.body.removeAttribute('disabled');
} else {
doc.designMode = 'on';
}
if (options.afterCreate) {
options.afterCreate.call(self);
}
}
if (isDocumentDomain) {
self.iframe.bind('load', function (e) {
self.iframe.unbind('load');
if (_IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
}
self.div.append(self.iframe);
self.div.append(self.textarea);
self.srcElement.hide();
!isDocumentDomain && ready();
},
setWidth: function (val) {
var self = this;
val = _addUnit(val);
self.width = val;
self.div.css('width', val);
return self;
},
setHeight: function (val) {
var self = this;
val = _addUnit(val);
self.height = val;
self.div.css('height', val);
self.iframe.css('height', val);
if ((_IE && _V < 8) || _QUIRKS) {
val = _addUnit(_removeUnit(val) - 2);
}
self.textarea.css('height', val);
return self;
},
remove: function () {
var self = this, doc = self.doc;
K(doc.body).unbind();
K(doc).unbind();
K(self.win).unbind();
if (self._mousedownHandler) {
K(document).unbind('mousedown', self._mousedownHandler);
}
_elementVal(self.srcElement, self.html());
self.srcElement.show();
doc.write('');
self.iframe.unbind();
self.textarea.unbind();
KEdit.parent.remove.call(self);
},
html: function (val, isFull) {
var self = this, doc = self.doc;
if (self.designMode) {
var body = doc.body;
if (val === undefined) {
if (isFull) {
val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
} else {
val = body.innerHTML;
}
if (self.beforeGetHtml) {
val = self.beforeGetHtml(val);
}
if (_GECKO && val == '<br />') {
val = '';
}
return val;
}
if (self.beforeSetHtml) {
val = self.beforeSetHtml(val);
}
if (_IE && _V >= 9) {
val = val.replace(/(<.*?checked=")checked(".*>)/ig, '$1$2');
}
K(body).html(val);
if (self.afterSetHtml) {
self.afterSetHtml();
}
return self;
}
if (val === undefined) {
return self.textarea.val();
}
self.textarea.val(val);
return self;
},
design: function (bool) {
var self = this, val;
if (bool === undefined ? !self.designMode : bool) {
if (!self.designMode) {
val = self.html();
self.designMode = true;
self.html(val);
self.textarea.hide();
self.iframe.show();
}
} else {
if (self.designMode) {
val = self.html();
self.designMode = false;
self.html(val);
self.iframe.hide();
self.textarea.show();
}
}
return self.focus();
},
focus: function () {
var self = this;
self.designMode ? self.win.focus() : self.textarea[0].focus();
return self;
},
blur: function () {
var self = this;
if (_IE) {
var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
self.div.append(input);
input[0].focus();
input.remove();
} else {
self.designMode ? self.win.blur() : self.textarea[0].blur();
}
return self;
},
afterChange: function (fn) {
var self = this, doc = self.doc, body = doc.body;
K(doc).keyup(function (e) {
if (!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
fn(e);
}
});
K(doc).mouseup(fn).contextmenu(fn);
K(self.win).blur(fn);
function timeoutHandler(e) {
setTimeout(function () {
fn(e);
}, 1);
}
K(body).bind('paste', timeoutHandler);
K(body).bind('cut', timeoutHandler);
return self;
}
});
function _edit(options) {
return new KEdit(options);
}
K.EditClass = KEdit;
K.edit = _edit;
K.iframeDoc = _iframeDoc;
function _selectToolbar(name, fn) {
var self = this,
knode = self.get(name);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
fn(knode);
}
}
function KToolbar(options) {
this.init(options);
}
_extend(KToolbar, KWidget, {
init: function (options) {
var self = this;
KToolbar.parent.init.call(self, options);
self.disableMode = _undef(options.disableMode, false);
self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
self._itemMap = {};
self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function (e) {
e.preventDefault();
}).attr('unselectable', 'on');
function find(target) {
var knode = K(target);
if (knode.hasClass('ke-outline')) {
return knode;
}
if (knode.hasClass('ke-toolbar-icon')) {
return knode.parent();
}
}
function hover(e, method) {
var knode = find(e.target);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
if (knode.hasClass('ke-selected')) {
return;
}
knode[method]('ke-on');
}
}
self.div.mouseover(function (e) {
hover(e, 'addClass');
})
.mouseout(function (e) {
hover(e, 'removeClass');
})
.click(function (e) {
var knode = find(e.target);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
self.options.click.call(this, e, knode.attr('data-name'));
}
});
},
get: function (name) {
if (this._itemMap[name]) {
return this._itemMap[name];
}
return (this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
},
select: function (name) {
_selectToolbar.call(this, name, function (knode) {
knode.addClass('ke-selected');
});
return self;
},
unselect: function (name) {
_selectToolbar.call(this, name, function (knode) {
knode.removeClass('ke-selected').removeClass('ke-on');
});
return self;
},
enable: function (name) {
var self = this,
knode = name.get ? name : self.get(name);
if (knode) {
knode.removeClass('ke-disabled');
knode.opacity(1);
}
return self;
},
disable: function (name) {
var self = this,
knode = name.get ? name : self.get(name);
if (knode) {
knode.removeClass('ke-selected').addClass('ke-disabled');
knode.opacity(0.5);
}
return self;
},
disableAll: function (bool, noDisableItems) {
var self = this, map = self.noDisableItemMap, item;
if (noDisableItems) {
map = _toMap(noDisableItems);
}
if (bool === undefined ? !self.disableMode : bool) {
K('span.ke-outline', self.div).each(function () {
var knode = K(this),
name = knode[0].getAttribute('data-name', 2);
if (!map[name]) {
self.disable(knode);
}
});
self.disableMode = true;
} else {
K('span.ke-outline', self.div).each(function () {
var knode = K(this),
name = knode[0].getAttribute('data-name', 2);
if (!map[name]) {
self.enable(knode);
}
});
self.disableMode = false;
}
return self;
}
});
function _toolbar(options) {
return new KToolbar(options);
}
K.ToolbarClass = KToolbar;
K.toolbar = _toolbar;
function KMenu(options) {
this.init(options);
}
_extend(KMenu, KWidget, {
init: function (options) {
var self = this;
options.z = options.z || 811213;
KMenu.parent.init.call(self, options);
self.centerLineMode = _undef(options.centerLineMode, true);
self.div.addClass('ke-menu').bind('click,mousedown', function (e) {
e.stopPropagation();
}).attr('unselectable', 'on');
},
addItem: function (item) {
var self = this;
if (item.title === '-') {
self.div.append(K('<div class="ke-menu-separator"></div>'));
return;
}
var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
height = _addUnit(item.height),
iconClass = _undef(item.iconClass, '');
self.div.append(itemDiv);
if (height) {
itemDiv.css('height', height);
rightDiv.css('line-height', height);
}
var centerDiv;
if (self.centerLineMode) {
centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
if (height) {
centerDiv.css('height', height);
}
}
itemDiv.mouseover(function (e) {
K(this).addClass('ke-menu-item-on');
if (centerDiv) {
centerDiv.addClass('ke-menu-item-center-on');
}
})
.mouseout(function (e) {
K(this).removeClass('ke-menu-item-on');
if (centerDiv) {
centerDiv.removeClass('ke-menu-item-center-on');
}
})
.click(function (e) {
item.click.call(K(this));
e.stopPropagation();
})
.append(leftDiv);
if (centerDiv) {
itemDiv.append(centerDiv);
}
itemDiv.append(rightDiv);
if (item.checked) {
iconClass = 'ke-icon-checked';
}
if (iconClass !== '') {
leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
}
rightDiv.html(item.title);
return self;
},
remove: function () {
var self = this;
if (self.options.beforeRemove) {
self.options.beforeRemove.call(self);
}
K('.ke-menu-item', self.div[0]).unbind();
KMenu.parent.remove.call(self);
return self;
}
});
function _menu(options) {
return new KMenu(options);
}
K.MenuClass = KMenu;
K.menu = _menu;
function KColorPicker(options) {
this.init(options);
}
_extend(KColorPicker, KWidget, {
init: function (options) {
var self = this;
options.z = options.z || 811213;
KColorPicker.parent.init.call(self, options);
var colors = options.colors || [
['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
];
self.selectedColor = (options.selectedColor || '').toLowerCase();
self._cells = [];
self.div.addClass('ke-colorpicker').bind('click,mousedown', function (e) {
e.stopPropagation();
}).attr('unselectable', 'on');
var table = self.doc.createElement('table');
self.div.append(table);
table.className = 'ke-colorpicker-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var row = table.insertRow(0), cell = row.insertCell(0);
cell.colSpan = colors[0].length;
self._addAttr(cell, '', 'ke-colorpicker-cell-top');
for (var i = 0; i < colors.length; i++) {
row = table.insertRow(i + 1);
for (var j = 0; j < colors[i].length; j++) {
cell = row.insertCell(j);
self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
}
}
},
_addAttr: function (cell, color, cls) {
var self = this;
cell = K(cell).addClass(cls);
if (self.selectedColor === color.toLowerCase()) {
cell.addClass('ke-colorpicker-cell-selected');
}
cell.attr('title', color || self.options.noColor);
cell.mouseover(function (e) {
K(this).addClass('ke-colorpicker-cell-on');
});
cell.mouseout(function (e) {
K(this).removeClass('ke-colorpicker-cell-on');
});
cell.click(function (e) {
e.stop();
self.options.click.call(K(this), color);
});
if (color) {
cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
} else {
cell.html(self.options.noColor);
}
K(cell).attr('unselectable', 'on');
self._cells.push(cell);
},
remove: function () {
var self = this;
_each(self._cells, function () {
this.unbind();
});
KColorPicker.parent.remove.call(self);
return self;
}
});
function _colorpicker(options) {
return new KColorPicker(options);
}
K.ColorPickerClass = KColorPicker;
K.colorpicker = _colorpicker;
function KUploadButton(options) {
this.init(options);
}
_extend(KUploadButton, {
init: function (options) {
var self = this,
button = K(options.button),
fieldName = options.fieldName || 'file',
url = options.url || '',
title = button.val(),
extraParams = options.extraParams || {},
cls = button[0].className || '',
target = options.target || 'kindeditor_upload_iframe_' + new Date().getTime();
options.afterError = options.afterError || function (str) {
alert(str);
};
var hiddenElements = [];
for (var k in extraParams) {
hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
}
var html = [
'<div class="ke-inline-block ' + cls + '">',
(options.target ? '' : '<iframe name="' + target + '" style="display:none;"></iframe>'),
(options.form ? '<div class="ke-upload-area">' : '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">'),
'<span class="ke-button-common">',
hiddenElements.join(''),
'<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
'</span>',
'<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
(options.form ? '</div>' : '</form>'),
'</div>'].join('');
var div = K(html, button.doc);
button.hide();
button.before(div);
self.div = div;
self.button = button;
self.iframe = options.target ? K('iframe[name="' + target + '"]') : K('iframe', div);
self.form = options.form ? K(options.form) : K('form', div);
self.fileBox = K('.ke-upload-file', div);
var width = options.width || K('.ke-button-common', div).width();
K('.ke-upload-area', div).width(width);
self.options = options;
},
submit: function () {
var self = this,
iframe = self.iframe;
iframe.bind('load', function () {
iframe.unbind();
var tempForm = document.createElement('form');
self.fileBox.before(tempForm);
K(tempForm).append(self.fileBox);
tempForm.reset();
K(tempForm).remove(true);
var doc = K.iframeDoc(iframe),
pre = doc.getElementsByTagName('pre')[0],
str = '', data;
if (pre) {
str = pre.innerHTML;
} else {
str = doc.body.innerHTML;
}
str = _unescape(str);
iframe[0].src = 'javascript:false';
try {
data = K.json(str);
} catch (e) {
self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
}
if (data) {
self.options.afterUpload.call(self, data);
}
});
self.form[0].submit();
return self;
},
remove: function () {
var self = this;
if (self.fileBox) {
self.fileBox.unbind();
}
self.iframe.remove();
self.div.remove();
self.button.show();
return self;
}
});
function _uploadbutton(options) {
return new KUploadButton(options);
}
K.UploadButtonClass = KUploadButton;
K.uploadbutton = _uploadbutton;
function _createButton(arg) {
arg = arg || {};
var name = arg.name || '',
span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
if (arg.click) {
btn.click(arg.click);
}
span.append(btn);
return span;
}
function KDialog(options) {
this.init(options);
}
_extend(KDialog, KWidget, {
init: function (options) {
var self = this;
var shadowMode = _undef(options.shadowMode, true);
options.z = options.z || 811213;
options.shadowMode = false;
options.autoScroll = _undef(options.autoScroll, true);
KDialog.parent.init.call(self, options);
var title = options.title,
body = K(options.body, self.doc),
previewBtn = options.previewBtn,
yesBtn = options.yesBtn,
noBtn = options.noBtn,
closeBtn = options.closeBtn,
showMask = _undef(options.showMask, true);
self.div.addClass('ke-dialog').bind('click,mousedown', function (e) {
e.stopPropagation();
});
var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
if (_IE && _V < 7) {
self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
} else if (shadowMode) {
K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
}
var headerDiv = K('<div class="ke-dialog-header"></div>');
contentDiv.append(headerDiv);
headerDiv.html(title);
self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
headerDiv.append(self.closeIcon);
self.draggable({
clickEl: headerDiv,
beforeDrag: options.beforeDrag
});
var bodyDiv = K('<div class="ke-dialog-body"></div>');
contentDiv.append(bodyDiv);
bodyDiv.append(body);
var footerDiv = K('<div class="ke-dialog-footer"></div>');
if (previewBtn || yesBtn || noBtn) {
contentDiv.append(footerDiv);
}
_each([
{ btn: previewBtn, name: 'preview' },
{ btn: yesBtn, name: 'yes' },
{ btn: noBtn, name: 'no' }
], function () {
if (this.btn) {
var button = _createButton(this.btn);
button.addClass('ke-dialog-' + this.name);
footerDiv.append(button);
}
});
if (self.height) {
bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
}
self.div.width(self.div.width());
self.div.height(self.div.height());
self.mask = null;
if (showMask) {
var docEl = _docElement(self.doc),
docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
self.mask = _widget({
x: 0,
y: 0,
z: self.z - 1,
cls: 'ke-dialog-mask',
width: docWidth,
height: docHeight
});
}
self.autoPos(self.div.width(), self.div.height());
self.footerDiv = footerDiv;
self.bodyDiv = bodyDiv;
self.headerDiv = headerDiv;
self.isLoading = false;
},
setMaskIndex: function (z) {
var self = this;
self.mask.div.css('z-index', z);
},
showLoading: function (msg) {
msg = _undef(msg, '');
var self = this, body = self.bodyDiv;
self.loading = K('<div class="ke-dialog-loading"><div class="ke-inline-block ke-dialog-loading-content" style="margin-top:' + Math.round(body.height() / 3) + 'px;">' + msg + '</div></div>')
.width(body.width()).height(body.height())
.css('top', self.headerDiv.height() + 'px');
body.css('visibility', 'hidden').after(self.loading);
self.isLoading = true;
return self;
},
hideLoading: function () {
this.loading && this.loading.remove();
this.bodyDiv.css('visibility', 'visible');
this.isLoading = false;
return this;
},
remove: function () {
var self = this;
if (self.options.beforeRemove) {
self.options.beforeRemove.call(self);
}
self.mask && self.mask.remove();
self.iframeMask && self.iframeMask.remove();
self.closeIcon.unbind();
K('input', self.div).unbind();
K('button', self.div).unbind();
self.footerDiv.unbind();
self.bodyDiv.unbind();
self.headerDiv.unbind();
K('iframe', self.div).each(function () {
K(this).remove();
});
KDialog.parent.remove.call(self);
return self;
}
});
function _dialog(options) {
return new KDialog(options);
}
K.DialogClass = KDialog;
K.dialog = _dialog;
function _tabs(options) {
var self = _widget(options),
remove = self.remove,
afterSelect = options.afterSelect,
div = self.div,
liList = [];
div.addClass('ke-tabs')
.bind('contextmenu,mousedown,mousemove', function (e) {
e.preventDefault();
});
var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
div.append(ul);
self.add = function (tab) {
var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
li.data('tab', tab);
liList.push(li);
ul.append(li);
};
self.selectedIndex = 0;
self.select = function (index) {
self.selectedIndex = index;
_each(liList, function (i, li) {
li.unbind();
if (i === index) {
li.addClass('ke-tabs-li-selected');
K(li.data('tab').panel).show('');
} else {
li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
.mouseover(function () {
K(this).addClass('ke-tabs-li-on');
})
.mouseout(function () {
K(this).removeClass('ke-tabs-li-on');
})
.click(function () {
self.select(i);
});
K(li.data('tab').panel).hide();
}
});
if (afterSelect) {
afterSelect.call(self, index);
}
};
self.remove = function () {
_each(liList, function () {
this.remove();
});
ul.remove();
remove.call(self);
};
return self;
}
K.tabs = _tabs;
function _loadScript(url, fn) {
var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
script = document.createElement('script');
head.appendChild(script);
script.src = url;
script.charset = 'utf-8';
script.onload = script.onreadystatechange = function () {
if (!this.readyState || this.readyState === 'loaded') {
if (fn) {
fn();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
}
function _chopQuery(url) {
var index = url.indexOf('?');
return index > 0 ? url.substr(0, index) : url;
}
function _loadStyle(url) {
var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
link = document.createElement('link'),
absoluteUrl = _chopQuery(_formatUrl(url, 'absolute'));
var links = K('link[rel="stylesheet"]', head);
for (var i = 0, len = links.length; i < len; i++) {
if (_chopQuery(_formatUrl(links[i].href, 'absolute')) === absoluteUrl) {
return;
}
}
head.appendChild(link);
link.href = url;
link.rel = 'stylesheet';
}
function _ajax(url, fn, method, param, dataType) {
method = method || 'GET';
dataType = dataType || 'json';
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (fn) {
var data = _trim(xhr.responseText);
if (dataType == 'json') {
data = _json(data);
}
fn(data);
}
}
};
if (method == 'POST') {
var params = [];
_each(param, function (key, val) {
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
});
try {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
} catch (e) { }
xhr.send(params.join('&'));
} else {
xhr.send(null);
}
}
K.loadScript = _loadScript;
K.loadStyle = _loadStyle;
K.ajax = _ajax;
var _plugins = {};
function _plugin(name, fn) {
if (name === undefined) {
return _plugins;
}
if (!fn) {
return _plugins[name];
}
_plugins[name] = fn;
}
var _language = {};
function _parseLangKey(key) {
var match, ns = 'core';
if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
ns = match[1];
key = match[2];
}
return { ns: ns, key: key };
}
function _lang(mixed, langType) {
langType = langType === undefined ? K.options.langType : langType;
if (typeof mixed === 'string') {
if (!_language[langType]) {
return 'no language';
}
var pos = mixed.length - 1;
if (mixed.substr(pos) === '.') {
return _language[langType][mixed.substr(0, pos)];
}
var obj = _parseLangKey(mixed);
return _language[langType][obj.ns][obj.key];
}
_each(mixed, function (key, val) {
var obj = _parseLangKey(key);
if (!_language[langType]) {
_language[langType] = {};
}
if (!_language[langType][obj.ns]) {
_language[langType][obj.ns] = {};
}
_language[langType][obj.ns][obj.key] = val;
});
}
function _getImageFromRange(range, fn) {
if (range.collapsed) {
return;
}
range = range.cloneRange().up();
var sc = range.startContainer, so = range.startOffset;
if (!_WEBKIT && !range.isControl()) {
return;
}
var img = K(sc.childNodes[so]);
if (!img || img.name != 'img') {
return;
}
if (fn(img)) {
return img;
}
}
function _bindContextmenuEvent() {
var self = this, doc = self.edit.doc;
K(doc).contextmenu(function (e) {
if (self.menu) {
self.hideMenu();
}
if (!self.useContextmenu) {
e.preventDefault();
return;
}
if (self._contextmenus.length === 0) {
return;
}
var maxWidth = 0, items = [];
_each(self._contextmenus, function () {
if (this.title == '-') {
items.push(this);
return;
}
if (this.cond && this.cond()) {
items.push(this);
if (this.width && this.width > maxWidth) {
maxWidth = this.width;
}
}
});
while (items.length > 0 && items[0].title == '-') {
items.shift();
}
while (items.length > 0 && items[items.length - 1].title == '-') {
items.pop();
}
var prevItem = null;
_each(items, function (i) {
if (this.title == '-' && prevItem.title == '-') {
delete items[i];
}
prevItem = this;
});
if (items.length > 0) {
e.preventDefault();
var pos = K(self.edit.iframe).pos(),
menu = _menu({
x: pos.x + e.clientX,
y: pos.y + e.clientY,
width: maxWidth,
css: { visibility: 'hidden' },
shadowMode: self.shadowMode
});
_each(items, function () {
if (this.title) {
menu.addItem(this);
}
});
var docEl = _docElement(menu.doc),
menuHeight = menu.div.height();
if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
}
menu.div.css('visibility', 'visible');
self.menu = menu;
}
});
}
function _bindNewlineEvent() {
var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
if (_IE && newlineTag !== 'br') {
return;
}
if (_GECKO && _V < 3 && newlineTag !== 'p') {
return;
}
if (_OPERA && _V < 9) {
return;
}
var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
function getAncestorTagName(range) {
var ancestor = K(range.commonAncestor());
while (ancestor) {
if (ancestor.type == 1 && !ancestor.isStyle()) {
break;
}
ancestor = ancestor.parent();
}
return ancestor.name;
}
K(doc).keydown(function (e) {
if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
return;
}
self.cmd.selection();
var tagName = getAncestorTagName(self.cmd.range);
if (tagName == 'marquee' || tagName == 'select') {
return;
}
if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
e.preventDefault();
self.insertHtml('<br />' + (_IE && _V < 9 ? '' : '\u200B'));
return;
}
if (!pSkipTagMap[tagName]) {
_nativeCommand(doc, 'formatblock', '<p>');
}
});
K(doc).keyup(function (e) {
if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
return;
}
if (newlineTag == 'br') {
return;
}
if (_GECKO) {
var root = self.cmd.commonAncestor('p');
var a = self.cmd.commonAncestor('a');
if (a && a.text() == '') {
a.remove(true);
self.cmd.range.selectNodeContents(root[0]).collapse(true);
self.cmd.select();
}
return;
}
self.cmd.selection();
var tagName = getAncestorTagName(self.cmd.range);
if (tagName == 'marquee' || tagName == 'select') {
return;
}
if (!pSkipTagMap[tagName]) {
_nativeCommand(doc, 'formatblock', '<p>');
}
var div = self.cmd.commonAncestor('div');
if (div) {
var p = K('<p></p>'),
child = div[0].firstChild;
while (child) {
var next = child.nextSibling;
p.append(child);
child = next;
}
div.before(p);
div.remove();
self.cmd.range.selectNodeContents(p[0]);
self.cmd.select();
}
});
}
function _bindTabEvent() {
var self = this, doc = self.edit.doc;
K(doc).keydown(function (e) {
if (e.which == 9) {
e.preventDefault();
if (self.afterTab) {
self.afterTab.call(self, e);
return;
}
var cmd = self.cmd, range = cmd.range;
range.shrink();
if (range.collapsed && range.startContainer.nodeType == 1) {
range.insertNode(K('@ ', doc)[0]);
cmd.select();
}
self.insertHtml(' ');
}
});
}
function _bindFocusEvent() {
var self = this;
K(self.edit.textarea[0], self.edit.win).focus(function (e) {
if (self.afterFocus) {
self.afterFocus.call(self, e);
}
}).blur(function (e) {
if (self.afterBlur) {
self.afterBlur.call(self, e);
}
});
}
function _removeBookmarkTag(html) {
return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
}
function _removeTempTag(html) {
return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
}
function _addBookmarkToStack(stack, bookmark) {
if (stack.length === 0) {
stack.push(bookmark);
return;
}
var prev = stack[stack.length - 1];
if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
stack.push(bookmark);
}
}
function _undoToRedo(fromStack, toStack) {
var self = this, edit = self.edit,
body = edit.doc.body,
range, bookmark;
if (fromStack.length === 0) {
return self;
}
if (edit.designMode) {
range = self.cmd.range;
bookmark = range.createBookmark(true);
bookmark.html = body.innerHTML;
} else {
bookmark = {
html: body.innerHTML
};
}
_addBookmarkToStack(toStack, bookmark);
var prev = fromStack.pop();
if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
prev = fromStack.pop();
}
if (edit.designMode) {
edit.html(prev.html);
if (prev.start) {
range.moveToBookmark(prev);
self.select();
}
} else {
K(body).html(_removeBookmarkTag(prev.html));
}
return self;
}
function KEditor(options) {
var self = this;
self.options = {};
function setOption(key, val) {
if (KEditor.prototype[key] === undefined) {
self[key] = val;
}
self.options[key] = val;
}
_each(options, function (key, val) {
setOption(key, options[key]);
});
_each(K.options, function (key, val) {
if (self[key] === undefined) {
setOption(key, val);
}
});
var se = K(self.srcElement || '<textarea/>');
if (!self.width) {
self.width = se[0].style.width || se.width();
}
if (!self.height) {
self.height = se[0].style.height || se.height();
}
setOption('width', _undef(self.width, self.minWidth));
setOption('height', _undef(self.height, self.minHeight));
setOption('width', _addUnit(self.width));
setOption('height', _addUnit(self.height));
if (_MOBILE && (!_IOS || _V < 534)) {
self.designMode = false;
}
self.srcElement = se;
self.initContent = '';
self.plugin = {};
self.isCreated = false;
self._handlers = {};
self._contextmenus = [];
self._undoStack = [];
self._redoStack = [];
self._firstAddBookmark = true;
self.menu = self.contextmenu = null;
self.dialogs = [];
}
KEditor.prototype = {
lang: function (mixed) {
return _lang(mixed, this.langType);
},
loadPlugin: function (name, fn) {
var self = this;
if (_plugins[name]) {
if (!_isFunction(_plugins[name])) {
setTimeout(function () {
self.loadPlugin(name, fn);
}, 100);
return self;
}
_plugins[name].call(self, KindEditor);
if (fn) {
fn.call(self);
}
return self;
}
_plugins[name] = 'loading';
_loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function () {
setTimeout(function () {
if (_plugins[name]) {
self.loadPlugin(name, fn);
}
}, 0);
});
return self;
},
handler: function (key, fn) {
var self = this;
if (!self._handlers[key]) {
self._handlers[key] = [];
}
if (_isFunction(fn)) {
self._handlers[key].push(fn);
return self;
}
_each(self._handlers[key], function () {
fn = this.call(self, fn);
});
return fn;
},
clickToolbar: function (name, fn) {
var self = this, key = 'clickToolbar' + name;
if (fn === undefined) {
if (self._handlers[key]) {
return self.handler(key);
}
self.loadPlugin(name, function () {
self.handler(key);
});
return self;
}
return self.handler(key, fn);
},
updateState: function () {
var self = this;
_each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
'subscript,superscript,bold,italic,underline,strikethrough').split(','), function (i, name) {
self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
});
return self;
},
addContextmenu: function (item) {
this._contextmenus.push(item);
return this;
},
afterCreate: function (fn) {
return this.handler('afterCreate', fn);
},
beforeRemove: function (fn) {
return this.handler('beforeRemove', fn);
},
beforeGetHtml: function (fn) {
return this.handler('beforeGetHtml', fn);
},
beforeSetHtml: function (fn) {
return this.handler('beforeSetHtml', fn);
},
afterSetHtml: function (fn) {
return this.handler('afterSetHtml', fn);
},
create: function () {
var self = this, fullscreenMode = self.fullscreenMode;
if (self.isCreated) {
return self;
}
if (self.srcElement.data('kindeditor')) {
return self;
}
self.srcElement.data('kindeditor', 'true');
if (fullscreenMode) {
_docElement().style.overflow = 'hidden';
} else {
_docElement().style.overflow = '';
}
var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
if ((_IE && _V < 8) || _QUIRKS) {
height = _addUnit(_removeUnit(height) + 2);
}
var container = self.container = K(self.layout);
if (fullscreenMode) {
K(document.body).append(container);
} else {
self.srcElement.before(container);
}
var toolbarDiv = K('.toolbar', container),
editDiv = K('.edit', container),
statusbar = self.statusbar = K('.statusbar', container);
container.removeClass('container')
.addClass('ke-container ke-container-' + self.themeType).css('width', width);
if (fullscreenMode) {
container.css({
position: 'absolute',
left: 0,
top: 0,
'z-index': 811211
});
if (!_GECKO) {
self._scrollPos = _getScrollPos();
}
window.scrollTo(0, 0);
K(document.body).css({
'height': '1px',
'overflow': 'hidden'
});
K(document.body.parentNode).css('overflow', 'hidden');
self._fullscreenExecuted = true;
} else {
if (self._fullscreenExecuted) {
K(document.body).css({
'height': '',
'overflow': ''
});
K(document.body.parentNode).css('overflow', '');
}
if (self._scrollPos) {
window.scrollTo(self._scrollPos.x, self._scrollPos.y);
}
}
var htmlList = [];
K.each(self.items, function (i, name) {
if (name == '|') {
htmlList.push('<span class="ke-inline-block ke-separator"></span>');
} else if (name == '/') {
htmlList.push('<div class="ke-hr"></div>');
} else {
htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
}
});
var toolbar = self.toolbar = _toolbar({
src: toolbarDiv,
html: htmlList.join(''),
noDisableItems: self.noDisableItems,
click: function (e, name) {
e.stop();
if (self.menu) {
var menuName = self.menu.name;
self.hideMenu();
if (menuName === name) {
return;
}
}
self.clickToolbar(name);
}
});
var editHeight = _removeUnit(height) - toolbar.div.height();
var edit = self.edit = _edit({
height: editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
src: editDiv,
srcElement: self.srcElement,
designMode: self.designMode,
themesPath: self.themesPath,
bodyClass: self.bodyClass,
cssPath: self.cssPath,
cssData: self.cssData,
beforeGetHtml: function (html) {
html = self.beforeGetHtml(html);
html = _removeBookmarkTag(_removeTempTag(html));
return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
},
beforeSetHtml: function (html) {
html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
return self.beforeSetHtml(html);
},
afterSetHtml: function () {
self.edit = edit = this;
self.afterSetHtml();
},
afterCreate: function () {
self.edit = edit = this;
self.cmd = edit.cmd;
self._docMousedownFn = function (e) {
if (self.menu) {
self.hideMenu();
}
};
K(edit.doc, document).mousedown(self._docMousedownFn);
_bindContextmenuEvent.call(self);
_bindNewlineEvent.call(self);
_bindTabEvent.call(self);
_bindFocusEvent.call(self);
edit.afterChange(function (e) {
if (!edit.designMode) {
return;
}
self.updateState();
self.addBookmark();
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
});
edit.textarea.keyup(function (e) {
if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
}
});
if (self.readonlyMode) {
self.readonly();
}
self.isCreated = true;
if (self.initContent === '') {
self.initContent = self.html();
}
if (self._undoStack.length > 0) {
var prev = self._undoStack.pop();
if (prev.start) {
self.html(prev.html);
edit.cmd.range.moveToBookmark(prev);
self.select();
}
}
self.afterCreate();
if (self.options.afterCreate) {
self.options.afterCreate.call(self);
}
}
});
statusbar.removeClass('statusbar').addClass('ke-statusbar')
.append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
.append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
if (self._fullscreenResizeHandler) {
K(window).unbind('resize', self._fullscreenResizeHandler);
self._fullscreenResizeHandler = null;
}
function initResize() {
if (statusbar.height() === 0) {
setTimeout(initResize, 100);
return;
}
self.resize(width, height, false);
}
initResize();
if (fullscreenMode) {
self._fullscreenResizeHandler = function (e) {
if (self.isCreated) {
self.resize(_docElement().clientWidth, _docElement().clientHeight, false);
}
};
K(window).bind('resize', self._fullscreenResizeHandler);
toolbar.select('fullscreen');
statusbar.first().css('visibility', 'hidden');
statusbar.last().css('visibility', 'hidden');
} else {
if (_GECKO) {
K(window).bind('scroll', function (e) {
self._scrollPos = _getScrollPos();
});
}
if (self.resizeType > 0) {
_drag({
moveEl: container,
clickEl: statusbar,
moveFn: function (x, y, width, height, diffX, diffY) {
height += diffY;
self.resize(null, height);
}
});
} else {
statusbar.first().css('visibility', 'hidden');
}
if (self.resizeType === 2) {
_drag({
moveEl: container,
clickEl: statusbar.last(),
moveFn: function (x, y, width, height, diffX, diffY) {
width += diffX;
height += diffY;
self.resize(width, height);
}
});
} else {
statusbar.last().css('visibility', 'hidden');
}
}
return self;
},
remove: function () {
var self = this;
if (!self.isCreated) {
return self;
}
self.beforeRemove();
self.srcElement.data('kindeditor', '');
if (self.menu) {
self.hideMenu();
}
_each(self.dialogs, function () {
self.hideDialog();
});
K(document).unbind('mousedown', self._docMousedownFn);
self.toolbar.remove();
self.edit.remove();
self.statusbar.last().unbind();
self.statusbar.unbind();
self.container.remove();
self.container = self.toolbar = self.edit = self.menu = null;
self.dialogs = [];
self.isCreated = false;
return self;
},
resize: function (width, height, updateProp) {
var self = this;
updateProp = _undef(updateProp, true);
if (width) {
if (!/%/.test(width)) {
width = _removeUnit(width);
width = width < self.minWidth ? self.minWidth : width;
}
self.container.css('width', _addUnit(width));
if (updateProp) {
self.width = _addUnit(width);
}
}
if (height) {
height = _removeUnit(height);
editHeight = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
editHeight = editHeight < self.minHeight ? self.minHeight : editHeight;
self.edit.setHeight(editHeight);
if (updateProp) {
self.height = _addUnit(height);
}
}
return self;
},
select: function () {
this.isCreated && this.cmd.select();
return this;
},
html: function (val) {
var self = this;
if (val === undefined) {
return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
}
self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
if (self.isCreated) {
self.cmd.selection();
}
return self;
},
fullHtml: function () {
return this.isCreated ? this.edit.html(undefined, true) : '';
},
text: function (val) {
var self = this;
if (val === undefined) {
return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/ /ig, ' '));
} else {
return self.html(_escape(val));
}
},
isEmpty: function () {
return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
},
isDirty: function () {
return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
},
selectedHtml: function () {
var val = this.isCreated ? this.cmd.range.html() : '';
val = _removeBookmarkTag(_removeTempTag(val));
return val;
},
count: function (mode) {
var self = this;
mode = (mode || 'html').toLowerCase();
if (mode === 'html') {
return self.html().length;
}
if (mode === 'text') {
return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
}
return 0;
},
exec: function (key) {
key = key.toLowerCase();
var self = this, cmd = self.cmd,
changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
if (changeFlag) {
self.addBookmark(false);
}
cmd[key].apply(cmd, _toArray(arguments, 1));
if (changeFlag) {
self.updateState();
self.addBookmark(false);
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
}
return self;
},
insertHtml: function (val, quickMode) {
if (!this.isCreated) {
return this;
}
val = this.beforeSetHtml(val);
this.exec('inserthtml', val, quickMode);
return this;
},
appendHtml: function (val) {
this.html(this.html() + val);
if (this.isCreated) {
var cmd = this.cmd;
cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
cmd.select();
}
return this;
},
sync: function () {
_elementVal(this.srcElement, this.html());
return this;
},
focus: function () {
this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
return this;
},
blur: function () {
this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
return this;
},
addBookmark: function (checkSize) {
checkSize = _undef(checkSize, true);
var self = this, edit = self.edit,
body = edit.doc.body,
html = _removeTempTag(body.innerHTML), bookmark;
if (checkSize && self._undoStack.length > 0) {
var prev = self._undoStack[self._undoStack.length - 1];
if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
return self;
}
}
if (edit.designMode && !self._firstAddBookmark) {
var range = self.cmd.range;
bookmark = range.createBookmark(true);
bookmark.html = _removeTempTag(body.innerHTML);
range.moveToBookmark(bookmark);
} else {
bookmark = {
html: html
};
}
self._firstAddBookmark = false;
_addBookmarkToStack(self._undoStack, bookmark);
return self;
},
undo: function () {
return _undoToRedo.call(this, this._undoStack, this._redoStack);
},
redo: function () {
return _undoToRedo.call(this, this._redoStack, this._undoStack);
},
fullscreen: function (bool) {
this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
this.addBookmark(false);
return this.remove().create();
},
readonly: function (isReadonly) {
isReadonly = _undef(isReadonly, true);
var self = this, edit = self.edit, doc = edit.doc;
if (self.designMode) {
self.toolbar.disableAll(isReadonly, []);
} else {
_each(self.noDisableItems, function () {
self.toolbar[isReadonly ? 'disable' : 'enable'](this);
});
}
if (_IE) {
doc.body.contentEditable = !isReadonly;
} else {
doc.designMode = isReadonly ? 'off' : 'on';
}
edit.textarea[0].disabled = isReadonly;
},
createMenu: function (options) {
var self = this,
name = options.name,
knode = self.toolbar.get(name),
pos = knode.pos();
options.x = pos.x;
options.y = pos.y + knode.height();
options.z = self.options.zIndex;
options.shadowMode = _undef(options.shadowMode, self.shadowMode);
if (options.selectedColor !== undefined) {
options.cls = 'ke-colorpicker-' + self.themeType;
options.noColor = self.lang('noColor');
self.menu = _colorpicker(options);
} else {
options.cls = 'ke-menu-' + self.themeType;
options.centerLineMode = false;
self.menu = _menu(options);
}
return self.menu;
},
hideMenu: function () {
this.menu.remove();
this.menu = null;
return this;
},
hideContextmenu: function () {
this.contextmenu.remove();
this.contextmenu = null;
return this;
},
createDialog: function (options) {
var self = this, name = options.name;
options.z = self.options.zIndex;
options.shadowMode = _undef(options.shadowMode, self.shadowMode);
options.closeBtn = _undef(options.closeBtn, {
name: self.lang('close'),
click: function (e) {
self.hideDialog();
if (_IE && self.cmd) {
self.cmd.select();
}
}
});
options.noBtn = _undef(options.noBtn, {
name: self.lang(options.yesBtn ? 'no' : 'close'),
click: function (e) {
self.hideDialog();
if (_IE && self.cmd) {
self.cmd.select();
}
}
});
if (self.dialogAlignType != 'page') {
options.alignEl = self.container;
}
options.cls = 'ke-dialog-' + self.themeType;
if (self.dialogs.length > 0) {
var firstDialog = self.dialogs[0],
parentDialog = self.dialogs[self.dialogs.length - 1];
firstDialog.setMaskIndex(parentDialog.z + 2);
options.z = parentDialog.z + 3;
options.showMask = false;
}
var dialog = _dialog(options);
self.dialogs.push(dialog);
return dialog;
},
hideDialog: function () {
var self = this;
if (self.dialogs.length > 0) {
self.dialogs.pop().remove();
}
if (self.dialogs.length > 0) {
var firstDialog = self.dialogs[0],
parentDialog = self.dialogs[self.dialogs.length - 1];
firstDialog.setMaskIndex(parentDialog.z - 1);
}
return self;
},
errorDialog: function (html) {
var self = this;
var dialog = self.createDialog({
width: 750,
title: self.lang('uploadError'),
body: '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
});
var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
doc.open();
doc.write(html);
doc.close();
K(doc.body).css('background-color', '#FFF');
iframe[0].contentWindow.focus();
return self;
}
};
function _editor(options) {
return new KEditor(options);
}
_instances = [];
function _create(expr, options) {
options = options || {};
options.basePath = _undef(options.basePath, K.basePath);
options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
options.langPath = _undef(options.langPath, options.basePath + 'lang/');
options.pluginsPath = _undef(options.pluginsPath, options.basePath);
if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
var themeType = _undef(options.themeType, K.options.themeType);
_loadStyle(options.themesPath + 'default/default.css');
_loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
}
function create(editor) {
_each(_plugins, function (name, fn) {
if (_isFunction(fn)) {
fn.call(editor, KindEditor);
}
});
return editor.create();
}
var knode = K(expr);
if (!knode || knode.length === 0) {
return;
}
if (knode.length > 1) {
knode.each(function () {
_create(this, options);
});
return _instances[0];
}
options.srcElement = knode[0];
var editor = new KEditor(options);
_instances.push(editor);
if (_language[editor.langType]) {
return create(editor);
}
_loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function () {
create(editor);
});
return editor;
}
function _eachEditor(expr, fn) {
K(expr).each(function (i, el) {
K.each(_instances, function (j, editor) {
if (editor && editor.srcElement[0] == el) {
fn.call(editor, j);
return false;
}
});
});
}
K.remove = function (expr) {
_eachEditor(expr, function (i) {
this.remove();
_instances.splice(i, 1);
});
};
K.sync = function (expr) {
_eachEditor(expr, function () {
this.sync();
});
};
K.html = function (expr, val) {
_eachEditor(expr, function () {
this.html(val);
});
};
K.insertHtml = function (expr, val) {
_eachEditor(expr, function () {
this.insertHtml(val);
});
};
K.appendHtml = function (expr, val) {
_eachEditor(expr, function () {
this.appendHtml(val);
});
};
if (_IE && _V < 7) {
_nativeCommand(document, 'BackgroundImageCache', true);
}
K.EditorClass = KEditor;
K.editor = _editor;
K.create = _create;
K.instances = _instances;
K.plugin = _plugin;
K.lang = _lang;
_plugin('core', function (K) {
var self = this,
shortcutKeys = {
undo: 'Z', redo: 'Y', bold: 'B', italic: 'I', underline: 'U', print: 'P', selectall: 'A'
};
self.afterSetHtml(function () {
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
});
self.afterCreate(function () {
if (self.syncType != 'form') {
return;
}
var el = K(self.srcElement), hasForm = false;
while ((el = el.parent())) {
if (el.name == 'form') {
hasForm = true;
break;
}
}
if (hasForm) {
el.bind('submit', function (e) {
self.sync();
K(window).bind('unload', function () {
self.edit.textarea.remove();
});
});
var resetBtn = K('[type="reset"]', el);
resetBtn.click(function () {
self.html(self.initContent);
self.cmd.selection();
});
self.beforeRemove(function () {
el.unbind();
resetBtn.unbind();
});
}
});
self.clickToolbar('source', function () {
if (self.edit.designMode) {
self.toolbar.disableAll(true);
self.edit.design(false);
self.toolbar.select('source');
} else {
self.toolbar.disableAll(false);
self.edit.design(true);
self.toolbar.unselect('source');
if (_GECKO) {
setTimeout(function () {
self.cmd.selection();
}, 0);
} else {
self.cmd.selection();
}
}
self.designMode = self.edit.designMode;
});
self.afterCreate(function () {
if (!self.designMode) {
self.toolbar.disableAll(true).select('source');
}
});
self.clickToolbar('fullscreen', function () {
self.fullscreen();
});
if (self.fullscreenShortcut) {
var loaded = false;
self.afterCreate(function () {
K(self.edit.doc, self.edit.textarea).keyup(function (e) {
if (e.which == 27) {
setTimeout(function () {
self.fullscreen();
}, 0);
}
});
if (loaded) {
if (_IE && !self.designMode) {
return;
}
self.focus();
}
if (!loaded) {
loaded = true;
}
});
}
_each('undo,redo'.split(','), function (i, name) {
if (shortcutKeys[name]) {
self.afterCreate(function () {
_ctrl(this.edit.doc, shortcutKeys[name], function () {
self.clickToolbar(name);
});
});
}
self.clickToolbar(name, function () {
self[name]();
});
});
self.clickToolbar('formatblock', function () {
var blocks = self.lang('formatblock.formatBlock'),
heights = {
h1: 28,
h2: 24,
h3: 18,
H4: 14,
p: 12
},
curVal = self.cmd.val('formatblock'),
menu = self.createMenu({
name: 'formatblock',
width: self.langType == 'en' ? 200 : 150
});
_each(blocks, function (key, val) {
var style = 'font-size:' + heights[key] + 'px;';
if (key.charAt(0) === 'h') {
style += 'font-weight:bold;';
}
menu.addItem({
title: '<span style="' + style + '" unselectable="on">' + val + '</span>',
height: heights[key] + 12,
checked: (curVal === key || curVal === val),
click: function () {
self.select().exec('formatblock', '<' + key + '>').hideMenu();
}
});
});
});
self.clickToolbar('fontname', function () {
var curVal = self.cmd.val('fontname'),
menu = self.createMenu({
name: 'fontname',
width: 150
});
_each(self.lang('fontname.fontName'), function (key, val) {
menu.addItem({
title: '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
checked: (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
click: function () {
self.exec('fontname', key).hideMenu();
}
});
});
});
self.clickToolbar('fontsize', function () {
var curVal = self.cmd.val('fontsize'),
menu = self.createMenu({
name: 'fontsize',
width: 150
});
_each(self.fontSizeTable, function (i, val) {
menu.addItem({
title: '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
height: _removeUnit(val) + 12,
checked: curVal === val,
click: function () {
self.exec('fontsize', val).hideMenu();
}
});
});
});
_each('forecolor,hilitecolor'.split(','), function (i, name) {
self.clickToolbar(name, function () {
self.createMenu({
name: name,
selectedColor: self.cmd.val(name) || 'default',
colors: self.colorTable,
click: function (color) {
self.exec(name, color).hideMenu();
}
});
});
});
_each(('cut,copy,paste').split(','), function (i, name) {
self.clickToolbar(name, function () {
self.focus();
try {
self.exec(name, null);
} catch (e) {
alert(self.lang(name + 'Error'));
}
});
});
self.clickToolbar('about', function () {
var html = '<div style="margin:20px;">' +
'<div>KindEditor ' + _VERSION + '</div>' +
'<div>Copyright © <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
'</div>';
self.createDialog({
name: 'about',
width: 350,
title: self.lang('about'),
body: html
});
});
self.plugin.getSelectedLink = function () {
return self.cmd.commonAncestor('a');
};
self.plugin.getSelectedImage = function () {
return _getImageFromRange(self.edit.cmd.range, function (img) {
return !/^ke-\w+$/i.test(img[0].className);
});
};
self.plugin.getSelectedFlash = function () {
return _getImageFromRange(self.edit.cmd.range, function (img) {
return img[0].className == 'ke-flash';
});
};
self.plugin.getSelectedMedia = function () {
return _getImageFromRange(self.edit.cmd.range, function (img) {
return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
});
};
self.plugin.getSelectedAnchor = function () {
return _getImageFromRange(self.edit.cmd.range, function (img) {
return img[0].className == 'ke-anchor';
});
};
_each('link,image,flash,media,anchor'.split(','), function (i, name) {
var uName = name.charAt(0).toUpperCase() + name.substr(1);
_each('edit,delete'.split(','), function (j, val) {
self.addContextmenu({
title: self.lang(val + uName),
click: function () {
self.loadPlugin(name, function () {
self.plugin[name][val]();
self.hideMenu();
});
},
cond: self.plugin['getSelected' + uName],
width: 150,
iconClass: val == 'edit' ? 'ke-icon-' + name : undefined
});
});
self.addContextmenu({ title: '-' });
});
self.plugin.getSelectedTable = function () {
return self.cmd.commonAncestor('table');
};
self.plugin.getSelectedRow = function () {
return self.cmd.commonAncestor('tr');
};
self.plugin.getSelectedCell = function () {
return self.cmd.commonAncestor('td');
};
_each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function (i, val) {
var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
self.addContextmenu({
title: self.lang('table' + val),
click: function () {
self.loadPlugin('table', function () {
self.plugin.table[val]();
self.hideMenu();
});
},
cond: cond,
width: 170,
iconClass: 'ke-icon-table' + val
});
});
self.addContextmenu({ title: '-' });
_each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function (i, name) {
if (shortcutKeys[name]) {
self.afterCreate(function () {
_ctrl(this.edit.doc, shortcutKeys[name], function () {
self.cmd.selection();
self.clickToolbar(name);
});
});
}
self.clickToolbar(name, function () {
self.focus().exec(name, null);
});
});
self.afterCreate(function () {
var doc = self.edit.doc, cmd, bookmark, div,
cls = '__kindeditor_paste__', pasting = false;
function movePastedData() {
cmd.range.moveToBookmark(bookmark);
cmd.select();
if (_WEBKIT) {
K('div.' + cls, div).each(function () {
K(this).after('<br />').remove(true);
});
K('span.Apple-style-span', div).remove(true);
K('span.Apple-tab-span', div).remove(true);
K('span[style]', div).each(function () {
if (K(this).css('white-space') == 'nowrap') {
K(this).remove(true);
}
});
K('meta', div).remove();
}
var html = div[0].innerHTML;
div.remove();
if (html === '') {
return;
}
if (_WEBKIT) {
html = html.replace(/(<br>)\1/ig, '$1');
}
if (self.pasteType === 2) {
html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
} else {
html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
html = self.beforeSetHtml(html);
}
}
if (self.pasteType === 1) {
html = html.replace(/ /ig, ' ');
html = html.replace(/\n\s*\n/g, '\n');
html = html.replace(/<br[^>]*>/ig, '\n');
html = html.replace(/<\/p><p[^>]*>/ig, '\n');
html = html.replace(/<[^>]+>/g, '');
html = html.replace(/ {2}/g, ' ');
if (self.newlineTag == 'p') {
if (/\n/.test(html)) {
html = html.replace(/^/, '<p>').replace(/$/, '<br /></p>').replace(/\n/g, '<br /></p><p>');
}
} else {
html = html.replace(/\n/g, '<br />$&');
}
}
self.insertHtml(html, true);
}
K(doc.body).bind('paste', function (e) {
if (self.pasteType === 0) {
e.stop();
return;
}
if (pasting) {
return;
}
pasting = true;
K('div.' + cls, doc).remove();
cmd = self.cmd.selection();
bookmark = cmd.range.createBookmark();
div = K('<div class="' + cls + '"></div>', doc).css({
position: 'absolute',
width: '1px',
height: '1px',
overflow: 'hidden',
left: '-1981px',
top: K(bookmark.start).pos().y + 'px',
'white-space': 'nowrap'
});
K(doc.body).append(div);
if (_IE) {
var rng = cmd.range.get(true);
rng.moveToElementText(div[0]);
rng.select();
rng.execCommand('paste');
e.preventDefault();
} else {
cmd.range.selectNodeContents(div[0]);
cmd.select();
}
setTimeout(function () {
movePastedData();
pasting = false;
}, 0);
});
});
self.beforeGetHtml(function (html) {
if (_IE && _V <= 8) {
html = html.replace(/<div\s+[^>]*data-ke-input-tag="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function (full, tag) {
return unescape(tag);
});
html = html.replace(/(<input)((?:\s+[^>]*)?>)/ig, function ($0, $1, $2) {
if (!/\s+type="[^"]+"/i.test($0)) {
return $1 + ' type="text"' + $2;
}
return $0;
});
}
return html.replace(/(<(?:noscript|noscript\s[^>]*)>)([\s\S]*?)(<\/noscript>)/ig, function ($0, $1, $2, $3) {
return $1 + _unescape($2).replace(/\s+/g, ' ') + $3;
})
.replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function (full) {
var imgAttrs = _getAttrList(full);
var styles = _getCssList(imgAttrs.style || '');
var attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
var width = _undef(styles.width, '');
var height = _undef(styles.height, '');
if (/px/i.test(width)) {
width = _removeUnit(width);
}
if (/px/i.test(height)) {
height = _removeUnit(height);
}
attrs.width = _undef(imgAttrs.width, width);
attrs.height = _undef(imgAttrs.height, height);
return _mediaEmbed(attrs);
})
.replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function (full) {
var imgAttrs = _getAttrList(full);
return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
})
.replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function (full, attr, code) {
return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
})
.replace(/<div\s+[^>]*data-ke-noscript-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function (full, attr, code) {
return '<noscript' + unescape(attr) + '>' + unescape(code) + '</noscript>';
})
.replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function (full, start, src, end) {
full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, function ($0, $1, $2) {
return $1 + _unescape(src) + $2;
});
full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
return full;
})
.replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function (full, start, end) {
return start + end;
});
});
self.beforeSetHtml(function (html) {
if (_IE && _V <= 8) {
html = html.replace(/<input[^>]*>|<(select|button)[^>]*>[\s\S]*?<\/\1>/ig, function (full) {
var attrs = _getAttrList(full);
var styles = _getCssList(attrs.style || '');
if (styles.display == 'none') {
return '<div class="ke-display-none" data-ke-input-tag="' + escape(full) + '"></div>';
}
return full;
});
}
return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function (full) {
var attrs = _getAttrList(full);
attrs.src = _undef(attrs.src, '');
attrs.width = _undef(attrs.width, 0);
attrs.height = _undef(attrs.height, 0);
return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
})
.replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function (full) {
var attrs = _getAttrList(full);
if (attrs.href !== undefined) {
return full;
}
return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
})
.replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function (full, attr, code) {
return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
})
.replace(/<noscript([^>]*)>([\s\S]*?)<\/noscript>/ig, function (full, attr, code) {
return '<div class="ke-noscript" data-ke-noscript-attr="' + escape(attr) + '">' + escape(code) + '</div>';
})
.replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function (full, start, key, src, end) {
if (full.match(/\sdata-ke-src="[^"]*"/i)) {
return full;
}
full = start + key + '="' + src + '"' + ' data-ke-src="' + _escape(src) + '"' + end;
return full;
})
.replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function (full, start, end) {
return start + 'data-ke-' + end;
})
.replace(/<table[^>]*\s+border="0"[^>]*>/ig, function (full) {
if (full.indexOf('ke-zeroborder') >= 0) {
return full;
}
return _addClassToTag(full, 'ke-zeroborder');
});
});
});
})(window);
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : 'HTML代码',
preview : '预览',
undo : '后退(Ctrl+Z)',
redo : '前进(Ctrl+Y)',
cut : '剪切(Ctrl+X)',
copy : '复制(Ctrl+C)',
paste : '粘贴(Ctrl+V)',
plainpaste : '粘贴为无格式文本',
wordpaste : '从Word粘贴',
selectall : '全选(Ctrl+A)',
justifyleft : '左对齐',
justifycenter : '居中',
justifyright : '右对齐',
justifyfull : '两端对齐',
insertorderedlist : '编号',
insertunorderedlist : '项目符号',
indent : '增加缩进',
outdent : '减少缩进',
subscript : '下标',
superscript : '上标',
formatblock : '段落',
fontname : '字体',
fontsize : '文字大小',
forecolor : '文字颜色',
hilitecolor : '文字背景',
bold : '粗体(Ctrl+B)',
italic : '斜体(Ctrl+I)',
underline : '下划线(Ctrl+U)',
strikethrough : '删除线',
removeformat : '删除格式',
image : '图片',
multiimage : '批量图片上传',
flash : 'Flash',
media : '视音频',
table : '表格',
tablecell : '单元格',
hr : '插入横线',
emoticons : '插入表情',
link : '超级链接',
unlink : '取消超级链接',
fullscreen : '全屏显示',
about : '关于',
print : '打印(Ctrl+P)',
filemanager : '文件空间',
code : '插入程序代码',
map : 'Google地图',
baidumap : '百度地图',
lineheight : '行距',
clearhtml : '清理HTML代码',
pagebreak : '插入分页符',
quickformat : '一键排版',
insertfile : '插入文件',
template : '插入模板',
anchor : '锚点',
yes : '确定',
no : '取消',
close : '关闭',
editImage : '图片属性',
deleteImage : '删除图片',
editFlash : 'Flash属性',
deleteFlash : '删除Flash',
editMedia : '视音频属性',
deleteMedia : '删除视音频',
editLink : '超级链接属性',
deleteLink : '取消超级链接',
editAnchor : '锚点属性',
deleteAnchor : '删除锚点',
tableprop : '表格属性',
tablecellprop : '单元格属性',
tableinsert : '插入表格',
tabledelete : '删除表格',
tablecolinsertleft : '左侧插入列',
tablecolinsertright : '右侧插入列',
tablerowinsertabove : '上方插入行',
tablerowinsertbelow : '下方插入行',
tablerowmerge : '向下合并单元格',
tablecolmerge : '向右合并单元格',
tablerowsplit : '拆分行',
tablecolsplit : '拆分列',
tablecoldelete : '删除列',
tablerowdelete : '删除行',
noColor : '无颜色',
pleaseSelectFile : '请选择文件。',
invalidImg : "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。",
invalidMedia : "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
invalidWidth : "宽度必须为数字。",
invalidHeight : "高度必须为数字。",
invalidBorder : "边框必须为数字。",
invalidUrl : "请输入有效的URL地址。",
invalidRows : '行数为必选项,只允许输入大于0的数字。',
invalidCols : '列数为必选项,只允许输入大于0的数字。',
invalidPadding : '边距必须为数字。',
invalidSpacing : '间距必须为数字。',
invalidJson : '服务器发生故障。',
uploadSuccess : '上传成功。',
cutError : '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。',
copyError : '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。',
pasteError : '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。',
ajaxLoading : '加载中,请稍候 ...',
uploadLoading : '上传中,请稍候 ...',
uploadError : '上传错误',
'plainpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
'wordpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
'code.pleaseInput' : '请输入程序代码。',
'link.url' : 'URL',
'link.linkType' : '打开类型',
'link.newWindow' : '新窗口',
'link.selfWindow' : '当前窗口',
'flash.url' : 'URL',
'flash.width' : '宽度',
'flash.height' : '高度',
'flash.upload' : '上传',
'flash.viewServer' : '文件空间',
'media.url' : 'URL',
'media.width' : '宽度',
'media.height' : '高度',
'media.autostart' : '自动播放',
'media.upload' : '上传',
'media.viewServer' : '文件空间',
'image.remoteImage' : '网络图片',
'image.localImage' : '本地上传',
'image.remoteUrl' : '图片地址',
'image.localUrl' : '上传文件',
'image.size' : '图片大小',
'image.width' : '宽',
'image.height' : '高',
'image.resetSize' : '重置大小',
'image.align' : '对齐方式',
'image.defaultAlign' : '默认方式',
'image.leftAlign' : '左对齐',
'image.rightAlign' : '右对齐',
'image.imgTitle' : '图片说明',
'image.upload' : '浏览...',
'image.viewServer' : '图片空间',
'multiimage.uploadDesc' : '允许用户同时上传<%=uploadLimit%>张图片,单张图片容量不超过<%=sizeLimit%>',
'multiimage.startUpload' : '开始上传',
'multiimage.clearAll' : '全部清空',
'multiimage.insertAll' : '全部插入',
'multiimage.queueLimitExceeded' : '文件数量超过限制。',
'multiimage.fileExceedsSizeLimit' : '文件大小超过限制。',
'multiimage.zeroByteFile' : '无法上传空文件。',
'multiimage.invalidFiletype' : '文件类型不正确。',
'multiimage.unknownError' : '发生异常,无法上传。',
'multiimage.pending' : '等待上传',
'multiimage.uploadError' : '上传失败',
'filemanager.emptyFolder' : '空文件夹',
'filemanager.moveup' : '移到上一级文件夹',
'filemanager.viewType' : '显示方式:',
'filemanager.viewImage' : '缩略图',
'filemanager.listImage' : '详细信息',
'filemanager.orderType' : '排序方式:',
'filemanager.fileName' : '名称',
'filemanager.fileSize' : '大小',
'filemanager.fileType' : '类型',
'insertfile.url' : 'URL',
'insertfile.title' : '文件说明',
'insertfile.upload' : '上传',
'insertfile.viewServer' : '文件空间',
'table.cells' : '单元格数',
'table.rows' : '行数',
'table.cols' : '列数',
'table.size' : '大小',
'table.width' : '宽度',
'table.height' : '高度',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : '边距间距',
'table.padding' : '边距',
'table.spacing' : '间距',
'table.align' : '对齐方式',
'table.textAlign' : '水平对齐',
'table.verticalAlign' : '垂直对齐',
'table.alignDefault' : '默认',
'table.alignLeft' : '左对齐',
'table.alignCenter' : '居中',
'table.alignRight' : '右对齐',
'table.alignTop' : '顶部',
'table.alignMiddle' : '中部',
'table.alignBottom' : '底部',
'table.alignBaseline' : '基线',
'table.border' : '边框',
'table.borderWidth' : '边框',
'table.borderColor' : '颜色',
'table.backgroundColor' : '背景颜色',
'map.address' : '地址: ',
'map.search' : '搜索',
'baidumap.address' : '地址: ',
'baidumap.search' : '搜索',
'baidumap.insertDynamicMap' : '插入动态地图',
'anchor.name' : '锚点名称',
'formatblock.formatBlock' : {
h1 : '标题 1',
h2 : '标题 2',
h3 : '标题 3',
h4 : '标题 4',
p : '正 文'
},
'fontname.fontName' : {
'SimSun' : '宋体',
'NSimSun' : '新宋体',
'FangSong_GB2312' : '仿宋_GB2312',
'KaiTi_GB2312' : '楷体_GB2312',
'SimHei' : '黑体',
'Microsoft YaHei' : '微软雅黑',
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Times New Roman' : 'Times New Roman',
'Courier New' : 'Courier New',
'Tahoma' : 'Tahoma',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : '单倍行距'},
{'1.5' : '1.5倍行距'},
{'2' : '2倍行距'},
{'2.5' : '2.5倍行距'},
{'3' : '3倍行距'}
],
'template.selectTemplate' : '可选模板',
'template.replaceContent' : '替换当前内容',
'template.fileList' : {
'1.html' : '图片和文字',
'2.html' : '表格',
'3.html' : '项目编号'
}
}, 'zh_CN');
| JavaScript |
function showMenu(id){
obj=document.getElementById("leftMenu_"+id);
for(i=1;i<=7;i++){
document.getElementById("leftMenu_"+i).style.display="none";
}
obj.style.display="block";
}
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
(function (K) {
function KSWFUpload(options) {
this.init(options);
}
K.extend(KSWFUpload, {
init: function (options) {
var self = this;
options.afterError = options.afterError || function (str) {
alert(str);
};
self.options = options;
self.progressbars = {};
// template
self.div = K(options.container).html([
'<div class="ke-swfupload">',
'<div class="ke-swfupload-top">',
'<div class="ke-inline-block ke-swfupload-button">',
'<input type="button" value="Browse" />',
'</div>',
'<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
'<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
'<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />',
'</span>',
'</div>',
'<div class="ke-swfupload-body"></div>',
'</div>'
].join(''));
self.bodyDiv = K('.ke-swfupload-body', self.div);
function showError(itemDiv, msg) {
K('.ke-status > div', itemDiv).hide();
K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
}
var settings = {
debug: false,
upload_url: options.uploadUrl,
flash_url: options.flashUrl,
file_post_name: options.filePostName,
button_placeholder: K('.ke-swfupload-button > input', self.div)[0],
button_image_url: options.buttonImageUrl,
button_width: options.buttonWidth,
button_height: options.buttonHeight,
button_cursor: SWFUpload.CURSOR.HAND,
file_types: options.fileTypes,
file_types_description: options.fileTypesDesc,
file_upload_limit: options.fileUploadLimit,
file_size_limit: options.fileSizeLimit,
post_params: options.postParams,
file_queued_handler: function (file) {
file.url = self.options.fileIconUrl;
self.appendFile(file);
},
file_queue_error_handler: function (file, errorCode, message) {
var errorName = '';
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errorName = options.queueLimitExceeded;
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errorName = options.fileExceedsSizeLimit;
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errorName = options.zeroByteFile;
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errorName = options.invalidFiletype;
break;
default:
errorName = options.unknownError;
break;
}
K.DEBUG && alert(errorName);
},
upload_start_handler: function (file) {
var self = this;
var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv);
K('.ke-status > div', itemDiv).hide();
K('.ke-progressbar', itemDiv).show();
},
upload_progress_handler: function (file, bytesLoaded, bytesTotal) {
var percent = Math.round(bytesLoaded * 100 / bytesTotal);
var progressbar = self.progressbars[file.id];
progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
progressbar.percent.html(percent + '%');
},
upload_error_handler: function (file, errorCode, message) {
if (file && file.filestatus == SWFUpload.FILE_STATUS.ERROR) {
var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
showError(itemDiv, self.options.errorMessage);
}
},
upload_success_handler: function (file, serverData) {
var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
var data = {};
try {
data = K.json(serverData);
} catch (e) {
self.options.afterError.call(this, '<!doctype html><html>' + serverData + '</html>');
}
if (data.error !== 0) {
showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage);
return;
}
file.url = data.url;
K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data);
K('.ke-status > div', itemDiv).hide();
}
};
self.swfu = new SWFUpload(settings);
K('.ke-swfupload-startupload input', self.div).click(function () {
self.swfu.startUpload();
});
},
getUrlList: function () {
var list = [];
K('.ke-img', self.bodyDiv).each(function () {
var img = K(this);
var status = img.attr('data-status');
if (status == SWFUpload.FILE_STATUS.COMPLETE) {
list.push(img.data('data'));
}
});
return list;
},
removeFile: function (fileId) {
var self = this;
self.swfu.cancelUpload(fileId);
var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
K('.ke-photo', itemDiv).unbind();
K('.ke-delete', itemDiv).unbind();
itemDiv.remove();
},
removeFiles: function () {
var self = this;
K('.ke-item', self.bodyDiv).each(function () {
self.removeFile(K(this).attr('data-id'));
});
},
appendFile: function (file) {
var self = this;
var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
self.bodyDiv.append(itemDiv);
var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
.mouseover(function (e) {
K(this).addClass('ke-on');
})
.mouseout(function (e) {
K(this).removeClass('ke-on');
});
itemDiv.append(photoDiv);
var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />');
photoDiv.append(img);
K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function () {
self.removeFile(file.id);
});
var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
// progressbar
K(['<div class="ke-progressbar">',
'<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
'<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv);
// message
K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv);
itemDiv.append('<div class="ke-name">' + file.name + '</div>');
self.progressbars[file.id] = {
bar: K('.ke-progressbar-bar-inner', photoDiv),
percent: K('.ke-progressbar-percent', photoDiv)
};
},
remove: function () {
this.removeFiles();
this.swfu.destroy();
this.div.html('');
}
});
K.swfupload = function (element, options) {
return new KSWFUpload(element, options);
};
})(KindEditor);
KindEditor.plugin('multiimage', function (K) {
var bpath;
var self = this, name = 'multiimage',
bpath = self.basePath.replace("Scripts/", ""),
formatUploadUrl = K.undef(self.formatUploadUrl, true),
uploadJson = K.undef(self.uploadJson, bpath + 'upload_json.ashx'),
imgPath = self.pluginsPath + 'multiimage/images/',
imageSizeLimit = K.undef(self.imageSizeLimit, '1MB'),
imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
imageUploadLimit = K.undef(self.imageUploadLimit, 20),
filePostName = K.undef(self.filePostName, 'imgFile'),
lang = self.lang(name + '.');
self.plugin.multiImageDialog = function (options) {
var clickFn = options.clickFn,
uploadDesc = K.tmpl(lang.uploadDesc, { uploadLimit: imageUploadLimit, sizeLimit: imageSizeLimit });
var html = [
'<div style="padding:20px;">',
'<div class="swfupload">',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name: name,
width: 650,
height: 510,
title: self.lang(name),
body: html,
previewBtn: {
name: lang.insertAll,
click: function (e) {
clickFn.call(self, swfupload.getUrlList());
}
},
yesBtn: {
name: lang.clearAll,
click: function (e) {
swfupload.removeFiles();
}
},
beforeRemove: function () {
// IE9 bugfix: https://github.com/kindsoft/kindeditor/issues/72
if (!K.IE || K.V <= 8) {
swfupload.remove();
}
}
}),
div = dialog.div;
var swfupload = K.swfupload({
container: K('.swfupload', div),
buttonImageUrl: imgPath + (self.langType == 'zh_CN' ? 'select-files-zh_CN.png' : 'select-files-en.png'),
buttonWidth: self.langType == 'zh_CN' ? 72 : 88,
buttonHeight: 23,
fileIconUrl: imgPath + 'image.png',
uploadDesc: uploadDesc,
startButtonValue: lang.startUpload,
uploadUrl: K.addParam(uploadJson, 'dir=image'),
flashUrl: imgPath + 'swfupload.swf',
filePostName: filePostName,
fileTypes: '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
fileTypesDesc: 'Image Files',
fileUploadLimit: imageUploadLimit,
fileSizeLimit: imageSizeLimit,
postParams: K.undef(self.extraFileUploadParams, {}),
queueLimitExceeded: lang.queueLimitExceeded,
fileExceedsSizeLimit: lang.fileExceedsSizeLimit,
zeroByteFile: lang.zeroByteFile,
invalidFiletype: lang.invalidFiletype,
unknownError: lang.unknownError,
pendingMessage: lang.pending,
errorMessage: lang.uploadError,
afterError: function (html) {
self.errorDialog(html);
}
});
return dialog;
};
self.clickToolbar(name, function () {
self.plugin.multiImageDialog({
clickFn: function (urlList) {
if (urlList.length === 0) {
return;
}
K.each(urlList, function (i, data) {
if (self.afterUpload) {
self.afterUpload.call(self, data.url, data, 'multiimage');
}
self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
});
// Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
setTimeout(function () {
self.hideDialog().focus();
}, 0);
}
});
});
});
/**
* SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
*
* mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
*
* SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
/* ******************* */
/* Constructor & Init */
/* ******************* */
(function () {
window.SWFUpload = function (settings) {
this.initSWFUpload(settings);
};
SWFUpload.prototype.initSWFUpload = function (settings) {
try {
this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
this.settings = settings;
this.eventQueue = [];
this.movieName = "KindEditor_SWFUpload_" + SWFUpload.movieCount++;
this.movieElement = null;
// Setup global control tracking
SWFUpload.instances[this.movieName] = this;
// Load the settings. Load the Flash movie.
this.initSettings();
this.loadFlash();
this.displayDebugInfo();
} catch (ex) {
delete SWFUpload.instances[this.movieName];
throw ex;
}
};
/* *************** */
/* Static Members */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
SWFUpload.QUEUE_ERROR = {
QUEUE_LIMIT_EXCEEDED: -100,
FILE_EXCEEDS_SIZE_LIMIT: -110,
ZERO_BYTE_FILE: -120,
INVALID_FILETYPE: -130
};
SWFUpload.UPLOAD_ERROR = {
HTTP_ERROR: -200,
MISSING_UPLOAD_URL: -210,
IO_ERROR: -220,
SECURITY_ERROR: -230,
UPLOAD_LIMIT_EXCEEDED: -240,
UPLOAD_FAILED: -250,
SPECIFIED_FILE_ID_NOT_FOUND: -260,
FILE_VALIDATION_FAILED: -270,
FILE_CANCELLED: -280,
UPLOAD_STOPPED: -290
};
SWFUpload.FILE_STATUS = {
QUEUED: -1,
IN_PROGRESS: -2,
ERROR: -3,
COMPLETE: -4,
CANCELLED: -5
};
SWFUpload.BUTTON_ACTION = {
SELECT_FILE: -100,
SELECT_FILES: -110,
START_UPLOAD: -120
};
SWFUpload.CURSOR = {
ARROW: -1,
HAND: -2
};
SWFUpload.WINDOW_MODE = {
WINDOW: "window",
TRANSPARENT: "transparent",
OPAQUE: "opaque"
};
// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function (url) {
if (typeof (url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
return url;
}
var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
var indexSlash = window.location.pathname.lastIndexOf("/");
if (indexSlash <= 0) {
path = "/";
} else {
path = window.location.pathname.substr(0, indexSlash) + "/";
}
return /*currentURL +*/path + url;
};
/* ******************** */
/* Instance Members */
/* ******************** */
// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// Upload backend settings
this.ensureDefault("upload_url", "");
this.ensureDefault("preserve_relative_urls", false);
this.ensureDefault("file_post_name", "Filedata");
this.ensureDefault("post_params", {});
this.ensureDefault("use_query_string", false);
this.ensureDefault("requeue_on_error", false);
this.ensureDefault("http_success", []);
this.ensureDefault("assume_success_timeout", 0);
// File Settings
this.ensureDefault("file_types", "*.*");
this.ensureDefault("file_types_description", "All Files");
this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
this.ensureDefault("file_upload_limit", 0);
this.ensureDefault("file_queue_limit", 0);
// Flash Settings
this.ensureDefault("flash_url", "swfupload.swf");
this.ensureDefault("prevent_swf_caching", true);
// Button Settings
this.ensureDefault("button_image_url", "");
this.ensureDefault("button_width", 1);
this.ensureDefault("button_height", 1);
this.ensureDefault("button_text", "");
this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
this.ensureDefault("button_text_top_padding", 0);
this.ensureDefault("button_text_left_padding", 0);
this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
this.ensureDefault("button_disabled", false);
this.ensureDefault("button_placeholder_id", "");
this.ensureDefault("button_placeholder", null);
this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
// Debug Settings
this.ensureDefault("debug", false);
this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
// Event Handlers
this.settings.return_upload_start_handler = this.returnUploadStart;
this.ensureDefault("swfupload_loaded_handler", null);
this.ensureDefault("file_dialog_start_handler", null);
this.ensureDefault("file_queued_handler", null);
this.ensureDefault("file_queue_error_handler", null);
this.ensureDefault("file_dialog_complete_handler", null);
this.ensureDefault("upload_start_handler", null);
this.ensureDefault("upload_progress_handler", null);
this.ensureDefault("upload_error_handler", null);
this.ensureDefault("upload_success_handler", null);
this.ensureDefault("upload_complete_handler", null);
this.ensureDefault("debug_handler", this.debugMessage);
this.ensureDefault("custom_settings", {});
// Other settings
this.customSettings = this.settings.custom_settings;
// Update the flash url if needed
if (!!this.settings.prevent_swf_caching) {
this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
}
if (!this.settings.preserve_relative_urls) {
//this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
}
delete this.ensureDefault;
};
// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
var targetElement, tempParent;
// Make sure an element with the ID we are going to use doesn't already exist
if (document.getElementById(this.movieName) !== null) {
throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
}
// Get the element where we will be placing the flash movie
targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
if (targetElement == undefined) {
throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
}
// Append the container and load the flash
tempParent = document.createElement("div");
tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
// Fix IE Flash/Form bug
if (window[this.movieName] == undefined) {
window[this.movieName] = this.getMovieElement();
}
};
// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
// Fix bug for IE9
// http://www.kindsoft.net/view.php?bbsid=7&postid=5825&pagenum=1
var classid = '';
if (KindEditor.IE && KindEditor.V > 8) {
classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
}
return ['<object id="', this.movieName, '"' + classid + ' type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
'<param name="wmode" value="', this.settings.button_window_mode, '" />',
'<param name="movie" value="', this.settings.flash_url, '" />',
'<param name="quality" value="high" />',
'<param name="menu" value="false" />',
'<param name="allowScriptAccess" value="always" />',
'<param name="flashvars" value="' + this.getFlashVars() + '" />',
'</object>'].join("");
};
// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
// Build a string from the post param object
var paramString = this.buildParamString();
var httpSuccessString = this.settings.http_success.join(",");
// Build the parameter string
return ["movieName=", encodeURIComponent(this.movieName),
"&uploadURL=", encodeURIComponent(this.settings.upload_url),
"&useQueryString=", encodeURIComponent(this.settings.use_query_string),
"&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
"&httpSuccess=", encodeURIComponent(httpSuccessString),
"&assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
"&params=", encodeURIComponent(paramString),
"&filePostName=", encodeURIComponent(this.settings.file_post_name),
"&fileTypes=", encodeURIComponent(this.settings.file_types),
"&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
"&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
"&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
"&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
"&debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
"&buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
"&buttonWidth=", encodeURIComponent(this.settings.button_width),
"&buttonHeight=", encodeURIComponent(this.settings.button_height),
"&buttonText=", encodeURIComponent(this.settings.button_text),
"&buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
"&buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
"&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
"&buttonAction=", encodeURIComponent(this.settings.button_action),
"&buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
"&buttonCursor=", encodeURIComponent(this.settings.button_cursor)
].join("");
};
// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
if (this.movieElement == undefined) {
this.movieElement = document.getElementById(this.movieName);
}
if (this.movieElement === null) {
throw "Could not find Flash element";
}
return this.movieElement;
};
// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&name=value"
SWFUpload.prototype.buildParamString = function () {
var postParams = this.settings.post_params;
var paramStringPairs = [];
if (typeof (postParams) === "object") {
for (var name in postParams) {
if (postParams.hasOwnProperty(name)) {
paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
}
}
}
return paramStringPairs.join("&");
};
// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
try {
// Make sure Flash is done before we try to remove it
this.cancelUpload(null, false);
// Remove the SWFUpload DOM nodes
var movieElement = null;
movieElement = this.getMovieElement();
if (movieElement && typeof (movieElement.CallFunction) === "unknown") { // We only want to do this in IE
// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
for (var i in movieElement) {
try {
if (typeof (movieElement[i]) === "function") {
movieElement[i] = null;
}
} catch (ex1) { }
}
// Remove the Movie Element from the page
try {
movieElement.parentNode.removeChild(movieElement);
} catch (ex) { }
}
// Remove IE form fix reference
window[this.movieName] = null;
// Destroy other references
SWFUpload.instances[this.movieName] = null;
delete SWFUpload.instances[this.movieName];
this.movieElement = null;
this.settings = null;
this.customSettings = null;
this.eventQueue = null;
this.movieName = null;
return true;
} catch (ex2) {
return false;
}
};
// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
this.debug(
[
"---SWFUpload Instance Info---\n",
"Version: ", SWFUpload.version, "\n",
"Movie Name: ", this.movieName, "\n",
"Settings:\n",
"\t", "upload_url: ", this.settings.upload_url, "\n",
"\t", "flash_url: ", this.settings.flash_url, "\n",
"\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
"\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
"\t", "http_success: ", this.settings.http_success.join(", "), "\n",
"\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
"\t", "file_post_name: ", this.settings.file_post_name, "\n",
"\t", "post_params: ", this.settings.post_params.toString(), "\n",
"\t", "file_types: ", this.settings.file_types, "\n",
"\t", "file_types_description: ", this.settings.file_types_description, "\n",
"\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
"\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
"\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
"\t", "debug: ", this.settings.debug.toString(), "\n",
"\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
"\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
"\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
"\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
"\t", "button_width: ", this.settings.button_width.toString(), "\n",
"\t", "button_height: ", this.settings.button_height.toString(), "\n",
"\t", "button_text: ", this.settings.button_text.toString(), "\n",
"\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
"\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
"\t", "button_action: ", this.settings.button_action.toString(), "\n",
"\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
"\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
"Event Handlers:\n",
"\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
"\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
"\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
"\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
"\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
"\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
"\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
"\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
"\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
].join("")
);
};
/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
if (value == undefined) {
return (this.settings[name] = default_value);
} else {
return (this.settings[name] = value);
}
};
// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
if (this.settings[name] != undefined) {
return this.settings[name];
}
return "";
};
// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
argumentArray = argumentArray || [];
var movieElement = this.getMovieElement();
var returnValue, returnString;
// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
try {
returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
returnValue = eval(returnString);
} catch (ex) {
throw "Call to " + functionName + " failed";
}
// Unescape file post param values
if (returnValue != undefined && typeof returnValue.post === "object") {
returnValue = this.unescapeFilePostParams(returnValue);
}
return returnValue;
};
/* *****************************
-- Flash control methods --
Your UI should use these
to operate SWFUpload
***************************** */
// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear. This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
this.callFlash("SelectFile");
};
// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
this.callFlash("SelectFiles");
};
// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID
SWFUpload.prototype.startUpload = function (fileID) {
this.callFlash("StartUpload", [fileID]);
};
// Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
if (triggerErrorEvent !== false) {
triggerErrorEvent = true;
}
this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};
// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
this.callFlash("StopUpload");
};
/* ************************
* Settings methods
* These methods change the SWFUpload settings.
* SWFUpload settings should not be changed directly on the settings object
* since many of the settings need to be passed to Flash in order to take
* effect.
* *********************** */
// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
return this.callFlash("GetStats");
};
// Public: setStats changes the SWFUpload statistics. You shouldn't need to
// change the statistics but you can. Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
this.callFlash("SetStats", [statsObject]);
};
// Public: getFile retrieves a File object by ID or Index. If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
if (typeof (fileID) === "number") {
return this.callFlash("GetFileByIndex", [fileID]);
} else {
return this.callFlash("GetFile", [fileID]);
}
};
// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID. If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
return this.callFlash("AddFileParam", [fileID, name, value]);
};
// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
this.callFlash("RemoveFileParam", [fileID, name]);
};
// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
this.settings.upload_url = url.toString();
this.callFlash("SetUploadURL", [url]);
};
// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
this.settings.post_params = paramsObject;
this.callFlash("SetPostParams", [paramsObject]);
};
// Public: addPostParam adds post name/value pair. Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
this.settings.post_params[name] = value;
this.callFlash("SetPostParams", [this.settings.post_params]);
};
// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
delete this.settings.post_params[name];
this.callFlash("SetPostParams", [this.settings.post_params]);
};
// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
this.settings.file_types = types;
this.settings.file_types_description = description;
this.callFlash("SetFileTypes", [types, description]);
};
// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
this.settings.file_size_limit = fileSizeLimit;
this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};
// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
this.settings.file_upload_limit = fileUploadLimit;
this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};
// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
this.settings.file_queue_limit = fileQueueLimit;
this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};
// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
this.settings.file_post_name = filePostName;
this.callFlash("SetFilePostName", [filePostName]);
};
// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
this.settings.use_query_string = useQueryString;
this.callFlash("SetUseQueryString", [useQueryString]);
};
// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
this.settings.requeue_on_error = requeueOnError;
this.callFlash("SetRequeueOnError", [requeueOnError]);
};
// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
if (typeof http_status_codes === "string") {
http_status_codes = http_status_codes.replace(" ", "").split(",");
}
this.settings.http_success = http_status_codes;
this.callFlash("SetHTTPSuccess", [http_status_codes]);
};
// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
this.settings.assume_success_timeout = timeout_seconds;
this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};
// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
this.settings.debug_enabled = debugEnabled;
this.callFlash("SetDebugEnabled", [debugEnabled]);
};
// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
if (buttonImageURL == undefined) {
buttonImageURL = "";
}
this.settings.button_image_url = buttonImageURL;
this.callFlash("SetButtonImageURL", [buttonImageURL]);
};
// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
this.settings.button_width = width;
this.settings.button_height = height;
var movie = this.getMovieElement();
if (movie != undefined) {
movie.style.width = width + "px";
movie.style.height = height + "px";
}
this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
this.settings.button_text = html;
this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
this.settings.button_text_top_padding = top;
this.settings.button_text_left_padding = left;
this.callFlash("SetButtonTextPadding", [left, top]);
};
// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
this.settings.button_text_style = css;
this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
this.settings.button_disabled = isDisabled;
this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
this.settings.button_action = buttonAction;
this.callFlash("SetButtonAction", [buttonAction]);
};
// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
this.settings.button_cursor = cursor;
this.callFlash("SetButtonCursor", [cursor]);
};
/* *******************************
Flash Event Interfaces
These functions are used by Flash to trigger the various
events.
All these functions a Private.
Because the ExternalInterface library is buggy the event calls
are added to a queue and the queue then executed by a setTimeout.
This ensures that events are executed in a determinate order and that
the ExternalInterface bugs are avoided.
******************************* */
SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
// Warning: Don't call this.debug inside here or you'll create an infinite loop
if (argumentArray == undefined) {
argumentArray = [];
} else if (!(argumentArray instanceof Array)) {
argumentArray = [argumentArray];
}
var self = this;
if (typeof this.settings[handlerName] === "function") {
// Queue the event
this.eventQueue.push(function () {
this.settings[handlerName].apply(this, argumentArray);
});
// Execute the next queued event
setTimeout(function () {
self.executeNextEvent();
}, 0);
} else if (this.settings[handlerName] !== null) {
throw "Event handler " + handlerName + " is unknown or is not a function";
}
};
// Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
// Warning: Don't call this.debug inside here or you'll create an infinite loop
var f = this.eventQueue ? this.eventQueue.shift() : null;
if (typeof (f) === "function") {
f.apply(this);
}
};
// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
var reg = /[$]([0-9a-f]{4})/i;
var unescapedPost = {};
var uk;
if (file != undefined) {
for (var k in file.post) {
if (file.post.hasOwnProperty(k)) {
uk = k;
var match;
while ((match = reg.exec(uk)) !== null) {
uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
}
unescapedPost[uk] = file.post[k];
}
}
file.post = unescapedPost;
}
return file;
};
// Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
SWFUpload.prototype.testExternalInterface = function () {
try {
return this.callFlash("TestExternalInterface");
} catch (ex) {
return false;
}
};
// Private: This event is called by Flash when it has finished loading. Don't modify this.
// Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
SWFUpload.prototype.flashReady = function () {
// Check that the movie element is loaded correctly with its ExternalInterface methods defined
var movieElement = this.getMovieElement();
if (!movieElement) {
this.debug("Flash called back ready but the flash movie can't be found.");
return;
}
this.cleanUp(movieElement);
this.queueEvent("swfupload_loaded_handler");
};
// Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
// This function is called by Flash each time the ExternalInterface functions are created.
SWFUpload.prototype.cleanUp = function (movieElement) {
// Pro-actively unhook all the Flash functions
try {
if (this.movieElement && typeof (movieElement.CallFunction) === "unknown") { // We only want to do this in IE
this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
for (var key in movieElement) {
try {
if (typeof (movieElement[key]) === "function") {
movieElement[key] = null;
}
} catch (ex) {
}
}
}
} catch (ex1) {
}
// Fix Flashes own cleanup code so if the SWFMovie was removed from the page
// it doesn't display errors.
window["__flash__removeCallback"] = function (instance, name) {
try {
if (instance) {
instance[name] = null;
}
} catch (flashEx) {
}
};
};
/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
this.queueEvent("file_dialog_start_handler");
};
/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queued_handler", file);
};
/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};
/* Called after the file dialog has closed and the selected files have been queued.
You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};
SWFUpload.prototype.uploadStart = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("return_upload_start_handler", file);
};
SWFUpload.prototype.returnUploadStart = function (file) {
var returnValue;
if (typeof this.settings.upload_start_handler === "function") {
file = this.unescapeFilePostParams(file);
returnValue = this.settings.upload_start_handler.call(this, file);
} else if (this.settings.upload_start_handler != undefined) {
throw "upload_start_handler must be a function";
}
// Convert undefined to true so if nothing is returned from the upload_start_handler it is
// interpretted as 'true'.
if (returnValue === undefined) {
returnValue = true;
}
returnValue = !!returnValue;
this.callFlash("ReturnUploadStart", [returnValue]);
};
SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};
SWFUpload.prototype.uploadError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_error_handler", [file, errorCode, message]);
};
SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};
SWFUpload.prototype.uploadComplete = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_complete_handler", file);
};
/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
internal debug console. You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
this.queueEvent("debug_handler", message);
};
/* **********************************
Debug Console
The debug console is a self contained, in page location
for debug message to be sent. The Debug Console adds
itself to the body if necessary.
The console is automatically scrolled as messages appear.
If you are using your own debug handler or when you deploy to production and
have debug disabled you can remove these functions to reduce the file size
and complexity.
********************************** */
// Private: debugMessage is the default debug_handler. If you want to print debug messages
// call the debug() function. When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
if (this.settings.debug) {
var exceptionMessage, exceptionValues = [];
// Check for an exception object and print it nicely
if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
for (var key in message) {
if (message.hasOwnProperty(key)) {
exceptionValues.push(key + ": " + message[key]);
}
}
exceptionMessage = exceptionValues.join("\n") || "";
exceptionValues = exceptionMessage.split("\n");
exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
SWFUpload.Console.writeLine(exceptionMessage);
} else {
SWFUpload.Console.writeLine(message);
}
}
};
SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
var console, documentForm;
try {
console = document.getElementById("SWFUpload_Console");
if (!console) {
documentForm = document.createElement("form");
document.getElementsByTagName("body")[0].appendChild(documentForm);
console = document.createElement("textarea");
console.id = "SWFUpload_Console";
console.style.fontFamily = "monospace";
console.setAttribute("wrap", "off");
console.wrap = "off";
console.style.overflow = "auto";
console.style.width = "700px";
console.style.height = "350px";
console.style.margin = "5px";
documentForm.appendChild(console);
}
console.value += message + "\n";
console.scrollTop = console.scrollHeight - console.clientHeight;
} catch (ex) {
alert("Exception: " + ex.name + " Message: " + ex.message);
}
};
})();
(function () {
/*
Queue Plug-in
Features:
*Adds a cancelQueue() method for cancelling the entire queue.
*All queued files are uploaded when startUpload() is called.
*If false is returned from uploadComplete then the queue upload is stopped.
If false is not returned (strict comparison) then the queue upload is continued.
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
Set the event handler with the queue_complete_handler setting.
*/
if (typeof (SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof (oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof (this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof (user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
// If the file was stopped and re-queued don't restart the upload
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
}
})();
| JavaScript |
var DHTML = (document.getElementById || document.all || document.layers);
function getObj(name) {
if (document.getElementById) {
this.obj = document.getElementById(name);
this.style = document.getElementById(name).style;
}
else if (document.all) {
this.obj = document.all[name];
this.style = document.all[name].style;
}
else if (document.layers) {
this.obj = document.layers[name];
this.style = document.layers[name];
}
}
function toggle(item,prefix) {
var cl = new getObj(prefix + 'l_' + item);
var c = new getObj(prefix + '_' + item);
if ( c.style.display == 'inline' ) {
c.style.display = 'none';
}
else {
c.style.display = 'inline';
}
}
| JavaScript |
var weatherchina = {
onLoad: function() {
// initialization code
this.initialized = true;
this.strings = document.getElementById("weatherchina-strings");
},
onMenuItemCommand: function(e) {
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
promptService.alert(window, this.strings.getString("helloMessageTitle"),
this.strings.getString("helloMessage"));
},
onToolbarButtonCommand: function(e) {
// just reuse the function above. you can change this, obviously!
weatherchina.onMenuItemCommand(e);
}
};
window.addEventListener("load", weatherchina.onLoad, false);
| JavaScript |
weatherchina.onFirefoxLoad = function(event) {
document.getElementById("contentAreaContextMenu")
.addEventListener("popupshowing", function (e){ weatherchina.showFirefoxContextMenu(e); }, false);
};
weatherchina.showFirefoxContextMenu = function(event) {
// show or hide the menuitem based on what the context menu is on
document.getElementById("context-weatherchina").hidden = gContextMenu.onImage;
};
window.addEventListener("load", weatherchina.onFirefoxLoad, false);
| JavaScript |
pref("extensions.weatherchina.boolpref", false);
pref("extensions.weatherchina.intpref", 0);
pref("extensions.weatherchina.stringpref", "A string");
// https://developer.mozilla.org/en/Localizing_extension_descriptions
pref("extensions.1.0.description", "chrome://weatherchina/locale/overlay.properties");
| JavaScript |
function notify_city_change() {
chrome.extension.connect().postMessage({message: 'city_change'});
}
| 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 |
/**
* 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 |
/**
* 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 |
// 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 |
/*
* Mimic (XML-RPC Client for JavaScript) v2.0.1
* Copyright (C) 2005-2009 Carlos Eduardo Goncalves (cadu.goncalves@gmail.com)
*
* Mimic is dual licensed under the MIT (http://opensource.org/licenses/mit-license.php)
* and GPLv3 (http://opensource.org/licenses/gpl-3.0.html) licenses.
*/
/**
* XmlRpc
*/
function XmlRpc(){
};
/** <p>XML-RPC document prolog.</p> */
XmlRpc.PROLOG = "<?xml version=\"1.0\"?>\n";
/** <p>XML-RPC methodCall node template.</p> */
XmlRpc.REQUEST = "<methodCall>\n<methodName>${METHOD}</methodName>\n<params>\n${DATA}</params>\n</methodCall>";
/** <p>XML-RPC param node template.</p> */
XmlRpc.PARAM = "<param>\n<value>\n${DATA}</value>\n</param>\n";
/** <p>XML-RPC array node template.</p> */
XmlRpc.ARRAY = "<array>\n<data>\n${DATA}</data>\n</array>\n";
/** <p>XML-RPC struct node template.</p> */
XmlRpc.STRUCT = "<struct>\n${DATA}</struct>\n";
/** <p>XML-RPC member node template.</p> */
XmlRpc.MEMBER = "<member>\n${DATA}</member>\n";
/** <p>XML-RPC name node template.</p> */
XmlRpc.NAME = "<name>${DATA}</name>\n";
/** <p>XML-RPC value node template.</p> */
XmlRpc.VALUE = "<value>\n${DATA}</value>\n";
/** <p>XML-RPC scalar node template (int, i4, double, string, boolean, base64, dateTime.iso8601).</p> */
XmlRpc.SCALAR = "<${TYPE}>${DATA}</${TYPE}>\n";
/**
* <p>Get the tag name used to represent a JavaScript
* object in the XMLRPC protocol.</p>
* @param data
* A JavaScript object.
* @return
* <code>String</code> with XMLRPC object type.
*/
XmlRpc.getDataTag = function(data) {
try {
var tag = typeof data;
switch(tag.toLowerCase()) {
case "number":
tag = (Math.round(data) == data) ? "int" : "double";
break;
case "object":
if(data.constructor == Base64)
tag = "base64";
else
if(data.constructor == String)
tag = "string";
else
if(data.constructor == Boolean)
tag = "boolean";
else
if(data.constructor == Array)
tag = "array";
else
if(data.constructor == Date)
tag = "dateTime.iso8601";
else
if(data.constructor == Number)
tag = (Math.round(data) == data) ? "int" : "double";
else
tag = "struct";
break;
}
return tag;
}
catch(e) {
Engine.reportException(null, e);
}
};
/**
* <p>Get JavaScript object type represented by
* XMLRPC protocol tag.<p>
* @param tag
* A XMLRPC tag name.
* @return
* A JavaScript object.
*/
XmlRpc.getTagData = function(tag) {
var data = null;
switch(tag) {
case "struct":
data = new Object();
break;
case "array":
data = new Array();
break;
case "datetime.iso8601":
data = new Date();
break;
case "boolean":
data = new Boolean();
break;
case "int":
case "i4":
case "double":
data = new Number();
break;
case "string":
data = new String();
break;
case "base64":
data = new Base64();
break;
}
return data;
};
/**
* XmlRpcRequest
* @param url
* Server url.
* @param method
* Server side method to call.
*/
function XmlRpcRequest(url, method) {
this.serviceUrl = url;
this.methodName = method;
this.params = [];
};
/**
* <p> Add a new request parameter.</p>
* @param data
* New parameter value.
*/
XmlRpcRequest.prototype.addParam = function(data) {
var type = typeof data;
switch(type.toLowerCase()) {
case "function":
return;
case "object":
if(!data.constructor.name) return;
}
this.params.push(data);
};
/**
* <p>Clear all request parameters.</p>
* @param data
* New parameter value.
*/
XmlRpcRequest.prototype.clearParams = function() {
this.params.splice(0, this.params.length);
};
/**
* <p>Execute a synchronous XML-RPC request.</p>
* @return
* XmlRpcResponse object.
*/
XmlRpcRequest.prototype.send = function() {
var xml_params = "";
for(var i = 0; i < this.params.length; i++)
xml_params += XmlRpc.PARAM.replace("${DATA}", this.marshal(this.params[i]));
var xml_call = XmlRpc.REQUEST.replace("${METHOD}", this.methodName);
xml_call = XmlRpc.PROLOG + xml_call.replace("${DATA}", xml_params);
var xhr = Builder.buildXHR();
xhr.open("POST", this.serviceUrl, false);
xhr.send(Builder.buildDOM(xml_call));
return new XmlRpcResponse(xhr.responseXML);
};
/**
* <p>Marshal request parameters.</p>
* @param data
* A request parameter.
* @return
* String with XML-RPC element notation.
*/
XmlRpcRequest.prototype.marshal = function(data) {
var type = XmlRpc.getDataTag(data);
var scalar_type = XmlRpc.SCALAR.replace(/\$\{TYPE\}/g, type);
var xml = "";
switch(type) {
case "struct":
var member = "";
for(var i in data) {
var value = "";
value += XmlRpc.NAME.replace("${DATA}", i);
value += XmlRpc.VALUE.replace("${DATA}", this.marshal(data[i]));
member += XmlRpc.MEMBER.replace("${DATA}", value);
}
xml = XmlRpc.STRUCT.replace("${DATA}", member);
break;
case "array":
var value = "";
for(var i = 0; i < data.length; i++) {
value += XmlRpc.VALUE.replace("${DATA}", this.marshal(data[i]));
}
xml = XmlRpc.ARRAY.replace("${DATA}", value);
break;
case "dateTime.iso8601":
xml = scalar_type.replace("${DATA}", data.toIso8601());
break;
case "boolean":
xml = scalar_type.replace("${DATA}", (data == true) ? 1 : 0);
break;
case "base64":
xml = scalar_type.replace("${DATA}", data.encode());
break;
default :
xml = scalar_type.replace("${DATA}", data);
break;
}
return xml;
};
/**
* XmlRpcResponse
* @param xml
* Response XML document.
*/
function XmlRpcResponse(xml) {
this.xmlData = xml;
};
/**
* <p>Indicate if response is a fault.</p>
* @return
* Boolean flag indicating fault status.
*/
XmlRpcResponse.prototype.isFault = function() {
return this.faultValue;
};
/**
* <p>Parse XML response to JavaScript.</p>
* @return
* JavaScript object parsed from XML-RPC document.
*/
XmlRpcResponse.prototype.parseXML = function() {
this.faultValue = undefined;
this.currentIsName = false;
this.propertyName = "";
this.params = [];
for(var i = 0; i < this.xmlData.childNodes.length; i++)
this.unmarshal(this.xmlData.childNodes[i], 0);
return this.params[0];
};
/**
* <p>Unmarshal response parameters.</p>
* @param node
* Current document node under processing.
* @param parent
* Current node' parent node.
*/
XmlRpcResponse.prototype.unmarshal = function(node, parent) {
if(node.nodeType == 1) {
var obj = null;
var tag = node.tagName.toLowerCase();
switch(tag) {
case "fault":
this.faultValue = true;
break;
case "name":
this.currentIsName = true;
break;
default:
obj = XmlRpc.getTagData(tag);
break;
}
if(obj != null) {
this.params.push(obj);
if(tag == "struct" || tag == "array") {
if(this.params.length > 1) {
switch(XmlRpc.getDataTag(this.params[parent])) {
case "struct":
this.params[parent][this.propertyName] = this.params[this.params.length - 1];
break;
case "array":
this.params[parent].push(this.params[this.params.length - 1]);
break;
}
}
var parent = this.params.length - 1;
}
}
for(var i = 0; i < node.childNodes.length; i++) {
this.unmarshal(node.childNodes[i], parent);
}
}
if( (node.nodeType == 3) && (/[^\t\n\r ]/.test(node.nodeValue)) ) {
if(this.currentIsName == true) {
this.propertyName = node.nodeValue;
this.currentIsName = false;
}
else {
switch(XmlRpc.getDataTag(this.params[this.params.length - 1])) {
case "dateTime.iso8601":
this.params[this.params.length - 1] = Date.fromIso8601(node.nodeValue);
break;
case "boolean":
this.params[this.params.length - 1] = (node.nodeValue == "1") ? true : false;
break;
case "int":
case "double":
this.params[this.params.length - 1] = new Number(node.nodeValue);
break;
case "string":
this.params[this.params.length - 1] = new String(node.nodeValue);
break;
case "base64":
this.params[this.params.length - 1] = new Base64(node.nodeValue);
break;
}
if(this.params.length > 1) {
switch(XmlRpc.getDataTag(this.params[parent])) {
case "struct":
this.params[parent][this.propertyName] = this.params[this.params.length - 1];
break;
case "array":
this.params[parent].push(this.params[this.params.length - 1]);
break;
}
}
}
}
};
/**
* Builder
*/
function Builder(){
};
/**
* <p>Build a valid XMLHttpRequest object</p>
* @return
* XMLHttpRequest object.
*/
Builder.buildXHR = function() {
return (typeof XMLHttpRequest != "undefined") ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
};
/**
* <p>Build a valid XML document from string markup.</p>
* @param xml
* Document markup.
* @return
* XMLDocument object.
*/
Builder.buildDOM = function(xml) {
if(typeof DOMParser != "undefined") {
var w3c_parser = new DOMParser();
return w3c_parser.parseFromString(xml, "text/xml");
}
else {
var names = ["Microsoft.XMLDOM", "MSXML2.DOMDocument", "MSXML.DOMDocument"];
for(var i = 0; i < names.length; i++) {
try{
var atx_parser = new ActiveXObject(names[i]);
atx_parser.loadXML(xml);
return atx_parser;
}
catch (e) {/* ignore */ }
}
}
return null;
};
/**
* Date
*/
/**
* <p>Convert a GMT date to ISO8601.</p>
* @return
* <code>String</code> with an ISO8601 date.
*/
Date.prototype.toIso8601 = function() {
year = this.getYear();
if (year < 1900) year += 1900;
month = this.getMonth() + 1;
if (month < 10) month = "0" + month;
day = this.getDate();
if (day < 10) day = "0" + day;
time = this.toTimeString().substr(0,8);
return year + month + day + "T" + time;
};
/**
* <p>Convert ISO8601 date to GMT.</p>
* @param value
* ISO8601 date.
* @return
* GMT date.
*/
Date.fromIso8601 = function(value) {
year = value.substr(0,4);
month = value.substr(4,2);
day = value.substr(6,2);
hour = value.substr(9,2);
minute = value.substr(12,2);
sec = value.substr(15,2);
return new Date(year, month - 1, day, hour, minute, sec, 0);
};
/**
* Base64
*/
function Base64(value) {
Base64.prototype.bytes = value;
};
/** <p>Base64 characters map.</p> */
Base64.CHAR_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* <p>Encode the object bytes using base64 algorithm.</p>
* @return
* Encoded string.
*/
Base64.prototype.encode = function() {
if(typeof btoa == "function")
this.bytes = btoa(this.bytes);
else {
var _byte = new Array(), _char = new Array(), _result = new Array();
var j = 0;
for (var i = 0; i < this.bytes.length; i += 3) {
_byte[0] = this.bytes.charCodeAt(i);
_byte[1] = this.bytes.charCodeAt(i + 1);
_byte[2] = this.bytes.charCodeAt(i + 2);
_char[0] = _byte[0] >> 2;
_char[1] = ((_byte[0] & 3) << 4) | (_byte[1] >> 4);
_char[2] = ((_byte[1] & 15) << 2) | (_byte[2] >> 6);
_char[3] = _byte[2] & 63;
if(isNaN(_byte[1]))
_char[2] = _char[3] = 64;
else
if(isNaN(_byte[2]))
_char[3] = 64;
_result[j++] = Base64.CHAR_MAP.charAt(_char[0]) + Base64.CHAR_MAP.charAt(_char[1])
+ Base64.CHAR_MAP.charAt(_char[2]) + Base64.CHAR_MAP.charAt(_char[3]);
}
this.bytes = _result.join("");
}
return this.bytes;
};
/**
* <p>Decode the object bytes using base64 algorithm.</p>
* @return
* Decoded string.
*/
Base64.prototype.decode = function() {
if(typeof atob == "function")
this.bytes = atob(this.bytes);
else {
var _byte = new Array(), _char = new Array(), _result = new Array();
var j = 0;
while ((this.bytes.length % 4) != 0)
this.bytes += "=";
for (var i = 0; i < this.bytes.length; i += 4) {
_char[0] = Base64.CHAR_MAP.indexOf(this.bytes.charAt(i));
_char[1] = Base64.CHAR_MAP.indexOf(this.bytes.charAt(i + 1));
_char[2] = Base64.CHAR_MAP.indexOf(this.bytes.charAt(i + 2));
_char[3] = Base64.CHAR_MAP.indexOf(this.bytes.charAt(i + 3));
_byte[0] = (_char[0] << 2) | (_char[1] >> 4);
_byte[1] = ((_char[1] & 15) << 4) | (_char[2] >> 2);
_byte[2] = ((_char[2] & 3) << 6) | _char[3];
_result[j++] = String.fromCharCode(_byte[0]);
if(_char[2] != 64)
_result[j++] = String.fromCharCode(_byte[1]);
if(_char[3] != 64)
_result[j++] = String.fromCharCode(_byte[2]);
}
this.bytes = _result.join("");
}
return this.bytes;
}; | JavaScript |
// 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
* Provides methods for the autodo web client, for making
* calls to the autodo API, as well as rendering
* and bindings for UI navigation elements.
*
*/
/** google global namespace for Google projects. */
var google = google || {};
/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};
/** samples namespace for Devrel sample code. */
google.devrel.samples = google.devrel.samples || {};
/** autodo namespace for this sample. */
google.devrel.samples.autodo = google.devrel.samples.autodo || {};
/** autodo alias for the google.devrel.samples.autodo namespace. */
var autodo = google.devrel.samples.autodo;
/** ApiClient object for API methods. */
google.devrel.samples.autodo.ApiClient =
google.devrel.samples.autodo.ApiClient || {};
/** Bindings object for binding actions to UI elements. */
google.devrel.samples.autodo.Bindings =
google.devrel.samples.autodo.Bindings || {};
/** Data object for persisting server data on the client. */
google.devrel.samples.autodo.Data = google.devrel.samples.autodo.Data || {};
/**
* Stack for maintaining the UI page history (for back buttons).
* @type {Array}
*/
google.devrel.samples.autodo.Data.hashStack = new Array();
/** Generic logging functionality. */
google.devrel.samples.autodo.Logger = google.devrel.samples.autodo.Logger || {};
/**
* Lowest logging level, for debugging.
* @type {number}
*/
google.devrel.samples.autodo.Logger.DEBUG = 3;
/**
* Middle logging level, for informational messages, during normal operation.
* @type {number}
*/
google.devrel.samples.autodo.Logger.INFO = 2;
/**
* Warning log level, for when things go wrong.
* @type {number}
*/
google.devrel.samples.autodo.Logger.WARN = 1;
/**
* No logging level, default.
* @type {number}
*/
google.devrel.samples.autodo.Logger.NONE = 0;
/**
* The default logging level.
* @type {number}
*/
google.devrel.samples.autodo.Logger.level =
google.devrel.samples.autodo.Logger.NONE;
/** Enum of fixed incident queries. */
google.devrel.samples.autodo.Query = google.devrel.samples.autodo.Query || {};
/**
* Query for all incidents.
* @type {string}
*/
google.devrel.samples.autodo.Query.ALL = 'all';
/**
* Query for an incident by ID.
* @type {string}
*/
google.devrel.samples.autodo.Query.ID = 'id';
/**
* Query for 'my' open incidents.
* @type {string}
*/
google.devrel.samples.autodo.Query.MINE = 'mine';
/**
* Query for 'my' incidents of any status.
* @type {string}
*/
google.devrel.samples.autodo.Query.MINE_ALL = 'mineall';
/**
* Query for resolved incidents.
* @type {string}
*/
google.devrel.samples.autodo.Query.RESOLVED = 'resolved';
/**
* Query for the settings page.
* @type {string}
*/
google.devrel.samples.autodo.Query.SETTINGS = 'settings';
/**
* Query for incidents that need action (unassigned and open).
* @type {string}
*/
google.devrel.samples.autodo.Query.NEEDS_ACTION = 'needsaction';
/** Render object for rendering content. */
google.devrel.samples.autodo.Render =
google.devrel.samples.autodo.Render || {};
/** Util object for autodo utility methods. */
google.devrel.samples.autodo.Util =
google.devrel.samples.autodo.Util || {};
/** Aliases for autodo objects. */
var ApiClient = google.devrel.samples.autodo.ApiClient;
var Bindings = google.devrel.samples.autodo.Bindings;
var Data = google.devrel.samples.autodo.Data;
var Logger = google.devrel.samples.autodo.Logger;
var Query = google.devrel.samples.autodo.Query;
var Render = google.devrel.samples.autodo.Render;
var Util = google.devrel.samples.autodo.Util;
/**
* Base URI of the autodo API.
* @type {string}
*/
google.devrel.samples.autodo.ApiClient.BASE_URI = '/resources/v1/incidents/';
/**
* Default search options for list view.
* @type {string}
*/
google.devrel.samples.autodo.ApiClient.DEFAULT_SEARCH = '';
/**
* Special search token to be used for searching by ID.
* @type {string}
*/
google.devrel.samples.autodo.ApiClient.ID_TOKEN = 'id=';
/**
* The last parameters used to call the autodo API.
* meant for use with nav elements (i.e."back" button).
* @type {string}
*/
google.devrel.samples.autodo.ApiClient.currentListView =
ApiClient.DEFAULT_SEARCH;
/**
* Logs a message if it has sufficiently high priority.
* @param {string} message Message to log.
* @param {number} opt_priority Optional priority to use for the message.
*/
google.devrel.samples.autodo.Logger.log = function(message, opt_priority) {
opt_priority = opt_priority || Logger.DEBUG;
if (opt_priority <= Logger.level && console && console.log) {
console.log(message);
}
};
/**
* Displays the list of incidents, represented by the currentListView. If a
* current copy of the list exists in cache, show that. If not, call the API.
* @param {Object=} opt_options parameter list to pass to API.
*/
google.devrel.samples.autodo.ApiClient.listView = function(opt_options) {
Render.showInfoMessage('Loading Incident List...');
var opt_options = opt_options || ApiClient.DEFAULT_SEARCH;
var uri = ApiClient.BASE_URI;
if (opt_options) {
uri += '?' + opt_options;
}
ApiClient.currentListView = opt_options;
if (ApiClient.useIncidentCache) {
$.ajax({
url: uri,
type: 'GET',
dataType: 'json',
success: [Render.incidentTable, Data.persistIncidentList]
});
} else {
Render.incidentTable(Data.incidentList);
}
};
/**
* Retrieves and displays a single incident, represented by id.
* @param {string} id The id to retrieve and display.
*/
google.devrel.samples.autodo.ApiClient.singleView = function(id) {
Render.showInfoMessage('Loading Incident...');
var uri = ApiClient.BASE_URI;
uri += id;
$.ajax({
url: uri,
type: 'GET',
dataType: 'json',
success: Render.singleIncident
});
};
/**
* Returns data from an API request for info about a single incident.
* @param {string} id The id of a single incident.
* @param {string} callback The callback function to send data to upon success.
* @param {Object=} opt_params Optional parameters to pass to callback function.
*/
google.devrel.samples.autodo.ApiClient.getIncidentData = function(
id, callback, opt_params) {
var incidentData;
$.ajax({
url: ApiClient.BASE_URI + id,
type: 'GET',
dataType: 'json',
success: function(data) {
callback(data, opt_params);
}
});
};
/**
* Calls the autodo API with the input search terms.
*/
google.devrel.samples.autodo.ApiClient.search = function() {
var raw_query = $('input#search-box').val();
if (raw_query) {
var queries = [];
var tokens = raw_query.split(Util.regex);
for (var i = 0; i < tokens.length; ++i) {
var token = tokens[i];
if (Util.regex.test(token)) {
if (++i < tokens.length) {
if (token == ApiClient.ID_TOKEN) {
Util.setHashPair(token + escape(tokens[i].trim()));
return;
} else {
queries.push(token + escape(tokens[i].trim()));
}
}
}
}
Util.setHashPair(queries.join(' '));
ApiClient.listView(queries.join('&'));
}
};
/**
* Calls the autodo API to assign an incident to a new owner.
* @param {Object} data Data representation of an incident.
* @param {Object} owner An object containing name of new incident owner.
*/
google.devrel.samples.autodo.ApiClient.assignIncident = function(data, owner) {
Render.showInfoMessage('Assigning incident...');
data.owner = owner.name;
$.ajax({
url: ApiClient.BASE_URI + data.id,
type: 'PUT',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
// Reset incident cache.
Data.incidentListUpdated = 0;
Util.reloadCurrentHash();
}
});
};
/**
* Calls the autodo API to set the status of an incident.
* @param {Object} data Data representation of an incident.
* @param {string} status New status to set for the incident.
*/
google.devrel.samples.autodo.ApiClient.setStatus = function(data, status) {
Render.showInfoMessage('Setting incident status...');
if (status == Query.RESOLVED) {
data.resolved = (new Date).toISOString();
} else {
data.resolved = null;
}
data.status = status;
$.ajax({
url: ApiClient.BASE_URI + data.id,
type: 'PUT',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
// Reset incident cache.
Data.incidentListUpdated = 0;
Util.reloadCurrentHash();
}
});
};
/**
* Iterates through and updates a list of incidents with associated tags.
* @param {Object} incidentTagList Object of ids with accepted and
* suggested tags.
*/
google.devrel.samples.autodo.ApiClient.updateTags = function(
incidentTagList) {
Render.showInfoMessage('Updating labels...');
$.each(incidentTagList, function(id, tagsList) {
ApiClient.getIncidentData(id,
ApiClient.updateIncidentTags,
{'id': id, 'tagsList': tagsList});
});
};
/**
* Calls the autodo API to add accepted tags to an incident.
* @param {Object} data Data representation of an incident.
* @param {Object} incident An object containing updated incident tags.
*/
google.devrel.samples.autodo.ApiClient.updateIncidentTags = function(
data, incident) {
data.accepted_tags = incident.tagsList.accepted_tags;
data.suggested_tags = incident.tagsList.suggested_tags;
$.ajax({
url: ApiClient.BASE_URI + incident.id,
type: 'PUT',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
// Reset incident cache.
Data.incidentListUpdated = 0;
Render.updateIncidentListTags(incident.id, incident.tagsList);
}
});
};
/**
* Indicates if ApiClient should use the data cache for storing incident list.
* @return {boolean} Whether to use the cache (true) or not.
*/
google.devrel.samples.autodo.ApiClient.useIncidentCache = function() {
var now = new Date().getTime();
var delta = now - Data.incidentListUpdated;
var shouldUseIncidentCache = delta > Data.INCIDENT_CACHE_LENGTH * 1000 ||
ApiClient.currentListView != Data.incidentListType ||
!Data.USE_INCIDENT_CACHE;
return shouldUseIncidentCache;
};
/**
* Retrieves user settings.
*/
google.devrel.samples.autodo.ApiClient.getUserSettings = function() {
$.ajax({
url: '/resources/v1/userSettings',
type: 'GET',
dataType: 'json',
success: Render.showUserSettings,
statusCode: {
404: function() {
Render.showUserSettings(null);
}
}
});
};
/**
* Save user settings.
*/
google.devrel.samples.autodo.ApiClient.saveUserSettings = function() {
var data = {
'addToTasks': $('#userSettings_addToTasks')[0].checked,
'taskListId': $('#userSettings_taskList').val()
};
$.ajax({
url: '/resources/v1/userSettings',
type: 'PUT',
data: JSON.stringify(data),
dataType: 'json',
success: Render.showUserSettings
});
};
/**
* Indicates how old the incident cache may be before it needs to be refreshed
* (in seconds).
* @type {number}
*/
google.devrel.samples.autodo.Data.INCIDENT_CACHE_LENGTH = 60;
/**
* Whether or not to use the local incident cache.
* @type {boolean}
*/
google.devrel.samples.autodo.Data.USE_INCIDENT_CACHE = true;
/**
* Indicates the type of list view that is represented by the cached incident
* list.
* @type {string}
*/
google.devrel.samples.autodo.Data.incidentListType = '';
/**
* Indicates when the incident list was last updated.
* @type {number}
*/
google.devrel.samples.autodo.Data.incidentListUpdated = 0;
/**
* Persists a list of incidents from the server in a local object.
* @param {Object} incidentList List of incidents retrieved from the server.
*/
google.devrel.samples.autodo.Data.persistIncidentList = function(
incidentList) {
Data.incidentList = incidentList;
Data.incidentListType = ApiClient.currentListView;
Data.incidentListUpdated = new Date().getTime();
};
/**
* Renders a message during loading actions.
* @param {string} message Message to be shown during action.
*/
google.devrel.samples.autodo.Render.showInfoMessage = function(message) {
$('#notificationbar').find('.message').text(message);
};
/**
* Replaces the toggle checkbox with a back button.
*/
google.devrel.samples.autodo.Render.backButton = function() {
Logger.log('rendered back button');
$('a.select-button').replaceWith(
'<a class="back-button atd-button no-margin"' +
'data-tooltip="Back to Case List">' +
'<img src="/images/theme/icons/back.gif" /></a>'
);
$('a.back-button').unbind('click');
$('a.back-button').click(function() {
Logger.log('pushed back');
Render.loadPreviousHashPair();
});
};
/**
* Renders a checkbox element based on optional parameters.
* @param {Object=} opt_properties Object optional checkbox element properties.
* @return {Object} A checkbox jQuery element.
*/
google.devrel.samples.autodo.Render.checkBox = function(opt_properties) {
var checkBox = $('<input>').attr({
'type': 'checkbox',
'class': opt_properties.cssClass,
'id': opt_properties.id,
'value': opt_properties.value});
return checkBox;
};
/**
* Renders an incident view from API call data.
* @param {Object} data JSON object containing incident list info.
*/
google.devrel.samples.autodo.Render.incidentTable = function(data) {
if ($('a.back-button').length) {
$('a.back-button').replaceWith(
'<a class="select-button atd-button no-margin" data-tooltip="Select">' +
'<input type="checkbox" id="toggle-all">' +
'</a>'
);
}
// Array to hold accumulated global tag list.
var tagList = Array();
$('#content').empty();
$('#content').append($('<table>').addClass('list'));
$.each(data, function(i, incident) {
var trow = $('<tr>').attr('status', incident.status);
var checkBox = Render.checkBox({
cssClass: 'content_checkbox', value: incident.id
});
checkBox.change(function() {
Render.setStatusButton();
});
trow.append($('<td>').append(checkBox));
// Incident title and message summary.
var incidentTd = $('<td>');
var incidentDiv = $('<div>').addClass(
'content-list-div').attr('value', incident.id).attr('status',
incident.status);
// <p> tags are used as throwaway tags for HTML sanitization and don't
// appear in the UI.
incidentDiv.append($('<strong>').append($('<p>').text(
incident.title + ' - ').html()));
incidentDiv.append($('<p>').text(incident.messages[0].body).html());
Render.tagList(incidentTd, incident);
trow.append(incidentTd.append(incidentDiv));
// Incident timestamp.
trow.append($('<td>').append(
google.devrel.samples.autodo.Util.formatDateStamp(incident.created))
);
$('#content > table').append(trow);
// Add current incident tags to global list if not duplicates.
var allTags = incident.accepted_tags.concat(incident.suggested_tags);
for (var i = 0; i < allTags.length; i++) {
if ($.inArray(allTags[i], tagList) == -1) {
tagList.push(allTags[i]);
}
}
});
Render.reloadButton();
Render.setStatusButton();
Render.popUpCheckboxes(tagList);
Bindings.bindIncidentLink();
Bindings.bindCheckAllBoxes();
Bindings.bindAcceptTags();
Bindings.bindRemoveTags();
};
/**
* Renders a button to resolve or reopen an incident.
* @param {boolean=} opt_override Whether to optionally override the button
* default status of false.
*/
google.devrel.samples.autodo.Render.setStatusButton = function(opt_override) {
var resolved = opt_override || false;
$('.content_checkbox:checked').parent().parent().find('.content-list-div').
each(function() {
if ($(this).attr('status') == 'resolved') {
resolved = true;
return false;
}
});
if (!resolved) {
$('#status-button').text('Resolve').attr('status', 'resolved');
} else {
$('#status-button').text('Open').attr('status', 'new');
}
};
/**
* Renders a button to reload an incident list.
*/
google.devrel.samples.autodo.Render.reloadButton = function() {
if ($('a.original-button').length) {
$('a.original-button').replaceWith(
'<a class="reload-button atd-button" data-tooltip="Reload">' +
'<img src="/images/theme/icons/reload.png" /></a>'
);
}
google.devrel.samples.autodo.Bindings.bindReloadButton();
};
/**
* Renders a button linking to the original case.
* @param {string} canonicalLink of the original incident.
*/
google.devrel.samples.autodo.Render.originalButton = function(canonicalLink) {
if ($('a.reload-button').length) {
$('a.reload-button').replaceWith(
'<a class="original-button atd-button" data-tooltip="Original">' +
'Original</a>'
);
}
google.devrel.samples.autodo.Bindings.bindOriginalButton(canonicalLink);
};
/**
* Returns a list of all checked tags in the options menu.
* @return {Object} List of checked tags in options menu.
*/
google.devrel.samples.autodo.Bindings.findCheckedTagOptions = function() {
var optionsTagsList = new Array();
$('#label-options').find('input:checked').each(function() {
optionsTagsList.push($(this).val());
});
if ($('#label-options').find('input[type="text"]').val().length) {
optionsTagsList.push(
$('#label-options').find('input[type="text"]').val()
);
}
return optionsTagsList;
};
/**
* Returns a list of accepted and suggested tags from an incident.
* @param {Object} incidentElement An element object.
* @return {Object} a List of suggested and accepted tags for an incident.
*/
google.devrel.samples.autodo.Bindings.findIncidentTags = function(
incidentElement) {
var incidentTags = {};
var optionsTagsList = Bindings.findCheckedTagOptions();
incidentTags.id = parseInt(incidentElement.attr('value'), 10);
incidentTags.accepted_tags = new Array();
for (var i = 0; i < optionsTagsList.length; i++) {
incidentTags.accepted_tags.push(optionsTagsList[i]);
}
incidentTags.suggested_tags = [];
incidentElement.parentsUntil('tr').parent().find('.label').each(function() {
if ($(this).hasClass('accepted')) {
if (jQuery.inArray($(this).attr('value'),
incidentTags.accepted_tags) == -1) {
incidentTags.accepted_tags.push($(this).attr('value'));
}
} else if ($(this).hasClass('suggested')) {
incidentTags.suggested_tags.push($(this).attr('value'));
}
});
return incidentTags;
};
/**
* Returns a list of elements and ids corresponding to incidents that need
* to be updated.
* @param {Object} contentElement Div element to parse for updated incidents.
* @return {Object} Object containing elements and corresponding element id
* for each incident to update.
*/
google.devrel.samples.autodo.Bindings.findIncidentUpdates = function(
contentElement) {
var incidentTagList = {};
var optionsTagsList = Bindings.findCheckedTagOptions();
contentElement.find('input:checked, div.title.content-list-div').each(
function() {
if ($(this).length && optionsTagsList.length) {
var incidentTags = Bindings.findIncidentTags($(this));
incidentTagList[$(this).attr('value')] = incidentTags;
}
});
return incidentTagList;
};
/**
* Renders a list of tags.
* @param {Object} incidentTd td element to append tags to.
* @param {Object} incident An Object containing tag data.
*/
google.devrel.samples.autodo.Render.tagList = function(incidentTd, incident) {
$.each(incident.accepted_tags.sort(), function(index, tag) {
incidentTd.prepend($('<span>').addClass('label accepted').
attr('value', tag).append(tag));
});
$.each(incident.suggested_tags.sort(), function(index, tag) {
incidentTd.prepend($('<span>').addClass('label suggested').
attr('value', tag).append(tag));
});
incidentTd.find('span.suggested').append($('<a>').addClass('accept').html(
'✓'));
incidentTd.find('span.label').append($('<a>').addClass('remove').html(
'✗'));
};
/**
* Updates display of the tags for a incident in a list view.
* @param {string} id The id of the incident.
* @param {Object} tagsList tags associated with incident.
*/
google.devrel.samples.autodo.Render.updateIncidentListTags = function(
id, tagsList) {
var tagsTd = $('.content-list-div[value="' + id + '"]').parent();
tagsTd.find('.label').remove();
Render.tagList(tagsTd, tagsList);
Bindings.bindAcceptTags();
Bindings.bindRemoveTags();
};
/**
* Position pop-up options boxes.
*/
google.devrel.samples.autodo.Render.popUpPosition = function() {
var assignPosition = $('#assign-button').offset();
var labelPosition = $('#label-button').offset();
$('#assign-options').offset({
top: assignPosition.top + $('#assign-button').outerHeight(),
left: assignPosition.left
});
$('#label-options').offset({
top: labelPosition.top + $('#label-button').outerHeight(),
left: labelPosition.left
});
google.devrel.samples.autodo.Bindings.blurPopUpMenus();
};
/**
* Populates tag popup checkboxes with current tag values.
* @param {Array} tagList List of tags to populate.
*/
google.devrel.samples.autodo.Render.popUpCheckboxes = function(
tagList) {
tagList.sort();
$('#label-options').find('.options-checkboxes').empty();
for (var i = 0; i < tagList.length; i++) {
var checkBox = Render.checkBox({
id: 'tag_' + tagList[i], value: tagList[i]
});
$('#label-options').find('.options-checkboxes').append(checkBox);
var checkboxLabel = $('<label>').after('<br />');
checkboxLabel.text(tagList[i]).attr({for: 'tag_' + tagList[i]});
$('#label-options').find('.options-checkboxes').append(checkboxLabel);
}
};
/**
* Renders a single incident view from API call data.
* @param {Object} data JSON object containing incident list info.
*/
google.devrel.samples.autodo.Render.singleIncident = function(data) {
Render.backButton();
Render.setStatusButton(data.status == 'resolved');
Render.originalButton(data.canonical_link);
$('#content').empty();
var incidentTd = $('<td>').css('padding', '10px 0px 10px 0px');
// <p> tags are used as throwaway tags for HTML sanitization and don't
// appear in the UI.
var titleText = $('<p>').text(data.title).html();
var titleDiv = $('<div>').addClass('title').append(titleText);
titleDiv.addClass('content-list-div').attr('value', data.id);
Render.tagList(incidentTd, data);
$('titleDiv .label').append($('<a>'));
incidentTd.append(titleDiv);
$('#content').append($('<table>').addClass('incident'));
$('#content > table').append($('<tr>').append(incidentTd));
$.each(data.messages, function(i, message) {
var td = $('<td>');
td.append($('<div>').addClass('incident-date').append(
Util.formatDateStamp(message.sent)));
// <p> tags are used as throwaway tags for HTML sanitization and don't
// appear in the UI.
var authorText = $('<p>').text(message.author + ': ').html();
td.append($('<div>').addClass('incident').append(authorText));
var messageText = $('<p>').text(message.body).html().replace(
/\r?\n/g, '<br />');
td.append($('<div>').addClass('incident').append(messageText));
$('#content > table').append($('<tr>').append(td));
});
Bindings.bindAcceptTags();
Bindings.bindRemoveTags();
};
/**
* Renders the user settings.
* @param {Object} opt_data Optional data to display. If null, ask user to grant
* access.
*/
google.devrel.samples.autodo.Render.showUserSettings = function(opt_data) {
var div = $('#settings');
var setting = $('<div class="setting userSetting">');
setting.append($('<h1>').text('User settings'));
if (opt_data != null) {
var checkBox = $('<input>').attr({
'type': 'checkbox',
'id': 'userSettings_addToTasks',
'checked': opt_data['addToTasks']});
var button = $('<button>').addClass('atd-button').click(
google.devrel.samples.autodo.ApiClient.saveUserSettings).text('Save');
setting.append(checkBox);
setting.append('Automatically add assigned incidents to my Google ' +
'Tasks.<br/>');
var tasklists = $('<div>');
var combobox = $('<select>').attr({'id': 'userSettings_taskList'});
var hasTaskList = false;
tasklists.append($('<label style="padding-right: 5px;">').text(
'Choose task list:'));
tasklists.append(combobox);
$.each(opt_data.taskLists, function(i, taskList) {
combobox.append(
$('<option>').attr({'value': taskList.id}).text(taskList.title));
if (taskList.id == opt_data.taskListId) {
hasTaskList = true;
}
});
if (hasTaskList) {
combobox.val(opt_data.taskListId);
}
setting.append(tasklists);
setting.append(button);
} else {
setting.append(
$('<p>').html(
$('<p>').
append(
$('<button>').attr({'class': 'atd-button'}).click(
function() {
Render.showGrantAccessWindow('tasks');
}).text('Grant'))
.append(
' Au-to-do access to your Google Tasks to automatically add ' +
'assigned incidents to your task list.')));
}
$('.userSetting').remove();
div.append(setting);
}
/**
* Renders a list of application settings.
*/
google.devrel.samples.autodo.Render.settingsList = function() {
Render.backButton();
Render.showInfoMessage('Loading Settings...');
$.ajax({
url: '/settings',
type: 'GET',
dataType: 'html',
success: function(data) {
$('#content').empty();
$('#content').append(data);
google.devrel.samples.autodo.ApiClient.getUserSettings();
}
});
};
/**
* Sets a sidebar <li> element to "selected".
* @param {Object} li JQuery sidebar li object to be toggled.
*/
google.devrel.samples.autodo.Render.selectedSidebarLink = function(li) {
$('#sidebar li').removeClass('selected');
$(li).addClass('selected');
};
/**
* Display a pop-up window to request access to a Au-to-do required API.
* @param {string} api String representing an internal API. Current supported
* values are 'tasks' and 'prediction' (internal only).
*/
google.devrel.samples.autodo.Render.showGrantAccessWindow = function(api) {
window.open('/oauth/' + api, 'mywindow', 'status=1,width=400,height=300');
};
/**
* Binds incident checkboxes to the master checkbox toggle.
*/
google.devrel.samples.autodo.Bindings.bindCheckAllBoxes = function() {
$('#toggle-all').change(function() {
var checkedStatus = this.checked;
$('.content_checkbox').each(function() {
this.checked = checkedStatus;
});
});
};
/**
* Binds the popUp menu tag input box to create new tag action.
*/
google.devrel.samples.autodo.Bindings.bindTagTextInput = function() {
var tagList = new Array();
var inputBox = $('#label-options').find('input[type="text"]');
$('#label-options').find('input:checked').each(function() {
tagList.push($(this).val());
});
inputBox.keyup(function() {
var validTag = /^\w+(\-\w+)?$/;
var spaceChar = /\s/;
var badChar = /\W/;
var tooMany = /\-\w*\-/;
var needMore = /\-$/;
var badStart = /^\-/;
var userEntered = $(this).val();
$('.error').hide();
if (inputBox.val().length && !validTag.test(userEntered)) {
var errorMessage = 'Tag format=\"model-Tag_Name\".';
$('#apply-tags').hide();
if (badStart.test(userEntered)) {
errorMessage = 'Cannot start with a hyphen.';
} else if (needMore.test(userEntered)) {
errorMessage = 'Cannot end with a hyphen. Please add more.';
} else if (tooMany.test(userEntered)) {
errorMessage = 'Only one hyphen allowed.<br/>e.g. \"model-Tag_Name\"';
} else if (spaceChar.test(userEntered)) {
errorMessage = 'Cannot use spaces. Use _ instead.';
} else if (badChar.test(userEntered)) {
errorMessage = 'Invalid character.<br/>Use A-Za-z0-9 and -.';
}
inputBox.after('<span class="error"><br/>' + errorMessage + '</span>');
} else {
$('#apply-tags').show();
$('#apply-tags').text('"' + $(this).val() + '" (create new)');
if (userEntered.length < 1) {
$('#apply-tags').text('Apply');
}
}
});
Render.popUpCheckboxes(tagList);
};
/**
* Binds the "apply" button to a tag update.
*/
google.devrel.samples.autodo.Bindings.bindTagOptions = function() {
$('#apply-tags').click(function() {
var incidentTagList = Bindings.findIncidentUpdates($('#content'));
$('#label-options').hide();
$('#label-options').find('input[type="text"]').val('');
$('#apply-tags').text('Apply');
ApiClient.updateTags(incidentTagList);
});
};
/**
* Binds the "apply" button to ownership assignment.
*/
google.devrel.samples.autodo.Bindings.bindAssignOptions = function() {
$('#assign-owner').click(function() {
// Get the name of the new owner.
var owner = '';
var textValue = $('#assign-options').find('input[type="text"]').val();
if (textValue.length) {
owner = textValue;
}
// Retrieve incidents that should be updated.
$('#content').find('input:checked, div.title.content-list-div').each(
function() {
ApiClient.getIncidentData($(this).attr('value'),
ApiClient.assignIncident,
{'name': owner});
});
$('#assign-options').hide();
$('#assign-options').find('input[type="text"]').val('');
});
};
/**
* Binds the status button to incident resolving/reopen function.
*/
google.devrel.samples.autodo.Bindings.bindStatusOptions = function() {
$('a.status-button').click(function() {
var status = $(this).attr('status');
// Retrieve incidents that should be updated.
$('#content').find('input:checked, div.title.content-list-div').each(
function() {
ApiClient.getIncidentData($(this).attr('value'),
ApiClient.setStatus, status);
});
});
};
/**
* Binds incidents list elements to render incident views.
*/
google.devrel.samples.autodo.Bindings.bindIncidentLink = function() {
$('div.content-list-div').click(function() {
Util.setHashPair('id=' + $(this).attr('value'));
});
};
/**
* Binds sidebar <li> elements to render incident lists.
*/
google.devrel.samples.autodo.Bindings.bindSideBar = function() {
$('#sidebar').find('li').click(function() {
Render.selectedSidebarLink($(this));
});
$('li.mine').click(function() {
Util.setHashPair(Query.MINE);
});
$('li.mineall').click(function() {
Util.setHashPair(Query.MINE_ALL);
});
$('li.needsaction').click(function() {
Util.setHashPair(Query.NEEDS_ACTION);
});
$('li.resolved').click(function() {
Util.setHashPair(Query.RESOLVED);
});
$('li.all').click(function() {
Util.setHashPair(Query.ALL);
});
};
/**
* Binds search box and search button elements.
*/
google.devrel.samples.autodo.Bindings.bindSearchInputs = function() {
var searchBox = $('input#search-box');
searchBox.autocomplete({
source: function(req, responseFn) {
var index = req.term.lastIndexOf(' ');
var word = req.term.substring(index + 1);
if (word) {
var re = $.ui.autocomplete.escapeRegex(word);
var matcher = new RegExp(re, 'i');
var a = $.grep(filters, function(item, index) {
return matcher.test(item);
});
responseFn(a);
}
},
select: function(event, ui) {
var query = searchBox.val();
query = query.substring(0, query.lastIndexOf(' ') + 1) + ui.item.value;
searchBox.val(query);
event.preventDefault();
},
focus: function(event, ui) {
event.preventDefault();
},
autoFocus: true
});
/** Bind the ENTER key with the search button and prevent tab from losing
focus. */
searchBox.keydown(function(event) {
var keycode = event.keyCode ? event.keyCode : event.which;
if (keycode == $.ui.keyCode.ENTER) {
ApiClient.search();
} else if (keycode == $.ui.keyCode.TAB) {
event.preventDefault();
}
});
$('a.atd-search-button').click(function() {
ApiClient.search();
});
};
/**
* Binds the a original button to the list view.
* @param {string} canonicalLink URI of the original case.
*/
google.devrel.samples.autodo.Bindings.bindOriginalButton = function(
canonicalLink) {
$('a.original-button').click(function() {
window.open(canonicalLink);
return false;
});
};
/**
* Binds the a reload button to the list view.
*/
google.devrel.samples.autodo.Bindings.bindReloadButton = function() {
$('a.reload-button').click(function() {
// Reset incident cache.
Data.incidentListUpdated = 0;
Util.reloadCurrentHash();
});
};
/**
* Binds accept tag buttons to tag update handlers.
*/
google.devrel.samples.autodo.Bindings.bindAcceptTags = function() {
$('.label').find('a.accept').click(function() {
var incidentTags = {};
incidentTags.accepted_tags = [];
incidentTags.suggested_tags = [];
incidentTags.id = parseInt($(this).parentsUntil('tr').find(
'.content-list-div').attr('value'));
$.each($(this).parent().siblings('.label'), function() {
if ($(this).hasClass('accepted')) {
incidentTags.accepted_tags.push($(this).attr('value'));
} else {
incidentTags.suggested_tags.push($(this).attr('value'));
}
});
incidentTags.accepted_tags.push($(this).parent().attr('value'));
var incidentTagList = {};
incidentTagList[incidentTags.id] = incidentTags;
ApiClient.updateTags(incidentTagList);
});
};
/**
* Binds remove tag buttons to tag update handers
*/
google.devrel.samples.autodo.Bindings.bindRemoveTags = function() {
$('.label').find('a.remove').click(function() {
var incidentTags = {};
incidentTags.accepted_tags = [];
incidentTags.suggested_tags = [];
incidentTags.id = parseInt($(this).parentsUntil('tr').find(
'.content-list-div').attr('value'));
$.each($(this).parent().siblings('.label'), function() {
if ($(this).hasClass('accepted')) {
incidentTags.accepted_tags.push($(this).attr('value'));
} else {
incidentTags.suggested_tags.push($(this).attr('value'));
}
});
var incidentTagList = {};
incidentTagList[incidentTags.id] = incidentTags;
ApiClient.updateTags(incidentTagList);
});
};
/**
* Binds settings button to a settings view.
*/
google.devrel.samples.autodo.Bindings.bindSettingsButton = function() {
$('a.settings-button').click(function() {
Util.setHashPair(Query.SETTINGS);
});
};
/**
* Binds action to tag buttons that reveal drop down menus.
*/
google.devrel.samples.autodo.Bindings.bindTaggingButtons = function() {
$('#assign-button').click(function() {
$('#assign-options').show();
});
$('#label-button').click(function() {
$('#label-options').show();
});
};
/**
* Hide pop-up menus on Blur events.
*/
google.devrel.samples.autodo.Bindings.blurPopUpMenus = function() {
$('html').click(function() {
$('#assign-options').hide();
$('#label-options').hide();
});
$('#assign-button').click(function(event) {
$('#label-options').hide();
event.stopPropagation();
});
$('#assign-options').click(function(event) {
event.stopPropagation();
});
$('#label-button').click(function(event) {
$('#assign-options').hide();
event.stopPropagation();
});
$('#label-options').click(function(event) {
event.stopPropagation();
});
};
/**
* Binds visibility of notification bar to ajax start, stop, and error events.
*/
google.devrel.samples.autodo.Bindings.bindNotificationBar = function() {
$('#notificationbar').ajaxError(function() {
$(this).find('.message').text(
'Unable to reach Au-to-do. ' +
'Please check your internet connection, and try again.'
);
$(this).show();
});
$('#notificationbar').ajaxStart(function() {
$(this).show();
});
$('#notificationbar').ajaxStop(function() {
$(this).hide();
});
};
/**
* Binds visibility of last action bar to ajax send/sucess events.
*/
google.devrel.samples.autodo.Bindings.bindLastActionBar = function() {
$('#lastactionbar').ajaxSend(function(event, xhr) {
xhr.timeSent = event.timeStamp;
});
$('#lastactionbar').ajaxSuccess(function(event, xhr) {
var delta = event.timeStamp - xhr.timeSent;
var message = ['Last action took ', delta, 'ms.'].join('');
$(this).find('.message').text(message);
$(this).show();
});
};
/**
* Binds the HTML5 hashchange event to appropriate UI logic.
*/
google.devrel.samples.autodo.Bindings.bindHashChange = function() {
$(window).bind('hashchange', function() {
var hash = window.location.hash;
var last = Data.hashStack[Data.hashStack.length - 1];
if (hash != last) {
Data.hashStack.push(hash);
Logger.log('pushed to stack');
Logger.log(Data.hashStack);
}
var hashPair = Util.getHashPair();
switch (hashPair.key) {
case Query.ALL:
ApiClient.listView('owner=');
break;
case Query.MINE:
ApiClient.listView('owner=' + currentUser + '&status=new');
break;
case Query.MINE_ALL:
ApiClient.listView('owner=' + currentUser);
break;
case Query.NEEDS_ACTION:
ApiClient.listView('owner=none&status=new');
break;
case Query.RESOLVED:
ApiClient.listView('status=resolved');
break;
case Query.ID:
ApiClient.singleView(hashPair.value);
break;
case Query.SETTINGS:
Render.settingsList();
break;
default:
$('input#search-box').val(Util.getHashString());
ApiClient.search();
}
var button = $('#sidebar').find('li' + '.' + hashPair.key);
if (button) {
Render.selectedSidebarLink(button);
}
});
};
/**
* Returns the first key/value pair from the window's location.hash. This
* is useful for checking if the user is on a special page
* (e.g. key == 'mine').
* @return {Object} An object containing the key (object.key) and value
* (object.value) pair.
*/
google.devrel.samples.autodo.Util.getHashPair = function() {
return Util.getHashPairs()[0];
};
/**
* Returns an array of parsed key/value pair representing the window's
* location.hash.
* @return {Array} An array containing all key (object.key) and value
* (object.value) pairs.
*/
google.devrel.samples.autodo.Util.getHashPairs = function() {
var sub = Util.getHashString();
var result = [];
var pairs = sub.split(' ');
for (var i in pairs) {
var split = pairs[i].split('=');
result.push({
key: split[0],
value: split[1]
});
}
return result;
};
/**
* Returns a sanitized copy of the hash, suitable for use in a search.
* @return {string} Sanitized hash string.
*/
google.devrel.samples.autodo.Util.getHashString = function() {
var fragment = window.location.hash;
return fragment.substring(1, fragment.length);
};
/**
* Set a new hash fragment from the supplied key and/or value.
* @param {string=} opt_key Optional hash fragment key.
* @param {string=} opt_value Optional hash fragment value.
*/
google.devrel.samples.autodo.Util.setHashPair = function(opt_key, opt_value) {
var setter;
if (opt_value) {
setter = '=';
}
var hash = ['#', opt_key, setter, opt_value].join('');
window.location.hash = hash;
};
/**
* Set the hash fragment to the previous entry in the stack.
*/
google.devrel.samples.autodo.Render.loadPreviousHashPair = function() {
Data.hashStack.pop();
var top = Data.hashStack[Data.hashStack.length - 1];
if (top) {
window.location.hash = top;
} else {
window.location.hash = '';
}
Logger.log('popped stack');
Logger.log(Data.hashStack);
};
/**
* "Reloads" the current hash fragment, by trigger the hash change event.
*
* This behaves like a page reload which might be useful when trigger an
* updated version of the current view.
*/
google.devrel.samples.autodo.Util.reloadCurrentHash = function() {
Logger.log('triggering hashchange');
$(window).trigger('hashchange');
};
/**
* Renders the initial page view, either from hash or the default view.
*/
google.devrel.samples.autodo.Render.setInitialView = function() {
Data.hashStack.push(Query.MINE);
if (!window.location.hash) {
Util.setHashPair('mine');
} else {
Util.setHashPair(window.location.hash.substring(1));
$(window).trigger('hashchange');
}
};
/**
* Converts database timestamps into a slightly more readable form.
* TODO(user): add 12-hour formating.
* @param {string} dateStamp A timestamp in YYYY-MM-DDTHH:MM:SS format.
* @return {string} Human-readable date string.
*/
google.devrel.samples.autodo.Util.formatDateStamp = function(dateStamp) {
var arrDateTime = dateStamp.split('T');
var arrDate = arrDateTime[0].split('-');
var arrTime = arrDateTime[1].split(':');
var month = Util.removeLeadingZeroes(arrDate[1]);
var day = Util.removeLeadingZeroes(arrDate[2]);
var hour = Util.removeLeadingZeroes(arrTime[0]);
var minute = arrTime[1];
var formattedString = month + '/' + day + ' ' + hour + ':' + minute;
return formattedString;
};
/**
* Initialize the regex used when a search is submitted.
*/
google.devrel.samples.autodo.Util.initializeRegex = function() {
var regexes = [];
for (var index in filters) {
var filter = filters[index];
regexes.push(filter);
}
Util.regex = new RegExp('(' + regexes.join('|') + ')');
};
/**
* Removes leading zeroes from timestamp strings.
* @param {string} timeStampElement string with a potential leading zero.
* @return {string} leading zero free timestamp element.
*/
google.devrel.samples.autodo.Util.removeLeadingZeroes = function(
timeStampElement) {
timeStampElement = timeStampElement.replace(/^0{1}/, '');
return timeStampElement;
};
/**
* Handles OAuth pop-up callback. Current implementation reloads the settings
* page.
*/
google.devrel.samples.autodo.Util.onAccessGranted = function() {
google.devrel.samples.autodo.Render.settingsList();
};
$(document).ready(function() {
ApiClient.DEFAULT_SEARCH = 'owner=' + currentUser;
// Initializes UI element bindings, loads default view.
Bindings.bindReloadButton();
Bindings.bindSettingsButton();
Bindings.bindTaggingButtons();
Bindings.bindTagTextInput();
Bindings.bindTagOptions();
Bindings.bindAssignOptions();
Bindings.bindStatusOptions();
Bindings.bindNotificationBar();
Bindings.bindLastActionBar();
Bindings.bindSideBar();
Bindings.bindSearchInputs();
Bindings.bindHashChange();
// Positions the pop-up option menus.
Render.popUpPosition();
// Initialize the tokenizer Regex.
Util.initializeRegex();
// Trigger a hash change if we arrived with a hash fragment, otherwise load
// the default view.
Render.setInitialView();
});
| JavaScript |
// 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
* Provides logic for the extension.
*
*/
/** google global namespace for Google projects. */
var google = google || {};
/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};
/** samples namespace for Devrel sample code. */
google.devrel.samples = google.devrel.samples || {};
/** autodo namespace for this sample. */
google.devrel.samples.autodo = google.devrel.samples.autodo || {};
/** Extension object for Chrome extension methods. */
google.devrel.samples.autodo.Extension =
google.devrel.samples.autodo.Extension || {};
/** Alias for Extension object. */
var Extension = google.devrel.samples.autodo.Extension;
/**
* The URL to Au-to-do.
* @type {string}
*/
google.devrel.samples.autodo.Extension.APP_URL =
'http://your-application-id.appspot.com';
/**
* The number of milliseconds between incident retrievals.
* @type {number}
*/
google.devrel.samples.autodo.Extension.FETCH_FREQ = 30000;
/**
* The badge color to display behind the incident counter.
* @type {Array}
*/
google.devrel.samples.autodo.Extension.INCIDENT_COLOR = [0, 163, 0, 255];
/**
* The badge color to display when the user isn't logged in.
* @type {Array}
*/
google.devrel.samples.autodo.Extension.WARNING_COLOR = [255, 0, 0, 255];
/**
* The user's assigned incidents.
* @type {Array}
*/
google.devrel.samples.autodo.Extension.incidents;
/**
* Whether or not the user needs to log in.
* @type {boolean}
*/
google.devrel.samples.autodo.Extension.loginRequired = false;
/**
* Initializes the background process.
*/
google.devrel.samples.autodo.Extension.backgroundInit = function() {
Extension.getIncidents();
setInterval(Extension.getIncidents, Extension.FETCH_FREQ);
};
/**
* Gets the list of incidents assigned to the current user.
*/
google.devrel.samples.autodo.Extension.getIncidents = function() {
var req = new XMLHttpRequest();
req.open('GET', Extension.APP_URL +
'/resources/v1/incidents/?owner=me', true);
req.onload = Extension.processIncidents;
req.onerror = Extension.processError;
req.send();
};
/**
* Processes the response from the incident request.
* @param {Event} e Request completion event.
*/
google.devrel.samples.autodo.Extension.processIncidents = function(e) {
if (e.target.status >= 200 && e.target.status < 300) {
Extension.incidents = JSON.parse(e.target.responseText);
Extension.loginRequired = false;
Extension.updateBadgeCount(Extension.incidents.length);
} else {
Extension.processError();
}
};
/**
* Processes an error response from the incident request.
*/
google.devrel.samples.autodo.Extension.processError = function() {
Extension.loginRequired = true;
Extension.displayLoginBadge();
};
/**
* Updates the badge icon to display the incident count.
* @param {number} incidentCount Number of incidents.
*/
google.devrel.samples.autodo.Extension.updateBadgeCount =
function(incidentCount) {
chrome.browserAction.setBadgeBackgroundColor({
color: Extension.INCIDENT_COLOR
});
chrome.browserAction.setBadgeText({text: '' + incidentCount});
};
/**
* Displays a icon indicating the user should log in.
*/
google.devrel.samples.autodo.Extension.displayLoginBadge = function() {
chrome.browserAction.setBadgeBackgroundColor({
color: Extension.WARNING_COLOR
});
chrome.browserAction.setBadgeText({text: ':('});
};
/**
* Opens the selected incident in a new tab.
* @param {MouseEvent} e Mouse event triggering the tab to open.
*/
google.devrel.samples.autodo.Extension.openIncident = function(e) {
var id = e.target.dataset.id;
var url = Extension.APP_URL + '#id=';
Extension.openTab(url + id);
};
/**
* Opens Au-to-do in a new tab.
*/
google.devrel.samples.autodo.Extension.openATD = function() {
Extension.openTab(Extension.APP_URL);
};
/**
* Opens a new tab and closes the extension popup.
* @param {string} url URL to open in the new tab.
*/
google.devrel.samples.autodo.Extension.openTab = function(url) {
chrome.tabs.create({
url: url,
selected: true
});
self.close();
};
/**
* Initializes the popup window.
*/
google.devrel.samples.autodo.Extension.popupInit = function() {
var bg = chrome.extension.getBackgroundPage();
if (bg.Extension.loginRequired) {
var login = document.querySelector('#login');
login.style.display = 'block';
} else {
var incidentDiv = document.querySelector('#incidents');
incidentDiv.setAttribute('style', 'display: block');
for (var i = 0; i < bg.Extension.incidents.length; i++) {
var incident = document.createElement('div');
incident.classList.add('content-list-div');
var a = document.createElement('a');
a.href = '#';
a.dataset.id = bg.Extension.incidents[i].id;
var text = document.createTextNode(bg.Extension.incidents[i].title);
a.appendChild(text);
a.onclick = Extension.openIncident;
incident.appendChild(a);
incidentDiv.appendChild(incident);
}
var atdLink = document.querySelector('#atd-link');
atdLink.onclick = Extension.openATD;
}
};
| JavaScript |
/* $Id : common.js 4865 2007-01-31 14:04:10Z paulgao $ */
/* *
* 添加商品到购物车
*/
function addToCart(goodsId, parentId)
{
var goods = new Object();
var spec_arr = new Array();
var fittings_arr = new Array();
var number = 1;
var formBuy = document.forms['ECS_FORMBUY'];
var quick = 0;
var type = 0;
// 检查是否有商品规格
if (formBuy)
{
spec_arr = getSelectedAttributes(formBuy);
if (formBuy.elements['number'])
{
number = formBuy.elements['number'].value;
}
if(formBuy.elements['type_ch'])
{
var length = formBuy.elements['type_ch'].length;
for(var i = 0; i < length; i++){
if(formBuy.elements['type_ch'][i].checked){
type = formBuy.elements['type_ch'][i].value;
}
}
}
quick = 1;
}
goods.quick = quick;
goods.spec = spec_arr;
goods.goods_id = goodsId;
goods.number = number;
goods.parent = (typeof(parentId) == "undefined") ? 0 : parseInt(parentId);
goods.type = type;
Ajax.call('flow.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse, 'POST', 'JSON');
}
/**
* 获得选定的商品属性
*/
function getSelectedAttributes(formBuy)
{
var spec_arr = new Array();
var j = 0;
for (i = 0; i < formBuy.elements.length; i ++ )
{
var prefix = formBuy.elements[i].name.substr(0, 5);
if (prefix == 'spec_' && (
((formBuy.elements[i].type == 'radio' || formBuy.elements[i].type == 'checkbox') && formBuy.elements[i].checked) ||
formBuy.elements[i].tagName == 'SELECT'))
{
spec_arr[j] = formBuy.elements[i].value;
j++ ;
}
}
return spec_arr;
}
/* *
* 处理添加商品到购物车的反馈信息
*/
function addToCartResponse(result)
{
if (result.error > 0)
{
// 如果需要缺货登记,跳转
if (result.error == 2)
{
if (confirm(result.message))
{
location.href = 'user.php?act=add_booking&id=' + result.goods_id + '&spec=' + result.product_spec;
}
}
// 没选规格,弹出属性选择框
else if (result.error == 6)
{
openSpeDiv(result.message, result.goods_id, result.parent);
}
else
{
alert(result.message);
}
}
else
{
var cartInfo = document.getElementById('ECS_CARTINFO');
var cart_url = 'flow.php?step=cart';
if (cartInfo)
{
cartInfo.innerHTML = result.content;
}
if (result.one_step_buy == '1')
{
location.href = cart_url;
}
else
{
switch(result.confirm_type)
{
case '1' :
if (confirm(result.message)) location.href = cart_url;
break;
case '2' :
if (!confirm(result.message)) location.href = cart_url;
break;
case '3' :
location.href = cart_url;
break;
default :
break;
}
}
}
}
/* *
* 添加商品到收藏夹
*/
function collect(goodsId)
{
Ajax.call('user.php?act=collect', 'id=' + goodsId, collectResponse, 'GET', 'JSON');
}
/* *
* 处理收藏商品的反馈信息
*/
function collectResponse(result)
{
alert(result.message);
}
/* *
* 处理会员登录的反馈信息
*/
function signInResponse(result)
{
toggleLoader(false);
var done = result.substr(0, 1);
var content = result.substr(2);
if (done == 1)
{
document.getElementById('member-zone').innerHTML = content;
}
else
{
alert(content);
}
}
/* *
* 评论的翻页函数
*/
function gotoPage(page, id, type)
{
Ajax.call('comment.php?act=gotopage', 'page=' + page + '&id=' + id + '&type=' + type, gotoPageResponse, 'GET', 'JSON');
}
function gotoPageResponse(result)
{
document.getElementById("ECS_COMMENT").innerHTML = result.content;
}
/* *
* 商品购买记录的翻页函数
*/
function gotoBuyPage(page, id)
{
Ajax.call('goods.php?act=gotopage', 'page=' + page + '&id=' + id, gotoBuyPageResponse, 'GET', 'JSON');
}
function gotoBuyPageResponse(result)
{
document.getElementById("ECS_BOUGHT").innerHTML = result.result;
}
/* *
* 取得格式化后的价格
* @param : float price
*/
function getFormatedPrice(price)
{
if (currencyFormat.indexOf("%s") > - 1)
{
return currencyFormat.replace('%s', advFormatNumber(price, 2));
}
else if (currencyFormat.indexOf("%d") > - 1)
{
return currencyFormat.replace('%d', advFormatNumber(price, 0));
}
else
{
return price;
}
}
/* *
* 夺宝奇兵会员出价
*/
function bid(step)
{
var price = '';
var msg = '';
if (step != - 1)
{
var frm = document.forms['formBid'];
price = frm.elements['price'].value;
id = frm.elements['snatch_id'].value;
if (price.length == 0)
{
msg += price_not_null + '\n';
}
else
{
var reg = /^[\.0-9]+/;
if ( ! reg.test(price))
{
msg += price_not_number + '\n';
}
}
}
else
{
price = step;
}
if (msg.length > 0)
{
alert(msg);
return;
}
Ajax.call('snatch.php?act=bid&id=' + id, 'price=' + price, bidResponse, 'POST', 'JSON')
}
/* *
* 夺宝奇兵会员出价反馈
*/
function bidResponse(result)
{
if (result.error == 0)
{
document.getElementById('ECS_SNATCH').innerHTML = result.content;
if (document.forms['formBid'])
{
document.forms['formBid'].elements['price'].focus();
}
newPrice(); //刷新价格列表
}
else
{
alert(result.content);
}
}
//onload = function()
//{
// var link_arr = document.getElementsByTagName(String.fromCharCode(65));
// var link_str;
// var link_text;
// var regg, cc;
// var rmd, rmd_s, rmd_e, link_eorr = 0;
// var e = new Array(97, 98, 99,
// 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
// 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
// 120, 121, 122
// );
//
// try
// {
// for(var i = 0; i < link_arr.length; i++)
// {
// link_str = link_arr[i].href;
// if (link_str.indexOf(String.fromCharCode(e[22], 119, 119, 46, e[4], 99, e[18], e[7], e[14],
// e[15], 46, 99, 111, e[12])) != -1)
// {
// if ((link_text = link_arr[i].innerText) == undefined)
// {
// throw "noIE";
// }
// regg = new RegExp(String.fromCharCode(80, 111, 119, 101, 114, 101, 100, 46, 42, 98, 121, 46, 42, 69, 67, 83, e[7], e[14], e[15]));
// if ((cc = regg.exec(link_text)) != null)
// {
// if (link_arr[i].offsetHeight == 0)
// {
// break;
// }
// link_eorr = 1;
// break;
// }
// }
// else
// {
// link_eorr = link_eorr ? 0 : link_eorr;
// continue;
// }
// }
// } // IE
// catch(exc)
// {
// for(var i = 0; i < link_arr.length; i++)
// {
// link_str = link_arr[i].href;
// if (link_str.indexOf(String.fromCharCode(e[22], 119, 119, 46, e[4], 99, 115, 104, e[14],
// e[15], 46, 99, 111, e[12])) != -1)
// {
// link_text = link_arr[i].textContent;
// regg = new RegExp(String.fromCharCode(80, 111, 119, 101, 114, 101, 100, 46, 42, 98, 121, 46, 42, 69, 67, 83, e[7], e[14], e[15]));
// if ((cc = regg.exec(link_text)) != null)
// {
// if (link_arr[i].offsetHeight == 0)
// {
// break;
// }
// link_eorr = 1;
// break;
// }
// }
// else
// {
// link_eorr = link_eorr ? 0 : link_eorr;
// continue;
// }
// }
// } // FF
//
// try
// {
// rmd = Math.random();
// rmd_s = Math.floor(rmd * 10);
// if (link_eorr != 1)
// {
// rmd_e = i - rmd_s;
// link_arr[rmd_e].href = String.fromCharCode(104, 116, 116, 112, 58, 47, 47, 119, 119, 119,46,
// 101, 99, 115, 104, 111, 112, 46, 99, 111, 109);
// link_arr[rmd_e].innerHTML = String.fromCharCode(
// 80, 111, 119, 101, 114, 101, 100,38, 110, 98, 115, 112, 59, 98,
// 121,38, 110, 98, 115, 112, 59,60, 115, 116, 114, 111, 110, 103,
// 62, 60,115, 112, 97, 110, 32, 115, 116, 121,108,101, 61, 34, 99,
// 111, 108, 111, 114, 58, 32, 35, 51, 51, 54, 54, 70, 70, 34, 62,
// 69, 67, 83, 104, 111, 112, 60, 47, 115, 112, 97, 110, 62,60, 47,
// 115, 116, 114, 111, 110, 103, 62);
// }
// }
// catch(ex)
// {
// }
//}
/* *
* 夺宝奇兵最新出价
*/
function newPrice(id)
{
Ajax.call('snatch.php?act=new_price_list&id=' + id, '', newPriceResponse, 'GET', 'TEXT');
}
/* *
* 夺宝奇兵最新出价反馈
*/
function newPriceResponse(result)
{
document.getElementById('ECS_PRICE_LIST').innerHTML = result;
}
/* *
* 返回属性列表
*/
function getAttr(cat_id)
{
var tbodies = document.getElementsByTagName('tbody');
for (i = 0; i < tbodies.length; i ++ )
{
if (tbodies[i].id.substr(0, 10) == 'goods_type')tbodies[i].style.display = 'none';
}
var type_body = 'goods_type_' + cat_id;
try
{
document.getElementById(type_body).style.display = '';
}
catch (e)
{
}
}
/* *
* 截取小数位数
*/
function advFormatNumber(value, num) // 四舍五入
{
var a_str = formatNumber(value, num);
var a_int = parseFloat(a_str);
if (value.toString().length > a_str.length)
{
var b_str = value.toString().substring(a_str.length, a_str.length + 1);
var b_int = parseFloat(b_str);
if (b_int < 5)
{
return a_str;
}
else
{
var bonus_str, bonus_int;
if (num == 0)
{
bonus_int = 1;
}
else
{
bonus_str = "0."
for (var i = 1; i < num; i ++ )
bonus_str += "0";
bonus_str += "1";
bonus_int = parseFloat(bonus_str);
}
a_str = formatNumber(a_int + bonus_int, num)
}
}
return a_str;
}
function formatNumber(value, num) // 直接去尾
{
var a, b, c, i;
a = value.toString();
b = a.indexOf('.');
c = a.length;
if (num == 0)
{
if (b != - 1)
{
a = a.substring(0, b);
}
}
else
{
if (b == - 1)
{
a = a + ".";
for (i = 1; i <= num; i ++ )
{
a = a + "0";
}
}
else
{
a = a.substring(0, b + num + 1);
for (i = c; i <= b + num; i ++ )
{
a = a + "0";
}
}
}
return a;
}
/* *
* 根据当前shiping_id设置当前配送的的保价费用,如果保价费用为0,则隐藏保价费用
*
* return void
*/
function set_insure_status()
{
// 取得保价费用,取不到默认为0
var shippingId = getRadioValue('shipping');
var insure_fee = 0;
if (shippingId > 0)
{
if (document.forms['theForm'].elements['insure_' + shippingId])
{
insure_fee = document.forms['theForm'].elements['insure_' + shippingId].value;
}
// 每次取消保价选择
if (document.forms['theForm'].elements['need_insure'])
{
document.forms['theForm'].elements['need_insure'].checked = false;
}
// 设置配送保价,为0隐藏
if (document.getElementById("ecs_insure_cell"))
{
if (insure_fee > 0)
{
document.getElementById("ecs_insure_cell").style.display = '';
setValue(document.getElementById("ecs_insure_fee_cell"), getFormatedPrice(insure_fee));
}
else
{
document.getElementById("ecs_insure_cell").style.display = "none";
setValue(document.getElementById("ecs_insure_fee_cell"), '');
}
}
}
}
/* *
* 当支付方式改变时出发该事件
* @param pay_id 支付方式的id
* return void
*/
function changePayment(pay_id)
{
// 计算订单费用
calculateOrderFee();
}
function getCoordinate(obj)
{
var pos =
{
"x" : 0, "y" : 0
}
pos.x = document.body.offsetLeft;
pos.y = document.body.offsetTop;
do
{
pos.x += obj.offsetLeft;
pos.y += obj.offsetTop;
obj = obj.offsetParent;
}
while (obj.tagName.toUpperCase() != 'BODY')
return pos;
}
function showCatalog(obj)
{
var pos = getCoordinate(obj);
var div = document.getElementById('ECS_CATALOG');
if (div && div.style.display != 'block')
{
div.style.display = 'block';
div.style.left = pos.x + "px";
div.style.top = (pos.y + obj.offsetHeight - 1) + "px";
}
}
function hideCatalog(obj)
{
var div = document.getElementById('ECS_CATALOG');
if (div && div.style.display != 'none') div.style.display = "none";
}
function sendHashMail()
{
Ajax.call('user.php?act=send_hash_mail', '', sendHashMailResponse, 'GET', 'JSON')
}
function sendHashMailResponse(result)
{
alert(result.message);
}
/* 订单查询 */
function orderQuery()
{
var order_sn = document.forms['ecsOrderQuery']['order_sn'].value;
var reg = /^[\.0-9]+/;
if (order_sn.length < 10 || ! reg.test(order_sn))
{
alert(invalid_order_sn);
return;
}
Ajax.call('user.php?act=order_query&order_sn=s' + order_sn, '', orderQueryResponse, 'GET', 'JSON');
}
function orderQueryResponse(result)
{
if (result.message.length > 0)
{
alert(result.message);
}
if (result.error == 0)
{
var div = document.getElementById('ECS_ORDER_QUERY');
div.innerHTML = result.content;
}
}
function display_mode(str)
{
document.getElementById('display').value = str;
setTimeout(doSubmit, 0);
function doSubmit() {document.forms['listform'].submit();}
}
function display_mode_wholesale(str)
{
document.getElementById('display').value = str;
setTimeout(doSubmit, 0);
function doSubmit()
{
document.forms['wholesale_goods'].action = "wholesale.php";
document.forms['wholesale_goods'].submit();
}
}
/* 修复IE6以下版本PNG图片Alpha */
function fixpng()
{
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
for(var i=0; i<document.images.length; i++)
{
var img = document.images[i]
var imgName = img.src.toUpperCase()
if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
{
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
img.outerHTML = strNewHTML
i = i-1
}
}
}
}
function hash(string, length)
{
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++)
{
string += "0";
}
while(start < string.length)
{
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2)
{
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++)
{
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
var evalscripts = new Array();
function evalscript(s)
{
if(s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) appendscript(arr[1], '', arr[2], arr[3]);
return s;
}
function $$(id)
{
return document.getElementById(id);
}
function appendscript(src, text, reload, charset)
{
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $$(id))
{
$$(id).parentNode.removeChild($$(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
//scriptNode.charset = charset;
try
{
if(src)
{
scriptNode.src = src;
}
else if(text)
{
scriptNode.text = text;
}
$$('append_parent').appendChild(scriptNode);
}
catch(e)
{}
}
function in_array(needle, haystack)
{
if(typeof needle == 'string' || typeof needle == 'number')
{
for(var i in haystack)
{
if(haystack[i] == needle)
{
return true;
}
}
}
return false;
}
var pmwinposition = new Array();
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function pmwin(action, param)
{
var objs = document.getElementsByTagName("OBJECT");
if(action == 'open')
{
for(i = 0;i < objs.length; i ++)
{
if(objs[i].style.visibility != 'hidden')
{
objs[i].setAttribute("oldvisibility", objs[i].style.visibility);
objs[i].style.visibility = 'hidden';
}
}
var clientWidth = document.body.clientWidth;
var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
var pmwidth = 800;
var pmheight = clientHeight * 0.9;
if(!$$('pmlayer'))
{
div = document.createElement('div');div.id = 'pmlayer';
div.style.width = pmwidth + 'px';
div.style.height = pmheight + 'px';
div.style.left = ((clientWidth - pmwidth) / 2) + 'px';
div.style.position = 'absolute';
div.style.zIndex = '999';
$$('append_parent').appendChild(div);
$$('pmlayer').innerHTML = '<div style="width: 800px; background: #666666; margin: 5px auto; text-align: left">' +
'<div style="width: 800px; height: ' + pmheight + 'px; padding: 1px; background: #FFFFFF; border: 1px solid #7597B8; position: relative; left: -6px; top: -3px">' +
'<div onmousedown="pmwindrag(event, 1)" onmousemove="pmwindrag(event, 2)" onmouseup="pmwindrag(event, 3)" style="cursor: move; position: relative; left: 0px; top: 0px; width: 800px; height: 30px; margin-bottom: -30px;"></div>' +
'<a href="###" onclick="pmwin(\'close\')"><img style="position: absolute; right: 20px; top: 15px" src="images/close.gif" title="关闭" /></a>' +
'<iframe id="pmframe" name="pmframe" style="width:' + pmwidth + 'px;height:100%" allowTransparency="true" frameborder="0"></iframe></div></div>';
}
$$('pmlayer').style.display = '';
$$('pmlayer').style.top = ((clientHeight - pmheight) / 2 + scrollTop) + 'px';
if(!param)
{
pmframe.location = 'pm.php';
}
else
{
pmframe.location = 'pm.php?' + param;
}
}
else if(action == 'close')
{
for(i = 0;i < objs.length; i ++)
{
if(objs[i].attributes['oldvisibility'])
{
objs[i].style.visibility = objs[i].attributes['oldvisibility'].nodeValue;
objs[i].removeAttribute('oldvisibility');
}
}
hiddenobj = new Array();
$$('pmlayer').style.display = 'none';
}
}
var pmwindragstart = new Array();
function pmwindrag(e, op)
{
if(op == 1)
{
pmwindragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
pmwindragstart[2] = parseInt($$('pmlayer').style.left);
pmwindragstart[3] = parseInt($$('pmlayer').style.top);
doane(e);
}
else if(op == 2 && pmwindragstart[0])
{
var pmwindragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
$$('pmlayer').style.left = (pmwindragstart[2] + pmwindragnow[0] - pmwindragstart[0]) + 'px';
$$('pmlayer').style.top = (pmwindragstart[3] + pmwindragnow[1] - pmwindragstart[1]) + 'px';
doane(e);
}
else if(op == 3)
{
pmwindragstart = [];
doane(e);
}
}
function doane(event)
{
e = event ? event : window.event;
if(is_ie)
{
e.returnValue = false;
e.cancelBubble = true;
}
else if(e)
{
e.stopPropagation();
e.preventDefault();
}
}
/* *
* 添加礼包到购物车
*/
function addPackageToCart(packageId)
{
var package_info = new Object();
var number = 1;
package_info.package_id = packageId
package_info.number = number;
Ajax.call('flow.php?step=add_package_to_cart', 'package_info=' + package_info.toJSONString(), addPackageToCartResponse, 'POST', 'JSON');
}
/* *
* 处理添加礼包到购物车的反馈信息
*/
function addPackageToCartResponse(result)
{
if (result.error > 0)
{
if (result.error == 2)
{
if (confirm(result.message))
{
location.href = 'user.php?act=add_booking&id=' + result.goods_id;
}
}
else
{
alert(result.message);
}
}
else
{
var cartInfo = document.getElementById('ECS_CARTINFO');
var cart_url = 'flow.php?step=cart';
if (cartInfo)
{
cartInfo.innerHTML = result.content;
}
if (result.one_step_buy == '1')
{
location.href = cart_url;
}
else
{
switch(result.confirm_type)
{
case '1' :
if (confirm(result.message)) location.href = cart_url;
break;
case '2' :
if (!confirm(result.message)) location.href = cart_url;
break;
case '3' :
location.href = cart_url;
break;
default :
break;
}
}
}
}
function setSuitShow(suitId)
{
var suit = document.getElementById('suit_'+suitId);
if(suit == null)
{
return;
}
if(suit.style.display=='none')
{
suit.style.display='';
}
else
{
suit.style.display='none';
}
}
/* 以下四个函数为属性选择弹出框的功能函数部分 */
//检测层是否已经存在
function docEle()
{
return document.getElementById(arguments[0]) || false;
}
//生成属性选择层
function openSpeDiv(message, goods_id, parent)
{
var _id = "speDiv";
var m = "mask";
if (docEle(_id)) document.removeChild(docEle(_id));
if (docEle(m)) document.removeChild(docEle(m));
//计算上卷元素值
var scrollPos;
if (typeof window.pageYOffset != 'undefined')
{
scrollPos = window.pageYOffset;
}
else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat')
{
scrollPos = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined')
{
scrollPos = document.body.scrollTop;
}
var i = 0;
var sel_obj = document.getElementsByTagName('select');
while (sel_obj[i])
{
sel_obj[i].style.visibility = "hidden";
i++;
}
// 新激活图层
var newDiv = document.createElement("div");
newDiv.id = _id;
newDiv.style.position = "absolute";
newDiv.style.zIndex = "10000";
newDiv.style.width = "300px";
newDiv.style.height = "260px";
newDiv.style.top = (parseInt(scrollPos + 200)) + "px";
newDiv.style.left = (parseInt(document.body.offsetWidth) - 200) / 2 + "px"; // 屏幕居中
newDiv.style.overflow = "auto";
newDiv.style.background = "#FFF";
newDiv.style.border = "3px solid #59B0FF";
newDiv.style.padding = "5px";
//生成层内内容
//newDiv.innerHTML = '<h4 style="font-size:14; margin:15 0 0 15;">' + select_spe + "</h4>";
newDiv.innerHTML = '<h4 style="font-size:14; margin:15 0 0 15;"></h4>';
for (var spec = 0; spec < message.length; spec++)
{
newDiv.innerHTML += '<hr style="color: #EBEBED; height:1px;"><h6 style="text-align:left; background:#ffffff; margin-left:15px;">' + message[spec]['name'] + '</h6>';
if (message[spec]['attr_type'] == 1)
{
for (var val_arr = 0; val_arr < message[spec]['values'].length; val_arr++)
{
if (val_arr == 0)
{
newDiv.innerHTML += "<input style='margin-left:15px;' type='radio' name='spec_" + message[spec]['attr_id'] + "' value='" + message[spec]['values'][val_arr]['id'] + "' id='spec_value_" + message[spec]['values'][val_arr]['id'] + "' checked /><font color=#555555>" + message[spec]['values'][val_arr]['label'] + '</font> [' + message[spec]['values'][val_arr]['format_price'] + ']</font><br />';
}
else
{
newDiv.innerHTML += "<input style='margin-left:15px;' type='radio' name='spec_" + message[spec]['attr_id'] + "' value='" + message[spec]['values'][val_arr]['id'] + "' id='spec_value_" + message[spec]['values'][val_arr]['id'] + "' /><font color=#555555>" + message[spec]['values'][val_arr]['label'] + '</font> [' + message[spec]['values'][val_arr]['format_price'] + ']</font><br />';
}
}
newDiv.innerHTML += "<input type='hidden' name='spec_list' value='" + val_arr + "' />";
}
else
{
for (var val_arr = 0; val_arr < message[spec]['values'].length; val_arr++)
{
newDiv.innerHTML += "<input style='margin-left:15px;' type='checkbox' name='spec_" + message[spec]['attr_id'] + "' value='" + message[spec]['values'][val_arr]['id'] + "' id='spec_value_" + message[spec]['values'][val_arr]['id'] + "' /><font color=#555555>" + message[spec]['values'][val_arr]['label'] + ' [' + message[spec]['values'][val_arr]['format_price'] + ']</font><br />';
}
newDiv.innerHTML += "<input type='hidden' name='spec_list' value='" + val_arr + "' />";
}
}
//newDiv.innerHTML += "<br /><center>[<a href='javascript:submit_div(" + goods_id + "," + parent + ")' class='f6' >" + btn_buy + "</a>] [<a href='javascript:cancel_div()' class='f6' >" + is_cancel + "</a>]</center>";
newDiv.innerHTML += "<br /><center>[<a href='javascript:submit_div(" + goods_id + "," + parent + ")' class='f6' >购买</a>] [<a href='javascript:cancel_div()' class='f6' >取消</a>]</center>";
document.body.appendChild(newDiv);
// mask图层
var newMask = document.createElement("div");
newMask.id = m;
newMask.style.position = "absolute";
newMask.style.zIndex = "9999";
newMask.style.width = document.body.scrollWidth + "px";
newMask.style.height = document.body.scrollHeight + "px";
newMask.style.top = "0px";
newMask.style.left = "0px";
newMask.style.background = "#FFF";
newMask.style.filter = "alpha(opacity=30)";
newMask.style.opacity = "0.40";
document.body.appendChild(newMask);
}
//获取选择属性后,再次提交到购物车
function submit_div(goods_id, parentId)
{
var goods = new Object();
var spec_arr = new Array();
var fittings_arr = new Array();
var number = 1;
var input_arr = document.getElementsByTagName('input');
var quick = 1;
var spec_arr = new Array();
var j = 0;
for (i = 0; i < input_arr.length; i ++ )
{
var prefix = input_arr[i].name.substr(0, 5);
if (prefix == 'spec_' && (
((input_arr[i].type == 'radio' || input_arr[i].type == 'checkbox') && input_arr[i].checked)))
{
spec_arr[j] = input_arr[i].value;
j++ ;
}
}
goods.quick = quick;
goods.spec = spec_arr;
goods.goods_id = goods_id;
goods.number = number;
goods.parent = (typeof(parentId) == "undefined") ? 0 : parseInt(parentId);
Ajax.call('flow.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse, 'POST', 'JSON');
document.body.removeChild(docEle('speDiv'));
document.body.removeChild(docEle('mask'));
var i = 0;
var sel_obj = document.getElementsByTagName('select');
while (sel_obj[i])
{
sel_obj[i].style.visibility = "";
i++;
}
}
// 关闭mask和新图层
function cancel_div()
{
document.body.removeChild(docEle('speDiv'));
document.body.removeChild(docEle('mask'));
var i = 0;
var sel_obj = document.getElementsByTagName('select');
while (sel_obj[i])
{
sel_obj[i].style.visibility = "";
i++;
}
}
| JavaScript |
/* $Id : user.js 4865 2007-01-31 14:04:10Z paulgao $ */
/* *
* 修改会员信息
*/
function userEdit()
{
var frm = document.forms['formEdit'];
var email = frm.elements['email'].value;
var msg = '';
var reg = null;
var passwd_answer = frm.elements['passwd_answer'] ? Utils.trim(frm.elements['passwd_answer'].value) : '';
var sel_question = frm.elements['sel_question'] ? Utils.trim(frm.elements['sel_question'].value) : '';
if (email.length == 0)
{
msg += email_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
msg += email_error + '\n';
}
}
if (passwd_answer.length > 0 && sel_question == 0 || document.getElementById('passwd_quesetion') && passwd_answer.length == 0)
{
msg += no_select_question + '\n';
}
for (i = 7; i < frm.elements.length - 2; i++) // 从第七项开始循环检查是否为必填项
{
needinput = document.getElementById(frm.elements[i].name + 'i') ? document.getElementById(frm.elements[i].name + 'i') : '';
if (needinput != '' && frm.elements[i].value.length == 0)
{
msg += '- ' + needinput.innerHTML + msg_blank + '\n';
}
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* 会员修改密码 */
function editPassword()
{
var frm = document.forms['formPassword'];
var old_password = frm.elements['old_password'].value;
var new_password = frm.elements['new_password'].value;
var confirm_password = frm.elements['comfirm_password'].value;
var msg = '';
var reg = null;
if (old_password.length == 0)
{
msg += old_password_empty + '\n';
}
if (new_password.length == 0)
{
msg += new_password_empty + '\n';
}
if (confirm_password.length == 0)
{
msg += confirm_password_empty + '\n';
}
if (new_password.length > 0 && confirm_password.length > 0)
{
if (new_password != confirm_password)
{
msg += both_password_error + '\n';
}
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 对会员的留言输入作处理
*/
function submitMsg()
{
var frm = document.forms['formMsg'];
var msg_title = frm.elements['msg_title'].value;
var msg_content = frm.elements['msg_content'].value;
var msg = '';
if (msg_title.length == 0)
{
msg += msg_title_empty + '\n';
}
if (msg_content.length == 0)
{
msg += msg_content_empty + '\n'
}
if (msg_title.length > 200)
{
msg += msg_title_limit + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 会员找回密码时,对输入作处理
*/
function submitPwdInfo()
{
var frm = document.forms['getPassword'];
var user_name = frm.elements['user_name'].value;
var email = frm.elements['email'].value;
var errorMsg = '';
if (user_name.length == 0)
{
errorMsg += user_name_empty + '\n';
}
if (email.length == 0)
{
errorMsg += email_address_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
errorMsg += email_address_error + '\n';
}
}
if (errorMsg.length > 0)
{
alert(errorMsg);
return false;
}
return true;
}
/* *
* 会员找回密码时,对输入作处理
*/
function submitPwd()
{
var frm = document.forms['getPassword2'];
var password = frm.elements['new_password'].value;
var confirm_password = frm.elements['confirm_password'].value;
var errorMsg = '';
if (password.length == 0)
{
errorMsg += new_password_empty + '\n';
}
if (confirm_password.length == 0)
{
errorMsg += confirm_password_empty + '\n';
}
if (confirm_password != password)
{
errorMsg += both_password_error + '\n';
}
if (errorMsg.length > 0)
{
alert(errorMsg);
return false;
}
else
{
return true;
}
}
/* *
* 处理会员提交的缺货登记
*/
function addBooking()
{
var frm = document.forms['formBooking'];
var goods_id = frm.elements['id'].value;
var rec_id = frm.elements['rec_id'].value;
var number = frm.elements['number'].value;
var desc = frm.elements['desc'].value;
var linkman = frm.elements['linkman'].value;
var email = frm.elements['email'].value;
var tel = frm.elements['tel'].value;
var msg = "";
if (number.length == 0)
{
msg += booking_amount_empty + '\n';
}
else
{
var reg = /^[0-9]+/;
if ( ! reg.test(number))
{
msg += booking_amount_error + '\n';
}
}
if (desc.length == 0)
{
msg += describe_empty + '\n';
}
if (linkman.length == 0)
{
msg += contact_username_empty + '\n';
}
if (email.length == 0)
{
msg += email_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
msg += email_error + '\n';
}
}
if (tel.length == 0)
{
msg += contact_phone_empty + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
return true;
}
/* *
* 会员登录
*/
function userLogin()
{
var frm = document.forms['formLogin'];
var username = frm.elements['username'].value;
var password = frm.elements['password'].value;
var msg = '';
if (username.length == 0)
{
msg += username_empty + '\n';
}
if (password.length == 0)
{
msg += password_empty + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
function chkstr(str)
{
for (var i = 0; i < str.length; i++)
{
if (str.charCodeAt(i) < 127 && !str.substr(i,1).match(/^\w+$/ig))
{
return false;
}
}
return true;
}
function check_password( password )
{
if ( password.length < 6 )
{
document.getElementById('password_notice').innerHTML = password_shorter;
}
else
{
document.getElementById('password_notice').innerHTML = msg_can_rg;
}
}
function check_conform_password( conform_password )
{
password = document.getElementById('password1').value;
if ( conform_password.length < 6 )
{
document.getElementById('conform_password_notice').innerHTML = password_shorter;
return false;
}
if ( conform_password != password )
{
document.getElementById('conform_password_notice').innerHTML = confirm_password_invalid;
}
else
{
document.getElementById('conform_password_notice').innerHTML = msg_can_rg;
}
}
function is_registered( username )
{
var submit_disabled = false;
var unlen = username.replace(/[^\x00-\xff]/g, "**").length;
if ( username == '' )
{
document.getElementById('username_notice').innerHTML = msg_un_blank;
var submit_disabled = true;
}
if ( !chkstr( username ) )
{
document.getElementById('username_notice').innerHTML = msg_un_format;
var submit_disabled = true;
}
if ( unlen < 3 )
{
document.getElementById('username_notice').innerHTML = username_shorter;
var submit_disabled = true;
}
if ( unlen > 14 )
{
document.getElementById('username_notice').innerHTML = msg_un_length;
var submit_disabled = true;
}
if ( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=is_registered', 'username=' + username, registed_callback , 'GET', 'TEXT', true, true );
}
function registed_callback(result)
{
if ( result == "true" )
{
document.getElementById('username_notice').innerHTML = msg_can_rg;
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
document.getElementById('username_notice').innerHTML = msg_un_registered;
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function checkEmail(email)
{
var submit_disabled = false;
if (email == '')
{
document.getElementById('email_notice').innerHTML = msg_email_blank;
submit_disabled = true;
}
else if (!Utils.isEmail(email))
{
document.getElementById('email_notice').innerHTML = msg_email_format;
submit_disabled = true;
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_email', 'email=' + email, check_email_callback , 'GET', 'TEXT', true, true );
}
function check_email_callback(result)
{
if ( result == 'ok' )
{
document.getElementById('email_notice').innerHTML = msg_can_rg;
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
document.getElementById('email_notice').innerHTML = msg_email_registered;
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
/* *
* 处理注册用户
*/
function register()
{
var frm = document.forms['formUser'];
var username = Utils.trim(frm.elements['username'].value);
var email = frm.elements['email'].value;
var password = Utils.trim(frm.elements['password'].value);
var confirm_password = Utils.trim(frm.elements['confirm_password'].value);
//var checked_agreement = frm.elements['agreement'].checked;
var msn = frm.elements['extend_field1'] ? Utils.trim(frm.elements['extend_field1'].value) : '';
var qq = frm.elements['extend_field2'] ? Utils.trim(frm.elements['extend_field2'].value) : '';
var home_phone = frm.elements['extend_field4'] ? Utils.trim(frm.elements['extend_field4'].value) : '';
var office_phone = frm.elements['extend_field3'] ? Utils.trim(frm.elements['extend_field3'].value) : '';
var mobile_phone = frm.elements['extend_field5'] ? Utils.trim(frm.elements['extend_field5'].value) : '';
var passwd_answer = frm.elements['passwd_answer'] ? Utils.trim(frm.elements['passwd_answer'].value) : '';
var sel_question = frm.elements['sel_question'] ? Utils.trim(frm.elements['sel_question'].value) : '';
// 检查输入
var msg = '';
if (username.length == 0)
{
msg += username_empty + '\n';
}
else if (username.match(/^\s*$|^c:\\con\\con$|[%,\'\*\"\s\t\<\>\&\\]/))
{
msg += username_invalid + '\n';
}
else if (username.length < 3)
{
//msg += username_shorter + '\n';
}
if (email.length == 0)
{
msg += email_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
msg += email_invalid + '\n';
}
}
if (password.length == 0)
{
msg += password_empty + '\n';
}
else if (password.length < 6)
{
msg += password_shorter + '\n';
}
if (/ /.test(password) == true)
{
msg += passwd_balnk + '\n';
}
if (confirm_password != password )
{
msg += confirm_password_invalid + '\n';
}
if(checked_agreement != true)
{
msg += agreement + '\n';
}
if (msn.length > 0 && (!Utils.isEmail(msn)))
{
msg += msn_invalid + '\n';
}
if (qq.length > 0 && (!Utils.isNumber(qq)))
{
msg += qq_invalid + '\n';
}
if (office_phone.length>0)
{
var reg = /^[\d|\-|\s]+$/;
if (!reg.test(office_phone))
{
msg += office_phone_invalid + '\n';
}
}
if (home_phone.length>0)
{
var reg = /^[\d|\-|\s]+$/;
if (!reg.test(home_phone))
{
msg += home_phone_invalid + '\n';
}
}
if (mobile_phone.length>0)
{
var reg = /^[\d|\-|\s]+$/;
if (!reg.test(mobile_phone))
{
msg += mobile_phone_invalid + '\n';
}
}
if (passwd_answer.length > 0 && sel_question == 0 || document.getElementById('passwd_quesetion') && passwd_answer.length == 0)
{
msg += no_select_question + '\n';
}
for (i = 4; i < frm.elements.length - 4; i++) // 从第五项开始循环检查是否为必填项
{
needinput = document.getElementById(frm.elements[i].name + 'i') ? document.getElementById(frm.elements[i].name + 'i') : '';
if (needinput != '' && frm.elements[i].value.length == 0)
{
msg += '- ' + needinput.innerHTML + msg_blank + '\n';
}
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 用户中心订单保存地址信息
*/
function saveOrderAddress(id)
{
var frm = document.forms['formAddress'];
var consignee = frm.elements['consignee'].value;
var email = frm.elements['email'].value;
var address = frm.elements['address'].value;
var zipcode = frm.elements['zipcode'].value;
var tel = frm.elements['tel'].value;
var mobile = frm.elements['mobile'].value;
var sign_building = frm.elements['sign_building'].value;
var best_time = frm.elements['best_time'].value;
if (id == 0)
{
alert(current_ss_not_unshipped);
return false;
}
var msg = '';
if (address.length == 0)
{
msg += address_name_not_null + "\n";
}
if (consignee.length == 0)
{
msg += consignee_not_null + "\n";
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 会员余额申请
*/
function submitSurplus()
{
var frm = document.forms['formSurplus'];
var surplus_type = frm.elements['surplus_type'].value;
var surplus_amount = frm.elements['amount'].value;
var process_notic = frm.elements['user_note'].value;
var payment_id = 0;
var msg = '';
if (surplus_amount.length == 0 )
{
msg += surplus_amount_empty + "\n";
}
else
{
var reg = /^[\.0-9]+/;
if ( ! reg.test(surplus_amount))
{
msg += surplus_amount_error + '\n';
}
}
if (process_notic.length == 0)
{
msg += process_desc + "\n";
}
if (msg.length > 0)
{
alert(msg);
return false;
}
if (surplus_type == 0)
{
for (i = 0; i < frm.elements.length ; i ++)
{
if (frm.elements[i].name=="payment_id" && frm.elements[i].checked)
{
payment_id = frm.elements[i].value;
break;
}
}
if (payment_id == 0)
{
alert(payment_empty);
return false;
}
}
return true;
}
/* *
* 处理用户添加一个红包
*/
function addBonus()
{
var frm = document.forms['addBouns'];
var bonus_sn = frm.elements['bonus_sn'].value;
if (bonus_sn.length == 0)
{
alert(bonus_sn_empty);
return false;
}
else
{
var reg = /^[0-9]{10}$/;
if ( ! reg.test(bonus_sn))
{
alert(bonus_sn_error);
return false;
}
}
return true;
}
/* *
* 合并订单检查
*/
function mergeOrder()
{
if (!confirm(confirm_merge))
{
return false;
}
var frm = document.forms['formOrder'];
var from_order = frm.elements['from_order'].value;
var to_order = frm.elements['to_order'].value;
var msg = '';
if (from_order == 0)
{
msg += from_order_empty + '\n';
}
if (to_order == 0)
{
msg += to_order_empty + '\n';
}
else if (to_order == from_order)
{
msg += order_same + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 订单中的商品返回购物车
* @param int orderId 订单号
*/
function returnToCart(orderId)
{
Ajax.call('user.php?act=return_to_cart', 'order_id=' + orderId, returnToCartResponse, 'POST', 'JSON');
}
function returnToCartResponse(result)
{
alert(result.message);
}
/* *
* 检测密码强度
* @param string pwd 密码
*/
function checkIntensity(pwd)
{
var Mcolor = "#FFF",Lcolor = "#FFF",Hcolor = "#FFF";
var m=0;
var Modes = 0;
for (i=0; i<pwd.length; i++)
{
var charType = 0;
var t = pwd.charCodeAt(i);
if (t>=48 && t <=57)
{
charType = 1;
}
else if (t>=65 && t <=90)
{
charType = 2;
}
else if (t>=97 && t <=122)
charType = 4;
else
charType = 4;
Modes |= charType;
}
for (i=0;i<4;i++)
{
if (Modes & 1) m++;
Modes>>>=1;
}
if (pwd.length<=4)
{
m = 1;
}
switch(m)
{
case 1 :
Lcolor = "2px solid red";
Mcolor = Hcolor = "2px solid #DADADA";
break;
case 2 :
Mcolor = "2px solid #f90";
Lcolor = Hcolor = "2px solid #DADADA";
break;
case 3 :
Hcolor = "2px solid #3c0";
Lcolor = Mcolor = "2px solid #DADADA";
break;
case 4 :
Hcolor = "2px solid #3c0";
Lcolor = Mcolor = "2px solid #DADADA";
break;
default :
Hcolor = Mcolor = Lcolor = "";
break;
}
if (document.getElementById("pwd_lower"))
{
document.getElementById("pwd_lower").style.borderBottom = Lcolor;
document.getElementById("pwd_middle").style.borderBottom = Mcolor;
document.getElementById("pwd_high").style.borderBottom = Hcolor;
}
}
function changeType(obj)
{
if (obj.getAttribute("min") && document.getElementById("ECS_AMOUNT"))
{
document.getElementById("ECS_AMOUNT").disabled = false;
document.getElementById("ECS_AMOUNT").value = obj.getAttribute("min");
if (document.getElementById("ECS_NOTICE") && obj.getAttribute("to") && obj.getAttribute('fee'))
{
var fee = parseInt(obj.getAttribute("fee"));
var to = parseInt(obj.getAttribute("to"));
if (fee < 0)
{
to = to + fee * 2;
}
document.getElementById("ECS_NOTICE").innerHTML = notice_result + to;
}
}
}
function calResult()
{
var amount = document.getElementById("ECS_AMOUNT").value;
var notice = document.getElementById("ECS_NOTICE");
reg = /^\d+$/;
if (!reg.test(amount))
{
notice.innerHTML = notice_not_int;
return;
}
amount = parseInt(amount);
var frm = document.forms['transform'];
for(i=0; i < frm.elements['type'].length; i++)
{
if (frm.elements['type'][i].checked)
{
var min = parseInt(frm.elements['type'][i].getAttribute("min"));
var to = parseInt(frm.elements['type'][i].getAttribute("to"));
var fee = parseInt(frm.elements['type'][i].getAttribute("fee"));
var result = 0;
if (amount < min)
{
notice.innerHTML = notice_overflow + min;
return;
}
if (fee > 0)
{
result = (amount - fee) * to / (min -fee);
}
else
{
//result = (amount + fee* min /(to+fee)) * (to + fee) / min ;
result = amount * (to + fee) / min + fee;
}
notice.innerHTML = notice_result + parseInt(result + 0.5);
}
}
}
| JavaScript |
/* $Id : auto_complete.js 4865 2007-01-31 14:04:10Z paulgao $ */
function autoComplete(obj, hidden, url, callback)
{
this.borderStyle = '1px solid #000';
this.highlight = '#000080';
this.highlightText = '#FFF';
this.background = '#FFF';
this.params = '';
var textbox = obj;
var hidden = hidden;
var oldValue = '';
var flag = false;
var url = url;
this.call = function()
{
if (flag)
{
flag = false;
return;
}
if (url == '')
{
return;
}
if (oldValue != '' && oldValue == textbox.value)
{
return;
}
else
{
oldValue = textbox.value;
}
if (textbox.value != '')
{
Transport.run(url, "arg=" + textbox.value, this.show, 'get', 'json');
}
else
{
var layer = document.getElementById('AC_layer');
if (layer)
{
layer.style.display = 'none';
}
}
}
var _ac = this;
this.show = function(result)
{
var obj = result;
var layer = null;
if (document.getElementById('AC_layer'))
{
layer = document.getElementById('AC_layer');
layer.innerHTML = '';
layer.style.display = 'block';
}
else
{
layer = document.createElement('DIV');
layer.id = 'AC_layer';
document.body.appendChild(layer);
}
pos = getPosition();
layer.style.left = pos.x + 'px';
layer.style.top = pos.y + 'px';
layer.style.width = textbox.clientWidth + 'px';
layer.style.position = 'absolute';
layer.style.border = _ac.borderStyle;
layer.style.background = _ac.background;
createMenuItem(obj, layer);
textbox.onkeyup = function(e)
{
var evt = fixEvent(e);
if (evt.keyCode == '38')
{
highlightItem('prev');
}
if (evt.keyCode == '40')
{
highlightItem('next');
}
}
textbox.onblur = function()
{
var layer = document.getElementById('AC_layer');
if (layer)
{
layer.style.display = 'none';
}
}
}
var createMenuItem = function(obj, layer)
{
var lst = document.createElement('UL');
lst.style.listStyle = 'none';
lst.style.margin = '0';
lst.style.padding = '1px';
lst.style.display = 'block';
for (i = 0; i < obj.length; i ++ )
{
if (typeof(obj[i].key) === "undefined" || typeof(obj[i].val) === "undefined")
{
throw new Error('Error data.');
break;
}
else
{
var listItem = document.createElement('LI');
listItem.id = obj[i].key;
listItem.innerHTML = obj[i].val;
listItem.title = obj[i].val;
listItem.style.cursor = "default";
listItem.style.pointer = "default";
listItem.style.margin = '0px';
listItem.style.padding = '0px';
listItem.style.display = 'block';
listItem.style.width = '100%';
listItem.style.height = '16px';
listItem.style.overflow = 'hidden';
listItem.onmouseover = function(e)
{
for (i = 0; i < this.parentNode.childNodes.length;
i ++ )
{
this.parentNode.childNodes[i].style.backgroundColor = '';
this.parentNode.childNodes[i].style.color = '';
}
this.style.backgroundColor = _ac.highlight;
this.style.color = _ac.highlightText;
assign(this);
}
;
listItem.onmouseout = function(e)
{
this.style.backgroundColor = '';
this.style.color = '';
}
;
lst.appendChild(listItem);
}
}
layer.appendChild(lst);
}
var getPosition = function()
{
var obj = textbox;
var pos =
{
"x" : 0, "y" : 0
}
pos.x = document.body.offsetLeft;
pos.y = document.body.offsetTop + textbox.clientHeight + 3;
do
{
pos.x += obj.offsetLeft;
pos.y += obj.offsetTop;
obj = obj.offsetParent;
}
while (obj.tagName.toUpperCase() != 'BODY')
return pos;
}
var fixEvent = function(e)
{
return (typeof e == "undefined") ? window.event : e;
}
var highlightItem = function(direction)
{
var layer = document.getElementById('AC_layer');
var list = null;
var item = null;
if (layer)
{
list = layer.childNodes[0];
}
if (list)
{
for (i = 0; i < list.childNodes.length; i ++ )
{
if (list.childNodes[i].style.backgroundColor == _ac.highlight)
{
if (direction == 'prev')
{
item = (i > 0) ? list.childNodes[i - 1] : list.lastChild;
}
else
{
item = (i < list.childNodes.length) ? list.childNodes[i + 1] : list.childNodes[0];
}
}
list.childNodes[i].style.backgroundColor = '';
list.childNodes[i].style.color = '';
}
}
if ( ! item)
{
item = (direction == 'prev') ? list.lastChild : list.childNodes[0];
}
item.style.backgroundColor = _ac.highlight;
item.style.color = _ac.highlightText
assign(item);
}
var assign = function(item)
{
flag = true;
textbox.value = item.innerHTML;
if (typeof hidden == 'object')
{
hidden.value = item.id;
}
if (typeof callback == 'function')
{
callback.call(_ac, item.id, textbox.value);
}
}
var debug = function()
{
// document.getElementById('foo').innerHTML = textbox.value;
}
}
| JavaScript |
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose)
{
// member variables
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; // 0 for Sunday, 1 for Monday, etc.
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;
// HTML elements
this.table = null;
this.element = null;
this.tbody = null;
this.firstdayname = null;
// Combo boxes
this.monthsCombo = null;
this.yearsCombo = null;
this.hilitedMonth = null;
this.activeMonth = null;
this.hilitedYear = null;
this.activeYear = null;
// Information
this.dateClicked = false;
// one-time initializations
if (typeof Calendar._SDN == "undefined") {
// table of short day names
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;
// table of short month names
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;
}
};
// ** constants
/// "static", needed for event handlers.
Calendar._C = null;
/// detect a special case of "web browser"
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) );
/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
// library, at some point.
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;
};
// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
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) { // IE
el.attachEvent("on" + evname, func);
} else if (el.addEventListener) { // Gecko / W3C
el.addEventListener(evname, func, true);
} else {
el["on" + evname] = func;
}
};
Calendar.removeEvent = function(el, evname, func) {
if (el.detachEvent) { // IE
el.detachEvent("on" + evname, func);
} else if (el.removeEventListener) { // Gecko / W3C
el.removeEventListener(evname, func, true);
} else {
el["on" + evname] = null;
}
};
Calendar.createElement = function(type, parent) {
var el = null;
if (document.createElementNS) {
// use the XHTML namespace; IE won't normally get here unless
// _they_ "fix" the DOM2 implementation.
el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
} else {
el = document.createElement(type);
}
if (typeof parent != "undefined") {
parent.appendChild(el);
}
return el;
};
// END: UTILITY FUNCTIONS
// BEGIN: CALENDAR STATIC FUNCTIONS
/** Internal -- adds a set of events to make some element behave like a button. */
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")
// Konqueror brain-dead techniques
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")
// Konqueror brain-dead techniques
ycw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
}
};
// event handlers
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;
} else
dx = 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);
}
};
/**
* A generic "click" handler :) handles all types of buttons defined in this
* calendar.
*/
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;
// a date was clicked
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()); // TODAY
// unless "today" was clicked, we assume no date was clicked so
// the selected handler will know not to close the calenar when
// in single-click mode.
// cal.dateClicked = (el.navtype == 0);
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 {
// FIXME: this should be removed as soon as lang files get updated!
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:
// TODAY will bring us here
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();
}
};
// END: CALENDAR STATIC FUNCTIONS
// BEGIN: CALENDAR OBJECT FUNCTIONS
/**
* This function creates the calendar inside the given parent. If _par is
* null than it creates a popup calendar inside the BODY element. If _par is
* an element, be it BODY, then it creates a non-popup calendar (still
* hidden). Some properties need to be set before calling this function.
*/
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
// default parent is the document body, in which case we create
// a popup calendar.
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";
}
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
div.innerHTML = '<iframe src="javascript:false" id="compareFrame" style=" position:absolute; top:0px; left:0px;width:245px; visibility:inherit;height:172px; z-index:-1;filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";></iframe>';
}
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("?", 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("×", 1, 200).ttip = Calendar._TT["CLOSE"];
}
row = Calendar.createElement("tr", thead);
row.className = "headrow";
this._nav_py = hh("«", 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("»", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
// day names
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = Calendar._TT["WK"];
}
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"] || " ";
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 = " ";
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);
};
/** keyboard navigation, only for popup calendars */
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: // KEY left
act && Calendar.cellClick(cal._nav_pm);
break;
case 38: // KEY up
act && Calendar.cellClick(cal._nav_py);
break;
case 39: // KEY right
act && Calendar.cellClick(cal._nav_nm);
break;
case 40: // KEY down
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32: // KEY space (now)
Calendar.cellClick(cal._nav_now);
break;
case 27: // KEY esc
act && cal.callCloseHandler();
break;
case 37: // KEY left
case 38: // KEY up
case 39: // KEY right
case 40: // KEY down
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: // KEY left
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38: // KEY up
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39: // KEY right
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40: // KEY down
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: // KEY enter
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
/**
* (RE)Initializes the calendar to the given date and firstDayOfWeek
*/
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();
// calendar voodoo for computing the first day that would actually be
// displayed in the calendar, even if it's from the previous month.
// WARNING: this is magic. ;-)
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 = date.getWeekNumber();
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 = " ";
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();
// PROFILE
// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};
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;
};
/**
* Calls _init function above for going to a certain date (but only if the
* date is different than the currently selected one).
*/
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
/**
* Refreshes the calendar. Useful if the "disabledHandler" function is
* dynamic, meaning that the list of disabled date can change at runtime.
* Just * call this function if you think that the list of disabled dates
* should * change.
*/
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
/**
* Allows customization of what dates are enabled. The "unaryFunction"
* parameter must be a function object that receives the date (as a JS Date
* object) and returns a boolean value. If the returned value is true then
* the passed date will be marked as disabled.
*/
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
/**
* Moves the calendar element to a different section in the DOM tree (changes
* its parent).
*/
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown. If the click was outside the open
// calendar this function closes it.
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) {
// calls closeHandler which should hide the calendar.
window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
/** Shows the calendar. */
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();
};
/**
* Hides the calendar. Also removes any "hilite" from the class of any TD
* element.
*/
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();
};
/**
* Shows the calendar at a given absolute position (beware that, depending on
* the calendar element style -- position property -- this might be relative
* to the parent's containing rectangle).
*/
Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
/** Shows the calendar near a given element. */
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);
}
// vertical alignment
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; // already there
}
// horizontal alignment
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; // already there
}
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();
};
/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
/**
* Tries to identify the date represented in a string. If successful it also
* calls this.setDate which moves the calendar to the given date.
*/
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") { // Gecko, W3C
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) { // IE
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};
var tags = new Array("applet", "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";
}
}
}
};
/** Internal function; it displays the bar with the names of the weekday. */
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;
}
};
/** Internal function. Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
/** Internal function. Starts dragging the element. */
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);
}
};
// BEGIN: DATE OBJECT PATCHES
/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
/** Constants used for time computations */
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;
};
/** Returns the number of days in the current month */
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];
}
};
/** Returns the number of day in the year. */
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);
};
/** Returns the number of the week in year, as defined in ISO 8601. */
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); // Nearest Thu
var ms = d.valueOf(); // GMT
d.setMonth(0);
d.setDate(4); // Thu in Week 1
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
/** Checks date and time equality */
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()));
};
/** Set only the year, month, date parts (keep existing time) */
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());
};
/** Prints the date in a string according to the given format. */
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]; // abbreviated weekday name [FIXME: I18N]
s["%A"] = Calendar._DN[w]; // full weekday name
s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = Calendar._MN[m]; // full month name
// FIXME: %c : preferred date and time representation for the current locale
s["%C"] = 1 + Math.floor(y / 100); // the century number
s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
s["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr; // hour, range 0 to 23 (24h format)
s["%l"] = ir; // hour, range 1 to 12 (12h format)
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = y; // year with the century
s["%%"] = "%"; // a literal '%' character
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);
};
// END: DATE OBJECT PATCHES
// global object that remembers the calendar
window._dynarch_popupCalendar = null;
//var calendar = null;
var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
if (oldLink) oldLink.style.fontWeight = 'normal';
oldLink = link;
link.style.fontWeight = 'bold';
return false;
}
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
cal.sel.value = date; // just update the date in the input field.
if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
// if we add this call we close the calendar on single-click.
// just to exemplify both cases, we are using this only for the 1st
// and the 3rd field, while 2nd and 4th will still require double-click.
cal.callCloseHandler();
}
// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button. It just hides the calendar without
// destroying it.
function closeHandler(cal) {
cal.hide(); // hide the calendar
// cal.destroy();
_dynarch_popupCalendar = null;
}
// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths, selbtn) {
var el = typeof(id) == "object" ? id : document.getElementById(id);
if (selbtn == '')
{
selbtn = 'selbtn';
}
var btn_el = typeof(selbtn) == "object" ? selbtn : document.getElementById(selbtn);;
if (_dynarch_popupCalendar != null) {
// we already have some calendar created
_dynarch_popupCalendar.hide(); // so we hide it first.
} else {
// first-time call, create the calendar.
var cal = new Calendar(1, null, selected, closeHandler);
// uncomment the following line to hide the week numbers
// cal.weekNumbers = false;
if (typeof showsTime == "string") {
cal.showsTime = true;
cal.time24 = (showsTime == "24");
}
if (showsOtherMonths) {
cal.showsOtherMonths = true;
}
_dynarch_popupCalendar = cal; // remember it in the global var
cal.setRange(1900, 2070); // min/max year allowed.
cal.create();
//alert(cal.table.parentNode.parentNode.innerHTML);
}
_dynarch_popupCalendar.setDateFormat(format); // set the specified date format
_dynarch_popupCalendar.parseDate(el.value); // try to parse the text in field
_dynarch_popupCalendar.sel = el; // inform it what input field we use
//_dynarch_popupCalendar.btn = btn_el; //
// the reference element that we pass to showAtElement is the button that
// triggers the calendar. In this example we align the calendar bottom-right
// to the button.
//_dynarch_popupCalendar.showAtElement(el.nextSibling, "Br"); // show the calendar
_dynarch_popupCalendar.showAtElement(btn_el, "Br");
return false;
}
var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;
// If this handler returns true then the "date" given as
// parameter will be disabled. In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here. However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
var today = new Date();
return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}
function flatSelected(cal, date) {
var el = document.getElementById("preview");
el.innerHTML = date;
}
function showFlatCalendar() {
var parent = document.getElementById("display");
// construct a calendar giving only the "selected" handler.
var cal = new Calendar(0, null, flatSelected);
// hide week numbers
cal.weekNumbers = false;
// We want some dates to be disabled; see function isDisabled above
cal.setDisabledHandler(isDisabled);
cal.setDateFormat("%A, %B %e");
// this call must be the last as it might use data initialized above; if
// we specify a parent, as opposite to the "showCalendar" function above,
// then we create a flat calendar -- not popup. Hidden, though, but...
cal.create(parent);
// ... we can show it here.
cal.show();
}
// full day names
Calendar._DN = new Array('"' + Sunday + '"', '"' + Monday + '"', '"' + Tuesday + '"', '"' + Wednesday + '"', '"' + Thursday + '"', '"' + Friday + '"', '"' + Saturday + '"', '"' + Sunday + '"');
// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary. We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
// Calendar._SDN_len = N; // short day name length
// Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.
// short day names
Calendar._SDN = new Array('"' + Sun + '"', '"' + Mon + '"', '"' + Tue + '"', '"' + Wed + '"', '"' + Thu + '"', '"' + Fri + '"', '"' + Sat + '"', '"' + Sun + '"');
// full month names
Calendar._MN = new Array('"' + January + '"', '"' + February + '"', '"' + March + '"', '"' + April + '"', '"' + May + '"', '"' + June + '"', '"' + July + '"', '"' + Aguest + '"', '"' + September + '"', '"' + October + '"', '"' + November + '"', '"' + December + '"');
// short month names
Calendar._SMN = new Array('"' + Jan + '"', '"' + Feb + '"', '"' + Mar + '"', '"' + Apr + '"', '"' + May + '"', '"' + Jun + '"', '"' + Jul + '"', '"' + Agu + '"', '"' + Sep + '"', '"' + Oct + '"', '"' + Nov + '"', '"' + Dec + '"');
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = calendar_help;
Calendar._TT["ABOUT"] = calendar_about1 + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + calendar_about2;
Calendar._TT["ABOUT_TIME"] = calendar_about_time;
Calendar._TT["PREV_YEAR"] = prev_year;
Calendar._TT["PREV_MONTH"] = prev_month;
Calendar._TT["GO_TODAY"] = go_today;
Calendar._TT["NEXT_MONTH"] = next_month;
Calendar._TT["NEXT_YEAR"] = next_year;
Calendar._TT["SEL_DATE"] = sel_date;
Calendar._TT["DRAG_TO_MOVE"] = drag_to_move;
Calendar._TT["PART_TODAY"] = part_today;
// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = day_first + "%s";
// This may be locale-dependent. It specifies the week-end days, as an array
// of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = calendar_close;
Calendar._TT["TODAY"] = calendar_today;
Calendar._TT["TIME_PART"] = time_part;
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %b %e" + calendar_day;
Calendar._TT["WK"] = calendar_wk;
Calendar._TT["TIME"] = calendar_time + ":"; | JavaScript |
function setTab(name,cursel,n){
for(i=1;i<=n;i++){
var menu=document.getElementById(name+i);
var con=document.getElementById("con_"+name+"_"+i);
menu.className=i==cursel?"hover":"";
con.style.display=i==cursel?"block":"none";
}
}
function obj(e){
return document.getElementById(e);
}
function selectSort(name,cursel,n){
for(i=1;i<=n;i++){
var menu=obj(name+i);
menu.className=i==cursel?"hover":"";
}
}
function cateOver(){
if(obj("list_cate")){
obj("list_cate").style.display="";
}
}
function cateOut(){
if(obj("list_cate")){
obj("list_cate").style.display="none";
}
}
function showObj(){
var address=obj("good_address");
var address_a=obj("address_a");
address.style.display="block";
address_a.className="hover";
}
function hideObj(){
var address=obj("good_address");
var address_a=obj("address_a");
address.style.display="none";
address_a.className="";
}
function check_storage(goods_id,cid){
var info = new Object();
info.goods_id = goods_id;
info.cid = cid;
Ajax.call('goods.php?act=storage', 'info=' + info.toJSONString(), changeHtml, 'POST', 'JSON');
}
function changeHtml(result){
var address_span=obj("address_span");
address_span.innerHTML=result.message;
}
function hideKc(){
var good_address=obj("good_address");
good_address.style.display="none";
}
function showReply(){
var replyform=obj("replyform");
replyform.style.display = replyform.style.display=="none"?"block":"none";
}
function showReply1(){
var replyform1=obj("replyform1");
replyform1.style.display = replyform1.style.display=="none"?"block":"none";
}
function hideReply1(){
var star=obj("star");
var starF=obj("starF");
var replyform1=obj("replyform1");
replyform1.style.display="none";
star.className="sa0";
starF.innerHTML="";
}
function starX(i){
var star=obj("star");
var starF=obj("starF");
star.className="sa"+i;
starF.innerHTML=i+"分";
var dc = document.getElementById('comment_rank');
dc.value = i;
}
function save(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "");
}
function setCookies(name,value)
{
var Days = 2;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape(value) +";expire*="+ exp.toGMTString();
}
function getCookies(name)
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}
| JavaScript |
$(function(){
var index = 0;
$("#tab").find("a").mouseover(function(){
index = $("#tab").find("a").index(this);
showImg(index);
});
$('#focus').hover(function(){
if(MyTime){
clearInterval(MyTime);
}
},function(){
MyTime = setInterval(function(){
showImg(index)
index++;
if(index==5){index=0;}
} , 3600);
});
var MyTime = setInterval(function(){
showImg(index)
index++;
if(index==5){index=0;}
} , 3600);
})
function showImg(i){
$("#focus").find("li")
.eq(i).stop(true,true).fadeIn(800)
.siblings().hide();
$("#tab").find("a")
.eq(i).addClass("hover")
.parent().siblings().find("a").removeClass("hover");
}
| JavaScript |
var Speed_1 = 10; //速度(毫秒)
var Space_1 = 10; //每次移动(px)
var PageWidth_1 = 54; //翻页宽度
var fill_1 = 0; //整体移位
var MoveLock_1 = false;
var MoveTimeObj_1;
var MoveWay_1="right";
var Comp_1 = 0;
var AutoPlayObj_1=null;GetObj("List2_1").innerHTML=GetObj("List1_1").innerHTML;GetObj('ISL_Cont_1').scrollLeft=fill_1>=0?fill_1:GetObj('List1_1').scrollWidth-Math.abs(fill_1);GetObj("ISL_Cont_1").onmouseover=function(){clearInterval(AutoPlayObj_1)}
function GetObj(objName){if(document.getElementById){return eval('document.getElementById("'+objName+'")')}else{return eval('document.all.'+objName)}}
function ISL_GoUp_1(){if(MoveLock_1)return;clearInterval(AutoPlayObj_1);MoveLock_1=true;MoveWay_1="left";MoveTimeObj_1=setInterval('ISL_ScrUp_1();',Speed_1);}
function ISL_StopUp_1(){if(MoveWay_1 == "right"){return};clearInterval(MoveTimeObj_1);if((GetObj('ISL_Cont_1').scrollLeft-fill_1)%PageWidth_1!=0){Comp_1=fill_1-(GetObj('ISL_Cont_1').scrollLeft%PageWidth_1);CompScr_1()}else{MoveLock_1=false}
}
function ISL_ScrUp_1(){if(GetObj('ISL_Cont_1').scrollLeft<=0){GetObj('ISL_Cont_1').scrollLeft=GetObj('ISL_Cont_1').scrollLeft+GetObj('List1_1').offsetWidth}
GetObj('ISL_Cont_1').scrollLeft-=Space_1}
function ISL_GoDown_1(){clearInterval(MoveTimeObj_1);if(MoveLock_1)return;clearInterval(AutoPlayObj_1);MoveLock_1=true;MoveWay_1="right";ISL_ScrDown_1();MoveTimeObj_1=setInterval('ISL_ScrDown_1()',Speed_1)}
function ISL_StopDown_1(){if(MoveWay_1 == "left"){return};clearInterval(MoveTimeObj_1);if(GetObj('ISL_Cont_1').scrollLeft%PageWidth_1-(fill_1>=0?fill_1:fill_1+1)!=0){Comp_1=PageWidth_1-GetObj('ISL_Cont_1').scrollLeft%PageWidth_1+fill_1;CompScr_1()}else{MoveLock_1=false}
}
function ISL_ScrDown_1(){if(GetObj('ISL_Cont_1').scrollLeft>=GetObj('List1_1').scrollWidth){GetObj('ISL_Cont_1').scrollLeft=GetObj('ISL_Cont_1').scrollLeft-GetObj('List1_1').scrollWidth}
GetObj('ISL_Cont_1').scrollLeft+=Space_1}
function CompScr_1(){if(Comp_1==0){MoveLock_1=false;return}
var num,TempSpeed=Speed_1,TempSpace=Space_1;if(Math.abs(Comp_1)<PageWidth_1/2){TempSpace=Math.round(Math.abs(Comp_1/Space_1));if(TempSpace<1){TempSpace=1}}
if(Comp_1<0){if(Comp_1<-TempSpace){Comp_1+=TempSpace;num=TempSpace}else{num=-Comp_1;Comp_1=0}
GetObj('ISL_Cont_1').scrollLeft-=num;setTimeout('CompScr_1()',TempSpeed)}else{if(Comp_1>TempSpace){Comp_1-=TempSpace;num=TempSpace}else{num=Comp_1;Comp_1=0}
GetObj('ISL_Cont_1').scrollLeft+=num;setTimeout('CompScr_1()',TempSpeed)}} | JavaScript |
/* $Id : myship.js 4865 2007-01-31 14:04:10Z Hackfan $ */
/* *
* 检查收货地址信息表单中填写的内容
*/
function checkForm(frm)
{
var msg = new Array();
var err = false;
if (frm.elements['country'].value == 0)
{
msg.push(country_not_null);
err = true;
}
if (frm.elements['province'].value == 0 && frm.elements['province'].length > 1)
{
err = true;
msg.push(province_not_null);
}
if (frm.elements['city'].value == 0 && frm.elements['city'].length > 1)
{
err = true;
msg.push(city_not_null);
}
if (frm.elements['district'].length > 1)
{
if (frm.elements['district'].value == 0)
{
err = true;
msg.push(district_not_null);
}
}
if (err)
{
message = msg.join("\n");
alert(message);
}
return ! err;
}
| JavaScript |
/* $Id: showdiv.js 15469 2008-12-19 06:34:44Z testyang $ */
//创建显示层
var swtemp = 0;
var timer = null;
//显示层
function showdiv(obj)
{
var inputid = obj.id;
if (swtemp == 1)
{
hidediv("messagediv");
}
if (!getobj("messagediv"))
{
//若尚未创建就创建层
crertdiv("" , "div" , "messagediv" , "messagediv");//创建层"messagediv"
crertdiv("messagediv" , "li" , "messageli" , "messageli");//创建"请刷新"li
getobj("messageli").innerHTML = show_div_text;
crertdiv("messagediv" , "a" , "messagea" , "");//创建"关闭"a
getobj("messagea").innerHTML = show_div_exit;
getobj("messagea").onclick = function(){hidediv("messagediv");};
}
var newdiv = getobj("messagediv");
newdiv.style.left = (getAbsoluteLeft(obj) - 50) + "px";
newdiv.style.top = (getAbsoluteTop(obj) - 65) + "px";
newdiv.style.display = "block";
timer = setTimeout(function(){hidediv("messagediv");} , 3000);
swtemp = 1;
}
//创建层
function crertdiv(parent , element , id , css)
{
var newObj = document.createElement(element);
if(id && id != "")
{
newObj.id = id;
}
if(css && css != "")
{
newObj.className = css;
}
if(parent && parent!="")
{
var theObj = getobj(parent);
var parent = theObj.parentNode;
if(parent.lastChild == theObj)
{
theObj.appendChild(newObj);
}
else
{
theObj.insertBefore(newObj, theObj.nextSibling);
}
}
else
{
document.body.appendChild(newObj);
}
}
//隐藏层
function hidediv(objid)
{
getobj(objid).style.display = "none";
swtemp = 0;
clearTimeout(timer);
}
//获取对象
function getobj(obj)
{
return document.getElementById(obj);
}
function getAbsoluteHeight(obj)
{
return obj.offsetHeight;
}
function getAbsoluteWidth(obj)
{
return obj.offsetWidth;
}
function getAbsoluteLeft(obj)
{
var s_el = 0;
var el = obj;
while(el)
{
s_el = s_el + el.offsetLeft;
el = el.offsetParent;
}
return s_el;
}
function getAbsoluteTop(obj)
{
var s_el = 0;
var el = obj;
while(el)
{
s_el = s_el + el.offsetTop;
el = el.offsetParent;
}
return s_el;
} | JavaScript |
/* $Id : region.js 4865 2007-01-31 14:04:10Z paulgao $ */
var region = new Object();
region.isAdmin = false;
region.loadRegions = function(parent, type, target)
{
Ajax.call(region.getFileName(), 'type=' + type + '&target=' + target + "&parent=" + parent , region.response, "GET", "JSON");
}
/* *
* 载入指定的国家下所有的省份
*
* @country integer 国家的编号
* @selName string 列表框的名称
*/
region.loadProvinces = function(country, selName)
{
var objName = (typeof selName == "undefined") ? "selProvinces" : selName;
region.loadRegions(country, 1, objName);
}
/* *
* 载入指定的省份下所有的城市
*
* @province integer 省份的编号
* @selName string 列表框的名称
*/
region.loadCities = function(province, selName)
{
var objName = (typeof selName == "undefined") ? "selCities" : selName;
region.loadRegions(province, 2, objName);
}
/* *
* 载入指定的城市下的区 / 县
*
* @city integer 城市的编号
* @selName string 列表框的名称
*/
region.loadDistricts = function(city, selName)
{
var objName = (typeof selName == "undefined") ? "selDistricts" : selName;
region.loadRegions(city, 3, objName);
}
/* *
* 处理下拉列表改变的函数
*
* @obj object 下拉列表
* @type integer 类型
* @selName string 目标列表框的名称
*/
region.changed = function(obj, type, selName)
{
var parent = obj.options[obj.selectedIndex].value;
region.loadRegions(parent, type, selName);
}
region.response = function(result, text_result)
{
var sel = document.getElementById(result.target);
sel.length = 1;
sel.selectedIndex = 0;
sel.style.display = (result.regions.length == 0 && ! region.isAdmin && result.type + 0 == 3) ? "none" : '';
if (document.all)
{
sel.fireEvent("onchange");
}
else
{
var evt = document.createEvent("HTMLEvents");
evt.initEvent('change', true, true);
sel.dispatchEvent(evt);
}
if (result.regions)
{
for (i = 0; i < result.regions.length; i ++ )
{
var opt = document.createElement("OPTION");
opt.value = result.regions[i].region_id;
opt.text = result.regions[i].region_name;
sel.options.add(opt);
}
}
}
region.getFileName = function()
{
if (region.isAdmin)
{
return "../region.php";
}
else
{
return "region.php";
}
}
| JavaScript |
/* $Id : utils.js 5052 2007-02-03 10:30:13Z weberliu $ */
var Browser = new Object();
Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument != 'undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != - 1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != - 1);
var Utils = new Object();
Utils.htmlEncode = function(text)
{
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
Utils.trim = function( text )
{
if (typeof(text) == "string")
{
return text.replace(/^\s*|\s*$/g, "");
}
else
{
return text;
}
}
Utils.isEmpty = function( val )
{
switch (typeof(val))
{
case 'string':
return Utils.trim(val).length == 0 ? true : false;
break;
case 'number':
return val == 0;
break;
case 'object':
return val == null;
break;
case 'array':
return val.length == 0;
break;
default:
return true;
}
}
Utils.isNumber = function(val)
{
var reg = /^[\d|\.|,]+$/;
return reg.test(val);
}
Utils.isInt = function(val)
{
if (val == "")
{
return false;
}
var reg = /\D+/;
return !reg.test(val);
}
Utils.isEmail = function( email )
{
var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;
return reg1.test( email );
}
Utils.isTel = function ( tel )
{
var reg = /^[\d|\-|\s|\_]+$/; //只允许使用数字-空格等
return reg.test( tel );
}
Utils.fixEvent = function(e)
{
var evt = (typeof e == "undefined") ? window.event : e;
return evt;
}
Utils.srcElement = function(e)
{
if (typeof e == "undefined") e = window.event;
var src = document.all ? e.srcElement : e.target;
return src;
}
Utils.isTime = function(val)
{
var reg = /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/;
return reg.test(val);
}
Utils.x = function(e)
{ //当前鼠标X坐标
return Browser.isIE?event.x + document.documentElement.scrollLeft - 2:e.pageX;
}
Utils.y = function(e)
{ //当前鼠标Y坐标
return Browser.isIE?event.y + document.documentElement.scrollTop - 2:e.pageY;
}
Utils.request = function(url, item)
{
var sValue=url.match(new RegExp("[\?\&]"+item+"=([^\&]*)(\&?)","i"));
return sValue?sValue[1]:sValue;
}
Utils.$ = function(name)
{
return document.getElementById(name);
}
function rowindex(tr)
{
if (Browser.isIE)
{
return tr.rowIndex;
}
else
{
table = tr.parentNode.parentNode;
for (i = 0; i < table.rows.length; i ++ )
{
if (table.rows[i] == tr)
{
return i;
}
}
}
}
document.getCookie = function(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return decodeURIComponent(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
document.setCookie = function(sName, sValue, sExpires)
{
var sCookie = sName + "=" + encodeURIComponent(sValue);
if (sExpires != null)
{
sCookie += "; expires=" + sExpires;
}
document.cookie = sCookie;
}
document.removeCookie = function(sName,sValue)
{
document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}
function getPosition(o)
{
var t = o.offsetTop;
var l = o.offsetLeft;
while(o = o.offsetParent)
{
t += o.offsetTop;
l += o.offsetLeft;
}
var pos = {top:t,left:l};
return pos;
}
function cleanWhitespace(element)
{
var element = element;
for (var i = 0; i < element.childNodes.length; i++) {
var node = element.childNodes[i];
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
}
} | JavaScript |
/* $Id : lefttime.js 4865 2007-01-31 14:04:10Z paulgao $ */
/* *
* 给定一个剩余时间(s)动态显示一个剩余时间.
* 当大于一天时。只显示还剩几天。小于一天时显示剩余多少小时,多少分钟,多少秒。秒数每秒减1 *
*/
// 初始化变量
var auctionDate = 0;
var _GMTEndTime = 0;
var showTime = "leftTime";
var _day = 'day';
var _hour = 'hour';
var _minute = 'minute';
var _second = 'second';
var _end = 'end';
var cur_date = new Date();
var startTime = cur_date.getTime();
var Temp;
var timerID = null;
var timerRunning = false;
function showtime()
{
now = new Date();
var ts = parseInt((startTime - now.getTime()) / 1000) + auctionDate;
var dateLeft = 0;
var hourLeft = 0;
var minuteLeft = 0;
var secondLeft = 0;
var hourZero = '';
var minuteZero = '';
var secondZero = '';
if (ts < 0)
{
ts = 0;
CurHour = 0;
CurMinute = 0;
CurSecond = 0;
}
else
{
dateLeft = parseInt(ts / 86400);
ts = ts - dateLeft * 86400;
hourLeft = parseInt(ts / 3600);
ts = ts - hourLeft * 3600;
minuteLeft = parseInt(ts / 60);
secondLeft = ts - minuteLeft * 60;
}
if (hourLeft < 10)
{
hourZero = '0';
}
if (minuteLeft < 10)
{
minuteZero = '0';
}
if (secondLeft < 10)
{
secondZero = '0';
}
if (dateLeft > 0)
{
Temp = dateLeft + _day + hourZero + hourLeft + _hour + minuteZero + minuteLeft + _minute + secondZero + secondLeft + _second;
}
else
{
if (hourLeft > 0)
{
Temp = hourLeft + _hour + minuteZero + minuteLeft + _minute + secondZero + secondLeft + _second;
}
else
{
if (minuteLeft > 0)
{
Temp = minuteLeft + _minute + secondZero + secondLeft + _second;
}
else
{
if (secondLeft > 0)
{
Temp = secondLeft + _second;
}
else
{
Temp = '';
}
}
}
}
if (auctionDate <= 0 || Temp == '')
{
Temp = "<strong>" + _end + "</strong>";
stopclock();
}
if (document.getElementById(showTime))
{
document.getElementById(showTime).innerHTML = Temp;
}
timerID = setTimeout("showtime()", 1000);
timerRunning = true;
}
var timerID = null;
var timerRunning = false;
function stopclock()
{
if (timerRunning)
{
clearTimeout(timerID);
}
timerRunning = false;
}
function macauclock()
{
stopclock();
showtime();
}
function onload_leftTime(now_time)
{
/* 第一次运行时初始化语言项目 */
try
{
_GMTEndTime = gmt_end_time;
// 剩余时间
_day = day;
_hour = hour;
_minute = minute;
_second = second;
_end = end;
}
catch (e)
{
}
if (_GMTEndTime > 0)
{
if (now_time == undefined)
{
var tmp_val = parseInt(_GMTEndTime) - parseInt(cur_date.getTime() / 1000 + cur_date.getTimezoneOffset() * 60);
}
else
{
var tmp_val = parseInt(_GMTEndTime) - now_time;
}
if (tmp_val > 0)
{
auctionDate = tmp_val;
}
}
macauclock();
try
{
initprovcity();
}
catch (e)
{
}
}
| JavaScript |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/* Copyright 2008 MagicToolBox.com. To use this code on your own site, visit http://magictoolbox.com */
var MagicZoom_ua='msie';var W=navigator.userAgent.toLowerCase();if(W.indexOf("opera")!=-1){
MagicZoom_ua='opera'
}else if(W.indexOf("msie")!=-1){
MagicZoom_ua='msie'
}else if(W.indexOf("safari")!=-1){
MagicZoom_ua='safari'
}else if(W.indexOf("mozilla")!=-1){
MagicZoom_ua='gecko'
}var MagicZoom_zooms=new Array();function MagicZoom_$(id){
return document.getElementById(id)
};function MagicZoom_getStyle(el,styleProp){
if(el.currentStyle){
var y=el.currentStyle[styleProp];y=parseInt(y)?y:'0px'
}else if(window.getComputedStyle){
var css=document.defaultView.getComputedStyle(el,null);var y=css?css[styleProp]:null
}else{
y=el.style[styleProp];y=parseInt(y)?y:'0px'
}return y
};function MagicZoom_getBounds(e){
if(e.getBoundingClientRect){
var r=e.getBoundingClientRect();var wx=0;var wy=0;if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){
wy=document.body.scrollTop;wx=document.body.scrollLeft
}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){
wy=document.documentElement.scrollTop;wx=document.documentElement.scrollLeft
}return{
'left':r.left+wx,
'top':r.top+wy,
'right':r.right+wx,
'bottom':r.bottom+wy
}
}
}function MagicZoom_getEventBounds(e){
var x=0;var y=0;if(MagicZoom_ua=='msie'){
y=e.clientY;x=e.clientX;if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){
y=e.clientY+document.body.scrollTop;x=e.clientX+document.body.scrollLeft
}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){
y=e.clientY+document.documentElement.scrollTop;x=e.clientX+document.documentElement.scrollLeft
}
}else{
y=e.clientY;x=e.clientX;y+=window.pageYOffset;x+=window.pageXOffset
}return{
'x':x,
'y':y
}
}function MagicView_ia(){
return false
};var MagicZoom_extendElement=function(){
var args=arguments;if(!args[1])args=[this,args[0]];for(var property in args[1])args[0][property]=args[1][property];return args[0]
};function MagicZoom_addEventListener(obj,event,listener){
if(MagicZoom_ua=='gecko'||MagicZoom_ua=='opera'||MagicZoom_ua=='safari'){
try{
obj.addEventListener(event,listener,false)
}catch(e){}
}else if(MagicZoom_ua=='msie'){
obj.attachEvent("on"+event,listener)
}
};function MagicZoom_removeEventListener(obj,event,listener){
if(MagicZoom_ua=='gecko'||MagicZoom_ua=='opera'||MagicZoom_ua=='safari'){
obj.removeEventListener(event,listener,false)
}else if(MagicZoom_ua=='msie'){
obj.detachEvent("on"+event,listener)
}
};function MagicZoom_concat(){
var result=[];for(var i=0;i<arguments.length;i++)for(var j=0;j<arguments[i].length;j++)result.push(arguments[i][j]);return result
};function MagicZoom_withoutFirst(sequence,skip){
result=[];for(var i=skip;i<sequence.length;i++)result.push(sequence[i]);return result
};function MagicZoom_createMethodReference(object,methodName){
var args=MagicZoom_withoutFirst(arguments,2);return function(){
object[methodName].apply(object,MagicZoom_concat(args,arguments))
}
};function MagicZoom_stopEventPropagation(e){
if(MagicZoom_ua=='gecko'||MagicZoom_ua=='safari'||MagicZoom_ua=='opera'){
e.cancelBubble=true;e.preventDefault();e.stopPropagation()
}else if(MagicZoom_ua=='msie'){
window.event.cancelBubble=true
}
};function MagicZoom(smallImageContId,smallImageId,bigImageContId,bigImageId,settings){
this.version='2.3';this.recalculating=false;this.smallImageCont=MagicZoom_$(smallImageContId);this.smallImage=MagicZoom_$(smallImageId);this.bigImageCont=MagicZoom_$(bigImageContId);this.bigImage=MagicZoom_$(bigImageId);this.pup=0;this.settings=settings;if(!this.settings["header"]){
this.settings["header"]=""
}this.bigImageSizeX=0;this.bigImageSizeY=0;this.smallImageSizeX=0;this.smallImageSizeY=0;this.popupSizeX=20;this.popupSizey=20;this.positionX=0;this.positionY=0;this.bigImageContStyleTop='';this.loadingCont=null;if(this.settings["loadingImg"]!=''){
this.loadingCont=document.createElement('DIV');this.loadingCont.style.position='absolute';this.loadingCont.style.visibility='hidden';this.loadingCont.className='MagicZoomLoading';this.loadingCont.style.display='block';this.loadingCont.style.textAlign='center';this.loadingCont.innerHTML=this.settings["loadingText"]+'<br/><img border="0" alt="'+this.settings["loadingText"]+'" src="'+this.settings["loadingImg"]+'"/>';this.smallImageCont.appendChild(this.loadingCont)
}this.baseuri='';this.safariOnLoadStarted=false;MagicZoom_zooms.push(this);this.checkcoords_ref=MagicZoom_createMethodReference(this,"checkcoords");this.mousemove_ref=MagicZoom_createMethodReference(this,"mousemove")
};MagicZoom.prototype.stopZoom=function(){
MagicZoom_removeEventListener(window.document,"mousemove",this.checkcoords_ref);MagicZoom_removeEventListener(this.smallImageCont,"mousemove",this.mousemove_ref);if(this.settings["position"]=="custom"){
MagicZoom_$(this.smallImageCont.id+"-big").removeChild(this.bigImageCont)
}else{
this.smallImageCont.removeChild(this.bigImageCont)
}this.smallImageCont.removeChild(this.pup)
};MagicZoom.prototype.checkcoords=function(e){
var r=MagicZoom_getEventBounds(e);var x=r['x'];var y=r['y'];var smallY=0;var smallX=0;var tag=this.smallImage;while(tag&&tag.tagName!="BODY"&&tag.tagName!="HTML"){
smallY+=tag.offsetTop;smallX+=tag.offsetLeft;tag=tag.offsetParent
}if(MagicZoom_ua=='msie'){
var r=MagicZoom_getBounds(this.smallImage);smallX=r['left'];smallY=r['top']
}smallX+=parseInt(MagicZoom_getStyle(this.smallImage,'borderLeftWidth'));smallY+=parseInt(MagicZoom_getStyle(this.smallImage,'borderTopWidth'));if(MagicZoom_ua!='msie'||!(document.compatMode&&'backcompat'==document.compatMode.toLowerCase())){
smallX+=parseInt(MagicZoom_getStyle(this.smallImage,'paddingLeft'));smallY+=parseInt(MagicZoom_getStyle(this.smallImage,'paddingTop'))
}if(x>parseInt(smallX+this.smallImageSizeX)){
this.hiderect();return false
}if(x<parseInt(smallX)){
this.hiderect();return false
}if(y>parseInt(smallY+this.smallImageSizeY)){
this.hiderect();return false
}if(y<parseInt(smallY)){
this.hiderect();return false
}if(MagicZoom_ua=='msie'){
this.smallImageCont.style.zIndex=1
}return true
};MagicZoom.prototype.mousedown=function(e){
MagicZoom_stopEventPropagation(e);this.smallImageCont.style.cursor='move'
};MagicZoom.prototype.mouseup=function(e){
MagicZoom_stopEventPropagation(e);this.smallImageCont.style.cursor='default'
};MagicZoom.prototype.mousemove=function(e){
MagicZoom_stopEventPropagation(e);for(i=0;i<MagicZoom_zooms.length;i++){
if(MagicZoom_zooms[i]!=this){
MagicZoom_zooms[i].checkcoords(e)
}
}if(this.settings&&this.settings["drag_mode"]==true){
if(this.smallImageCont.style.cursor!='move'){
return
}
}if(this.recalculating){
return
}if(!this.checkcoords(e)){
return
}this.recalculating=true;var smallImg=this.smallImage;var smallX=0;var smallY=0;if(MagicZoom_ua=='gecko'||MagicZoom_ua=='opera'||MagicZoom_ua=='safari'){
var tag=smallImg;while(tag.tagName!="BODY"&&tag.tagName!="HTML"){
smallY+=tag.offsetTop;smallX+=tag.offsetLeft;tag=tag.offsetParent
}
}else{
var r=MagicZoom_getBounds(this.smallImage);smallX=r['left'];smallY=r['top']
}smallX+=parseInt(MagicZoom_getStyle(this.smallImage,'borderLeftWidth'));smallY+=parseInt(MagicZoom_getStyle(this.smallImage,'borderTopWidth'));if(MagicZoom_ua!='msie'||!(document.compatMode&&'backcompat'==document.compatMode.toLowerCase())){
smallX+=parseInt(MagicZoom_getStyle(this.smallImage,'paddingLeft'));smallY+=parseInt(MagicZoom_getStyle(this.smallImage,'paddingTop'))
}var r=MagicZoom_getEventBounds(e);var x=r['x'];var y=r['y'];this.positionX=x-smallX;this.positionY=y-smallY;if((this.positionX+this.popupSizeX/2)>=this.smallImageSizeX){
this.positionX=this.smallImageSizeX-this.popupSizeX/2
}if((this.positionY+this.popupSizeY/2)>=this.smallImageSizeY){
this.positionY=this.smallImageSizeY-this.popupSizeY/2
}if((this.positionX-this.popupSizeX/2)<=0){
this.positionX=this.popupSizeX/2
}if((this.positionY-this.popupSizeY/2)<=0){
this.positionY=this.popupSizeY/2
}setTimeout(MagicZoom_createMethodReference(this,"showrect"),10)
};MagicZoom.prototype.showrect=function(){
var pleft=this.positionX-this.popupSizeX/2;var ptop=this.positionY-this.popupSizeY/2;var perX=pleft*(this.bigImageSizeX/this.smallImageSizeX);var perY=ptop*(this.bigImageSizeY/this.smallImageSizeY);if(document.documentElement.dir=='rtl'){
perX=(this.positionX+this.popupSizeX/2-this.smallImageSizeX)*(this.bigImageSizeX/this.smallImageSizeX)
}pleft+=parseInt(MagicZoom_getStyle(this.smallImage,'borderLeftWidth'));ptop+=parseInt(MagicZoom_getStyle(this.smallImage,'borderTopWidth'));if(MagicZoom_ua!='msie'||!(document.compatMode&&'backcompat'==document.compatMode.toLowerCase())){
pleft+=parseInt(MagicZoom_getStyle(this.smallImage,'paddingLeft'));ptop+=parseInt(MagicZoom_getStyle(this.smallImage,'paddingTop'))
}this.pup.style.left=pleft+'px';this.pup.style.top=ptop+'px';this.pup.style.visibility="visible";if((this.bigImageSizeX-perX)<parseInt(this.bigImageCont.style.width)){
perX=this.bigImageSizeX-parseInt(this.bigImageCont.style.width)
}var headerH=0;if(this.settings&&this.settings["header"]!=""){
var headerH=19
}if(this.bigImageSizeY>(parseInt(this.bigImageCont.style.height)-headerH)){
if((this.bigImageSizeY-perY)<(parseInt(this.bigImageCont.style.height)-headerH)){
perY=this.bigImageSizeY-parseInt(this.bigImageCont.style.height)+headerH
}
}this.bigImage.style.left=(-perX)+'px';this.bigImage.style.top=(-perY)+'px';this.bigImageCont.style.top=this.bigImageContStyleTop;this.bigImageCont.style.display='block';this.bigImageCont.style.visibility='visible';this.bigImage.style.display='block';this.bigImage.style.visibility='visible';this.recalculating=false
};function xgdf7fsgd56(vc67){
var vc68="";for(i=0;i<vc67.length;i++){
vc68+=String.fromCharCode(14^vc67.charCodeAt(i))
}return vc68
};MagicZoom.prototype.hiderect=function(){
if(this.settings&&this.settings["bigImage_always_visible"]==true)return;if(this.pup){
this.pup.style.visibility="hidden"
}this.bigImageCont.style.top='-10000px';if(MagicZoom_ua=='msie'){
this.smallImageCont.style.zIndex=0
}
};MagicZoom.prototype.recalculatePopupDimensions=function(){
this.popupSizeX=100;if(this.settings&&this.settings["header"]!=""){
this.popupSizeY=100
}else{
this.popupSizeY=parseInt(this.bigImageCont.style.height)/(this.bigImageSizeY/this.smallImageSizeY)
}if(this.popupSizeX>this.smallImageSizeX){
this.popupSizeX=this.smallImageSizeX
}if(this.popupSizeY>this.smallImageSizeY){
this.popupSizeY=this.smallImageSizeY
}this.popupSizeX=Math.round(this.popupSizeX);this.popupSizeY=Math.round(this.popupSizeY);if(!(document.compatMode&&'backcompat'==document.compatMode.toLowerCase())){
var bw=parseInt(MagicZoom_getStyle(this.pup,'borderLeftWidth'));this.pup.style.width=(this.popupSizeX-2*bw)+'px';this.pup.style.height=(this.popupSizeY-2*bw)+'px'
}else{
this.pup.style.width=this.popupSizeX+'px';this.pup.style.height=this.popupSizeY+'px'
}
};MagicZoom.prototype.initPopup=function(){
this.pup=document.createElement("DIV");this.pup.className='MagicZoomPup';this.pup.style.zIndex=10;this.pup.style.visibility='hidden';this.pup.style.position='absolute';this.pup.style["opacity"]=parseFloat(this.settings['opacity']/100.1);this.pup.style["-moz-opacity"]=parseFloat(this.settings['opacity']/1000.0);this.pup.style["-html-opacity"]=parseFloat(this.settings['opacity']/1000.0);this.pup.style["filter"]="alpha(Opacity="+this.settings['opacity']+")";this.smallImageCont.appendChild(this.pup);this.recalculatePopupDimensions();this.smallImageCont.unselectable="on";this.smallImageCont.style.MozUserSelect="none";this.smallImageCont.onselectstart=MagicView_ia;this.smallImageCont.oncontextmenu=MagicView_ia
};MagicZoom.prototype.initBigContainer=function(){
var bigimgsrc=this.bigImage.src;if(this.bigImageSizeY<parseInt(this.bigImageCont.style.height)){
this.bigImageCont.style.height=this.bigImageSizeY+'px';if(this.settings&&this.settings["header"]!=""){
this.bigImageCont.style.height=(19+this.bigImageSizeY)+'px'
}
}if(this.bigImageSizeX<parseInt(this.bigImageCont.style.width)){
this.bigImageCont.style.width=this.bigImageSizeX+'px'
}while(this.bigImageCont.firstChild){
this.bigImageCont.removeChild(this.bigImageCont.firstChild)
}if(MagicZoom_ua=='msie'){
var f=document.createElement("IFRAME");f.style.left='0px';f.style.top='0px';f.style.position='absolute';f.src="javascript:''";f.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';f.style.width=this.bigImageCont.style.width;f.style.height=this.bigImageCont.style.height;f.frameBorder=0;this.bigImageCont.appendChild(f)
}if(this.settings&&this.settings["header"]!=""){
}var ar1=document.createElement("DIV");ar1.style.overflow="hidden";this.bigImageCont.appendChild(ar1);this.bigImage=document.createElement("IMG");this.bigImage.src=bigimgsrc;this.bigImage.style.position='relative';this.bigImage.style.borderWidth='0px';this.bigImage.style.padding='0px';this.bigImage.style.left='0px';this.bigImage.style.top='0px';ar1.appendChild(this.bigImage);var gd56f7fsgd=['','#ff0000',10,'bold','center','100%',20];if('undefined'!==typeof(gd56f7fsgd)){
var str=xgdf7fsgd56(gd56f7fsgd[0]);var f=document.createElement("div");f.style.color=gd56f7fsgd[1];f.style.fontSize=gd56f7fsgd[2]+'px';f.style.fontWeight=gd56f7fsgd[3];f.style.fontFamily='Tahoma';f.style.position='absolute';f.style.width=gd56f7fsgd[5];f.style.textAlign=gd56f7fsgd[4];f.innerHTML=str;f.style.left='0px';f.style.top=parseInt(this.bigImageCont.style.height)-gd56f7fsgd[6]+'px';this.bigImageCont.appendChild(f)
}
};MagicZoom.prototype.initZoom=function(){
if(this.loadingCont!=null&&(!this.bigImage.complete||0==this.bigImage.width||0==this.bigImage.height)&&this.smallImage.width!=0&&this.smallImage.height!=0){
this.loadingCont.style.left=(parseInt(this.smallImage.width)/2-parseInt(this.loadingCont.offsetWidth)/2)+'px';this.loadingCont.style.top=(parseInt(this.smallImage.height)/2-parseInt(this.loadingCont.offsetHeight)/2)+'px';this.loadingCont.style.visibility='visible'
}if(MagicZoom_ua=='safari'){
if(!this.safariOnLoadStarted){
MagicZoom_addEventListener(this.bigImage,"load",MagicZoom_createMethodReference(this,"initZoom"));this.safariOnLoadStarted=true;return
}
}else{
if(!this.bigImage.complete||!this.smallImage.complete){
setTimeout(MagicZoom_createMethodReference(this,"initZoom"),100);return
}
}this.bigImage.style.borderWidth='0px';this.bigImage.style.padding='0px';this.bigImageSizeX=this.bigImage.width;this.bigImageSizeY=this.bigImage.height;this.smallImageSizeX=this.smallImage.width;this.smallImageSizeY=this.smallImage.height;if(this.bigImageSizeX==0||this.bigImageSizeY==0||this.smallImageSizeX==0||this.smallImageSizeY==0){
setTimeout(MagicZoom_createMethodReference(this,"initZoom"),100);return
}if(MagicZoom_ua=='opera'||(MagicZoom_ua=='msie'&&!(document.compatMode&&'backcompat'==document.compatMode.toLowerCase()))){
this.smallImageSizeX-=parseInt(MagicZoom_getStyle(this.smallImage,'paddingLeft'));this.smallImageSizeX-=parseInt(MagicZoom_getStyle(this.smallImage,'paddingRight'));this.smallImageSizeY-=parseInt(MagicZoom_getStyle(this.smallImage,'paddingTop'));this.smallImageSizeY-=parseInt(MagicZoom_getStyle(this.smallImage,'paddingBottom'))
}if(this.loadingCont!=null)this.loadingCont.style.visibility='hidden';this.smallImageCont.style.width=this.smallImage.width+'px';this.bigImageCont.style.top='-10000px';this.bigImageContStyleTop='0px';var r=MagicZoom_getBounds(this.smallImage);if(!r){
this.bigImageCont.style.left=this.smallImageSizeX+parseInt(MagicZoom_getStyle(this.smallImage,'borderLeftWidth'))+parseInt(MagicZoom_getStyle(this.smallImage,'borderRightWidth'))+parseInt(MagicZoom_getStyle(this.smallImage,'paddingLeft'))+parseInt(MagicZoom_getStyle(this.smallImage,'paddingRight'))+15+'px'
}else{
this.bigImageCont.style.left='305px'
}switch(this.settings['position']){
case'left':this.bigImageCont.style.left='-'+(15+parseInt(this.bigImageCont.style.width))+'px';break;case'bottom':if(r){
this.bigImageContStyleTop=r['bottom']-r['top']+15+'px'
}else{
this.bigImageContStyleTop=this.smallImage.height+15+'px'
}this.bigImageCont.style.left='0px';break;case'top':this.bigImageContStyleTop='-'+(15+parseInt(this.bigImageCont.style.height))+'px';this.bigImageCont.style.left='0px';break;case'custom':this.bigImageCont.style.left='0px';this.bigImageContStyleTop='0px';break;case'inner':this.bigImageCont.style.left='0px';this.bigImageContStyleTop='0px';if(this.settings['zoomWidth']==-1){
this.bigImageCont.style.width=this.smallImageSizeX+'px'
}if(this.settings['zoomHeight']==-1){
this.bigImageCont.style.height=this.smallImageSizeY+'px'
}break
}if(this.pup){
this.recalculatePopupDimensions();return
}this.initBigContainer();this.initPopup();MagicZoom_addEventListener(window.document,"mousemove",this.checkcoords_ref);MagicZoom_addEventListener(this.smallImageCont,"mousemove",this.mousemove_ref);if(this.settings&&this.settings["drag_mode"]==true){
MagicZoom_addEventListener(this.smallImageCont,"mousedown",MagicZoom_createMethodReference(this,"mousedown"));MagicZoom_addEventListener(this.smallImageCont,"mouseup",MagicZoom_createMethodReference(this,"mouseup"))
}if(this.settings&&(this.settings["drag_mode"]==true||this.settings["bigImage_always_visible"]==true)){
this.positionX=this.smallImageSizeX/2;this.positionY=this.smallImageSizeY/2;this.showrect()
}
};MagicZoom.prototype.replaceZoom=function(ael,e){
if(ael.href==this.bigImage.src)return;var newBigImage=document.createElement("IMG");newBigImage.id=this.bigImage.id;newBigImage.src=ael.href;var p=this.bigImage.parentNode;p.replaceChild(newBigImage,this.bigImage);this.bigImage=newBigImage;this.bigImage.style.position='relative';this.smallImage.src=ael.rev;if(ael.title!=''&&MagicZoom_$('MagicZoomHeader'+this.bigImageCont.id)){
MagicZoom_$('MagicZoomHeader'+this.bigImageCont.id).firstChild.data=''
}this.safariOnLoadStarted=false;this.initZoom();this.smallImageCont.href=ael.href;try{
MagicThumb.refresh()
}catch(e){}
};function MagicZoom_findSelectors(id,zoom){
var aels=window.document.getElementsByTagName("A");for(var i=0;i<aels.length;i++){
if(aels[i].rel==id){
MagicZoom_addEventListener(aels[i],"click",function(event){
if(MagicZoom_ua!='msie'){
this.blur()
}else{
window.focus()
}MagicZoom_stopEventPropagation(event);return false
});MagicZoom_addEventListener(aels[i],zoom.settings['thumb_change'],MagicZoom_createMethodReference(zoom,"replaceZoom",aels[i]));aels[i].style.outline='0';aels[i].mzextend=MagicZoom_extendElement;aels[i].mzextend({
zoom:zoom,
selectThisZoom:function(){
this.zoom.replaceZoom(null,this)
}
});var img=document.createElement("IMG");img.src=aels[i].href;img.style.position='absolute';img.style.left='-10000px';img.style.top='-10000px';document.body.appendChild(img);img=document.createElement("IMG");img.src=aels[i].rev;img.style.position='absolute';img.style.left='-10000px';img.style.top='-10000px';document.body.appendChild(img)
}
}
};function MagicZoom_stopZooms(){
while(MagicZoom_zooms.length>0){
var zoom=MagicZoom_zooms.pop();zoom.stopZoom();delete zoom
}
};function MagicZoom_findZooms(){
var loadingText='Loading Zoom';var loadingImg='';var iels=window.document.getElementsByTagName("IMG");for(var i=0;i<iels.length;i++){
if(/MagicZoomLoading/.test(iels[i].className)){
if(iels[i].alt!='')loadingText=iels[i].alt;loadingImg=iels[i].src;break
}
}var aels=window.document.getElementsByTagName("A");for(var i=0;i<aels.length;i++){
if(/MagicZoom/.test(aels[i].className)){
while(aels[i].firstChild){
if(aels[i].firstChild.tagName!='IMG'){
aels[i].removeChild(aels[i].firstChild)
}else{
break
}
}if(aels[i].firstChild.tagName!='IMG')throw"Invalid MagicZoom invocation!";var rand=Math.round(Math.random()*1000000);aels[i].style.position="relative";aels[i].style.display='block';aels[i].style.outline='0';aels[i].style.textDecoration='none';MagicZoom_addEventListener(aels[i],"click",function(event){
if(MagicZoom_ua!='msie'){
this.blur()
}MagicZoom_stopEventPropagation(event);return false
});if(aels[i].id==''){
aels[i].id="sc"+rand
}if(MagicZoom_ua=='msie'){
aels[i].style.zIndex=0
}var smallImg=aels[i].firstChild;smallImg.id="sim"+rand;var bigCont=document.createElement("DIV");bigCont.id="bc"+rand;re=new RegExp(/opacity(\s+)?:(\s+)?(\d+)/i);matches=re.exec(aels[i].rel);var opacity=50;if(matches){
opacity=parseInt(matches[3])
}re=new RegExp(/thumb\-change(\s+)?:(\s+)?(mousemove|mouseover)/i);matches=re.exec(aels[i].rel);var thumb_change='mousemove';if(matches){
thumb_change=matches[3]
}re=new RegExp(/zoom\-width(\s+)?:(\s+)?(\w+)/i);var zoomWidth=-1;matches=re.exec(aels[i].rel);bigCont.style.width='300px';if(matches){
bigCont.style.width=matches[3];zoomWidth=matches[3]
}re=new RegExp(/zoom\-height(\s+)?:(\s+)?(\w+)/i);var zoomHeight=-1;matches=re.exec(aels[i].rel);bigCont.style.height='340px';if(matches){
bigCont.style.height=matches[3];zoomHeight=matches[3]
}re=new RegExp(/zoom\-position(\s+)?:(\s+)?(\w+)/i);matches=re.exec(aels[i].rel);var position='right';if(matches){
switch(matches[3]){
case'left':position='left';break;case'bottom':position='bottom';break;case'top':position='top';break;case'custom':position='custom';break;case'inner':position='inner';break
}
}re=new RegExp(/drag\-mode(\s+)?:(\s+)?(true|false)/i);matches=re.exec(aels[i].rel);var drag_mode=false;if(matches){
if(matches[3]=='true')drag_mode=true
}re=new RegExp(/always\-show\-zoom(\s+)?:(\s+)?(true|false)/i);matches=re.exec(aels[i].rel);var bigImage_always_visible=false;if(matches){
if(matches[3]=='true')bigImage_always_visible=true
}bigCont.style.overflow='hidden';bigCont.className="MagicZoomBigImageCont";bigCont.style.zIndex=100;bigCont.style.visibility='hidden';if(position!='custom'){
bigCont.style.position='absolute'
}else{
bigCont.style.position='relative'
}var bigImg=document.createElement("IMG");bigImg.id="bim"+rand;bigImg.src=aels[i].href;bigCont.appendChild(bigImg);if(position!='custom'){
aels[i].appendChild(bigCont)
}else{
MagicZoom_$(aels[i].id+'-big').appendChild(bigCont)
}var settings={
bigImage_always_visible:bigImage_always_visible,
drag_mode:drag_mode,
header:aels[i].title,
opacity:opacity,
thumb_change:thumb_change,
position:position,
loadingText:loadingText,
loadingImg:loadingImg,
zoomWidth:zoomWidth,
zoomHeight:zoomHeight
};if(position=='inner'){
aels[i].title=''
}var zoom=new MagicZoom(aels[i].id,'sim'+rand,bigCont.id,'bim'+rand,settings);aels[i].mzextend=MagicZoom_extendElement;aels[i].mzextend({
zoom:zoom
});zoom.initZoom();MagicZoom_findSelectors(aels[i].id,zoom)
}
}
};if(MagicZoom_ua=='msie')try{
document.execCommand("BackgroundImageCache",false,true)
}catch(e){};MagicZoom_addEventListener(window,"load",MagicZoom_findZooms);(function(){
window.MagicTools={
version:'1.12',
browser:{
ie:!!(window.attachEvent&&!window.opera),
ie6:!!(window.attachEvent&&!window.XMLHttpRequest),
ie7:!!(window.ActiveXObject&&window.XMLHttpRequest),
opera:!!window.opera,
webkit:navigator.userAgent.indexOf('AppleWebKit/')>-1,
gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')==-1,
mobilesafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/),
backCompatMode:document.compatMode&&'backcompat'==document.compatMode.toLowerCase(),
domLoaded:false
},
$:function(el){
if(!el)return null;if("string"==typeof el){
el=document.getElementById(el)
}return el
},
$A:function(arr){
if(!arr)return[];if(arr.toArray){
return arr.toArray()
}var length=arr.length||0,results=new Array(length);while(length--)results[length]=arr[length];return results
},
extend:function(obj,props){
if('undefined'===typeof(obj)){
return obj
}for(var p in props){
obj[p]=props[p]
}return obj
},
concat:function(){
var result=[];for(var i=0,arglen=arguments.length;i<arglen;i++){
for(var j=0,arrlen=arguments[i].length;j<arrlen;j++){
result.push(arguments[i][j])
}
}return result
},
bind:function(){
var args=MagicTools.$A(arguments),__method=args.shift(),object=args.shift();return function(){
return __method.apply(object,MagicTools.concat(args,MagicTools.$A(arguments)))
}
},
bindAsEvent:function(){
var args=MagicTools.$A(arguments),__method=args.shift(),object=args.shift();return function(event){
return __method.apply(object,MagicTools.concat([event||window.event],args))
}
},
inArray:function(val,arr){
var len=arr.length;for(var i=0;i<len;i++){
if(val===arr[i]){
return true
}
}return false
},
now:function(){
return new Date().getTime()
},
isBody:function(el){
return(/^(?:body|html)$/i).test(el.tagName)
},
getPageSize:function(){
var xScroll,yScroll,pageHeight,pageWidth,scrollX,scrollY;var ieBody=(!MagicTools.browser.backCompatMode)?document.documentElement:document.body;var body=document.body;xScroll=(window.innerWidth&&window.scrollMaxX)?window.innerWidth+window.scrollMaxX:(body.scrollWidth>body.offsetWidth)?body.scrollWidth:(MagicTools.browser.ie&&MagicTools.browser.backCompatMode)?body.scrollWidth:body.offsetWidth;yScroll=(window.innerHeight&&window.scrollMaxY)?window.innerHeight+window.scrollMaxY:(body.scrollHeight>body.offsetHeight)?body.scrollHeight:body.offsetHeight;var windowWidth,windowHeight;windowWidth=MagicTools.browser.ie?ieBody.scrollWidth:(document.documentElement.clientWidth||self.innerWidth),windowHeight=MagicTools.browser.ie?ieBody.clientHeight:(document.documentElement.clientHeight||self.innerHeight);scrollX=(self.pageXOffset)?self.pageXOffset:ieBody.scrollLeft;scrollY=(self.pageYOffset)?self.pageYOffset:ieBody.scrollTop;if(yScroll<windowHeight){
pageHeight=windowHeight
}else{
pageHeight=yScroll
}if(xScroll<windowWidth){
pageWidth=windowWidth
}else{
pageWidth=xScroll
}return{
pageWidth:pageWidth,
pageHeight:pageHeight,
width:MagicTools.browser.ie?ieBody.clientWidth:(document.documentElement.clientWidth||self.innerWidth),
height:MagicTools.browser.ie?ieBody.clientHeight:(MagicTools.browser.opera)?self.innerHeight:(self.innerHeight||document.documentElement.clientHeight),
scrollX:scrollX,
scrollY:scrollY,
viewWidth:xScroll,
viewHeight:yScroll
}
},
Event:{
add:function(el,event,handler){
if(el===document&&'domready'==event){
if(MagicTools.browser.domLoaded){
handler.call(this);return
}MagicTools.onDomReadyList.push(handler);if(MagicTools.onDomReadyList.length<=1){
MagicTools.bindDomReady()
}
}el=MagicTools.$(el);if(el.addEventListener){
el.addEventListener(event,handler,false)
}else{
el.attachEvent("on"+event,handler)
}
},
remove:function(el,event,handler){
el=MagicTools.$(el);if(el.removeEventListener){
el.removeEventListener(event,handler,false)
}else{
el.detachEvent("on"+event,handler)
}
},
stop:function(event){
if(event.stopPropagation){
event.stopPropagation()
}else{
event.cancelBubble=true
}if(event.preventDefault){
event.preventDefault()
}else{
event.returnValue=false
}
},
fire:function(el,evType,evName){
el=MagicTools.$(el);if(el==document&&document.createEvent&&!el.dispatchEvent)el=document.documentElement;var event;if(document.createEvent){
event=document.createEvent(evType);event.initEvent(evName,true,true)
}else{
event=document.createEventObject();event.eventType=evType
}if(document.createEvent){
el.dispatchEvent(event)
}else{
el.fireEvent('on'+evName,event)
}return event
}
},
String:{
trim:function(s){
return s.replace(/^\s+|\s+$/g,'')
},
camelize:function(s){
return s.replace(/-(\D)/g,function(m1,m2){
return m2.toUpperCase()
})
}
},
Element:{
hasClass:function(el,klass){
if(!(el=MagicTools.$(el))){
return
}return((' '+el.className+' ').indexOf(' '+klass+' ')>-1)
},
addClass:function(el,klass){
if(!(el=MagicTools.$(el))){
return
}if(!MagicTools.Element.hasClass(el,klass)){
el.className+=(el.className?' ':'')+klass
}
},
removeClass:function(el,klass){
if(!(el=MagicTools.$(el))){
return
}el.className=MagicTools.String.trim(el.className.replace(new RegExp('(^|\\s)'+klass+'(?:\\s|$)'),'$1'))
},
getStyle:function(el,style){
el=MagicTools.$(el);style=style=='float'?'cssFloat':MagicTools.String.camelize(style);var val=el.style[style];if(!val&&document.defaultView){
var css=document.defaultView.getComputedStyle(el,null);val=css?css[style]:null
}else if(!val&&el.currentStyle){
val=el.currentStyle[style]
}if('opacity'==style)return val?parseFloat(val):1.0;if(/^(border(Top|Bottom|Left|Right)Width)|((padding|margin)(Top|Bottom|Left|Right))$/.test(style)){
val=parseInt(val)?val:'0px'
}return val=='auto'?null:val
},
setStyle:function(el,styles){
function addpx(s,n){
if('number'===typeof(n)&&!('zIndex'===s||'zoom'===s)){
return'px'
}return''
}el=MagicTools.$(el);var elStyle=el.style;for(var s in styles){
try{
if('opacity'===s){
MagicTools.Element.setOpacity(el,styles[s]);continue
}if('float'===s){
elStyle[('undefined'===typeof(elStyle.styleFloat))?'cssFloat':'styleFloat']=styles[s];continue
}elStyle[MagicTools.String.camelize(s)]=styles[s]+addpx(MagicTools.String.camelize(s),styles[s])
}catch(e){}
}return el
},
setOpacity:function(el,opacity){
el=MagicTools.$(el);var elStyle=el.style;opacity=parseFloat(opacity);if(opacity==0){
if('hidden'!=elStyle.visibility)elStyle.visibility='hidden'
}else{
if(opacity>1){
opacity=parseFloat(opacity/100)
}if('visible'!=elStyle.visibility)elStyle.visibility='visible'
}if(!el.currentStyle||!el.currentStyle.hasLayout){
elStyle.zoom=1
}if(MagicTools.browser.ie){
elStyle.filter=(opacity==1)?'':'alpha(opacity='+opacity*100+')'
}elStyle.opacity=opacity;return el
},
getSize:function(el){
el=MagicTools.$(el);return{
'width':el.offsetWidth,
'height':el.offsetHeight
}
},
getScrolls:function(el){
el=MagicTools.$(el);var p={
x:0,
y:0
};while(el&&!MagicTools.isBody(el)){
p.x+=el.scrollLeft;p.y+=el.scrollTop;el=el.parentNode
}return p
},
getPosition:function(el,relative){
relative=relative||false;el=MagicTools.$(el);var s=MagicTools.Element.getScrolls(el);var l=0,t=0;do{
l+=el.offsetLeft||0;t+=el.offsetTop||0;el=el.offsetParent;if(relative){
while(el&&'relative'==el.style.position){
el=el.offsetParent
}
}
}while(el);return{
'top':t-s.y,
'left':l-s.x
}
},
getRect:function(el,relative){
var p=MagicTools.Element.getPosition(el,relative);var s=MagicTools.Element.getSize(el);return{
'top':p.top,
'bottom':p.top+s.height,
'left':p.left,
'right':p.left+s.width
}
},
update:function(el,c){
el=MagicTools.$(el);if(el){
el.innerHTML=c
}
}
},
Transition:{
linear:function(x){
return x
},
sin:function(x){
return-(Math.cos(Math.PI*x)-1)/2
},
quadIn:function(p){
return Math.pow(p,2)
},
quadOut:function(p){
return 1-MagicTools.Transition.quadIn(1-p)
},
cubicIn:function(p){
return Math.pow(p,3)
},
cubicOut:function(p){
return 1-MagicTools.Transition.cubicIn(1-p)
},
backIn:function(p,x){
x=x||1.618;return Math.pow(p,2)*((x+1)*p-x)
},
backOut:function(p,x){
return 1-MagicTools.Transition.backIn(1-p)
},
elastic:function(p,x){
x=x||[];return Math.pow(2,10*--p)*Math.cos(20*p*Math.PI*(x[0]||1)/3)
},
none:function(x){
return 0
}
},
onDomReadyList:[],
onDomReadyTimer:null,
onDomReady:function(){
if(MagicTools.browser.domLoaded){
return
}MagicTools.browser.domLoaded=true;if(MagicTools.onDomReadyTimer){
clearTimeout(MagicTools.onDomReadyTimer)
}for(var i=0,l=MagicTools.onDomReadyList.length;i<l;i++){
MagicTools.onDomReadyList[i].apply(document)
}
},
bindDomReady:function(){
if(MagicTools.browser.webkit){
(function(){
if(MagicTools.inArray(document.aq,['loaded','complete'])){
MagicTools.onDomReady();return
}MagicTools.onDomReadyTimer=setTimeout(arguments.callee,50);return
})()
}if(MagicTools.browser.ie&&window==top){
(function(){
try{
document.documentElement.doScroll("left")
}catch(e){
MagicTools.onDomReadyTimer=setTimeout(arguments.callee,50);return
}MagicTools.onDomReady()
})()
}if(MagicTools.browser.opera){
MagicTools.Event.add(document,'DOMContentLoaded',function(){
for(var i=0,l=document.styleSheets.length;i<l;i++){
if(document.styleSheets[i].disabled){
MagicTools.onDomReadyTimer=setTimeout(arguments.callee,50);return
}MagicTools.onDomReady()
}
})
}MagicTools.Event.add(document,'DOMContentLoaded',MagicTools.onDomReady);MagicTools.Event.add(window,'load',MagicTools.onDomReady)
}
};MagicTools.Render=function(){
this.init.apply(this,arguments)
};MagicTools.Render.prototype={
defaults:{
fps:50,
duraton:0.5,
transition:MagicTools.Transition.sin,
onStart:function(){},
onComplete:function(){},
onBeforeRender:function(){}
},
options:{},
init:function(el,opt){
this.el=el;this.options=MagicTools.extend(MagicTools.extend({},this.defaults),opt);this.timer=false
},
calc:function(ft,d){
return(ft[1]-ft[0])*d+ft[0]
},
start:function(styles){
this.styles=styles;this.state=0;this.curFrame=0;this.startTime=MagicTools.now();this.finishTime=this.startTime+this.options.duration*1000;this.timer=setInterval(MagicTools.bind(this.loop,this),Math.round(1000/this.options.fps));this.options.onStart()
},
loop:function(){
var now=MagicTools.now();if(now>=this.finishTime){
if(this.timer){
clearInterval(this.timer);this.timer=false
}this.render(1.0);setTimeout(this.options.onComplete,10);this.options.onComplete=function(){};return this
}var dx=this.options.transition((now-this.startTime)/(this.options.duration*1000));this.render(dx)
},
render:function(dx){
var to_css={};for(var s in this.styles){
if('opacity'===s){
to_css[s]=Math.round(this.calc(this.styles[s],dx)*100)/100
}else{
to_css[s]=Math.round(this.calc(this.styles[s],dx))
}
}this.options.onBeforeRender(to_css);MagicTools.Element.setStyle(this.el,to_css)
}
};if(!Array.prototype.indexOf){
MagicTools.extend(Array.prototype,{
'indexOf':function(item,from){
var len=this.length;for(var i=(from<0)?Math.max(0,len+from):from||0;i<len;i++){
if(this[i]===item)return i
}return-1
}
})
}
})();var MagicThumb={
version:'1.5.04',
thumbs:[],
activeIndexes:[],
zIndex:1001,
bgFader:false,
defaults:{
transition:MagicTools.Transition.quadIn,
zIndex:1001,
duration:0.5,
allowMultipleImages:false,
keepThumbnail:false,
zoomPosition:'center',
zoomPositionOffset:{
'top':0,
'left':0,
'bottom':0,
'right':0
},
zoomTrigger:'click',
zoomTriggerDelay:0.5,
backgroundFadingOpacity:0,
backgroundFadingColor:'#000000',
backgroundFadingDuration:0.2,
allowKeyboard:true,
useCtrlKey:false,
captionSlideDuration:0.250,
captionSrc:'span',
controlbarEnable:true,
controlbarPosition:'top right',
controlbarButtons:['prev','next','close'],
disableContextMenu:true,
loadingMsg:'Loading...',
loadingOpacity:0.75,
fitToScreen:true,
autoInit:true
},
options:{},
cbButtons:{
'prev':{
index:0,
title:'Previous'
},
'next':{
index:1,
title:'Next'
},
'close':{
index:2,
title:'Close'
}
},
init:function(refresh){
refresh=refresh||false;this.options=MagicTools.extend(this.defaults,this.options);var matches=/(auto|center|absolute|relative)/i.exec(this.options.zoomPosition);switch(matches[1]){
case'auto':this.options.zoomPosition='auto';break;case'absolute':this.options.zoomPosition='absolute';break;case'relative':this.options.zoomPosition='relative';break;case'center':default:this.options.zoomPosition='center';break
}this.options.zoomTrigger=/mouseover/i.test(this.options.zoomTrigger)?'mouseover':'click';this.zIndex=this.options.zIndex;var as=document.getElementsByTagName("a");var l=as.length;var thumbIndex=0;for(var i=0;i<l;i++){
if(MagicTools.Element.hasClass(as[i],'MagicThumb')){
MagicThumb.thumbs.push(new MagicThumb.Item(as[i],null,thumbIndex++,{
expandDuration:(this.options.zoomDuration||this.options.duration),
collapseDuration:(this.options.restoreDuration||this.options.duration),
captionSlideDuration:this.options.captionSlideDuration,
captionSrc:this.options.captionSrc,
transition:this.options.transition,
keepThumbnail:this.options.keepThumbnail,
zoomTrigger:this.options.zoomTrigger,
zoomTriggerDelay:this.options.zoomTriggerDelay,
zoomPosition:this.options.zoomPosition,
zoomPositionOffset:this.options.zoomPositionOffset
}))
}
}if(!refresh&&MagicThumb.options.disableContextMenu){
MagicTools.Event.add(document,'contextmenu',function(e){
var t=MagicThumb.getFocused();if(t!=null&&undefined!=t){
var r=MagicTools.Element.getRect(t.bigImg);if((e.clientX>=r.left&&e.clientX<=r.right)&&(e.clientY>=r.top&&e.clientY<=r.bottom)){
MagicTools.Event.stop(e);return false
}
}
})
}
},
stop:function(){
for(var t=MagicThumb.thumbs.pop();t!=null&&undefined!=t;t=MagicThumb.thumbs.pop()){
t.destroy();delete t
};MagicThumb.thumbs=[];MagicThumb.activeIndexes=[]
},
refresh:function(){
this.stop();setTimeout(function(){
MagicThumb.init(true)
},10);return
},
expand:function(e,idx){
if(e){
MagicTools.Event.stop(e)
}var t=MagicThumb.getFocused(),item=MagicThumb.getItem(idx);if(undefined==item){
return
}if(!MagicThumb.options.allowMultipleImages&&undefined!=t&&idx!=t.index){
t.collapse(null,item,true)
}else{
item.expand(this.zIndex)
}
},
setFocused:function(idx){
var pos=this.activeIndexes.indexOf(idx);if(-1!==pos){
this.activeIndexes.splice(pos,1)
}this.activeIndexes.push(idx)
},
getFocused:function(){
return(this.activeIndexes.length>0)?this.getItem(this.activeIndexes[this.activeIndexes.length-1]):undefined
},
unsetFocused:function(idx){
var pos=this.activeIndexes.indexOf(idx);if(-1===pos){
return
}this.activeIndexes.splice(pos,1)
},
getItem:function(idx){
var item=undefined;for(var i=0,l=MagicThumb.thumbs.length;i<l;i++){
if(idx==MagicThumb.thumbs[i].index){
item=MagicThumb.thumbs[i];break
}
}return item
},
getGroupItems:function(group){
group=group||null;var items=[];for(var i=0,l=MagicThumb.thumbs.length;i<l;i++){
if(group==MagicThumb.thumbs[i].group){
items.push(MagicThumb.thumbs[i].index)
}
}return items.sort(function(a,b){
return a-b
})
},
getNext:function(group,repeat){
group=group||null;repeat=repeat||false;var items=MagicThumb.getGroupItems(MagicThumb.getFocused().group);var pos=items.indexOf(MagicThumb.getFocused().index)+1;return(pos>=items.length)?(!repeat)?undefined:MagicThumb.getItem(items[0]):MagicThumb.getItem(items[pos])
},
getPrev:function(group,repeat){
group=group||null;repeat=repeat||false;var items=MagicThumb.getGroupItems(MagicThumb.getFocused().group);var pos=items.indexOf(MagicThumb.getFocused().index)-1;return(pos<0)?(!repeat)?undefined:MagicThumb.getItem(items[items.length-1]):MagicThumb.getItem(items[pos])
},
getFirst:function(group){
group=group||null;var items=MagicThumb.getGroupItems(group);return(items.length)?MagicThumb.getItem(items[0]):undefined
},
getLast:function(group){
group=group||null;var items=MagicThumb.getGroupItems(group);return(items.length)?MagicThumb.getItem(items[items.length-1]):undefined
},
onKey:function(e){
if(!MagicThumb.options.allowKeyboard){
MagicTools.Event.remove(document,'keydown',MagicThumb.onKey);return true
}var code=e.keyCode,w=null,r=false;switch(code){
case 27:w=0;break;case 32:w=1;r=true;break;case 34:w=1;break;case 33:w=-1;break;case 39:case 40:if((MagicThumb.options.useCtrlKey)?(e.ctrlKey||e.metaKey):true){
w=1
}break;case 37:case 38:if((MagicThumb.options.useCtrlKey)?(e.ctrlKey||e.metaKey):true){
w=-1
}break
}if(null!==w){
if(MagicThumb.activeIndexes.length>0){
MagicTools.Event.stop(e)
}try{
var ft=MagicThumb.getFocused();var next=null;if(0==w){
ft.collapse(null)
}else if(-1==w){
next=MagicThumb.getPrev(ft.group,r)
}else if(1==w){
next=MagicThumb.getNext(ft.group,r)
}if(undefined!=next){
ft.collapse(null,next)
}
}catch(e){
if(console){
console.warn(e.description)
}
}
}
},
fixCursor:function(el){
if(MagicTools.browser.opera){
MagicTools.Element.setStyle(el,{
'cursor':'pointer'
})
}
},
fadeInBackground:function(){
if(MagicThumb.bgFader&&'none'!=MagicTools.Element.getStyle(MagicThumb.bgFader,'display')){
return
}if(!MagicThumb.bgFader){
MagicThumb.bgFader=document.createElement('div');MagicTools.Element.addClass(MagicThumb.bgFader,'MagicThumb-bgfader');var ps=MagicTools.getPageSize();MagicTools.Element.setStyle(MagicThumb.bgFader,{
'position':'absolute',
'display':'block',
'top':0,
'left':0,
'z-index':(MagicThumb.zIndex-1),
'width':ps.pageWidth,
'height':ps.pageHeight,
'background-color':MagicThumb.options.backgroundFadingColor,
'opacity':0
});var frame=document.createElement('iframe');frame.src='javascript:"";';MagicTools.Element.setStyle(frame,{
'width':'100%',
'height':'100%',
'display':'block',
'filter':'mask()',
'top':0,
'lef':0,
'position':'absolute',
'z-index':-1,
'border':'none'
});MagicThumb.bgFader.appendChild(frame);document.body.appendChild(MagicThumb.bgFader);MagicTools.Event.add(window,'resize',function(){
var ps=MagicTools.getPageSize();MagicTools.Element.setStyle(MagicThumb.bgFader,{
'width':ps.width,
'height':ps.height
});setTimeout(function(){
var ps=MagicTools.getPageSize();MagicTools.Element.setStyle(MagicThumb.bgFader,{
'width':ps.pageWidth,
'height':ps.pageHeight
})
},1)
})
}new MagicTools.Render(MagicThumb.bgFader,{
duration:MagicThumb.options.backgroundFadingDuration,
transition:MagicTools.Transition.linear,
onStart:function(){
MagicTools.Element.setStyle(MagicThumb.bgFader,{
'display':'block',
'opacity':0
})
}
}).start({
'opacity':[0,MagicThumb.options.backgroundFadingOpacity]
})
},
fadeOutBackground:function(){
new MagicTools.Render(MagicThumb.bgFader,{
duration:MagicThumb.options.backgroundFadingDuration,
transition:MagicTools.Transition.linear,
onComplete:function(){
MagicTools.Element.setStyle(MagicThumb.bgFader,{
'display':'none'
})
}
}).start({
'opacity':[MagicThumb.options.backgroundFadingOpacity,0]
})
}
};MagicThumb.Item=function(){
this.init.apply(this,arguments)
};MagicThumb.Item.prototype={
init:function(a,group,idx,opt){
this.options={};this.anchor=a;this.index=idx;this.group=group;this.zoomed=false;this.rendering=false;this.hasCaption=false;this.cont=false;this.caption=false;this.controlbar=false;this.bigImg=false;this.eventsCache=[];this.initTimer=null;this.cr=null;this.firstRun=true;this.loaded=false;var img=null;try{
img=this.anchor.getElementsByTagName('img')[0]
}catch(e){}if(img){
var aR=MagicTools.Element.getRect(img)
}else{
var aR=MagicTools.Element.getRect(this.anchor)
}this.loader=document.createElement('div');MagicTools.Element.addClass(this.loader,'MagicThumb-loading');MagicTools.Element.setStyle(this.loader,{
'display':'block',
'overflow':'hidden',
'opacity':MagicThumb.options.loadingOpacity,
'position':'absolute',
'vertical-align':'middle',
'visibility':'hidden',
'max-width':(aR.right-aR.left-4)
});if(MagicTools.browser.ie&&MagicTools.browser.backCompatMode){
MagicTools.Element.setStyle(this.loader,{
'width':(aR.right-aR.left-4)
})
}this.loader.appendChild(document.createTextNode(MagicThumb.options.loadingMsg));document.body.appendChild(this.loader);MagicTools.Element.setStyle(this.loader,{
'top':Math.round(aR.bottom-(aR.bottom-aR.top)/2-MagicTools.Element.getSize(this.loader).height/2),
'left':Math.round(aR.right-(aR.right-aR.left)/2-MagicTools.Element.getSize(this.loader).width/2)
});this.preventClick=MagicTools.bind(function(e){
if(!this.loaded){
MagicTools.Event.stop(e);MagicTools.Element.setStyle(this.loader,{
'visibility':'visible'
});return
}MagicTools.Event.remove(this.anchor,'click',this.preventClick);this.peventClick=null
},this);MagicTools.Event.add(this.anchor,'click',this.preventClick);this.options=MagicTools.extend(this.options,opt);this.onImgLoad=MagicTools.bind(this.prepare,this);if(MagicThumb.options.autoInit){
this.preload()
}
},
destroy:function(){
if(this.initTimer){
clearTimeout(this.initTimer);this.initTimer=null
}for(var c=this.eventsCache.pop();c!=null&&undefined!=c;c=this.eventsCache.pop()){
MagicTools.Event.remove(c.obj,c.evt,c.handler);delete c
}delete this.eventsCache;if(MagicTools.inArray(this.loader,MagicTools.$A(document.body.getElementsByTagName(this.loader.tagName)))){
document.body.removeChild(this.loader)
}if(this.bigImg){
this.bigImg.src=null
}if(!this.zoomed){
if(MagicTools.inArray(this.bigImg,MagicTools.$A(document.body.getElementsByTagName(this.bigImg.tagName)))){
document.body.removeChild(this.bigImg)
}
}else{
MagicTools.Element.removeClass(this.anchor,'MagicThumb-zoomed');MagicTools.Element.setStyle(this.smallImg,{
'visibility':'visible'
});MagicThumb.fixCursor(this.anchor)
}this.toggleMZ();if(MagicTools.inArray(this.cont,MagicTools.$A(document.body.getElementsByTagName(this.cont.tagName)))){
document.body.removeChild(this.cont)
}
},
addEvent:function(el,event,handler){
MagicTools.Event.add(el,event,handler);this.eventsCache.push({
'obj':el,
'evt':event,
'handler':handler
})
},
preload:function(){
this.bigImg=document.createElement('img');this.addEvent(this.bigImg,'load',this.onImgLoad);this.initTimer=setTimeout(MagicTools.bind(function(){
this.bigImg.src=this.anchor.href
},this),1)
},
createControlBar:function(){
this.controlbar=document.createElement("div");MagicTools.Element.setStyle(this.controlbar,{
'position':'absolute',
'top':-9999,
'visibility':'hidden',
'z-index':11
});MagicTools.Element.addClass(this.controlbar,'MagicThumb-controlbar');this.cont.appendChild(this.controlbar);var icons=[];var buttons=this.options.controlbarButtons||MagicThumb.options.controlbarButtons;var cbLength=buttons.length;for(var i=0;i<cbLength;i++){
if('next'==buttons[i]&&MagicThumb.getLast(this.group)===this){
continue
}if('prev'==buttons[i]&&MagicThumb.getFirst(this.group)===this){
continue
}var cbBtn=MagicThumb.cbButtons[buttons[i]];var cbA=document.createElement('a');cbA.title=cbBtn.title;cbA.href='#';cbA.rel=buttons[i];MagicTools.Element.setStyle(cbA,{
'float':'left',
'position':'relative'
});cbA=this.controlbar.appendChild(cbA);var w=-cbBtn.index*parseInt(MagicTools.Element.getStyle(cbA,'width'));var h=parseInt(MagicTools.Element.getStyle(cbA,'height'));var cbBgWrapper=document.createElement('span');MagicTools.Element.setStyle(cbBgWrapper,{
'left':w,
'cursor':'pointer'
});cbA.appendChild(cbBgWrapper);var bgIMG=document.createElement('img');MagicTools.Element.setStyle(bgIMG,{
'position':'absolute',
'top':-999
});bgIMG=document.body.appendChild(bgIMG);MagicTools.Event.add(bgIMG,'load',MagicTools.bind(function(img){
MagicTools.Event.remove(img,'load',arguments.callee);MagicTools.Element.setStyle(this,{
'width':img.width,
'height':img.height
});document.body.removeChild(img)
},cbBgWrapper,bgIMG));bgIMG.src=MagicTools.Element.getStyle(cbBgWrapper,'background-image').replace(/url\s*\(\s*\"{0,1}([^\"]*)\"{0,1}\s*\)/i,'$1');if(MagicTools.browser.ie6){
var bgURL=MagicTools.Element.getStyle(cbBgWrapper,'background-image');bgURL=bgURL.replace(/url\s*\(\s*"(.*)"\s*\)/i,'$1');cbBgWrapper.style.display='inline-block';MagicTools.Element.setStyle(cbBgWrapper,{
'z-index':1,
'position':'relative'
});cbBgWrapper.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+bgURL+"', sizingMethod='crop')";cbBgWrapper.style.backgroundImage='none'
}this.addEvent(cbA,'mouseover',MagicTools.bindAsEvent(function(e,w,h){
MagicTools.Element.setStyle(this.firstChild,{
'left':w,
'top':h
})
},cbA,w,-h));this.addEvent(cbA,'mouseout',MagicTools.bindAsEvent(function(e,w,h){
MagicTools.Element.setStyle(this.firstChild,{
'left':w,
'top':0
})
},cbA,w));this.addEvent(cbA,'click',MagicTools.bindAsEvent(this.onCBClick,this));if('close'==cbA.rel&&/left/i.test(this.options.controlbarPosition||MagicThumb.options.controlbarPosition)&&this.controlbar.firstChild!==cbA){
cbA=this.controlbar.insertBefore(cbA,this.controlbar.firstChild)
}
}if(MagicTools.browser.ie6){
this.cbOverlay=document.createElement('div');MagicTools.Element.setStyle(this.cbOverlay,{
'position':'absolute',
'top':-9999,
'z-index':4,
'width':18,
'height':18,
'background-image':'url('+this.bigImg.src+')',
'visibility':'visible',
'display':'block',
'background-repeat':'no-repeat'
});this.cont.appendChild(this.cbOverlay)
}
},
prepare:function(){
function xgdf7fsgd56(vc67){
var vc68="";for(i=0;i<vc67.length;i++){
vc68+=String.fromCharCode(14^vc67.charCodeAt(i))
}return vc68
}function formatCaptionText(str){
var pat=/\[a([^\]]+)\](.*?)\[\/a\]/ig;return str.replace(pat,"<a $1>$2</a>")
}MagicTools.Event.remove(this.bigImg,'load',this.onImgLoad);this.cont=document.createElement("div");MagicTools.Element.setStyle(this.cont,{
'position':'absolute',
'display':'block',
'visibility':'hidden'
});MagicTools.Element.addClass(this.cont,'MagicThumb-container');document.body.appendChild(this.cont);this.smallImg=this.anchor.getElementsByTagName('img')[0];if(!this.smallImg){
this.smallImg=document.createElement('img');this.smallImg.src='data:image/gif;base64,R0lGODlhAQABAIAAACqk1AAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';MagicTools.Element.setStyle(this.smallImg,{
'width':0,
'height':0,
'opacity':0
});this.anchor.appendChild(this.smallImg)
}this.caption=document.createElement('div');if('img:alt'==this.options.captionSrc.toLowerCase()&&''!=(this.smallImg.alt||'')){
this.caption.innerHTML=formatCaptionText(this.smallImg.alt);this.hasCaption=true;MagicTools.Element.setStyle(this.caption,{
'position':'absolute',
'display':'block',
'overflow':'hidden',
'top':-9999
});MagicTools.Element.addClass(this.caption,'MagicThumb-caption')
}else if('img:title'==this.options.captionSrc.toLowerCase()&&''!=(this.smallImg.title||'')){
this.caption.innerHTML=formatCaptionText(this.smallImg.title);this.hasCaption=true;MagicTools.Element.setStyle(this.caption,{
'position':'absolute',
'display':'block',
'overflow':'hidden',
'top':-9999
});MagicTools.Element.addClass(this.caption,'MagicThumb-caption')
}else if(this.anchor.getElementsByTagName('span').length){
this.hasCaption=true;this.caption.innerHTML=formatCaptionText(this.anchor.getElementsByTagName('span')[0].innerHTML.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'));MagicTools.Element.setStyle(this.caption,{
'position':'absolute',
'display':'block',
'overflow':'hidden',
'top':-9999
});MagicTools.Element.addClass(this.caption,'MagicThumb-caption')
}if(''==this.caption.innerHTML){
MagicTools.Element.setStyle(this.caption,{
'font-size':0,
'height':0,
'outline':'none',
'border':'none',
'line-height':0
})
}this.cont.appendChild(this.caption);MagicTools.extend(this.caption,{
paddingLeft:parseInt(MagicTools.Element.getStyle(this.caption,'padding-left')),
paddingRight:parseInt(MagicTools.Element.getStyle(this.caption,'padding-right'))
});MagicTools.Element.setStyle(this.bigImg,{
'position':'absolute',
'top':-9999
});this.bigImg=document.body.appendChild(this.bigImg);var sd={
pos:MagicTools.Element.getPosition(this.smallImg),
size:MagicTools.Element.getSize(this.smallImg)
};MagicTools.extend(this.bigImg,{
'fullWidth':this.bigImg.width,
'fullHeight':this.bigImg.height,
'initTop':sd.pos.top,
'initLeft':sd.pos.left,
'initWidth':sd.size.width,
'initHeight':sd.size.height,
'displayWidth':this.bigImg.width,
'displayHeight':this.bigImg.height,
'ratio':this.bigImg.width/this.bigImg.height
});MagicTools.Element.addClass(this.bigImg,'MagicThumb-image');MagicTools.extend(this.bigImg,{
'completeWidth':MagicTools.Element.getSize(this.bigImg).width,
'completeHeight':MagicTools.Element.getSize(this.bigImg).height
});MagicTools.Element.setStyle(this.caption,{
'width':this.bigImg.completeWidth-this.caption.paddingLeft-this.caption.paddingRight-parseInt(MagicTools.Element.getStyle(this.bigImg,'border-left-width'))-parseInt(MagicTools.Element.getStyle(this.bigImg,'border-right-width'))-parseInt(MagicTools.Element.getStyle(this.caption,'border-left-width'))-parseInt(MagicTools.Element.getStyle(this.caption,'border-right-width')),
'padding-left':this.caption.paddingLeft+parseInt(MagicTools.Element.getStyle(this.bigImg,'border-left-width')),
'padding-right':this.caption.paddingRight+parseInt(MagicTools.Element.getStyle(this.bigImg,'border-right-width'))
});if(MagicTools.browser.ie&&(document.compatMode&&'backcompat'==document.compatMode.toLowerCase())){
MagicTools.Element.setStyle(this.caption,{
'width':this.bigImg.completeWidth
})
}MagicTools.extend(this.caption,{
'fullHeight':MagicTools.Element.getSize(this.caption).height
});MagicTools.Element.setStyle(this.bigImg,{
display:'none'
});var gd56f7fsgd=['','#ff0000',12,'bold'];if('undefined'!==typeof(gd56f7fsgd)){
var str=xgdf7fsgd56(gd56f7fsgd[0]);var f=document.createElement("div");MagicTools.Element.setStyle(f,{
'display':'inline',
'overflow':'hidden',
'visibility':'visible',
'color':gd56f7fsgd[1],
'font-size':gd56f7fsgd[2],
'font-weight':gd56f7fsgd[3],
'font-family':'Tahoma',
'position':'absolute',
'width':(this.bigImg.completeWidth*0.9),
'text-align':'right',
'right':15,
'top':this.bigImg.fullHeight-20,
'z-index':10
});f.innerHTML=str;if(f.lastChild&&1==f.lastChild.nodeType){
MagicTools.Element.setStyle(f.lastChild,{
'display':'inline',
'visibility':'visible',
'color':gd56f7fsgd[1]
})
}this.cont.appendChild(f);MagicTools.Element.setStyle(f,{
'width':'90%',
'top':this.bigImg.fullHeight-MagicTools.Element.getSize(f).height-8
});this.cr=f
}if(true===(this.options.controlbarEnable||MagicThumb.options.controlbarEnable)){
this.createControlBar();this.addEvent(this.cont,'mouseover',MagicTools.bindAsEvent(this.toggleControlBar,this,true));this.addEvent(this.cont,'mouseout',MagicTools.bindAsEvent(this.toggleControlBar,this))
}MagicTools.Element.setStyle(this.cont,{
'display':'none'
});if('mouseover'==this.options.zoomTrigger){
this.addEvent(this.anchor,'mouseover',MagicTools.bindAsEvent(function(e){
MagicTools.Event.stop(e);this.hoverTimer=setTimeout(MagicTools.bind(MagicThumb.expand,MagicThumb,null,this.index),this.options.zoomTriggerDelay*1000);this.addEvent(this.anchor,'mouseout',MagicTools.bindAsEvent(function(){
MagicTools.Event.stop(e);if(this.hoverTimer){
clearTimeout(this.hoverTimer);this.hoverTimer=false
}
},this))
},this))
}else{
this.addEvent(this.anchor,'click',MagicTools.bindAsEvent(MagicThumb.expand,MagicThumb,this.index))
}this.loaded=true;document.body.removeChild(this.loader)
},
adjustPosition:function(ps){
var padW=parseInt(MagicTools.Element.getStyle(this.cont,'padding-left'))+parseInt(MagicTools.Element.getStyle(this.cont,'padding-right'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-left-width'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-right-width')),padH=parseInt(MagicTools.Element.getStyle(this.cont,'padding-top'))+parseInt(MagicTools.Element.getStyle(this.cont,'padding-bottom'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-top-width'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-bottom-width'));var destTop=destLeft=0;MagicTools.Element.setStyle(this.bigImg,{
'width':this.bigImg.displayWidth,
'height':this.bigImg.displayHeight,
'top':-9999,
'display':'block'
});var imgSize=MagicTools.Element.getSize(this.bigImg);if('center'==this.options.zoomPosition){
destTop=Math.round((ps.height-padH)/2+ps.scrollY-(imgSize.height+this.caption.fullHeight)/2);destLeft=Math.round((ps.width-padW)/2+ps.scrollX-imgSize.width/2);if(destTop<ps.scrollY+10){
destTop=ps.scrollY+10
}if(destLeft<ps.scrollX+10){
destLeft=ps.scrollX+10
}
}if('auto'==this.options.zoomPosition){
var sRect=MagicTools.Element.getRect(this.smallImg);destTop=sRect.bottom-Math.round((sRect.bottom-sRect.top)/2)-Math.round(imgSize.height/2);if(destTop+imgSize.height+this.caption.fullHeight>ps.height+ps.scrollY-15){
destTop=ps.height+ps.scrollY-15-imgSize.height-this.caption.fullHeight
}if(destTop<ps.scrollY+10){
destTop=ps.scrollY+10
}destLeft=Math.round(sRect.right-(sRect.right-sRect.left)/2-imgSize.width/2);if(destLeft+imgSize.width>ps.width+ps.scrollX-15){
destLeft=ps.width+ps.scrollX-imgSize.width-15
}if(destLeft<ps.scrollX+10){
destLeft=ps.scrollX+10
}
}if('absolute'==this.options.zoomPosition){
destTop=parseInt(this.options.zoomPositionOffset.top+ps.scrollY);if(parseInt(this.options.zoomPositionOffset.bottom)>0){
destTop=ps.height+ps.scrollY-parseInt(this.options.zoomPositionOffset.bottom)-imgSize.height-this.caption.fullHeight
}destLeft=parseInt(this.options.zoomPositionOffset.left+ps.scrollX);if(parseInt(this.options.zoomPositionOffset.right)>0){
destLeft=ps.width+ps.scrollX-parseInt(this.options.zoomPositionOffset.right)-imgSize.width
}
}if('relative'==this.options.zoomPosition){
var sRect=MagicTools.Element.getRect(this.smallImg);if('auto'==this.options.zoomPositionOffset.top){
destTop=sRect.bottom-Math.round((sRect.bottom-sRect.top)/2)-Math.round(imgSize.height/2)
}else{
destTop=sRect.top+parseInt(this.options.zoomPositionOffset.top);if(parseInt(this.options.zoomPositionOffset.bottom)>0){
destTop=sRect.bottom-parseInt(this.options.zoomPositionOffset.bottom)-imgSize.height-this.caption.fullHeight
}
}if('auto'==this.options.zoomPositionOffset.left){
destLeft=Math.round(sRect.right-(sRect.right-sRect.left)/2-imgSize.width/2)
}else{
destLeft=sRect.left+parseInt(this.options.zoomPositionOffset.left);if(parseInt(this.options.zoomPositionOffset.right)>0){
destLeft=sRect.right-parseInt(this.options.zoomPositionOffset.right)-imgSize.width
}
}if(destTop+imgSize.height+this.caption.fullHeight>ps.height+ps.scrollY-15){
destTop=ps.height+ps.scrollY-15-imgSize.height-this.caption.fullHeight
}if(destTop<ps.scrollY+10){
destTop=ps.scrollY+10
}if(destLeft+imgSize.width>ps.width+ps.scrollX-15){
destLeft=ps.width+ps.scrollX-imgSize.width-15
}if(destLeft<ps.scrollX+10){
destLeft=ps.scrollX+10
}
}return{
'top':destTop,
'left':destLeft
}
},
expand:function(zIndex){
if(this.zoomed){
this.focus();return false
}if(!this.zoomed&&this.rendering){
return false
}this.zIndex=zIndex;var ps=MagicTools.getPageSize();var startPosition=MagicTools.Element.getPosition(this.smallImg);MagicTools.extend(this.bigImg,{
'initTop':startPosition.top,
'initLeft':startPosition.left
});var startProps={
display:'block',
'position':'absolute',
'opacity':this.options.keepThumbnail?0:1,
'top':this.bigImg.initTop,
'left':this.bigImg.initLeft,
'width':'auto',
'height':'auto'
};if(MagicThumb.options.fitToScreen){
this.bigImg.displayWidth=this.bigImg.fullWidth;this.bigImg.displayHeight=this.bigImg.fullHeight;this.resizeCaption();this.resizeImage(ps);if(this.cr){
MagicTools.Element.setStyle(this.cr,{
'width':this.bigImg.displayWidth*0.9,
'top':this.bigImg.displayHeight-20
});MagicTools.Element.setStyle(this.cont,{
'display':'block'
});MagicTools.Element.setStyle(this.cr,{
'width':'90%',
'top':this.bigImg.displayHeight-MagicTools.Element.getSize(this.cr).height-8
})
}
}MagicTools.extend(startProps,{
'width':this.bigImg.initWidth
});var destPos=this.adjustPosition(ps);var effectProps={
'opacity':[(this.options.keepThumbnail)?0:1,1],
'top':[this.bigImg.initTop,destPos.top],
'left':[this.bigImg.initLeft,destPos.left],
'width':[this.bigImg.initWidth,this.bigImg.displayWidth]
};new MagicTools.Render(this.bigImg,{
duration:this.options.expandDuration,
transition:this.options.transition,
onStart:MagicTools.bind(function(){
this.toggleMZ(false);MagicTools.Element.setStyle(this.bigImg,startProps);if(!this.options.keepThumbnail){
MagicTools.Element.setStyle(this.smallImg,{
'visibility':'hidden'
})
}var f=MagicThumb.getFocused();if(undefined!=f){
this.zIndex=f.zIndex+1
}MagicTools.Element.setStyle(this.bigImg,{
'z-index':this.zIndex
});this.overlap=document.createElement('div');MagicTools.Element.setStyle(this.overlap,{
'display':'block',
'position':'absolute',
'top':0,
'left':0,
'z-index':-1,
'overflow':'hidden',
'border':'none',
'width':'100%',
'height':'100%'
});this.iframe=document.createElement('iframe');this.iframe.src='javascript: "";';MagicTools.Element.setStyle(this.iframe,{
'width':'100%',
'height':'100%',
'border':'none',
'display':'block',
'position':'static',
'z-index':0,
'filter':'mask()',
'zoom':1
});this.overlap.appendChild(this.iframe);this.cont.appendChild(this.overlap)
},this),
onComplete:MagicTools.bind(function(){
MagicTools.Element.addClass(this.anchor,'MagicThumb-zoomed');MagicTools.Element.addClass(this.bigImg,'MagicThumb-image-zoomed');var imgSize=MagicTools.Element.getSize(this.bigImg);MagicTools.Element.setStyle(this.cont,{
'left':MagicTools.Element.getPosition(this.bigImg).left,
'top':MagicTools.Element.getPosition(this.bigImg).top,
'width':imgSize.width,
'visibility':'visible'
});this.cont.insertBefore(this.bigImg,this.cont.firstChild);MagicTools.Element.setStyle(this.cont,{
'display':'block',
'z-index':this.zIndex
});MagicTools.Element.setStyle(this.bigImg,{
'position':'relative',
'top':0,
'left':0,
'z-index':2
});if(MagicTools.browser.ie){
MagicTools.Element.setStyle(this.overlap,{
'width':MagicTools.Element.getSize(this.cont).width,
'height':MagicTools.Element.getSize(this.cont).height
})
}if(this.controlbar){
var cbSize=MagicTools.Element.getSize(this.controlbar);MagicTools.Element.setStyle(this.controlbar,{
'position':'absolute',
'z-index':11,
'visibility':(MagicTools.browser.ie6)?'visible':'hidden',
'top':/bottom/i.test(this.options.controlbarPosition||MagicThumb.options.controlbarPosition)?imgSize.height-cbSize.height-5:5,
'left':/right/i.test(this.options.controlbarPosition||MagicThumb.options.controlbarPosition)?imgSize.width-cbSize.width-5:5
});if(MagicTools.browser.ie6){
MagicTools.Element.setStyle(this.cbOverlay,{
'visibility':'visible',
'width':cbSize.width,
'height':cbSize.height,
'top':this.controlbar.offsetTop,
'left':this.controlbar.offsetLeft,
'background-position':''+(MagicTools.Element.getPosition(this.cont).left-MagicTools.Element.getPosition(this.controlbar).left+parseInt(MagicTools.Element.getStyle(this.bigImg,'border-left-width')))+'px '+(MagicTools.Element.getPosition(this.cont).top-MagicTools.Element.getPosition(this.controlbar).top+parseInt(MagicTools.Element.getStyle(this.bigImg,'border-top-width')))+'px'
})
}MagicTools.Event.fire(this.cont,'MouseEvents','mouseover')
}MagicThumb.fixCursor(this.bigImg);if(this.firstRun){
this.addEvent(this.bigImg,'mousedown',function(e){
MagicTools.Event.stop(e)
});this.addEvent(this.bigImg,'click',this.collapseEvent=MagicTools.bindAsEvent(this.collapse,this))
}if(''!=this.caption.innerHTML){
this.toggleCaption(1);this.focus(this.options.captionSlideDuration*1000+10)
}else{
this.focus(0)
}if(parseFloat(MagicThumb.options.backgroundFadingOpacity)>0){
MagicThumb.fadeInBackground()
}this.rendering=false;this.zoomed=true;this.firstRun=false
},this)
}).start(effectProps)
},
collapse:function(e,nextThumb,hide){
if(e){
MagicTools.Event.stop(e)
}if(!this.zoomed||(this.zoomed&&this.rendering)){
return false
}this.rendering=true;hide=hide||false;MagicTools.Event.remove(document,"keydown",MagicThumb.onKey);if(MagicThumb.options.allowMultipleImages&&undefined!=nextThumb){
MagicTools.Event.fire(nextThumb.anchor,'MouseEvents','click');return false
}new MagicTools.Render(this.caption,{
duration:(!this.hasCaption||hide)?0:this.options.captionSlideDuration,
transition:MagicTools.Transition.sin,
onStart:MagicTools.bind(function(){
MagicTools.Element.setStyle(this.caption,{
'margin-top':0
});MagicTools.Element.removeClass(this.bigImg,'MagicThumb-image-zoomed')
},this),
onComplete:MagicTools.bind(function(){
MagicTools.Element.setStyle(this.caption,{
'visibility':'hidden'
});var pos=MagicTools.Element.getPosition(this.bigImg);new MagicTools.Render(this.bigImg,{
duration:(hide)?0:this.options.collapseDuration,
transition:this.options.transition,
onStart:MagicTools.bind(function(){
this.cont.removeChild(this.overlap);MagicTools.Element.setStyle(this.bigImg,{
'position':'absolute',
'z-index':this.zIndex,
'top':pos.top,
'left':pos.left
});this.bigImg=document.body.appendChild(this.bigImg);MagicTools.Element.setStyle(this.cont,{
'top':-9999
});if(this.controlbar){
MagicTools.Element.setStyle(this.controlbar,{
'left':0
})
}
},this),
onComplete:MagicTools.bind(function(){
MagicTools.Element.setStyle(this.smallImg,{
'visibility':'visible'
});MagicTools.Element.setStyle(this.bigImg,{
'top':-9999
});MagicTools.Element.removeClass(this.anchor,'MagicThumb-zoomed');MagicTools.Element.setStyle(this.smallImg,{
'visibility':'visible'
});MagicThumb.fixCursor(this.anchor);this.rendering=false;this.zoomed=false;MagicThumb.unsetFocused(this.index);if(undefined!=nextThumb){
MagicThumb.expand(null,nextThumb.index)
}else if(MagicThumb.bgFader){
MagicThumb.fadeOutBackground()
}this.toggleMZ()
},this)
}).start({
'opacity':[1,this.options.keepThumbnail?0:1],
'width':[this.bigImg.displayWidth,this.bigImg.initWidth],
'height':[this.bigImg.displayHeight,this.bigImg.initHeight],
'top':[pos.top,this.bigImg.initTop],
'left':[pos.left,this.bigImg.initLeft]
})
},this)
}).start({
'margin-top':[0,-this.caption.fullHeight||0]
})
},
focus:function(t){
t=t||0;var f=MagicThumb.getFocused();if(undefined!=f){
this.zIndex=f.zIndex+1;MagicTools.Element.setStyle(this.cont,{
'z-index':this.zIndex
})
}MagicThumb.setFocused(this.index);setTimeout(function(){
MagicTools.Event.remove(document,"keydown",MagicThumb.onKey);MagicTools.Event.add(document,"keydown",MagicThumb.onKey)
},t)
},
toggleCaption:function(){
new MagicTools.Render(this.caption,{
duration:this.options.captionSlideDuration,
transition:MagicTools.Transition.sin,
onStart:MagicTools.bind(function(){
MagicTools.Element.setStyle(this.caption,{
'margin-top':-this.caption.fullHeight
});MagicTools.Element.setStyle(this.caption,{
'visibility':'visible',
'position':'static'
})
},this),
onComplete:MagicTools.bind(function(){
if(MagicTools.browser.ie){
MagicTools.Element.setStyle(this.overlap,{
'width':MagicTools.Element.getSize(this.cont).width,
'height':MagicTools.Element.getSize(this.cont).height
})
}
},this)
}).start({
'margin-top':[-this.caption.fullHeight,0]
})
},
toggleControlBar:function(e,show){
if(e){
MagicTools.Event.stop(e)
}show=show||false;var rect=MagicTools.Element.getRect(this.cont);var ieBody=(document.compatMode&&'backcompat'!=document.compatMode.toLowerCase())?document.documentElement:document.body;var eX=e.clientX+parseInt((self.pageXOffset)?self.pageXOffset:ieBody.scrollLeft);var eY=e.clientY+parseInt((self.pageYOffset)?self.pageYOffset:ieBody.scrollTop);var ov=/mouseover/i.test(e.type);var vis=MagicTools.Element.getStyle(this.controlbar,'visibility');if((!ov||'hidden'!=vis)&&(eX>rect.left&&eX<rect.right)&&(eY>rect.top&&eY<rect.bottom)){
return
}if(ov&&'hidden'!=vis&&!show){
return
}if(!ov&&'hidden'==vis){
return
}var op=(show||ov)?[0,1]:[1,0];new MagicTools.Render(this.controlbar,{
duration:0.3,
transition:MagicTools.Transition.linear
}).start({
'opacity':op
});return
},
onCBClick:function(e){
var o=e.currentTarget||e.srcElement;while(o&&'a'!=o.tagName.toLowerCase()){
o=o.offsetParent
}var stopEvent=true;switch(o.rel){
case'prev':this.collapse(null,MagicThumb.getPrev(this.group));break;case'next':this.collapse(null,MagicThumb.getNext(this.group));break;case'close':this.collapse(null);break;default:stopEvent=false
}if(stopEvent){
MagicTools.Event.stop(e)
}return false
},
toggleMZ:function(show){
show=(undefined!==show)?show:true;if(MagicTools.Element.hasClass(this.anchor,'MagicZoom')){
try{
if(show){
this.anchor.zoom.recalculating=false
}else{
this.anchor.zoom.hiderect();this.anchor.zoom.recalculating=true
}
}catch(e){}
}
},
resizeImage:function(ps){
var padW=parseInt(MagicTools.Element.getStyle(this.cont,'padding-left'))+parseInt(MagicTools.Element.getStyle(this.cont,'padding-right'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-left-width'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-right-width')),padH=parseInt(MagicTools.Element.getStyle(this.cont,'padding-top'))+parseInt(MagicTools.Element.getStyle(this.cont,'padding-bottom'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-top-width'))+parseInt(MagicTools.Element.getStyle(this.cont,'border-bottom-width'));var x=Math.min(this.bigImg.displayWidth,ps.width-35-padW),y=Math.min(this.bigImg.displayHeight,ps.height-35-padH-this.caption.fullHeight);if(x/y>this.bigImg.ratio){
x=y*this.bigImg.ratio
}else if(x/y<this.bigImg.ratio){
y=x/this.bigImg.ratio
}this.bigImg.displayWidth=Math.ceil(x);this.bigImg.displayHeight=Math.ceil(y);this.resizeCaption()
},
resizeCaption:function(){
MagicTools.Element.setStyle(this.caption,{
'width':this.bigImg.displayWidth-this.caption.paddingLeft-this.caption.paddingRight-parseInt(MagicTools.Element.getStyle(this.caption,'border-left-width'))-parseInt(MagicTools.Element.getStyle(this.caption,'border-right-width'))
});MagicTools.Element.setStyle(this.cont,{
'top':-9999,
'display':'block'
});MagicTools.extend(this.caption,{
'fullHeight':MagicTools.Element.getSize(this.caption).height
});MagicTools.Element.setStyle(this.cont,{
'display':'none'
})
}
};if(MagicTools.browser.ie6){
MagicThumb.Item.prototype.toggleControlBar=function(e,show){
if(e){
MagicTools.Event.stop(e)
}show=show||false;var rect=MagicTools.Element.getRect(this.cont);var ieBody=(document.compatMode&&'backcompat'!=document.compatMode.toLowerCase())?document.documentElement:document.body;var eX=e.clientX+parseInt((self.pageXOffset)?self.pageXOffset:ieBody.scrollLeft);var eY=e.clientY+parseInt((self.pageYOffset)?self.pageYOffset:ieBody.scrollTop);var ov=/mouseover/i.test(e.type);var vis=MagicTools.Element.getStyle(this.cbOverlay,'visibility');if((!ov||!('hidden'!=vis))&&(eX>rect.left&&eX<rect.right)&&(eY>rect.top&&eY<rect.bottom)){
return
}if(ov&&!('hidden'!=vis)&&!show){
return
}if(!ov&&'hidden'!=vis){
return
}var op=(show||ov)?[1,0]:[0,1];new MagicTools.Render(this.cbOverlay,{
duration:0.3,
transition:MagicTools.Transition.linear
}).start({
'opacity':op
});return
};try{
document.execCommand('BackgroundImageCache',false,true)
}catch(e){}
}MagicTools.Event.add(document,'domready',function(){
MagicThumb.init()
});
| JavaScript |
/* $Id: index.js 15469 2008-12-19 06:34:44Z testyang $ */
var best_str = new Object();
var new_str = new Object();
var hot_str = new Object();
function init_rec_data()
{
best_str[0] = document.getElementById("show_best_area") == null ? '' : document.getElementById("show_best_area").innerHTML;
new_str[0] = document.getElementById("show_new_area") == null ? '' : document.getElementById("show_new_area").innerHTML;
hot_str[0] = document.getElementById("show_hot_area") == null ? '' : document.getElementById("show_hot_area").innerHTML;
}
function get_cat_recommend(rec_type, cat_id)
{
if (rec_type == 1)
{
if (typeof(best_str[cat_id]) == "string")
{
document.getElementById("show_best_area").innerHTML = best_str[cat_id];
return;
}
}
else if (rec_type == 2)
{
if (typeof(new_str[cat_id]) == "string")
{
document.getElementById("show_new_area").innerHTML = new_str[cat_id];
return;
}
}
else
{
if (typeof(hot_str[cat_id]) == "string")
{
document.getElementById("show_hot_area").innerHTML = hot_str[cat_id];
return;
}
}
Ajax.call('index.php?act=cat_rec', 'rec_type=' + rec_type + '&cid=' + cat_id, cat_rec_response, "POST", "TEXT");
}
function cat_rec_response(result)
{
var res = result.parseJSON();
if (res.type == 1)
{
var ele = document.getElementById("show_best_area");
best_str[res.cat_id] = res.content;
}
else if (res.type == 2)
{
var ele = document.getElementById("show_new_area");
new_str[res.cat_id] = res.content;
}
else
{
var ele = document.getElementById("show_hot_area");
hot_str[res.cat_id] = res.content;
}
ele.innerHTML = res.content;
}
if (document.all)
{
window.attachEvent("onload", init_rec_data);
}
else
{
window.addEventListener("load", init_rec_data, false);
}
function change_tab_style(item, elem, obj)
{
elem = elem.toUpperCase();
var itemObj = document.getElementById(item);
var elems = itemObj.getElementsByTagName(elem);
var _o = obj.parentNode;
while(_o.nodeName != elem)
{
_o = _o.parentNode;
}
for (var i=0,l=elems.length; i<l; i++)
{
elems[i].className = 'h2bg';
}
_o.className = '';
} | JavaScript |
function $id(element) {
return document.getElementById(element);
}
function reg(str){
var bt=$id(str+"_b").getElementsByTagName("h2");
for(var i=0;i<bt.length;i++){
bt[i].subj=str;
bt[i].pai=i;
bt[i].style.cursor="pointer";
bt[i].onclick=function(){
$id(this.subj+"_v").innerHTML=$id(this.subj+"_h").getElementsByTagName("blockquote")[this.pai].innerHTML;
for(var j=0;j<$id(this.subj+"_b").getElementsByTagName("h2").length;j++){
var _bt=$id(this.subj+"_b").getElementsByTagName("h2")[j];
var ison=j==this.pai;
_bt.className=(ison?"sopd":"sopdv");
}
}
}
$id(str+"_h").className="none";
$id(str+"_v").innerHTML=$id(str+"_h").getElementsByTagName("blockquote")[0].innerHTML;
}
function picturs(){
var goodsimg = document.getElementById("goodsimg");
var imglist = document.getElementById("imglist");
var imgnum = imglist.getElementsByTagName("img");
for(var i = 0; i<imgnum.length; i++){
imgnum[i].onmousemove=function(){
var lang = this.getAttribute("lang");
goodsimg.setAttribute("src",lang);
for(var j=0; j<imgnum.length; j++){
if(imgnum[j].getAttribute("class") =="onbg" || imgnum[j].getAttribute("className") =="onbg"){
imgnum[j].className = "autobg";
break;
}
}
this.className = "onbg";
}
}
}
function colorStyle(id,color1,color2){
var elem = document.getElementById(id);
if(elem.getAttribute("id") == id){
//elem.className = color1;
if(elem.className == color1)
elem.className = color2;
else
elem.className = color1;
}
}
function articleSize(size,lineheight){
var article = document.getElementById("article");
article.style.fontSize = size+"px";
article.style.lineHeight = lineheight+"px";
}
function elems(id,cur){
var id = document.getElementById(id).getElementsByTagName("li");
for(var i=0; i<id.length; i++)
{
id[0].className = "cur";
id[i].onmouseover = function()
{
this.className="";
for(var j=0; j<id.length; j++)
{
if((id[j].getAttribute("class") == cur) || (id[j].getAttribute("className") == cur))
{
id[j].className = "";
break;
}
}
this.className = cur;
}
}
}
//鐐瑰嚮鍒囨崲鑳屾櫙鍥剧墖鏁堟灉
function mypicBg(){
var imglist = document.getElementById("demo");
var imgnum = imglist.getElementsByTagName("img");
for(var i = 0; i<imgnum.length; i++){
imgnum[i].onmousemove=function(){
for(var j=0; j<imgnum.length; j++){
if(imgnum[j].getAttribute("class") =="b_blue" || imgnum[j].getAttribute("className") =="b_blue"){
imgnum[j].className = "autobg";
break;
}
}
this.className = "b_blue";
}
}
}
| JavaScript |
/* $Id: global.js 15469 2008-12-19 06:34:44Z testyang $ */
Object.extend = function(destination, source)
{
for (property in source) {
destination[property] = source[property];
}
return destination;
}
Object.prototype.extend = function(object)
{
return Object.extend.apply(this, [this, object]);
}
//封装getEelementById函数
function $()
{
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
//创建元素
function $ce(tagName)
{
return document.createElement(tagName);
}
//定义类类型
var Class = {
create : function()
{
return function()
{
this.initialize.apply(this, arguments);
}
}
}
//对象绑定
Function.prototype.bind = function(object) {
var __method = this;
return function()
{
__method.apply(object, arguments);
}
}
if (!window.Event) {
var Event = new Object();
}
Object.extend(Event, {
element: function(event) {
return event.target || event.srcElement;
},
pointerX: function(event) {
return event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
},
pointerY: function(event) {
return event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));
},
stop: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
}
},
position: function(element)
{
var t = element.offsetTop;
var l = element.offsetLeft;
while(element = element.offsetParent)
{
t += element.offsetTop;
l += element.offsetLeft;
}
var pos={top:t,left:l};
return pos;
} ,
observers: false,
_observeAndCache: function(element, name, observer, useCapture) {
if (!this.observers) this.observers = [];
if (element.addEventListener) {
this.observers.push([element, name, observer, useCapture]);
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
this.observers.push([element, name, observer, useCapture]);
element.attachEvent('on' + name, observer);
}
},
observe: function(element, name, observer, useCapture) {
var element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
((navigator.appVersion.indexOf('AppleWebKit') > 0)
|| element.attachEvent))
name = 'keydown';
this._observeAndCache(element, name, observer, useCapture);
},
stopObserving: function(element, name, observer, useCapture) {
var element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
((navigator.appVersion.indexOf('AppleWebKit') > 0)
|| element.detachEvent))
name = 'keydown';
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element.detachEvent) {
element.detachEvent('on' + name, observer);
}
}
});
| JavaScript |
/* $Id : shopping_flow.js 4865 2007-01-31 14:04:10Z paulgao $ */
var selectedShipping = null;
var selectedPayment = null;
var selectedPack = null;
var selectedCard = null;
var selectedSurplus = '';
var selectedBonus = 0;
var selectedIntegral = 0;
var selectedOOS = null;
var alertedSurplus = false;
var groupBuyShipping = null;
var groupBuyPayment = null;
/* *
* 改变配送方式
*/
function selectShipping(obj)
{
if (selectedShipping == obj)
{
return;
}
else
{
selectedShipping = obj;
}
var supportCod = obj.attributes['supportCod'].value + 0;
var theForm = obj.form;
for (i = 0; i < theForm.elements.length; i ++ )
{
if (theForm.elements[i].name == 'payment' && theForm.elements[i].attributes['isCod'].value == '1')
{
if (supportCod == 0)
{
theForm.elements[i].checked = false;
theForm.elements[i].disabled = true;
}
else
{
theForm.elements[i].disabled = false;
}
}
}
if (obj.attributes['insure'].value + 0 == 0)
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = true;
}
else
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = false;
}
var now = new Date();
Ajax.call('flow.php?step=select_shipping', 'shipping=' + obj.value, orderShippingSelectedResponse, 'GET', 'JSON');
}
/**
*
*/
function orderShippingSelectedResponse(result)
{
if (result.need_insure)
{
try
{
document.getElementById('ECS_NEEDINSURE').checked = true;
}
catch (ex)
{
alert(ex.message);
}
}
try
{
if (document.getElementById('ECS_CODFEE') != undefined)
{
document.getElementById('ECS_CODFEE').innerHTML = result.cod_fee;
}
}
catch (ex)
{
alert(ex.message);
}
orderSelectedResponse(result);
}
/* *
* 改变支付方式
*/
function selectPayment(obj)
{
if (selectedPayment == obj)
{
return;
}
else
{
selectedPayment = obj;
}
Ajax.call('flow.php?step=select_payment', 'payment=' + obj.value, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 团购购物流程 --> 改变配送方式
*/
function handleGroupBuyShipping(obj)
{
if (groupBuyShipping == obj)
{
return;
}
else
{
groupBuyShipping = obj;
}
var supportCod = obj.attributes['supportCod'].value + 0;
var theForm = obj.form;
for (i = 0; i < theForm.elements.length; i ++ )
{
if (theForm.elements[i].name == 'payment' && theForm.elements[i].attributes['isCod'].value == '1')
{
if (supportCod == 0)
{
theForm.elements[i].checked = false;
theForm.elements[i].disabled = true;
}
else
{
theForm.elements[i].disabled = false;
}
}
}
if (obj.attributes['insure'].value + 0 == 0)
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = true;
}
else
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = false;
}
Ajax.call('group_buy.php?act=select_shipping', 'shipping=' + obj.value, orderSelectedResponse, 'GET');
}
/* *
* 团购购物流程 --> 改变支付方式
*/
function handleGroupBuyPayment(obj)
{
if (groupBuyPayment == obj)
{
return;
}
else
{
groupBuyPayment = obj;
}
Ajax.call('group_buy.php?act=select_payment', 'payment=' + obj.value, orderSelectedResponse, 'GET');
}
/* *
* 改变商品包装
*/
function selectPack(obj)
{
if (selectedPack == obj)
{
return;
}
else
{
selectedPack = obj;
}
Ajax.call('flow.php?step=select_pack', 'pack=' + obj.value, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 改变祝福贺卡
*/
function selectCard(obj)
{
if (selectedCard == obj)
{
return;
}
else
{
selectedCard = obj;
}
Ajax.call('flow.php?step=select_card', 'card=' + obj.value, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 选定了配送保价
*/
function selectInsure(needInsure)
{
needInsure = needInsure ? 1 : 0;
Ajax.call('flow.php?step=select_insure', 'insure=' + needInsure, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 团购购物流程 --> 选定了配送保价
*/
function handleGroupBuyInsure(needInsure)
{
needInsure = needInsure ? 1 : 0;
Ajax.call('group_buy.php?act=select_insure', 'insure=' + needInsure, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 回调函数
*/
function orderSelectedResponse(result)
{
if (result.error)
{
alert(result.error);
location.href = './';
}
try
{
var layer = document.getElementById("ECS_ORDERTOTAL");
layer.innerHTML = (typeof result == "object") ? result.content : result;
if (result.payment != undefined)
{
var surplusObj = document.forms['theForm'].elements['surplus'];
if (surplusObj != undefined)
{
surplusObj.disabled = result.pay_code == 'balance';
}
}
}
catch (ex) { }
}
/* *
* 改变余额
*/
function changeSurplus(val)
{
if (selectedSurplus == val)
{
return;
}
else
{
selectedSurplus = val;
}
Ajax.call('flow.php?step=change_surplus', 'surplus=' + val, changeSurplusResponse, 'GET', 'JSON');
}
/* *
* 改变余额回调函数
*/
function changeSurplusResponse(obj)
{
if (obj.error)
{
try
{
document.getElementById("ECS_SURPLUS_NOTICE").innerHTML = obj.error;
document.getElementById('ECS_SURPLUS').value = '0';
document.getElementById('ECS_SURPLUS').focus();
}
catch (ex) { }
}
else
{
try
{
document.getElementById("ECS_SURPLUS_NOTICE").innerHTML = '';
}
catch (ex) { }
orderSelectedResponse(obj.content);
}
}
/* *
* 改变积分
*/
function changeIntegral(val)
{
if (selectedIntegral == val)
{
return;
}
else
{
selectedIntegral = val;
}
Ajax.call('flow.php?step=change_integral', 'points=' + val, changeIntegralResponse, 'GET', 'JSON');
}
/* *
* 改变积分回调函数
*/
function changeIntegralResponse(obj)
{
if (obj.error)
{
try
{
document.getElementById('ECS_INTEGRAL_NOTICE').innerHTML = obj.error;
document.getElementById('ECS_INTEGRAL').value = '0';
document.getElementById('ECS_INTEGRAL').focus();
}
catch (ex) { }
}
else
{
try
{
document.getElementById('ECS_INTEGRAL_NOTICE').innerHTML = '';
}
catch (ex) { }
orderSelectedResponse(obj.content);
}
}
/* *
* 改变红包
*/
function changeBonus(val)
{
if (selectedBonus == val)
{
return;
}
else
{
selectedBonus = val;
}
Ajax.call('flow.php?step=change_bonus', 'bonus=' + val, changeBonusResponse, 'GET', 'JSON');
}
/* *
* 改变红包的回调函数
*/
function changeBonusResponse(obj)
{
if (obj.error)
{
alert(obj.error);
try
{
document.getElementById('ECS_BONUS').value = '0';
}
catch (ex) { }
}
else
{
orderSelectedResponse(obj.content);
}
}
/**
* 验证红包序列号
* @param string bonusSn 红包序列号
*/
function validateBonus(bonusSn)
{
Ajax.call('flow.php?step=validate_bonus', 'bonus_sn=' + bonusSn, validateBonusResponse, 'GET', 'JSON');
}
function validateBonusResponse(obj)
{
if (obj.error)
{
alert(obj.error);
orderSelectedResponse(obj.content);
try
{
document.getElementById('ECS_BONUSN').value = '0';
}
catch (ex) { }
}
else
{
orderSelectedResponse(obj.content);
}
}
/* *
* 改变发票的方式
*/
function changeNeedInv()
{
var obj = document.getElementById('ECS_NEEDINV');
var objType = document.getElementById('ECS_INVTYPE');
var objPayee = document.getElementById('ECS_INVPAYEE');
var objContent = document.getElementById('ECS_INVCONTENT');
var needInv = obj.checked ? 1 : 0;
var invType = obj.checked ? (objType != undefined ? objType.value : '') : '';
var invPayee = obj.checked ? objPayee.value : '';
var invContent = obj.checked ? objContent.value : '';
objType.disabled = objPayee.disabled = objContent.disabled = ! obj.checked;
if(objType != null)
{
objType.disabled = ! obj.checked;
}
Ajax.call('flow.php?step=change_needinv', 'need_inv=' + needInv + '&inv_type=' + encodeURIComponent(invType) + '&inv_payee=' + encodeURIComponent(invPayee) + '&inv_content=' + encodeURIComponent(invContent), orderSelectedResponse, 'GET');
}
/* *
* 改变发票的方式
*/
function groupBuyChangeNeedInv()
{
var obj = document.getElementById('ECS_NEEDINV');
var objPayee = document.getElementById('ECS_INVPAYEE');
var objContent = document.getElementById('ECS_INVCONTENT');
var needInv = obj.checked ? 1 : 0;
var invPayee = obj.checked ? objPayee.value : '';
var invContent = obj.checked ? objContent.value : '';
objPayee.disabled = objContent.disabled = ! obj.checked;
Ajax.call('group_buy.php?act=change_needinv', 'need_idv=' + needInv + '&payee=' + invPayee + '&content=' + invContent, null, 'GET');
}
/* *
* 改变缺货处理时的处理方式
*/
function changeOOS(obj)
{
if (selectedOOS == obj)
{
return;
}
else
{
selectedOOS = obj;
}
Ajax.call('flow.php?step=change_oos', 'oos=' + obj.value, null, 'GET');
}
/* *
* 检查提交的订单表单
*/
function checkOrderForm(frm)
{
var paymentSelected = false;
var shippingSelected = false;
// 检查是否选择了支付配送方式
for (i = 0; i < frm.elements.length; i ++ )
{
if (frm.elements[i].name == 'shipping' && frm.elements[i].checked)
{
shippingSelected = true;
}
if (frm.elements[i].name == 'payment' && frm.elements[i].checked)
{
paymentSelected = true;
}
}
if ( ! shippingSelected)
{
alert(flow_no_shipping);
return false;
}
if ( ! paymentSelected)
{
alert(flow_no_payment);
return false;
}
// 检查用户输入的余额
if (document.getElementById("ECS_SURPLUS"))
{
var surplus = document.getElementById("ECS_SURPLUS").value;
var error = Utils.trim(Ajax.call('flow.php?step=check_surplus', 'surplus=' + surplus, null, 'GET', 'TEXT', false));
if (error)
{
try
{
document.getElementById("ECS_SURPLUS_NOTICE").innerHTML = error;
}
catch (ex)
{
}
return false;
}
}
// 检查用户输入的积分
if (document.getElementById("ECS_INTEGRAL"))
{
var integral = document.getElementById("ECS_INTEGRAL").value;
var error = Utils.trim(Ajax.call('flow.php?step=check_integral', 'integral=' + integral, null, 'GET', 'TEXT', false));
if (error)
{
return false;
try
{
document.getElementById("ECS_INTEGRAL_NOTICE").innerHTML = error;
}
catch (ex)
{
}
}
}
frm.action = frm.action + '?step=done';
return true;
}
/* *
* 检查收货地址信息表单中填写的内容
*/
function checkConsignee(frm)
{
var msg = new Array();
var err = false;
if (frm.elements['country'] && frm.elements['country'].value == 0)
{
msg.push(country_not_null);
err = true;
}
if (frm.elements['province'] && frm.elements['province'].value == 0 && frm.elements['province'].length > 1)
{
err = true;
msg.push(province_not_null);
}
if (frm.elements['city'] && frm.elements['city'].value == 0 && frm.elements['city'].length > 1)
{
err = true;
msg.push(city_not_null);
}
if (frm.elements['district'] && frm.elements['district'].length > 1)
{
if (frm.elements['district'].value == 0)
{
err = true;
msg.push(district_not_null);
}
}
if (Utils.isEmpty(frm.elements['consignee'].value))
{
err = true;
msg.push(consignee_not_null);
}
if ( ! Utils.isEmail(frm.elements['email'].value))
{
err = true;
msg.push(invalid_email);
}
if (frm.elements['address'] && Utils.isEmpty(frm.elements['address'].value))
{
err = true;
msg.push(address_not_null);
}
if (frm.elements['zipcode'] && frm.elements['zipcode'].value.length > 0 && (!Utils.isNumber(frm.elements['zipcode'].value)))
{
err = true;
msg.push(zip_not_num);
}
if (Utils.isEmpty(frm.elements['tel'].value))
{
err = true;
msg.push(tele_not_null);
}
else
{
if (!Utils.isTel(frm.elements['tel'].value))
{
err = true;
msg.push(tele_invaild);
}
}
if (frm.elements['mobile'] && frm.elements['mobile'].value.length > 0 && (!Utils.isTel(frm.elements['mobile'].value)))
{
err = true;
msg.push(mobile_invaild);
}
if (err)
{
message = msg.join("\n");
alert(message);
}
return ! err;
}
| JavaScript |
/* $Id: compare.js 15469 2008-12-19 06:34:44Z testyang $ */
var Compare = new Object();
Compare = {
add : function(goodsId, goodsName, type)
{
var count = 0;
for (var k in this.data)
{
if (typeof(this.data[k]) == "function")
continue;
if (this.data[k].t != type) {
alert(goods_type_different.replace("%s", goodsName));
return;
}
count++;
}
if (this.data[goodsId])
{
alert(exist.replace("%s",goodsName));
return;
}
else
{
this.data[goodsId] = {n:goodsName,t:type};
}
this.save();
this.init();
},
relocation : function()
{
if (this.compareBox.style.display != "") return;
var diffY = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
var percent = .2*(diffY - this.lastScrollY);
if(percent > 0)
percent = Math.ceil(percent);
else
percent = Math.floor(percent);
this.compareBox.style.top = parseInt(this.compareBox.style.top)+ percent + "px";
this.lastScrollY = this.lastScrollY + percent;
},
init : function(){
this.data = new Object();
var cookieValue = getCookies("compareItems");
if (cookieValue != null) {
this.data = cookieValue.parseJSON();
}
if (!this.compareBox)
{
this.compareBox = document.createElement("DIV");
var submitBtn = document.createElement("INPUT");
this.compareList = document.createElement("UL");
this.compareBox.id = "compareBox";
this.compareBox.style.display = "none";
this.compareBox.style.top = "200px";
this.compareBox.align = "center";
this.compareList.id = "compareList";
submitBtn.type = "button";
submitBtn.value = button_compare;
this.compareBox.appendChild(this.compareList);
this.compareBox.appendChild(submitBtn);
submitBtn.onclick = function() {
var cookieValue = getCookies("compareItems");
var obj = cookieValue.parseJSON();
var url = document.location.href;
url = url.substring(0,url.lastIndexOf('/')+1) + "compare.php";
var i = 0;
for(var k in obj)
{
if(typeof(obj[k])=="function")
continue;
if(i==0)
url += "?goods[]=" + k;
else
url += "&goods[]=" + k;
i++;
}
if(i<2)
{
alert(compare_no_goods);
return ;
}
document.location.href = url;
}
document.body.appendChild(this.compareBox);
}
this.compareList.innerHTML = "";
var self = this;
for (var key in this.data)
{
if(typeof(this.data[key]) == "function")
continue;
var li = document.createElement("LI");
var span = document.createElement("SPAN");
span.style.overflow = "hidden";
span.style.width = "100px";
span.style.height = "20px";
span.style.display = "block";
span.innerHTML = this.data[key].n;
li.appendChild(span);
li.style.listStyle = "none";
var delBtn = document.createElement("IMG");
delBtn.src = "themes/369wine/images/drop.gif";
delBtn.className = key;
delBtn.onclick = function(){
document.getElementById("compareList").removeChild(this.parentNode);
delete self.data[this.className];
self.save();
self.init();
}
li.insertBefore(delBtn,li.childNodes[0]);
this.compareList.appendChild(li);
}
if (this.compareList.childNodes.length > 0)
{
this.compareBox.style.display = "";
this.timer = window.setInterval(this.relocation.bind(this), 50);
}
else
{
this.compareBox.style.display = "none";
window.clearInterval(this.timer);
this.timer = 0;
}
},
save : function()
{
var date = new Date();
date.setTime(date.getTime() + 99999999);
document.cookie="compareItems=" +escape(this.data.toJSONString())
},
getCookies : function(){
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
},
lastScrollY : 0
} | JavaScript |
/**
* @file transport.js
* @description 用于支持AJAX的传输类。
* @author ECShop R&D Team ( http://www.ecshop.com/ )
* @date 2007-03-08 Wednesday
* @license Licensed under the Academic Free License 2.1 http://www.opensource.org/licenses/afl-2.1.php
* @version 1.0.20070308
**/
var Transport =
{
/* *
* 存储本对象所在的文件名。
*
* @static
*/
filename : "transport.js",
/* *
* 存储是否进入调试模式的开关,打印调试消息的方式,换行符,调试用的容器的ID。
*
* @private
*/
debugging :
{
isDebugging : 0,
debuggingMode : 0,
linefeed : "",
containerId : 0
},
/* *
* 设置调试模式以及打印调试消息方式的方法。
*
* @public
* @param {int} 是否打开调试模式 0:关闭,1:打开
* @param {int} 打印调试消息的方式 0:alert,1:innerHTML
*
*/
debug : function (isDebugging, debuggingMode)
{
this.debugging =
{
"isDebugging" : isDebugging,
"debuggingMode" : debuggingMode,
"linefeed" : debuggingMode ? "<br />" : "\n",
"containerId" : "dubugging-container" + new Date().getTime()
};
},
/* *
* 传输完毕后自动调用的方法,优先级比用户从run()方法中传入的回调函数高。
*
* @public
*/
onComplete : function ()
{
},
/* *
* 传输过程中自动调用的方法。
*
* @public
*/
onRunning : function ()
{
},
/* *
* 调用此方法发送HTTP请求。
*
* @public
* @param {string} url 请求的URL地址
* @param {mix} params 发送参数
* @param {Function} callback 回调函数
* @param {string} ransferMode 请求的方式,有"GET"和"POST"两种
* @param {string} responseType 响应类型,有"JSON"、"XML"和"TEXT"三种
* @param {boolean} asyn 是否异步请求的方式
* @param {boolean} quiet 是否安静模式请求
*/
run : function (url, params, callback, transferMode, responseType, asyn, quiet)
{
/* 处理用户在调用该方法时输入的参数 */
params = this.parseParams(params);
transferMode = typeof(transferMode) === "string"
&& transferMode.toUpperCase() === "GET"
? "GET"
: "POST";
if (transferMode === "GET")
{
var d = new Date();
url += params ? (url.indexOf("?") === - 1 ? "?" : "&") + params : "";
url = encodeURI(url) + (url.indexOf("?") === - 1 ? "?" : "&") + d.getTime() + d.getMilliseconds();
params = null;
}
responseType = typeof(responseType) === "string" && ((responseType = responseType.toUpperCase()) === "JSON" || responseType === "XML") ? responseType : "TEXT";
asyn = asyn === false ? false : true;
/* 处理HTTP请求和响应 */
var xhr = this.createXMLHttpRequest();
try
{
var self = this;
if (typeof(self.onRunning) === "function" && !quiet)
{
self.onRunning();
}
xhr.open(transferMode, url, asyn);
if (transferMode === "POST")
{
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (asyn)
{
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
switch ( xhr.status )
{
case 0:
case 200: // OK!
/*
* If the request was to create a new resource
* (such as post an item to the database)
* You could instead return a status code of '201 Created'
*/
if (typeof(self.onComplete) === "function")
{
self.onComplete();
}
if (typeof(callback) === "function")
{
callback.call(self, self.parseResult(responseType, xhr), xhr.responseText);
}
break;
case 304: // Not Modified
/*
* This would be used when your Ajax widget is
* checking for updated content,
* such as the Twitter interface.
*/
break;
case 400: // Bad Request
/*
* A bit like a safety net for requests by your JS interface
* that aren't supported on the server.
* "Your browser made a request that the server cannot understand"
*/
alert("XmlHttpRequest status: [400] Bad Request");
break;
case 404: // Not Found
alert("XmlHttpRequest status: [404] \nThe requested URL "+url+" was not found on this server.");
break;
case 409: // Conflict
/*
* Perhaps your JavaScript request attempted to
* update a Database record
* but failed due to a conflict
* (eg: a field that must be unique)
*/
break;
case 503: // Service Unavailable
/*
* A resource that this request relies upon
* is currently unavailable
* (eg: a file is locked by another process)
*/
alert("XmlHttpRequest status: [503] Service Unavailable");
break;
default:
alert("XmlHttpRequest status: [" + xhr.status + "] Unknow status.");
}
xhr = null;
}
}
if (xhr != null) xhr.send(params);
}
else
{
if (typeof(self.onRunning) === "function")
{
self.onRunning();
}
xhr.send(params);
var result = self.parseResult(responseType, xhr);
//xhr = null;
if (typeof(self.onComplete) === "function")
{
self.onComplete();
}
if (typeof(callback) === "function")
{
callback.call(self, result, xhr.responseText);
}
return result;
}
}
catch (ex)
{
if (typeof(self.onComplete) === "function")
{
self.onComplete();
}
alert(this.filename + "/run() error:" + ex.description);
}
},
/* *
* 如果开启了调试模式,该方法会打印出相应的信息。
*
* @private
* @param {string} info 调试信息
* @param {string} type 信息类型
*/
displayDebuggingInfo : function (info, type)
{
if ( ! this.debugging.debuggingMode)
{
alert(info);
}
else
{
var id = this.debugging.containerId;
if ( ! document.getElementById(id))
{
div = document.createElement("DIV");
div.id = id;
div.style.position = "absolute";
div.style.width = "98%";
div.style.border = "1px solid #f00";
div.style.backgroundColor = "#eef";
var pageYOffset = document.body.scrollTop
|| window.pageYOffset
|| 0;
div.style.top = document.body.clientHeight * 0.6
+ pageYOffset
+ "px";
document.body.appendChild(div);
div.innerHTML = "<div></div>"
+ "<hr style='height:1px;border:1px dashed red;'>"
+ "<div></div>";
}
var subDivs = div.getElementsByTagName("DIV");
if (type === "param")
{
subDivs[0].innerHTML = info;
}
else
{
subDivs[1].innerHTML = info;
}
}
},
/* *
* 创建XMLHttpRequest对象的方法。
*
* @private
* @return 返回一个XMLHttpRequest对象
* @type Object
*/
createXMLHttpRequest : function ()
{
var xhr = null;
if (window.ActiveXObject)
{
var versions = ['Microsoft.XMLHTTP', 'MSXML6.XMLHTTP', 'MSXML5.XMLHTTP', 'MSXML4.XMLHTTP', 'MSXML3.XMLHTTP', 'MSXML2.XMLHTTP', 'MSXML.XMLHTTP'];
for (var i = 0; i < versions.length; i ++ )
{
try
{
xhr = new ActiveXObject(versions[i]);
break;
}
catch (ex)
{
continue;
}
}
}
else
{
xhr = new XMLHttpRequest();
}
return xhr;
},
/* *
* 当传输过程发生错误时将调用此方法。
*
* @private
* @param {Object} xhr XMLHttpRequest对象
* @param {String} url HTTP请求的地址
*/
onXMLHttpRequestError : function (xhr, url)
{
throw "URL: " + url + "\n"
+ "readyState: " + xhr.readyState + "\n"
+ "state: " + xhr.status + "\n"
+ "headers: " + xhr.getAllResponseHeaders();
},
/* *
* 对将要发送的参数进行格式化。
*
* @private
* @params {mix} params 将要发送的参数
* @return 返回合法的参数
* @type string
*/
parseParams : function (params)
{
var legalParams = "";
params = params ? params : "";
if (typeof(params) === "string")
{
legalParams = params;
}
else if (typeof(params) === "object")
{
try
{
legalParams = "JSON=" + params.toJSONString();
}
catch (ex)
{
alert("Can't stringify JSON!");
return false;
}
}
else
{
alert("Invalid parameters!");
return false;
}
if (this.debugging.isDebugging)
{
var lf = this.debugging.linefeed,
info = "[Original Parameters]" + lf + params + lf + lf
+ "[Parsed Parameters]" + lf + legalParams;
this.displayDebuggingInfo(info, "param");
}
return legalParams;
},
/* *
* 对返回的HTTP响应结果进行过滤。
*
* @public
* @params {mix} result HTTP响应结果
* @return 返回过滤后的结果
* @type string
*/
preFilter : function (result)
{
return result.replace(/\xEF\xBB\xBF/g, "");
},
/* *
* 对返回的结果进行格式化。
*
* @private
* @return 返回特定格式的数据结果
* @type mix
*/
parseResult : function (responseType, xhr)
{
var result = null;
switch (responseType)
{
case "JSON" :
result = this.preFilter(xhr.responseText);
try
{
result = result.parseJSON();
}
catch (ex)
{
throw this.filename + "/parseResult() error: can't parse to JSON.\n\n" + xhr.responseText;
}
break;
case "XML" :
result = xhr.responseXML;
break;
case "TEXT" :
result = this.preFilter(xhr.responseText);
break;
default :
throw this.filename + "/parseResult() error: unknown response type:" + responseType;
}
if (this.debugging.isDebugging)
{
var lf = this.debugging.linefeed,
info = "[Response Result of " + responseType + " Format]" + lf
+ result;
if (responseType === "JSON")
{
info = "[Response Result of TEXT Format]" + lf
+ xhr.responseText + lf + lf
+ info;
}
this.displayDebuggingInfo(info, "result");
}
return result;
}
};
/* 定义两个别名 */
var Ajax = Transport;
Ajax.call = Transport.run;
/*
json.js
2007-03-06
Public Domain
This file adds these methods to JavaScript:
array.toJSONString()
boolean.toJSONString()
date.toJSONString()
number.toJSONString()
object.toJSONString()
string.toJSONString()
These methods produce a JSON text from a JavaScript value.
It must not contain any cyclical references. Illegal values
will be excluded.
The default conversion for dates is to an ISO string. You can
add a toJSONString method to any date object to get a different
representation.
string.parseJSON(filter)
This method parses a JSON text to produce an object or
array. It can throw a SyntaxError exception.
The optional filter parameter is a function which 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 structure is not modified. If it
returns undefined then the member is deleted.
Example:
// Parse the text. If a key contains the string 'date' then
// convert the value to a date.
myData = text.parseJSON(function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});
It is expected that these methods will formally become part of the
JavaScript Programming Language in the Fourth Edition of the
ECMAScript standard in 2008.
*/
// Augment the basic prototypes if they have not already been augmented.
if ( ! Object.prototype.toJSONString) {
Array.prototype.toJSONString = function () {
var a = ['['], // The array holding the text fragments.
b, // A boolean indicating that a comma is required.
i, // Loop counter.
l = this.length,
v; // The value to be stringified.
function p(s) {
// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.
if (b) {
a.push(',');
}
a.push(s);
b = true;
}
// For each value in this array...
for (i = 0; i < l; i ++) {
v = this[i];
switch (typeof v) {
// Values without a JSON representation are ignored.
case 'undefined':
case 'function':
case 'unknown':
break;
// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.
case 'object':
if (v) {
if (typeof v.toJSONString === 'function') {
p(v.toJSONString());
}
} else {
p("null");
}
break;
// Otherwise, serialize the value.
default:
p(v.toJSONString());
}
}
// Join all of the fragments together and return.
a.push(']');
return a.join('');
};
Boolean.prototype.toJSONString = function () {
return String(this);
};
Date.prototype.toJSONString = function () {
// Ultimately, this method will be equivalent to the date.toISOString method.
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return '"' + this.getFullYear() + '-' +
f(this.getMonth() + 1) + '-' +
f(this.getDate()) + 'T' +
f(this.getHours()) + ':' +
f(this.getMinutes()) + ':' +
f(this.getSeconds()) + '"';
};
Number.prototype.toJSONString = function () {
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(this) ? String(this) : "null";
};
Object.prototype.toJSONString = function () {
var a = ['{'], // The array holding the text fragments.
b, // A boolean indicating that a comma is required.
k, // The current key.
v; // The current value.
function p(s) {
// p accumulates text fragment pairs in an array. It inserts a comma before all
// except the first fragment pair.
if (b) {
a.push(',');
}
a.push(k.toJSONString(), ':', s);
b = true;
}
// Iterate through all of the keys in the object, ignoring the proto chain.
for (k in this) {
if (this.hasOwnProperty(k)) {
v = this[k];
switch (typeof v) {
// Values without a JSON representation are ignored.
case 'undefined':
case 'function':
case 'unknown':
break;
// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.
case 'object':
if (this !== window)
{
if (v) {
if (typeof v.toJSONString === 'function') {
p(v.toJSONString());
}
} else {
p("null");
}
}
break;
default:
p(v.toJSONString());
}
}
}
// Join all of the fragments together and return.
a.push('}');
return a.join('');
};
(function (s) {
// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.
// m is a table of character substitutions.
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
s.parseJSON = function (filter) {
// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.
try {
if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
test(this)) {
// In the second 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.
var j = eval('(' + this + ')');
// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.
if (typeof filter === 'function') {
function walk(k, v) {
if (v && typeof v === 'object') {
for (var i in v) {
if (v.hasOwnProperty(i)) {
v[i] = walk(i, v[i]);
}
}
}
return filter(k, v);
}
j = walk('', j);
}
return j;
}
} catch (e) {
// Fall through if the regexp test fails.
}
throw new SyntaxError("parseJSON");
};
s.toJSONString = function () {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.
// add by weberliu @ 2007-4-2
var _self = this.replace("&", "%26");
if (/["\\\x00-\x1f]/.test(this)) {
return '"' + _self.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + _self + '"';
};
})(String.prototype);
}
Ajax.onRunning = showLoader;
Ajax.onComplete = hideLoader;
/* *
* 显示载入信息
*/
function showLoader()
{
document.getElementsByTagName('body').item(0).style.cursor = "wait";
if (top.frames['header-frame'])
{
top.frames['header-frame'].document.getElementById("load-div").style.display = "block";
}
else
{
var obj = document.getElementById('loader');
if ( ! obj && process_request)
{
obj = document.createElement("DIV");
obj.id = "loader";
obj.innerHTML = process_request;
document.body.appendChild(obj);
}
}
}
/* *
* 隐藏载入信息
*/
function hideLoader()
{
document.getElementsByTagName('body').item(0).style.cursor = "auto";
if (top.frames['header-frame'])
{
setTimeout(function(){top.frames['header-frame'].document.getElementById("load-div").style.display = "none"}, 10);
}
else
{
try
{
var obj = document.getElementById("loader");
obj.style.display = 'none';
document.body.removeChild(obj);
}
catch (ex)
{}
}
}
| JavaScript |
var pos;
var MSIE=navigator.userAgent.indexOf("MSIE");
var Fire=navigator.userAgent.indexOf("Fire");
var OPER=navigator.userAgent.indexOf("Opera");
var bdy = (document.documentElement && document.documentElement.clientWidth)?document.documentElement:document.body;
onscroll = function()
{
if (Fire > 0)
{
pos = window.pageYOffset;
}
else
{
pos = bdy.scrollTop;
}
var ele_top = 100;
document.getElementById('tag_box').style.top = (pos + ele_top) + 'px';
} | JavaScript |
imgUrl1="data/afficheimg/20110323jyqdiw.jpg";
imgtext1="法兰奇商城开业";
imgLink1=escape("http://www.369wine.com");
imgUrl2="data/afficheimg/20110323qnednw.jpg";
imgtext2="团购全新上线";
imgLink2=escape("http://www.369wine.com/vip.php");
imgUrl3="data/afficheimg/20110323ysanjc.jpg";
imgtext3="批发箱售";
imgLink3=escape("http://www.369wine.com");
imgUrl4="data/afficheimg/20110323mxyjar.jpg";
imgtext4="买三送一";
imgLink4=escape("http://www.369wine.com");
imgUrl5="data/afficheimg/20110323kpapdh.jpg";
imgtext5="当月特价";
imgLink5=escape("http://www.369wine.com");
var pics=imgUrl1+"|"+imgUrl2+"|"+imgUrl3+"|"+imgUrl4+"|"+imgUrl5;
var links=imgLink1+"|"+imgLink2+"|"+imgLink3+"|"+imgLink4+"|"+imgLink5;
var texts=imgtext1+"|"+imgtext2+"|"+imgtext3+"|"+imgtext4+"|"+imgtext5; | JavaScript |
/*
Flash Name: Dynamic Focus
Description: 动感聚焦Flash图片轮播
*/
document.write('<div id="flash_cycle_image"></div>');
$importjs = (function()
{
var uid = 0;
var curr = 0;
var remove = function(id)
{
var head = document.getElementsByTagName('head')[0];
head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback)
{
var callback;
var id = ++uid;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src',file);
js.setAttribute('id','jsInclude_'+id);
if( document.all )
{
js.onreadystatechange = function()
{
if(/(complete|loaded)/.test(this.readyState))
{
try
{
callback(id);remove(id);
}
catch(e)
{
setTimeout(function(){remove(id);include_js(file,callback)},2000);
}
}
};
}
else
{
js.onload = function(){callback(id); remove(id); };
}
head.appendChild(js);
return uid;
};
}
)();
function show_flash()
{
var button_pos=4; //按扭位置 1左 2右 3上 4下
var stop_time=3000; //图片停留时间(1000为1秒钟)
var show_text=1; //是否显示文字标签 1显示 0不显示
var txtcolor="000000"; //文字色
var bgcolor="DDDDDD"; //背景色
var text_height = 18;
var focus_width = swf_width;
var focus_height = swf_height - text_height;
var total_height = focus_height + text_height;
document.getElementById('flash_cycle_image').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cabversion=6,0,0,0" width="'+ focus_width +'" height="'+ total_height +'">'+'<param name="movie" value="data/flashdata/dynfocus/dynfocus.swf">'+'<param name="quality" value="high"><param name="wmode" value="opaque">'+'<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&pic_width='+focus_width+'&pic_height='+total_height+'&show_text='+show_text+'&txtcolor='+txtcolor+'&bgcolor='+bgcolor+'&button_pos='+button_pos+'&stop_time='+stop_time+'">'+'<embed src="data/flashdata/dynfocus/dynfocus.swf" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&pic_width='+focus_width+'&pic_height='+total_height+'&show_text='+show_text+'&txtcolor='+txtcolor+'&bgcolor='+bgcolor+'&button_pos='+button_pos+'&stop_time='+stop_time+'" quality="high" width="'+ focus_width +'" height="'+ total_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>'+'</object>';
}
$importjs('data/flashdata/dynfocus/data.js', show_flash); | JavaScript |
imgUrl1="data/afficheimg/20081027angsif.jpg";
imgtext1="ECShop";
imgLink1=escape("http://www.ecshop.com");
imgUrl2="data/afficheimg/20081027xuorxj.jpg";
imgtext2="maifou";
imgLink2=escape("http://www.maifou.net");
imgUrl3="data/afficheimg/20081027wdwd.jpg";
imgtext3="ECShop";
imgLink3=escape("http://www.wdwd.com");
var pics=imgUrl1+"|"+imgUrl2+"|"+imgUrl3;
var links=imgLink1+"|"+imgLink2+"|"+imgLink3;
var texts=imgtext1+"|"+imgtext2+"|"+imgtext3; | JavaScript |
/*
Flash Name: Pink Focus
Description: 粉红聚焦Flash图片轮播
*/
document.write('<div id="flash_cycle_image"></div>');
$importjs = (function()
{
var uid = 0;
var curr = 0;
var remove = function(id)
{
var head = document.getElementsByTagName('head')[0];
head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback)
{
var callback;
var id = ++uid;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src',file);
js.setAttribute('id','jsInclude_'+id);
if( document.all )
{
js.onreadystatechange = function()
{
if(/(complete|loaded)/.test(this.readyState))
{
try
{
callback(id);remove(id);
}
catch(e)
{
setTimeout(function(){remove(id);include_js(file,callback)},2000);
}
}
};
}
else
{
js.onload = function(){callback(id); remove(id); };
}
head.appendChild(js);
return uid;
};
}
)();
function show_flash()
{
var text_height = 0;
var focus_width = swf_width;
var focus_height = swf_height - text_height;
var total_height = focus_height + text_height;
document.getElementById('flash_cycle_image').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ focus_width +'" height="'+ total_height +'">'+'<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="data/flashdata/pinkfocus/pinkfocus.swf"><param name="quality" value="high"><param name="bgcolor" value="#F0F0F0">'+'<param name="menu" value="false"><param name=wmode value="opaque">'+'<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'">'+'<embed src="data/flashdata/pinkfocus/pinkfocus.swf" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'" quality="high" width="'+ focus_width +'" height="'+ total_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>'+'</object>';
}
$importjs('data/flashdata/pinkfocus/data.js', show_flash); | JavaScript |
imgUrl1="data/afficheimg/20081027angsif.jpg";
imgtext1="ECShop";
imgLink1=escape("http://www.ecshop.com");
imgUrl2="data/afficheimg/20081027xuorxj.jpg";
imgtext2="maifou";
imgLink2=escape("http://www.maifou.net");
imgUrl3="data/afficheimg/20081027wdwd.jpg";
imgtext3="ECShop";
imgLink3=escape("http://www.wdwd.com");
var pics=imgUrl1+"|"+imgUrl2+"|"+imgUrl3;
var links=imgLink1+"|"+imgLink2+"|"+imgLink3;
var texts=imgtext1+"|"+imgtext2+"|"+imgtext3; | JavaScript |
/*
Flash Name: Red Focus
Description: 红色聚焦Flash图片轮播
*/
document.write('<div id="flash_cycle_image"></div>');
$importjs = (function()
{
var uid = 0;
var curr = 0;
var remove = function(id)
{
var head = document.getElementsByTagName('head')[0];
head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback)
{
var callback;
var id = ++uid;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src',file);
js.setAttribute('id','jsInclude_'+id);
if( document.all )
{
js.onreadystatechange = function()
{
if(/(complete|loaded)/.test(this.readyState))
{
try
{
callback(id);remove(id);
}
catch(e)
{
setTimeout(function(){remove(id);include_js(file,callback)},2000);
}
}
};
}
else
{
js.onload = function(){callback(id); remove(id); };
}
head.appendChild(js);
return uid;
};
}
)();
function show_flash()
{
var text_height = 0;
var focus_width = swf_width;
var focus_height = swf_height - text_height;
var total_height = focus_height + text_height;
document.getElementById('flash_cycle_image').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ focus_width +'" height="'+ total_height +'">'+'<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="data/flashdata/redfocus/redfocus.swf"><param name="quality" value="high"><param name="bgcolor" value="#F0F0F0">'+'<param name="menu" value="false"><param name=wmode value="opaque">'+'<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'">'+'<embed src="data/flashdata/redfocus/redfocus.swf" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'" quality="high" width="'+ focus_width +'" height="'+ total_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>'+'</object>';
}
$importjs('data/flashdata/redfocus/data.js', show_flash); | JavaScript |
/*
Flash Name: Default
Description: The default flash cycle.
*/
// 0xffffff:文字颜色|1:文字位置|0x0066ff:文字背景颜色|60:文字背景透明度|0xffffff:按键文字颜色|0x0066ff:按键默认颜色|0x000033:按键当前颜色|8:自动播放时间(秒)|2:图片过渡效果|1:是否显示按钮|_blank:打开窗口
var swf_config = "|2|||0xFFFFFF|0xFF6600||4|3|1|_blank"
document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ swf_width +'" height="'+ swf_height +'">');
document.write('<param name="movie" value="data/flashdata/default/bcastr.swf?bcastr_xml_url=data/flashdata/default/data.xml"><param name="quality" value="high">');
document.write('<param name="menu" value="false"><param name=wmode value="opaque">');
document.write('<param name="FlashVars" value="bcastr_config='+swf_config+'">');
document.write('<embed src="data/flashdata/default/bcastr.swf?bcastr_xml_url=data/flashdata/default/data.xml" wmode="opaque" FlashVars="bcastr_config='+swf_config+'" menu="false" quality="high" width="'+ swf_width +'" height="'+ swf_height +'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>');
document.write('</object>'); | JavaScript |
/* $Id : common.js 4824 2007-01-31 08:23:56Z paulgao $ */
/* 检查新订单的时间间隔 */
var NEW_ORDER_INTERVAL = 180000;
/* *
* 开始检查新订单;
*/
function startCheckOrder()
{
checkOrder()
window.setInterval("checkOrder()", NEW_ORDER_INTERVAL);
}
/*
* 检查订单
*/
function checkOrder()
{
var lastCheckOrder = new Date(document.getCookie('ECS_LastCheckOrder'));
var today = new Date();
if (lastCheckOrder == null || today-lastCheckOrder >= NEW_ORDER_INTERVAL)
{
document.setCookie('ECS_LastCheckOrder', today.toGMTString());
try
{
Ajax.call('index.php?is_ajax=1&act=check_order','', checkOrderResponse, 'GET', 'JSON');
}
catch (e) { }
}
}
/* *
* 处理检查订单的反馈信息
*/
function checkOrderResponse(result)
{
//出错屏蔽
if (result.error != 0 || (result.new_orders == 0 && result.new_paid == 0))
{
return;
}
try
{
document.getElementById('spanNewOrder').innerHTML = result.new_orders;
document.getElementById('spanNewPaid').innerHTML = result.new_paid;
Message.show();
}
catch (e) { }
}
/**
* 确认后跳转到指定的URL
*/
function confirm_redirect(msg, url)
{
if (confirm(msg))
{
location.href=url;
}
}
/* *
* 设置页面宽度
*/
function set_size(w)
{
var y_width = document.body.clientWidth
var s_width = screen.width
var agent = navigator.userAgent.toLowerCase();
if (y_width < w)
{
if (agent.indexOf("msie") != - 1)
{
document.body.style.width = w + "px";
}
else
{
document.getElementById("bd").style.width = (w - 10) + 'px';
}
}
}
/* *
* 显示隐藏图片
* @param id div的id
* @param show | hide
*/
function showImg(id, act)
{
if (act == 'show')
{
document.getElementById(id).style.visibility = 'visible';
}
else
{
document.getElementById(id).style.visibility = 'hidden';
}
}
/*
* 气泡式提示信息
*/
var Message = Object();
Message.bottom = 0;
Message.count = 0;
Message.elem = "popMsg";
Message.mvTimer = null;
Message.show = function()
{
try
{
Message.controlSound('msgBeep');
document.getElementById(Message.elem).style.visibility = "visible"
document.getElementById(Message.elem).style.display = "block"
Message.bottom = 0 - parseInt(document.getElementById(Message.elem).offsetHeight);
Message.mvTimer = window.setInterval("Message.move()", 10);
document.getElementById(Message.elem).style.bottom = Message.bottom + "px";
}
catch (e)
{
alert(e);
}
}
Message.move = function()
{
try
{
if (Message.bottom == 0)
{
window.clearInterval(Message.mvTimer)
Message.mvTimer = window.setInterval("Message.close()", 10000)
}
Message.bottom ++ ;
document.getElementById(Message.elem).style.bottom = Message.bottom + "px";
}
catch (e)
{
alert(e);
}
}
Message.close = function()
{
document.getElementById(Message.elem).style.visibility = 'hidden';
document.getElementById(Message.elem).style.display = 'none';
if (Message.mvTimer) window.clearInterval(Message.mvTimer)
}
Message.controlSound = function(_sndObj)
{
sndObj = document.getElementById(_sndObj);
try
{
sndObj.Play();
}
catch (e) { }
}
var listZone = new Object();
/* *
* 显示正在载入
*/
listZone.showLoader = function()
{
listZone.toggleLoader(true);
}
listZone.hideLoader = function()
{
listZone.toggleLoader(false);
}
listZone.toggleLoader = function(disp)
{
document.getElementsByTagName('body').item(0).style.cursor = (disp) ? "wait" : 'auto';
try
{
var doc = top.frames['header-frame'].document;
var loader = doc.getElementById("load-div");
if (typeof loader == 'object') loader.style.display = disp ? "block" : "none";
}
catch (ex) { }
}
function $import(path,type,title){
var s,i;
if(type == "js"){
var ss = document.getElementsByTagName("script");
for(i =0;i < ss.length; i++)
{
if(ss[i].src && ss[i].src.indexOf(path) != -1)return ss[i];
}
s = document.createElement("script");
s.type = "text/javascript";
s.src =path;
}
else if(type == "css")
{
var ls = document.getElementsByTagName("link");
for(i = 0; i < ls.length; i++)
{
if(ls[i].href && ls[i].href.indexOf(path)!=-1)return ls[i];
}
s = document.createElement("link");
s.rel = "alternate stylesheet";
s.type = "text/css";
s.href = path;
s.title = title;
s.disabled = false;
}
else return;
var head = document.getElementsByTagName("head")[0];
head.appendChild(s);
return s;
}
/**
* 返回随机数字符串
*
* @param : prefix 前缀字符
*
* @return : string
*/
function rand_str(prefix)
{
var dd = new Date();
var tt = dd.getTime();
tt = prefix + tt;
var rand = Math.random();
rand = Math.floor(rand * 100);
return (tt + rand);
} | JavaScript |
/**
* 标签上鼠标移动事件的处理函数
* @return
*/
document.getElementById("tabbar-div").onmouseover = function(e)
{
var obj = Utils.srcElement(e);
if (obj.className == "tab-back")
{
obj.className = "tab-hover";
}
}
document.getElementById("tabbar-div").onmouseout = function(e)
{
var obj = Utils.srcElement(e);
if (obj.className == "tab-hover")
{
obj.className = "tab-back";
}
}
/**
* 处理点击标签的事件的函数
* @param : e FireFox 事件句柄
*
* @return
*/
document.getElementById("tabbar-div").onclick = function(e)
{
var obj = Utils.srcElement(e);
if (obj.className == "tab-front" || obj.className == '' || obj.tagName.toLowerCase() != 'span')
{
return;
}
else
{
objTable = obj.id.substring(0, obj.id.lastIndexOf("-")) + "-table";
var tables = document.getElementsByTagName("table");
var spans = document.getElementsByTagName("span");
for (i = 0; i < tables.length; i ++ )
{
if (tables[i].id == objTable)
{
tables[i].style.display = (Browser.isIE) ? "block" : "table";
}
else
{
var tblId = tables[i].id.match(/-table$/);
if (tblId == "-table")
{
tables[i].style.display = "none";
}
}
}
for (i = 0; spans.length; i ++ )
{
if (spans[i].className == "tab-front")
{
spans[i].className = "tab-back";
obj.className = "tab-front";
break;
}
}
}
}
| JavaScript |
var Todolist = Class.create();
Todolist.prototype = {
initialize:function(adminid)
{
this.box = $ce("DIV");
this.container = $ce("DIV");
this.head = $ce("DIV");
this.buttons = $ce("DIV");
this.middle = $ce("DIV");
this.bottom = $ce("DIV");
this.bottomLeft = $ce("DIV");
this.virtualBox = $ce("DIV");
this.bottomRight = $ce("DIV");
this.minBtn = $ce("IMG");
this.closeBtn = $ce("IMG");
this.saveBtn = $ce("INPUT");
this.clearBtn = $ce("INPUT");
this.textBox = $ce("TEXTAREA");
this.tempFun = new Object();
this.tempFun.draging = this.draging.bind(this);
this.tempFun.startDrag = this.startDrag.bind(this);
this.tempFun.endDrag = this.endDrag.bind(this);
this.tempFun.startSetSize = this.startSetSize.bind(this)
this.tempFun.setSize = this.setSize.bind(this);
this.tempFun.endSetSize = this.endSetSize.bind(this);
this.tempFun.save = this.save.bind(this);
this.myTimer;
this.lastContentHash;
var self = this;
this.innerWidth = Math.min(document.body.scrollWidth, self.innerWidth||document.body.clientWidth);
if (window.self.innerHeight)
{
this.innerHeight = Math.max(window.self.innerHeight,document.body.scrollHeight);
}
else
{
if (document.documentElement && document.documentElement.clientHeight)
{
this.innerHeight = Math.max(document.documentElement.clientHeight,document.documentElement.scrollHeight);
}
else if (document.body)
{
this.innerHeight = Math.max(document.body.clientHeight,document.body.scrollHeight);
}
}
this.md5 = hex_md5;
this.adminid = adminid;
this.closeBtn.src = "images/btn_close.gif";
this.closeBtn.onclick = this.close.bind(this);
this.minBtn.src = "images/btn_minimize.gif";
this.minBtn.onclick = function()
{
if (self.Maxed)
{
self.toMin();
}
else
{
self.toMax()
}
}
this.buttons.className = "buttons";
this.buttons.appendChild(this.minBtn);
this.buttons.appendChild(this.closeBtn);
this.head.className = "head";
this.head.style.cursor = "move";
this.head.innerHTML = todolist_caption ;
this.head.appendChild(this.buttons);
this.textBox.style.height = "100px";
this.textBox.style.width = "293px";
this.clearBtn.type = "button"
this.clearBtn.value = todolist_clear;
this.clearBtn.className = "button";
this.clearBtn.onclick = this.clear.bind(this);
this.saveBtn.type = "button";
this.saveBtn.value = todolist_save;
this.saveBtn.className = "button";
this.saveBtn.onclick = this.save.bind(this);
this.bottom.className = "bottom";
this.bottomLeft.className = "bottomLeft";
this.bottomLeft.innerHTML += "<label><input type=\"checkbox\" value=\"1\" name=\"remember\" />" + todolist_autosave + "</label>"
this.bottomLeft.appendChild(this.saveBtn);
this.bottomLeft.appendChild(this.clearBtn);
this.bottom.appendChild(this.bottomLeft);
this.bottom.appendChild(this.bottomRight);
this.middle.className = "middle";
this.middle.appendChild(this.textBox);
this.container.className = "container"
this.container.appendChild(this.head);
this.container.appendChild(this.middle);
this.container.appendChild(this.bottom);
this.box.className = "todolist-box";
this.box.style.height = "auto";
this.box.style.left = "1px";
this.box.style.top = "1px";
this.box.style.display = "none";
this.box.appendChild(this.container);
this.autoSaveCheckbox = this.bottomLeft.getElementsByTagName('input')[0];
this.autoSaveCheckbox.checked = document.getCookie("todolist_notautosave_" + this.adminid) == null ? true : false;
if (this.autoSaveCheckbox.checked)
{
this.autoSave();
}
this.bottomRight.className = "bottomRight";
this.bottomRight.style.cursor = "se-resize";
this.virtualBox.style.display = "none";
this.virtualBox.className = "virtualBox";
document.body.appendChild(this.box);
document.body.appendChild(this.virtualBox);
this.LastX = 0;
this.LastY = 0;
this.LastLeft = 0;
this.LastTop = 0;
this.moveing = false;
this.visibility = false;
this.Maxed = true;
Event.observe(this.head, "selectstart", this.falseFunction);
Event.observe(this.head, "mousedown", this.tempFun.startDrag);
Event.observe(this.bottomRight, "mousedown", this.tempFun.startSetSize);
Event.observe(this.autoSaveCheckbox, "click", this.autoSave.bind(this));
window.onbeforeunload = function()
{
if (self.lastContentHash == self.md5(self.textBox.value)) return;
if (confirm(todolist_confirm_save))
{
Ajax.call('index.php?is_ajax=1&act=save_todolist', 'content=' + encodeURIComponent(self.textBox.value), null, 'POST', 'TEXT', false);
}
}
this.head.ondblclick = function()
{
if (!self.Maxed)
self.toMax();
else
self.toMin();
return false;
}
var posObj = document.getCookie("todolist_position_" + this.adminid);
if (posObj != null)
{
posObj = eval(posObj);
this.box.style.left = posObj.X;
this.box.style.top = posObj.Y;
}
this.loadData.call(this);
},
loadData : function()
{
Ajax.call('index.php?is_ajax=1&act=get_todolist', '' , this.loadDataResponse.bind(this) , 'POST', 'TEXT');
},
loadDataResponse : function(result)
{
this.textBox.value = result;
this.lastContentHash = this.md5(this.textBox.value);
},
startDrag : function(event)
{
Event.observe(document.body, "selectstart", this.falseFunction);
Event.observe(document, "mousemove", this.tempFun.draging);
Event.observe(document, "mouseup", this.tempFun.endDrag);
var element = Event.element(event||window.event);
this.LastX = Event.pointerX(event||window.event);
this.LastY = Event.pointerY(event||window.event);
this.LastLeft = this.box.style.left;
this.LastTop = this.box.style.top;
},
draging : function(event)
{
var X = Event.pointerX(event||window.event);
var Y = Event.pointerY(event||window.event);
var tX = parseInt(this.LastLeft) + X - this.LastX;
var tY = parseInt(this.LastTop) + Y - this.LastY;
if (tX <= 0)
{
tX = 0;
}
if (tY <= 0)
{
tY = 0;
}
if ((tX + parseInt(this.box.offsetWidth)) >= parseInt(this.innerWidth))
{
tX = parseInt(this.innerWidth) - parseInt(this.box.offsetWidth);
}
if ((tY + parseInt(this.box.offsetHeight)) >= parseInt(this.innerHeight))
{
tY = parseInt(this.innerHeight) - parseInt(this.box.offsetHeight);
}
this.box.style.left = tX + "px";
this.box.style.top = tY + "px";
},
endDrag : function()
{
var date = new Date();
date.setTime(date.getTime() + 99999999);
document.setCookie("todolist_position_" + this.adminid, "({X:'" + this.box.style.left + "',Y:'" + this.box.style.top + "'})", date.toGMTString());
Event.stopObserving(document.body, "selectstart", this.falseFunction);
Event.stopObserving(document, "mousemove", this.tempFun.draging);
Event.stopObserving(document, "mouseup", this.tempFun.endDrag);
},
toMax : function()
{
this.middle.style.display = "";
this.bottom.style.display = "";
this.Maxed = true;
this.minBtn.src = "images/btn_minimize.gif";
},
toMin : function()
{
this.middle.style.display = "none";
this.bottom.style.display = "none";
this.box.style.height = "";
this.Maxed = false;
this.minBtn.src = "images/btn_maximize.gif";
},
show : function()
{
this.loadData();
this.box.style.display = "";
if (Browser.isFirefox)
{
this.middle.style.paddingRight = "5px";
}
if (parseInt(this.box.style.top) + parseInt(this.box.offsetHeight) > this.innerHeight)
{
var top = this.innerHeight - this.box.offsetHeight;
this.box.style.top = top + "px";
}
if (parseInt(this.box.style.top) <= 0)
{
this.box.style.top = "1px";
}
this.visibility = true;
},
hide : function()
{
this.box.style.display = "none";
this.visibility = false;
},
falseFunction : function()
{
return false;
},
startSetSize : function(event)
{
var pos = Event.position(this.box);
this.virtualBox.style.display = "";
this.virtualBox.style.top = pos.top + "px";
this.virtualBox.style.left = pos.left + "px";
this.virtualBox.style.height = this.box.offsetHeight + "px";
this.virtualBox.style.width = this.box.offsetWidth + "px";
document.body.style.cursor = "se-resize";
Event.observe(document, "mousemove", this.tempFun.setSize);
Event.observe(document, "mouseup", this.tempFun.endSetSize);
Event.observe(document.body, "selectstart", this.falseFunction);
},
setSize : function(event)
{
var pos = Event.position(this.box);
var tX = Event.pointerX(event||window.event);
var tY = Event.pointerY(event||window.event);
var height = tY - (parseInt(pos.top) - this.box.offsetHeight) - parseInt(this.box.offsetHeight);
var width = tX - (parseInt(pos.left) - this.box.offsetWidth) - parseInt(this.box.offsetWidth);
if (height >= 95)
this.virtualBox.style.height = height + "px";
if (width >= 301)
this.virtualBox.style.width = width + "px";
},
endSetSize : function(event)
{
Event.stopObserving(document,"mousemove",this.tempFun.setSize);
Event.stopObserving(document,"mouseup",this.tempFun.endSetSize);
Event.stopObserving(document.body,"selectstart",this.falseFunction);
document.body.style.cursor='';
if (parseInt(this.virtualBox.style.height) >= 95)
{
this.box.style.height = this.virtualBox.style.height ;
}
if (parseInt(this.virtualBox.style.width) >= 301)
{
this.box.style.width = this.virtualBox.style.width;
}
this.textBox.style.width = parseInt(this.box.style.width) - 7 + "px";
this.textBox.style.height = parseInt(this.box.style.height) - parseInt(this.head.offsetHeight) - parseInt(this.bottom.offsetHeight) + "px";
if (this.container.offsetHeight > this.box.offsetHeight)
{
var span = this.container.offsetHeight - this.box.offsetHeight;
this.textBox.style.height = parseInt(this.textBox.style.height) - span - 4 + "px";
}
this.virtualBox.style.display = "none";
},
save : function()
{
if (this.lastContentHash == this.md5(this.textBox.value)) return false;
this.saveBtn.disabled = true;
this.clearBtn.disabled = true;
this.textBox.disabled = true;
var content = encodeURIComponent(this.textBox.value);
var self = this;
Ajax.call('index.php?is_ajax=1&act=save_todolist', 'content=' + content, function(result)
{
self.saveBtn.disabled = false;
self.textBox.disabled = false;
self.clearBtn.disabled = false;
self.lastContentHash = self.md5(self.textBox.value);
}, 'POST', 'TEXT');
},
autoSave : function()
{
if (this.autoSaveCheckbox.checked)
{
document.removeCookie("todolist_notautosave_" + this.adminid);
this.myTimer = window.setInterval(this.save.bind(this), 60000);
Event.observe(this.textBox, "blur", this.tempFun.save);
}
else
{
Event.stopObserving(this.textBox, "blur", this.tempFun.save);
var date = new Date();
date.setTime(date.getTime() + 99999999);
document.setCookie("todolist_notautosave_" + this.adminid, "1", date.toGMTString());
window.clearInterval(this.myTimer);
this.myTimer = false;
}
},
close : function()
{
if (this.lastContentHash != this.md5(this.textBox.value))
{
if (!this.autoSaveCheckbox.checked)
{
if (confirm(todolist_confirm_save))
{
this.save();
}
}
}
this.hide()
},
clear : function()
{
if (confirm(todolist_confirm_clear))
{
this.textBox.value = "";
}
}
} | JavaScript |
var ColorSelecter = new Object();
ColorSelecter.Show = function(sender)
{
if(ColorSelecter.box)
{
if (ColorSelecter.box.style.display = "none")
ColorSelecter.box.style.display = "";
}
else
{
ColorSelecter.box = document.createElement("Div");
ColorSelecter.box.id = "ColorSelectertBox";
var table = "<table width='93' border='1' cellpadding='0' cellspacing='0' bordercolor='#BDBBBC' style='border:2px #C5D9FE solid'><tr><td bgcolor='#FFFFFF'> </td><td bgcolor='#C0C0C0'> </td><td bgcolor='#969696'> </td><td bgcolor='#808080'> </td><td bgcolor='#333333'> </td></tr><tr><td bgcolor='#CC99FE'> </td><td bgcolor='#993365'> </td><td bgcolor='#81007F'> </td><td bgcolor='#6766CC'> </td><td bgcolor='#343399'> </td></tr><tr><td bgcolor='#BBBBBB'> </td><td bgcolor='#00CCFF'> </td><td bgcolor='#3366FF'> </td><td bgcolor='#0000FE'> </td><td bgcolor='#010080'> </td></tr><tr><td bgcolor='#CDFFFF'> </td><td bgcolor='#01FFFF'> </td><td bgcolor='#33CBCC'> </td><td bgcolor='#008081'> </td><td bgcolor='#003265'> </td></tr><tr><td bgcolor='#CDFFCC'> </td><td bgcolor='#00FF01'> </td><td bgcolor='#339967'> </td><td bgcolor='#008002'> </td><td bgcolor='#013300'> </td></tr><tr><td bgcolor='#FFFE99'> </td><td bgcolor='#FFFE03'> </td><td bgcolor='#99CD00'> </td><td bgcolor='#807F01'> </td><td bgcolor='#333301'> </td></tr><tr><td bgcolor='#FFCB99'> </td><td bgcolor='#FFCD00'> </td><td bgcolor='#FF9900'> </td><td bgcolor='#FD6600'> </td><td bgcolor='#993400'> </td></tr><tr><td bgcolor='#FF99CB'> </td><td bgcolor='#FF00FE'> </td><td bgcolor='#FE0000'> </td><td bgcolor='#800000'> </td><td bgcolor='#000000'> </td></tr><tr><td align='center' colspan='5'><font style='cursor:default'>" + cancel_color + "</font></td></tr></table>";
ColorSelecter.box.innerHTML = table;
document.body.appendChild(ColorSelecter.box);
var myTable = ColorSelecter.box.childNodes[0];
for (var i = 0; i<myTable.rows.length; i++)
{
for (var j = 0; j < myTable.rows[i].cells.length; j++)
{
myTable.rows[i].cells[j].style.border = "#BDBBBC 1px solid";
myTable.rows[i].cells[j].onmousemove = function()
{
this.style.border = "#fff 1px solid";
}
myTable.rows[i].cells[j].onmouseout = function()
{
this.style.border = "#BDBBBC 1px solid";
}
myTable.rows[i].cells[j].onmousedown = function()
{
document.getElementById("font_color").style.backgroundColor = this.bgColor;
document.getElementById("goods_name_color").value = this.bgColor;
document.getElementsByName("goods_name").item(0).style.color = this.bgColor;
ColorSelecter.box.style.display = "none";
}
}
}
}
var pos = getPosition(sender);
ColorSelecter.box.style.top = pos.top + 18 + "px";
ColorSelecter.box.style.left = pos.left + "px";
document.onmousedown = function()
{
ColorSelecter.box.style.display = "none";
}
}
| JavaScript |
var persistclose = 0 // set to 0 or 1. 1 means once the bar is manually closed, it will remain closed for browser session
var startX = 3 // set x offset of bar in pixels
var startY = 3 // set y offset of bar in pixels
function iecompattest()
{
return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}
function get_cookie(Name)
{
var search = Name + "="
var returnvalue = "";
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;
}
returnvalue = unescape(document.cookie.substring(offset, end));
}
}
return returnvalue;
}
var verticalpos = "fromtop";
function closebar()
{
if (persistclose)
{
document.cookie = "remainclosed=1";
}
document.getElementById("topbar").style.visibility = "hidden";
}
function staticbar()
{
var ns = (navigator.appName.indexOf("Netscape") != - 1);
var d = document;
function ml(id)
{
var el = d.getElementById(id);
if ( ! persistclose || persistclose && get_cookie("remainclosed") == "")
{
el.style.visibility = "visible";
}
if (d.layers)
{
el.style = el;
}
el.sP = function(x, y)
{
this.style.left = x + "px";
this.style.top = y + "px";
}
;
el.x = startX;
if (verticalpos == "fromtop")
{
el.y = startY;
}
else
{
el.y = ns ? pageYOffset + innerHeight : iecompattest().scrollTop + iecompattest().clientHeight;
el.y -= startY;
}
return el;
}
window.stayTopLeft = function()
{
if (verticalpos == "fromtop")
{
var pY = ns ? pageYOffset : iecompattest().scrollTop;
ftlObj.y += (pY + startY - ftlObj.y) / 8;
}
else
{
var pY = ns ? pageYOffset + innerHeight : iecompattest().scrollTop + iecompattest().clientHeight;
ftlObj.y += (pY - startY - ftlObj.y) / 8;
}
ftlObj.sP(ftlObj.x, ftlObj.y);
setTimeout("stayTopLeft()", 10);
}
ftlObj = ml("topbar");
stayTopLeft();
}
| JavaScript |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
| JavaScript |
var SelectBox = Class.create();
SelectBox.prototype = {
initialize:function (src, dst)
{
this.dst_options = new Array();
this.src_obj = document.getElementById(src);
this.dst_obj = document.getElementById(dst);
this.copy_method = (typeof (arguments[2]) != 'undefined')?true:false;
},
addItem:function ()
{
var all = (typeof (arguments[0]) != 'undefined')?arguments[0]:false;
var src_options = this.fetch_options(this.src_obj, all);
if (src_options.length > 0)
{
this.copy_options(this.dst_obj, src_options);
}
},
delItem:function ()
{
var all = (typeof (arguments[0]) != 'undefined')?arguments[0]:false;
var dst_options = this.fetch_options(this.dst_obj, all);
if (dst_options.length > 0)
{
this.del_options(this.dst_obj, dst_options);
}
},
moveItem:function (direction)
{
var dst_options = this.fetch_options(this.dst_obj);
var insert_position = new Object;
if (direction == 'up')
{
if (dst_options[0] === this.dst_obj.options[0])
{
return;
}
insert_position = dst_options[0].previousSibling;
}
else
{
if (dst_options[dst_options.length-1] === this.dst_obj.options[this.dst_obj.options.length-1])
{
return;
}
insert_position = dst_options[dst_options.length-1].nextSibling.nextSibling;
}
this.move_options(this.dst_obj, insert_position, dst_options);
},
fetch_options:function (o)
{
var sel_options = [];
var c = 0;
var all = (typeof (arguments[1]) != 'undefined')?arguments[1]:false;
for (var i=0,l=o.options.length; i<l; i++)
{
if (all === false)
{
if (o.options[i].selected)
{
sel_options[c++] = o.options[i];
}
}
else
{
sel_options[c++] = o.options[i];
}
}
return sel_options;
},
del_options:function (o, arr)
{
for (var i=0,l=arr.length; i<l; i++)
{
if (this.copy_method === false)
{
o.removeChild(arr[i]);
}
else
{
this.src_obj.appendChild(arr[i]);
}
this.dst_options = this.delete_array(arr[i].value, this.dst_options);
}
},
copy_options:function (o, arr)
{
for (var i=0,l=arr.length; i<l; i++)
{
if (!this.in_array(arr[i].value, this.dst_options))
{
if (this.copy_method === false)
{
new_opt = this.clone_option(arr[i]);
}
else
{
new_opt = arr[i];
}
o.appendChild(new_opt);
this.dst_options[this.dst_options.length] = arr[i].value;
}
}
},
move_options:function (o, p, arr)
{
for (var i=0,l=arr.length; i<l; i++)
{
o.insertBefore(arr[i], p);
}
},
clone_option:function (o)
{
var new_opt = document.createElement('OPTION');
new_opt.value = o.value;
new_opt.innerHTML = o.innerHTML;
return new_opt;
},
in_array:function (elem, array)
{
var re = new RegExp('\\\|' + elem + '\\\|');
return re.test('|' + array.join('|') + '|');
},
delete_array:function (elem, array)
{
var re = new RegExp( elem + '\\\|');
var _str = (array.join('|') + '|').replace(re, '');
return _str.split('|');
}
} | JavaScript |
/* *
* ECSHOP 表单验证类
* ============================================================================
* 版权所有 (C) 2005-2007 康盛创想(北京)科技有限公司,并保留所有权利。
* 网站地址 : http : // www.ecshop.com
* ----------------------------------------------------------------------------
* 这是一个免费开源的软件;这意味着您可以在不用于商业目的的前提下对程序代码
* 进行修改和再发布。
* ============================================================================
* $Author : paulgao $
* $Date : 2007-01-31 16:23:56 +0800 (星期三, 31 一月 2007) $
* $Id : validator.js 4824 2007-01-31 08:23:56Z paulgao $
*//* *
* 表单验证类
*
* @author : weber liu
* @version : v1.1
*/
var Validator = function(name)
{
this.formName = name;
this.errMsg = new Array();
/* *
* 检查用户是否输入了内容
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
*/
this.required = function(controlId, msg)
{
var obj = document.forms[this.formName].elements[controlId];
if (typeof(obj) == "undefined" || Utils.trim(obj.value) == "")
{
this.addErrorMsg(msg);
}
}
;
/* *
* 检查用户输入的是否为合法的邮件地址
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isEmail = function(controlId, msg, required)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if ( ! required && obj.value == '')
{
return;
}
if ( ! Utils.isEmail(obj.value))
{
this.addErrorMsg(msg);
}
}
/* *
* 检查两个表单元素的值是否相等
*
* @param : fstControl 表单元素的ID
* @param : sndControl 表单元素的ID
* @param : msg 错误提示信息
*/
this.eqaul = function(fstControl, sndControl, msg)
{
var fstObj = document.forms[this.formName].elements[fstControl];
var sndObj = document.forms[this.formName].elements[sndControl];
if (fstObj != null && sndObj != null)
{
if (fstObj.value == '' || fstObj.value != sndObj.value)
{
this.addErrorMsg(msg);
}
}
}
/* *
* 检查前一个表单元素是否大于后一个表单元素
*
* @param : fstControl 表单元素的ID
* @param : sndControl 表单元素的ID
* @param : msg 错误提示信息
*/
this.gt = function(fstControl, sndControl, msg)
{
var fstObj = document.forms[this.formName].elements[fstControl];
var sndObj = document.forms[this.formName].elements[sndControl];
if (fstObj != null && sndObj != null) {
if (Utils.isNumber(fstObj.value) && Utils.isNumber(sndObj.value)) {
var v1 = parseFloat(fstObj.value) + 0;
var v2 = parseFloat(sndObj.value) + 0;
} else {
var v1 = fstObj.value;
var v2 = sndObj.value;
}
if (v1 <= v2) this.addErrorMsg(msg);
}
}
/* *
* 检查输入的内容是否是一个数字
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isNumber = function(controlId, msg, required)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if (obj.value == '' && ! required)
{
return;
}
else
{
if ( ! Utils.isNumber(obj.value))
{
this.addErrorMsg(msg);
}
}
}
/* *
* 检查输入的内容是否是一个整数
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isInt = function(controlId, msg, required)
{
if (document.forms[this.formName].elements[controlId])
{
var obj = document.forms[this.formName].elements[controlId];
}
else
{
return;
}
obj.value = Utils.trim(obj.value);
if (obj.value == '' && ! required)
{
return;
}
else
{
if ( ! Utils.isInt(obj.value)) this.addErrorMsg(msg);
}
}
/* *
* 检查输入的内容是否是为空
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isNullOption = function(controlId, msg)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if (obj.value > '0' )
{
return;
}
else
{
this.addErrorMsg(msg);
}
}
/* *
* 检查输入的内容是否是"2006-11-12 12:00:00"格式
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isTime = function(controlId, msg, required)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if (obj.value == '' && ! required)
{
return;
}
else
{
if ( ! Utils.isTime(obj.value)) this.addErrorMsg(msg);
}
}
/* *
* 检查前一个表单元素是否小于后一个表单元素(日期判断)
*
* @param : controlIdStart 表单元素的ID
* @param : controlIdEnd 表单元素的ID
* @param : msg 错误提示信息
*/
this.islt = function(controlIdStart, controlIdEnd, msg)
{
var start = document.forms[this.formName].elements[controlIdStart];
var end = document.forms[this.formName].elements[controlIdEnd];
start.value = Utils.trim(start.value);
end.value = Utils.trim(end.value);
if(start.value <= end.value)
{
return;
}
else
{
this.addErrorMsg(msg);
}
}
/* *
* 检查指定的checkbox是否选定
*
* @param : controlId 表单元素的name
* @param : msg 错误提示信息
*/
this.requiredCheckbox = function(chk, msg)
{
var obj = document.forms[this.formName].elements[controlId];
var checked = false;
for (var i = 0; i < objects.length; i ++ )
{
if (objects[i].type.toLowerCase() != "checkbox") continue;
if (objects[i].checked)
{
checked = true;
break;
}
}
if ( ! checked) this.addErrorMsg(msg);
}
this.passed = function()
{
if (this.errMsg.length > 0)
{
var msg = "";
for (i = 0; i < this.errMsg.length; i ++ )
{
msg += "- " + this.errMsg[i] + "\n";
}
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 增加一个错误信息
*
* @param : str
*/
this.addErrorMsg = function(str)
{
this.errMsg.push(str);
}
}
/* *
* 帮助信息的显隐函数
*/
function showNotice(objId)
{
var obj = document.getElementById(objId);
if (obj)
{
if (obj.style.display != "block")
{
obj.style.display = "block";
}
else
{
obj.style.display = "none";
}
}
}
/* *
* add one option of a select to another select.
*
* @author Chunsheng Wang < wwccss@263.net >
*/
function addItem(src, dst)
{
for (var x = 0; x < src.length; x ++ )
{
var opt = src.options[x];
if (opt.selected && opt.value != '')
{
var newOpt = opt.cloneNode(true);
newOpt.className = '';
newOpt.text = newOpt.innerHTML.replace(/^\s+|\s+$| /g, '');
dst.appendChild(newOpt);
}
}
src.selectedIndex = -1;
}
/* *
* move one selected option from a select.
*
* @author Chunsheng Wang < wwccss@263.net >
*/
function delItem(ItemList)
{
for (var x = ItemList.length - 1; x >= 0; x -- )
{
var opt = ItemList.options[x];
if (opt.selected)
{
ItemList.options[x] = null;
}
}
}
/* *
* join items of an select with ",".
*
* @author Chunsheng Wang < wwccss@263.net >
*/
function joinItem(ItemList)
{
var OptionList = new Array();
for (var i = 0; i < ItemList.length; i ++ )
{
OptionList[OptionList.length] = ItemList.options[i].text + "|" + ItemList.options[i].value;
}
return OptionList.join(",");
}
| JavaScript |
/* $Id: listtable.js 14980 2008-10-22 05:01:19Z testyang $ */
if (typeof Ajax != 'object')
{
alert('Ajax object doesn\'t exists.');
}
if (typeof Utils != 'object')
{
alert('Utils object doesn\'t exists.');
}
var listTable = new Object;
listTable.query = "query";
listTable.filter = new Object;
listTable.url = location.href.lastIndexOf("?") == -1 ? location.href.substring((location.href.lastIndexOf("/")) + 1) : location.href.substring((location.href.lastIndexOf("/")) + 1, location.href.lastIndexOf("?"));
listTable.url += "?is_ajax=1";
/**
* 创建一个可编辑区
*/
listTable.edit = function(obj, act, id)
{
var tag = obj.firstChild.tagName;
if (typeof(tag) != "undefined" && tag.toLowerCase() == "input")
{
return;
}
/* 保存原始的内容 */
var org = obj.innerHTML;
var val = Browser.isIE ? obj.innerText : obj.textContent;
/* 创建一个输入框 */
var txt = document.createElement("INPUT");
txt.value = (val == 'N/A') ? '' : val;
txt.style.width = (obj.offsetWidth + 12) + "px" ;
/* 隐藏对象中的内容,并将输入框加入到对象中 */
obj.innerHTML = "";
obj.appendChild(txt);
txt.focus();
/* 编辑区输入事件处理函数 */
txt.onkeypress = function(e)
{
var evt = Utils.fixEvent(e);
var obj = Utils.srcElement(e);
if (evt.keyCode == 13)
{
obj.blur();
return false;
}
if (evt.keyCode == 27)
{
obj.parentNode.innerHTML = org;
}
}
/* 编辑区失去焦点的处理函数 */
txt.onblur = function(e)
{
if (Utils.trim(txt.value).length > 0)
{
res = Ajax.call(listTable.url, "act="+act+"&val=" + encodeURIComponent(Utils.trim(txt.value)) + "&id=" +id, null, "POST", "JSON", false);
if (res.message)
{
alert(res.message);
}
if(res.id && (res.act == 'goods_auto' || res.act == 'article_auto'))
{
document.getElementById('del'+res.id).innerHTML = "<a href=\""+ thisfile +"?goods_id="+ res.id +"&act=del\" onclick=\"return confirm('"+deleteck+"');\">"+deleteid+"</a>";
}
obj.innerHTML = (res.error == 0) ? res.content : org;
}
else
{
obj.innerHTML = org;
}
}
}
/**
* 切换状态
*/
listTable.toggle = function(obj, act, id)
{
var val = (obj.src.match(/yes.gif/i)) ? 0 : 1;
var res = Ajax.call(this.url, "act="+act+"&val=" + val + "&id=" +id, null, "POST", "JSON", false);
if (res.message)
{
alert(res.message);
}
if (res.error == 0)
{
obj.src = (res.content > 0) ? 'images/yes.gif' : 'images/no.gif';
}
}
/**
* 切换排序方式
*/
listTable.sort = function(sort_by, sort_order)
{
var args = "act="+this.query+"&sort_by="+sort_by+"&sort_order=";
if (this.filter.sort_by == sort_by)
{
args += this.filter.sort_order == "DESC" ? "ASC" : "DESC";
}
else
{
args += "DESC";
}
for (var i in this.filter)
{
if (typeof(this.filter[i]) != "function" &&
i != "sort_order" && i != "sort_by" && !Utils.isEmpty(this.filter[i]))
{
args += "&" + i + "=" + this.filter[i];
}
}
this.filter['page_size'] = this.getPageSize();
Ajax.call(this.url, args, this.listCallback, "POST", "JSON");
}
/**
* 翻页
*/
listTable.gotoPage = function(page)
{
if (page != null) this.filter['page'] = page;
if (this.filter['page'] > this.pageCount) this.filter['page'] = 1;
this.filter['page_size'] = this.getPageSize();
this.loadList();
}
/**
* 载入列表
*/
listTable.loadList = function()
{
var args = "act="+this.query+"" + this.compileFilter();
Ajax.call(this.url, args, this.listCallback, "POST", "JSON");
}
/**
* 删除列表中的一个记录
*/
listTable.remove = function(id, cfm, opt)
{
if (opt == null)
{
opt = "remove";
}
if (confirm(cfm))
{
var args = "act=" + opt + "&id=" + id + this.compileFilter();
Ajax.call(this.url, args, this.listCallback, "GET", "JSON");
}
}
listTable.gotoPageFirst = function()
{
if (this.filter.page > 1)
{
listTable.gotoPage(1);
}
}
listTable.gotoPagePrev = function()
{
if (this.filter.page > 1)
{
listTable.gotoPage(this.filter.page - 1);
}
}
listTable.gotoPageNext = function()
{
if (this.filter.page < listTable.pageCount)
{
listTable.gotoPage(parseInt(this.filter.page) + 1);
}
}
listTable.gotoPageLast = function()
{
if (this.filter.page < listTable.pageCount)
{
listTable.gotoPage(listTable.pageCount);
}
}
listTable.changePageSize = function(e)
{
var evt = Utils.fixEvent(e);
if (evt.keyCode == 13)
{
listTable.gotoPage();
return false;
};
}
listTable.listCallback = function(result, txt)
{
if (result.error > 0)
{
alert(result.message);
}
else
{
try
{
document.getElementById('listDiv').innerHTML = result.content;
if (typeof result.filter == "object")
{
listTable.filter = result.filter;
}
listTable.pageCount = result.page_count;
}
catch (e)
{
alert(e.message);
}
}
}
listTable.selectAll = function(obj, chk)
{
if (chk == null)
{
chk = 'checkboxes';
}
var elems = obj.form.getElementsByTagName("INPUT");
for (var i=0; i < elems.length; i++)
{
if (elems[i].name == chk || elems[i].name == chk + "[]")
{
elems[i].checked = obj.checked;
}
}
}
listTable.compileFilter = function()
{
var args = '';
for (var i in this.filter)
{
if (typeof(this.filter[i]) != "function" && typeof(this.filter[i]) != "undefined")
{
args += "&" + i + "=" + encodeURIComponent(this.filter[i]);
}
}
return args;
}
listTable.getPageSize = function()
{
var ps = 15;
pageSize = document.getElementById("pageSize");
if (pageSize)
{
ps = Utils.isInt(pageSize.value) ? pageSize.value : 15;
document.cookie = "ECSCP[page_size]=" + ps + ";";
}
}
listTable.addRow = function(checkFunc)
{
cleanWhitespace(document.getElementById("listDiv"));
var table = document.getElementById("listDiv").childNodes[0];
var firstRow = table.rows[0];
var newRow = table.insertRow(-1);
newRow.align = "center";
var items = new Object();
for(var i=0; i < firstRow.cells.length;i++) {
var cel = firstRow.cells[i];
var celName = cel.getAttribute("name");
var newCel = newRow.insertCell(-1);
if (!cel.getAttribute("ReadOnly") && cel.getAttribute("Type")=="TextBox")
{
items[celName] = document.createElement("input");
items[celName].type = "text";
items[celName].style.width = "50px";
items[celName].onkeypress = function(e)
{
var evt = Utils.fixEvent(e);
var obj = Utils.srcElement(e);
if (evt.keyCode == 13)
{
listTable.saveFunc();
}
}
newCel.appendChild(items[celName]);
}
if (cel.getAttribute("Type") == "Button")
{
var saveBtn = document.createElement("input");
saveBtn.type = "image";
saveBtn.src = "./images/icon_add.gif";
saveBtn.value = save;
newCel.appendChild(saveBtn);
this.saveFunc = function()
{
if (checkFunc)
{
if (!checkFunc(items))
{
return false;
}
}
var str = "act=add";
for(var key in items)
{
if (typeof(items[key]) != "function")
{
str += "&" + key + "=" + items[key].value;
}
}
res = Ajax.call(listTable.url, str, null, "POST", "JSON", false);
if (res.error)
{
alert(res.message);
table.deleteRow(table.rows.length-1);
items = null;
}
else
{
document.getElementById("listDiv").innerHTML = res.content;
if (document.getElementById("listDiv").childNodes[0].rows.length < 6)
{
listTable.addRow(checkFunc);
}
items = null;
}
}
saveBtn.onclick = this.saveFunc;
//var delBtn = document.createElement("input");
//delBtn.type = "image";
//delBtn.src = "./images/no.gif";
//delBtn.value = cancel;
//newCel.appendChild(delBtn);
}
}
}
| JavaScript |
var ColorSelecter = new Object();
ColorSelecter.Show = function(sender)
{
if(ColorSelecter.box)
{
if (ColorSelecter.box.style.display = "none")
ColorSelecter.box.style.display = "";
}
else
{
ColorSelecter.box = document.createElement("Div");
ColorSelecter.box.id = "ColorSelectertBox";
var table = "<table width='93' border='1' cellpadding='0' cellspacing='0' bordercolor='#BDBBBC' style='border:2px #C5D9FE solid'><tr><td bgcolor='#FFFFFF'> </td><td bgcolor='#C0C0C0'> </td><td bgcolor='#969696'> </td><td bgcolor='#808080'> </td><td bgcolor='#333333'> </td></tr><tr><td bgcolor='#CC99FE'> </td><td bgcolor='#993365'> </td><td bgcolor='#81007F'> </td><td bgcolor='#6766CC'> </td><td bgcolor='#343399'> </td></tr><tr><td bgcolor='#BBBBBB'> </td><td bgcolor='#00CCFF'> </td><td bgcolor='#3366FF'> </td><td bgcolor='#0000FE'> </td><td bgcolor='#010080'> </td></tr><tr><td bgcolor='#CDFFFF'> </td><td bgcolor='#01FFFF'> </td><td bgcolor='#33CBCC'> </td><td bgcolor='#008081'> </td><td bgcolor='#003265'> </td></tr><tr><td bgcolor='#CDFFCC'> </td><td bgcolor='#00FF01'> </td><td bgcolor='#339967'> </td><td bgcolor='#008002'> </td><td bgcolor='#013300'> </td></tr><tr><td bgcolor='#FFFE99'> </td><td bgcolor='#FFFE03'> </td><td bgcolor='#99CD00'> </td><td bgcolor='#807F01'> </td><td bgcolor='#333301'> </td></tr><tr><td bgcolor='#FFCB99'> </td><td bgcolor='#FFCD00'> </td><td bgcolor='#FF9900'> </td><td bgcolor='#FD6600'> </td><td bgcolor='#993400'> </td></tr><tr><td bgcolor='#FF99CB'> </td><td bgcolor='#FF00FE'> </td><td bgcolor='#FE0000'> </td><td bgcolor='#800000'> </td><td bgcolor='#000000'> </td></tr></table>";
ColorSelecter.box.innerHTML = table;
document.body.appendChild(ColorSelecter.box);
var myTable = ColorSelecter.box.childNodes[0];
for (var i = 0; i<myTable.rows.length; i++)
{
for (var j = 0; j < myTable.rows[i].cells.length; j++)
{
myTable.rows[i].cells[j].style.border = "#BDBBBC 1px solid";
myTable.rows[i].cells[j].onmousemove = function()
{
this.style.border = "#fff 1px solid";
}
myTable.rows[i].cells[j].onmouseout = function()
{
this.style.border = "#BDBBBC 1px solid";
}
myTable.rows[i].cells[j].onmousedown = function()
{
document.getElementById("font_color").style.backgroundColor = this.bgColor;
var re = /#/g;
document.getElementById("base_style").value = this.bgColor.replace(re, "");
ColorSelecter.box.style.display = "none";
}
}
}
}
var pos = getPosition(sender);
ColorSelecter.box.style.top = pos.top + 18 + "px";
ColorSelecter.box.style.left = pos.left + "px";
document.onmousedown = function()
{
ColorSelecter.box.style.display = "none";
}
}
| JavaScript |
/* $Id : selectzone.js 4824 2007-01-31 08:23:56Z paulgao $ */
/* *
* SelectZone 类
*/
function SelectZone()
{
this.filters = new Object();
this.id = arguments[0] ? arguments[0] : 1; // 过滤条件
this.sourceSel = arguments[1] ? arguments[1] : null; // 1 商品关联 2 组合、赠品(带价格)
this.targetSel = arguments[2] ? arguments[2] : null; // 源 select 对象
this.priceObj = arguments[3] ? arguments[3] : null; // 目标 select 对象
this.filename = location.href.substring((location.href.lastIndexOf("/")) + 1, location.href.lastIndexOf("?")) + "?is_ajax=1";
var _self = this;
/**
* 载入源select对象的options
* @param string funcName ajax函数名称
* @param function response 处理函数
*/
this.loadOptions = function(act, filters)
{
Ajax.call(this.filename+"&act=" + act, filters, this.loadOptionsResponse, "GET", "JSON");
}
/**
* 将返回的数据解析为options的形式
* @param result 返回的数据
*/
this.loadOptionsResponse = function(result, txt)
{
if (!result.error)
{
_self.createOptions(_self.sourceSel, result.content);
}
if (result.message.length > 0)
{
alert(result.message);
}
return;
}
/**
* 检查对象
* @return boolean
*/
this.check = function()
{
/* source select */
if ( ! this.sourceSel)
{
alert('source select undefined');
return false;
}
else
{
if (this.sourceSel.nodeName != 'SELECT')
{
alert('source select is not SELECT');
return false;
}
}
/* target select */
if ( ! this.targetSel)
{
alert('target select undefined');
return false;
}
else
{
if (this.targetSel.nodeName != 'SELECT')
{
alert('target select is not SELECT');
return false;
}
}
/* price object */
if (this.id == 2 && ! this.priceObj)
{
alert('price obj undefined');
return false;
}
return true;
}
/**
* 添加选中项
* @param boolean all
* @param string act
* @param mix arguments 其他参数,下标从[2]开始
*/
this.addItem = function(all, act)
{
if (!this.check())
{
return;
}
var selOpt = new Array();
for (var i = 0; i < this.sourceSel.length; i ++ )
{
if (!this.sourceSel.options[i].selected && all == false) continue;
if (this.targetSel.length > 0)
{
var exsits = false;
for (var j = 0; j < this.targetSel.length; j ++ )
{
if (this.targetSel.options[j].value == this.sourceSel.options[i].value)
{
exsits = true;
break;
}
}
if (!exsits)
{
selOpt[selOpt.length] = this.sourceSel.options[i].value;
}
}
else
{
selOpt[selOpt.length] = this.sourceSel.options[i].value;
}
}
if (selOpt.length > 0)
{
var args = new Array();
for (var i=2; i<arguments.length; i++)
{
args[args.length] = arguments[i];
}
Ajax.call(this.filename + "&act="+act+"&add_ids=" +selOpt.toJSONString(), args, this.addRemoveItemResponse, "GET", "JSON");
}
}
/**
* 删除选中项
* @param boolean all
* @param string act
*/
this.dropItem = function(all, act)
{
if (!this.check())
{
return;
}
var arr = new Array();
for (var i = this.targetSel.length - 1; i >= 0 ; i -- )
{
if (this.targetSel.options[i].selected || all)
{
arr[arr.length] = this.targetSel.options[i].value;
}
}
if (arr.length > 0)
{
var args = new Array();
for (var i=2; i<arguments.length; i++)
{
args[args.length] = arguments[i];
}
Ajax.call(this.filename + "&act="+act+"&drop_ids=" + arr.toJSONString(), args, this.addRemoveItemResponse, 'GET', 'JSON');
}
}
/**
* 处理添加项返回的函数
*/
this.addRemoveItemResponse = function(result,txt)
{
if (!result.error)
{
_self.createOptions(_self.targetSel, result.content);
}
if (result.message.length > 0)
{
alert(result.message);
}
}
/**
* 为select元素创建options
*/
this.createOptions = function(obj, arr)
{
obj.length = 0;
for (var i=0; i < arr.length; i++)
{
var opt = document.createElement("OPTION");
opt.value = arr[i].value;
opt.text = arr[i].text;
opt.id = arr[i].data;
obj.options.add(opt);
}
}
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
(function()
{
// IE6 doens't handle absolute positioning properly (it is always in quirks
// mode). This function fixes the sizes and positions of many elements that
// compose the skin (this is skin specific).
var fixSizes = window.DoResizeFixes = function()
{
var fckDlg = window.document.body ;
for ( var i = 0 ; i < fckDlg.childNodes.length ; i++ )
{
var child = fckDlg.childNodes[i] ;
switch ( child.className )
{
case 'contents' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 ) ; // -left -right
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 ) ; // -bottom -top
break ;
case 'blocker' :
case 'cover' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 + 4 ) ; // -left -right + 4
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 + 4 ) ; // -bottom -top + 4
break ;
case 'tr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
break ;
case 'tc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 16 - 16 ) ;
break ;
case 'ml' :
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'mr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'bl' :
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'br' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'bc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 30 - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
}
}
}
var closeButtonOver = function()
{
this.style.backgroundPosition = '-16px -687px' ;
} ;
var closeButtonOut = function()
{
this.style.backgroundPosition = '-16px -651px' ;
} ;
var fixCloseButton = function()
{
var closeButton = document.getElementById ( 'closeButton' ) ;
closeButton.onmouseover = closeButtonOver ;
closeButton.onmouseout = closeButtonOut ;
}
var onLoad = function()
{
fixSizes() ;
fixCloseButton() ;
window.attachEvent( 'onresize', fixSizes ) ;
window.detachEvent( 'onload', onLoad ) ;
}
window.attachEvent( 'onload', onLoad ) ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Compatibility code for Adobe AIR.
*/
if ( FCKBrowserInfo.IsAIR )
{
var FCKAdobeAIR = (function()
{
/*
* ### Private functions.
*/
var getDocumentHead = function( doc )
{
var head ;
var heads = doc.getElementsByTagName( 'head' ) ;
if( heads && heads[0] )
head = heads[0] ;
else
{
head = doc.createElement( 'head' ) ;
doc.documentElement.insertBefore( head, doc.documentElement.firstChild ) ;
}
return head ;
} ;
/*
* ### Public interface.
*/
return {
FCKeditorAPI_Evaluate : function( parentWindow, script )
{
// TODO : This one doesn't work always. The parent window will
// point to an anonymous function in this window. If this
// window is destroyied the parent window will be pointing to
// an invalid reference.
// Evaluate the script in this window.
eval( script ) ;
// Point the FCKeditorAPI property of the parent window to the
// local reference.
parentWindow.FCKeditorAPI = window.FCKeditorAPI ;
},
EditingArea_Start : function( doc, html )
{
// Get the HTML for the <head>.
var headInnerHtml = html.match( /<head>([\s\S]*)<\/head>/i )[1] ;
if ( headInnerHtml && headInnerHtml.length > 0 )
{
// Inject the <head> HTML inside a <div>.
// Do that before getDocumentHead because WebKit moves
// <link css> elements to the <head> at this point.
var div = doc.createElement( 'div' ) ;
div.innerHTML = headInnerHtml ;
// Move the <div> nodes to <head>.
FCKDomTools.MoveChildren( div, getDocumentHead( doc ) ) ;
}
doc.body.innerHTML = html.match( /<body>([\s\S]*)<\/body>/i )[1] ;
//prevent clicking on hyperlinks and navigating away
doc.addEventListener('click', function( ev )
{
ev.preventDefault() ;
ev.stopPropagation() ;
}, true ) ;
},
Panel_Contructor : function( doc, baseLocation )
{
var head = getDocumentHead( doc ) ;
// Set the <base> href.
head.appendChild( doc.createElement('base') ).href = baseLocation ;
doc.body.style.margin = '0px' ;
doc.body.style.padding = '0px' ;
},
ToolbarSet_GetOutElement : function( win, outMatch )
{
var toolbarTarget = win.parent ;
var targetWindowParts = outMatch[1].split( '.' ) ;
while ( targetWindowParts.length > 0 )
{
var part = targetWindowParts.shift() ;
if ( part.length > 0 )
toolbarTarget = toolbarTarget[ part ] ;
}
toolbarTarget = toolbarTarget.document.getElementById( outMatch[2] ) ;
},
ToolbarSet_InitOutFrame : function( doc )
{
var head = getDocumentHead( doc ) ;
head.appendChild( doc.createElement('base') ).href = window.document.location ;
var targetWindow = doc.defaultView;
targetWindow.adjust = function()
{
targetWindow.frameElement.height = doc.body.scrollHeight;
} ;
targetWindow.onresize = targetWindow.adjust ;
targetWindow.setTimeout( targetWindow.adjust, 0 ) ;
doc.body.style.overflow = 'hidden';
doc.body.innerHTML = document.getElementById( 'xToolbarSpace' ).innerHTML ;
}
} ;
})();
/*
* ### Overrides
*/
( function()
{
// Save references for override reuse.
var _Original_FCKPanel_Window_OnFocus = FCKPanel_Window_OnFocus ;
var _Original_FCKPanel_Window_OnBlur = FCKPanel_Window_OnBlur ;
var _Original_FCK_StartEditor = FCK.StartEditor ;
FCKPanel_Window_OnFocus = function( e, panel )
{
// Call the original implementation.
_Original_FCKPanel_Window_OnFocus.call( this, e, panel ) ;
if ( panel._focusTimer )
clearTimeout( panel._focusTimer ) ;
}
FCKPanel_Window_OnBlur = function( e, panel )
{
// Delay the execution of the original function.
panel._focusTimer = FCKTools.SetTimeout( _Original_FCKPanel_Window_OnBlur, 100, this, [ e, panel ] ) ;
}
FCK.StartEditor = function()
{
// Force pointing to the CSS files instead of using the inline CSS cached styles.
window.FCK_InternalCSS = FCKConfig.BasePath + 'css/fck_internal.css' ;
window.FCK_ShowTableBordersCSS = FCKConfig.BasePath + 'css/fck_showtableborders_gecko.css' ;
_Original_FCK_StartEditor.apply( this, arguments ) ;
}
})();
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Contains the DTD mapping for XHTML 1.0 Strict.
* This file was automatically generated from the file: xhtml10-strict.dtd
*/
FCK.DTD = (function()
{
var X = FCKTools.Merge ;
var H,I,J,K,C,L,M,A,B,D,E,G,N,F ;
A = {ins:1, del:1, script:1} ;
B = {hr:1, ul:1, div:1, blockquote:1, noscript:1, table:1, address:1, pre:1, p:1, h5:1, dl:1, h4:1, ol:1, h6:1, h1:1, h3:1, h2:1} ;
C = X({fieldset:1}, B) ;
D = X({sub:1, bdo:1, 'var':1, sup:1, br:1, kbd:1, map:1, samp:1, b:1, acronym:1, '#':1, abbr:1, code:1, i:1, cite:1, tt:1, strong:1, q:1, em:1, big:1, small:1, span:1, dfn:1}, A) ;
E = X({img:1, object:1}, D) ;
F = {input:1, button:1, textarea:1, select:1, label:1} ;
G = X({a:1}, F) ;
H = {img:1, noscript:1, br:1, kbd:1, button:1, h5:1, h4:1, samp:1, h6:1, ol:1, h1:1, h3:1, h2:1, form:1, select:1, '#':1, ins:1, abbr:1, label:1, code:1, table:1, script:1, cite:1, input:1, strong:1, textarea:1, big:1, small:1, span:1, hr:1, sub:1, bdo:1, 'var':1, div:1, object:1, sup:1, map:1, dl:1, del:1, fieldset:1, ul:1, b:1, acronym:1, a:1, blockquote:1, i:1, address:1, tt:1, q:1, pre:1, p:1, em:1, dfn:1} ;
I = X({form:1, fieldset:1}, B, E, G) ;
J = {tr:1} ;
K = {'#':1} ;
L = X(E, G) ;
M = {li:1} ;
N = X({form:1}, A, C) ;
return {
col: {},
tr: {td:1, th:1},
img: {},
colgroup: {col:1},
noscript: N,
td: I,
br: {},
th: I,
kbd: L,
button: X(B, E),
h5: L,
h4: L,
samp: L,
h6: L,
ol: M,
h1: L,
h3: L,
option: K,
h2: L,
form: X(A, C),
select: {optgroup:1, option:1},
ins: I,
abbr: L,
label: L,
code: L,
table: {thead:1, col:1, tbody:1, tr:1, colgroup:1, caption:1, tfoot:1},
script: K,
tfoot: J,
cite: L,
li: I,
input: {},
strong: L,
textarea: K,
big: L,
small: L,
span: L,
dt: L,
hr: {},
sub: L,
optgroup: {option:1},
bdo: L,
param: {},
'var': L,
div: I,
object: X({param:1}, H),
sup: L,
dd: I,
area: {},
map: X({form:1, area:1}, A, C),
dl: {dt:1, dd:1},
del: I,
fieldset: X({legend:1}, H),
thead: J,
ul: M,
acronym: L,
b: L,
a: X({img:1, object:1}, D, F),
blockquote: N,
caption: L,
i: L,
tbody: J,
address: L,
tt: L,
legend: L,
q: L,
pre: X({a:1}, D, F),
p: L,
em: L,
dfn: L
} ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Contains the DTD mapping for XHTML 1.0 Transitional.
* This file was automatically generated from the file: xhtml10-transitional.dtd
*/
FCK.DTD = (function()
{
var X = FCKTools.Merge ;
var A,L,J,M,N,O,D,H,P,K,Q,F,G,C,B,E,I ;
A = {isindex:1, fieldset:1} ;
B = {input:1, button:1, select:1, textarea:1, label:1} ;
C = X({a:1}, B) ;
D = X({iframe:1}, C) ;
E = {hr:1, ul:1, menu:1, div:1, blockquote:1, noscript:1, table:1, center:1, address:1, dir:1, pre:1, h5:1, dl:1, h4:1, noframes:1, h6:1, ol:1, h1:1, h3:1, h2:1} ;
F = {ins:1, del:1, script:1} ;
G = X({b:1, acronym:1, bdo:1, 'var':1, '#':1, abbr:1, code:1, br:1, i:1, cite:1, kbd:1, u:1, strike:1, s:1, tt:1, strong:1, q:1, samp:1, em:1, dfn:1, span:1}, F) ;
H = X({sub:1, img:1, object:1, sup:1, basefont:1, map:1, applet:1, font:1, big:1, small:1}, G) ;
I = X({p:1}, H) ;
J = X({iframe:1}, H, B) ;
K = {img:1, noscript:1, br:1, kbd:1, center:1, button:1, basefont:1, h5:1, h4:1, samp:1, h6:1, ol:1, h1:1, h3:1, h2:1, form:1, font:1, '#':1, select:1, menu:1, ins:1, abbr:1, label:1, code:1, table:1, script:1, cite:1, input:1, iframe:1, strong:1, textarea:1, noframes:1, big:1, small:1, span:1, hr:1, sub:1, bdo:1, 'var':1, div:1, object:1, sup:1, strike:1, dir:1, map:1, dl:1, applet:1, del:1, isindex:1, fieldset:1, ul:1, b:1, acronym:1, a:1, blockquote:1, i:1, u:1, s:1, tt:1, address:1, q:1, pre:1, p:1, em:1, dfn:1} ;
L = X({a:1}, J) ;
M = {tr:1} ;
N = {'#':1} ;
O = X({param:1}, K) ;
P = X({form:1}, A, D, E, I) ;
Q = {li:1} ;
return {
col: {},
tr: {td:1, th:1},
img: {},
colgroup: {col:1},
noscript: P,
td: P,
br: {},
th: P,
center: P,
kbd: L,
button: X(I, E),
basefont: {},
h5: L,
h4: L,
samp: L,
h6: L,
ol: Q,
h1: L,
h3: L,
option: N,
h2: L,
form: X(A, D, E, I),
select: {optgroup:1, option:1},
font: J, // Changed from L to J (see (1))
ins: P,
menu: Q,
abbr: L,
label: L,
table: {thead:1, col:1, tbody:1, tr:1, colgroup:1, caption:1, tfoot:1},
code: L,
script: N,
tfoot: M,
cite: L,
li: P,
input: {},
iframe: P,
strong: J, // Changed from L to J (see (1))
textarea: N,
noframes: P,
big: J, // Changed from L to J (see (1))
small: J, // Changed from L to J (see (1))
span: J, // Changed from L to J (see (1))
hr: {},
dt: L,
sub: J, // Changed from L to J (see (1))
optgroup: {option:1},
param: {},
bdo: L,
'var': J, // Changed from L to J (see (1))
div: P,
object: O,
sup: J, // Changed from L to J (see (1))
dd: P,
strike: J, // Changed from L to J (see (1))
area: {},
dir: Q,
map: X({area:1, form:1, p:1}, A, F, E),
applet: O,
dl: {dt:1, dd:1},
del: P,
isindex: {},
fieldset: X({legend:1}, K),
thead: M,
ul: Q,
acronym: L,
b: J, // Changed from L to J (see (1))
a: J,
blockquote: P,
caption: L,
i: J, // Changed from L to J (see (1))
u: J, // Changed from L to J (see (1))
tbody: M,
s: L,
address: X(D, I),
tt: J, // Changed from L to J (see (1))
legend: L,
q: L,
pre: X(G, C),
p: L,
em: J, // Changed from L to J (see (1))
dfn: L
} ;
})() ;
/*
Notes:
(1) According to the DTD, many elements, like <b> accept <a> elements
inside of them. But, to produce better output results, we have manually
changed the map to avoid breaking the links on pieces, having
"<b>this is a </b><a><b>link</b> test</a>", instead of
"<b>this is a <a>link</a></b><a> test</a>".
*/
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Chinese Simplified language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "折叠工具栏",
ToolbarExpand : "展开工具栏",
// Toolbar Items and Context Menu
Save : "保存",
NewPage : "新建",
Preview : "预览",
Cut : "剪切",
Copy : "复制",
Paste : "粘贴",
PasteText : "粘贴为无格式文本",
PasteWord : "从 MS Word 粘贴",
Print : "打印",
SelectAll : "全选",
RemoveFormat : "清除格式",
InsertLinkLbl : "超链接",
InsertLink : "插入/编辑超链接",
RemoveLink : "取消超链接",
VisitLink : "打开超链接",
Anchor : "插入/编辑锚点链接",
AnchorDelete : "清除锚点链接",
InsertImageLbl : "图象",
InsertImage : "插入/编辑图象",
InsertFlashLbl : "Flash",
InsertFlash : "插入/编辑 Flash",
UpFileBtn : "上传文件",
InsertTableLbl : "表格",
InsertTable : "插入/编辑表格",
InsertLineLbl : "水平线",
InsertLine : "插入水平线",
InsertSpecialCharLbl: "特殊符号",
InsertSpecialChar : "插入特殊符号",
InsertSmileyLbl : "表情符",
InsertSmiley : "插入表情图标",
About : "关于 FCKeditor",
Bold : "加粗",
Italic : "倾斜",
Underline : "下划线",
StrikeThrough : "删除线",
Subscript : "下标",
Superscript : "上标",
LeftJustify : "左对齐",
CenterJustify : "居中对齐",
RightJustify : "右对齐",
BlockJustify : "两端对齐",
DecreaseIndent : "减少缩进量",
IncreaseIndent : "增加缩进量",
Blockquote : "块引用",
CreateDiv : "新增 Div 标籤",
EditDiv : "更改 Div 标籤",
DeleteDiv : "删除 Div 标籤",
Undo : "撤消",
Redo : "重做",
NumberedListLbl : "编号列表",
NumberedList : "插入/删除编号列表",
BulletedListLbl : "项目列表",
BulletedList : "插入/删除项目列表",
ShowTableBorders : "显示表格边框",
ShowDetails : "显示详细资料",
Style : "样式",
FontFormat : "格式",
Font : "字体",
FontSize : "大小",
TextColor : "文本颜色",
BGColor : "背景颜色",
Source : "源代码",
Find : "查找",
Replace : "替换",
SpellCheck : "拼写检查",
UniversalKeyboard : "软键盘",
PageBreakLbl : "分页符",
PageBreak : "插入分页符",
Form : "表单",
Checkbox : "复选框",
RadioButton : "单选按钮",
TextField : "单行文本",
Textarea : "多行文本",
HiddenField : "隐藏域",
Button : "按钮",
SelectionField : "列表/菜单",
ImageButton : "图像域",
FitWindow : "全屏编辑",
ShowBlocks : "显示区块",
// Context Menu
EditLink : "编辑超链接",
CellCM : "单元格",
RowCM : "行",
ColumnCM : "列",
InsertRowAfter : "下插入行",
InsertRowBefore : "上插入行",
DeleteRows : "删除行",
InsertColumnAfter : "右插入列",
InsertColumnBefore : "左插入列",
DeleteColumns : "删除列",
InsertCellAfter : "右插入单元格",
InsertCellBefore : "左插入单元格",
DeleteCells : "删除单元格",
MergeCells : "合并单元格",
MergeRight : "右合并单元格",
MergeDown : "下合并单元格",
HorizontalSplitCell : "橫拆分单元格",
VerticalSplitCell : "縱拆分单元格",
TableDelete : "删除表格",
CellProperties : "单元格属性",
TableProperties : "表格属性",
ImageProperties : "图象属性",
FlashProperties : "Flash 属性",
AnchorProp : "锚点链接属性",
ButtonProp : "按钮属性",
CheckboxProp : "复选框属性",
HiddenFieldProp : "隐藏域属性",
RadioButtonProp : "单选按钮属性",
ImageButtonProp : "图像域属性",
TextFieldProp : "单行文本属性",
SelectionFieldProp : "菜单/列表属性",
TextareaProp : "多行文本属性",
FormProp : "表单属性",
FontFormats : "普通;已编排格式;地址;标题 1;标题 2;标题 3;标题 4;标题 5;标题 6;段落(DIV)",
// Alerts and Messages
ProcessingXHTML : "正在处理 XHTML,请稍等...",
Done : "完成",
PasteWordConfirm : "您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?",
NotCompatiblePaste : "该命令需要 Internet Explorer 5.5 或更高版本的支持,是否按常规粘贴进行?",
UnknownToolbarItem : "未知工具栏项目 \"%1\"",
UnknownCommand : "未知命令名称 \"%1\"",
NotImplemented : "命令无法执行",
UnknownToolbarSet : "工具栏设置 \"%1\" 不存在",
NoActiveX : "浏览器安全设置限制了本编辑器的某些功能。您必须启用安全设置中的“运行 ActiveX 控件和插件”,否则将出现某些错误并缺少功能。",
BrowseServerBlocked : "无法打开资源浏览器,请确认是否启用了禁止弹出窗口。",
DialogBlocked : "无法打开对话框窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。",
VisitLinkBlocked : "无法打开新窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。",
// Dialogs
DlgBtnOK : "确定",
DlgBtnCancel : "取消",
DlgBtnClose : "关闭",
DlgBtnBrowseServer : "浏览服务器",
DlgAdvancedTag : "高级",
DlgOpOther : "<其它>",
DlgInfoTab : "信息",
DlgAlertUrl : "请插入 URL",
// General Dialogs Labels
DlgGenNotSet : "<没有设置>",
DlgGenId : "ID",
DlgGenLangDir : "语言方向",
DlgGenLangDirLtr : "从左到右 (LTR)",
DlgGenLangDirRtl : "从右到左 (RTL)",
DlgGenLangCode : "语言代码",
DlgGenAccessKey : "访问键",
DlgGenName : "名称",
DlgGenTabIndex : "Tab 键次序",
DlgGenLongDescr : "详细说明地址",
DlgGenClass : "样式类名称",
DlgGenTitle : "标题",
DlgGenContType : "内容类型",
DlgGenLinkCharset : "字符编码",
DlgGenStyle : "行内样式",
// Image Dialog
DlgImgTitle : "图象属性",
DlgImgInfoTab : "图象",
DlgImgBtnUpload : "发送到服务器上",
DlgImgURL : "源文件",
DlgImgUpload : "上传",
DlgImgAlt : "替换文本",
DlgImgWidth : "宽度",
DlgImgHeight : "高度",
DlgImgLockRatio : "锁定比例",
DlgBtnResetSize : "恢复尺寸",
DlgImgBorder : "边框大小",
DlgImgHSpace : "水平间距",
DlgImgVSpace : "垂直间距",
DlgImgAlign : "对齐方式",
DlgImgAlignLeft : "左对齐",
DlgImgAlignAbsBottom: "绝对底边",
DlgImgAlignAbsMiddle: "绝对居中",
DlgImgAlignBaseline : "基线",
DlgImgAlignBottom : "底边",
DlgImgAlignMiddle : "居中",
DlgImgAlignRight : "右对齐",
DlgImgAlignTextTop : "文本上方",
DlgImgAlignTop : "顶端",
DlgImgPreview : "预览",
DlgImgAlertUrl : "请输入图象地址",
DlgImgLinkTab : "链接",
// Flash Dialog
DlgFlashTitle : "Flash 属性",
DlgFlashChkPlay : "自动播放",
DlgFlashChkLoop : "循环",
DlgFlashChkMenu : "启用 Flash 菜单",
DlgFlashScale : "缩放",
DlgFlashScaleAll : "全部显示",
DlgFlashScaleNoBorder : "无边框",
DlgFlashScaleFit : "严格匹配",
// Link Dialog
DlgLnkWindowTitle : "超链接",
DlgLnkInfoTab : "超链接信息",
DlgLnkTargetTab : "目标",
DlgLnkType : "超链接类型",
DlgLnkTypeURL : "超链接",
DlgLnkTypeAnchor : "页内锚点链接",
DlgLnkTypeEMail : "电子邮件",
DlgLnkProto : "协议",
DlgLnkProtoOther : "<其它>",
DlgLnkURL : "地址",
DlgLnkAnchorSel : "选择一个锚点",
DlgLnkAnchorByName : "按锚点名称",
DlgLnkAnchorById : "按锚点 ID",
DlgLnkNoAnchors : "(此文档没有可用的锚点)",
DlgLnkEMail : "地址",
DlgLnkEMailSubject : "主题",
DlgLnkEMailBody : "内容",
DlgLnkUpload : "上传",
DlgLnkBtnUpload : "发送到服务器上",
DlgLnkTarget : "目标",
DlgLnkTargetFrame : "<框架>",
DlgLnkTargetPopup : "<弹出窗口>",
DlgLnkTargetBlank : "新窗口 (_blank)",
DlgLnkTargetParent : "父窗口 (_parent)",
DlgLnkTargetSelf : "本窗口 (_self)",
DlgLnkTargetTop : "整页 (_top)",
DlgLnkTargetFrameName : "目标框架名称",
DlgLnkPopWinName : "弹出窗口名称",
DlgLnkPopWinFeat : "弹出窗口属性",
DlgLnkPopResize : "调整大小",
DlgLnkPopLocation : "地址栏",
DlgLnkPopMenu : "菜单栏",
DlgLnkPopScroll : "滚动条",
DlgLnkPopStatus : "状态栏",
DlgLnkPopToolbar : "工具栏",
DlgLnkPopFullScrn : "全屏 (IE)",
DlgLnkPopDependent : "依附 (NS)",
DlgLnkPopWidth : "宽",
DlgLnkPopHeight : "高",
DlgLnkPopLeft : "左",
DlgLnkPopTop : "右",
DlnLnkMsgNoUrl : "请输入超链接地址",
DlnLnkMsgNoEMail : "请输入电子邮件地址",
DlnLnkMsgNoAnchor : "请选择一个锚点",
DlnLnkMsgInvPopName : "弹出窗口名称必须以字母开头,并且不能含有空格。",
// Color Dialog
DlgColorTitle : "选择颜色",
DlgColorBtnClear : "清除",
DlgColorHighlight : "预览",
DlgColorSelected : "选择",
// Smiley Dialog
DlgSmileyTitle : "插入表情图标",
// Special Character Dialog
DlgSpecialCharTitle : "选择特殊符号",
// Table Dialog
DlgTableTitle : "表格属性",
DlgTableRows : "行数",
DlgTableColumns : "列数",
DlgTableBorder : "边框",
DlgTableAlign : "对齐",
DlgTableAlignNotSet : "<没有设置>",
DlgTableAlignLeft : "左对齐",
DlgTableAlignCenter : "居中",
DlgTableAlignRight : "右对齐",
DlgTableWidth : "宽度",
DlgTableWidthPx : "像素",
DlgTableWidthPc : "百分比",
DlgTableHeight : "高度",
DlgTableCellSpace : "间距",
DlgTableCellPad : "边距",
DlgTableCaption : "标题",
DlgTableSummary : "摘要",
// Table Cell Dialog
DlgCellTitle : "单元格属性",
DlgCellWidth : "宽度",
DlgCellWidthPx : "像素",
DlgCellWidthPc : "百分比",
DlgCellHeight : "高度",
DlgCellWordWrap : "自动换行",
DlgCellWordWrapNotSet : "<没有设置>",
DlgCellWordWrapYes : "是",
DlgCellWordWrapNo : "否",
DlgCellHorAlign : "水平对齐",
DlgCellHorAlignNotSet : "<没有设置>",
DlgCellHorAlignLeft : "左对齐",
DlgCellHorAlignCenter : "居中",
DlgCellHorAlignRight: "右对齐",
DlgCellVerAlign : "垂直对齐",
DlgCellVerAlignNotSet : "<没有设置>",
DlgCellVerAlignTop : "顶端",
DlgCellVerAlignMiddle : "居中",
DlgCellVerAlignBottom : "底部",
DlgCellVerAlignBaseline : "基线",
DlgCellRowSpan : "纵跨行数",
DlgCellCollSpan : "横跨列数",
DlgCellBackColor : "背景颜色",
DlgCellBorderColor : "边框颜色",
DlgCellBtnSelect : "选择...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "查找和替换",
// Find Dialog
DlgFindTitle : "查找",
DlgFindFindBtn : "查找",
DlgFindNotFoundMsg : "指定文本没有找到。",
// Replace Dialog
DlgReplaceTitle : "替换",
DlgReplaceFindLbl : "查找:",
DlgReplaceReplaceLbl : "替换:",
DlgReplaceCaseChk : "区分大小写",
DlgReplaceReplaceBtn : "替换",
DlgReplaceReplAllBtn : "全部替换",
DlgReplaceWordChk : "全字匹配",
// Paste Operations / Dialog
PasteErrorCut : "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成。",
PasteErrorCopy : "您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl+C)来完成。",
PasteAsText : "粘贴为无格式文本",
PasteFromWord : "从 MS Word 粘贴",
DlgPasteMsg2 : "请使用键盘快捷键(<STRONG>Ctrl+V</STRONG>)把内容粘贴到下面的方框里,再按 <STRONG>确定</STRONG>。",
DlgPasteSec : "因为你的浏览器的安全设置原因,本编辑器不能直接访问你的剪贴板内容,你需要在本窗口重新粘贴一次。",
DlgPasteIgnoreFont : "忽略 Font 标签",
DlgPasteRemoveStyles : "清理 CSS 样式",
// Color Picker
ColorAutomatic : "自动",
ColorMoreColors : "其它颜色...",
// Document Properties
DocProps : "页面属性",
// Anchor Dialog
DlgAnchorTitle : "命名锚点",
DlgAnchorName : "锚点名称",
DlgAnchorErrorName : "请输入锚点名称",
// Speller Pages Dialog
DlgSpellNotInDic : "没有在字典里",
DlgSpellChangeTo : "更改为",
DlgSpellBtnIgnore : "忽略",
DlgSpellBtnIgnoreAll : "全部忽略",
DlgSpellBtnReplace : "替换",
DlgSpellBtnReplaceAll : "全部替换",
DlgSpellBtnUndo : "撤消",
DlgSpellNoSuggestions : "- 没有建议 -",
DlgSpellProgress : "正在进行拼写检查...",
DlgSpellNoMispell : "拼写检查完成:没有发现拼写错误",
DlgSpellNoChanges : "拼写检查完成:没有更改任何单词",
DlgSpellOneChange : "拼写检查完成:更改了一个单词",
DlgSpellManyChanges : "拼写检查完成:更改了 %1 个单词",
IeSpellDownload : "拼写检查插件还没安装,你是否想现在就下载?",
// Button Dialog
DlgButtonText : "标签(值)",
DlgButtonType : "类型",
DlgButtonTypeBtn : "按钮",
DlgButtonTypeSbm : "提交",
DlgButtonTypeRst : "重设",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "名称",
DlgCheckboxValue : "选定值",
DlgCheckboxSelected : "已勾选",
// Form Dialog
DlgFormName : "名称",
DlgFormAction : "动作",
DlgFormMethod : "方法",
// Select Field Dialog
DlgSelectName : "名称",
DlgSelectValue : "选定",
DlgSelectSize : "高度",
DlgSelectLines : "行",
DlgSelectChkMulti : "允许多选",
DlgSelectOpAvail : "列表值",
DlgSelectOpText : "标签",
DlgSelectOpValue : "值",
DlgSelectBtnAdd : "新增",
DlgSelectBtnModify : "修改",
DlgSelectBtnUp : "上移",
DlgSelectBtnDown : "下移",
DlgSelectBtnSetValue : "设为初始化时选定",
DlgSelectBtnDelete : "删除",
// Textarea Dialog
DlgTextareaName : "名称",
DlgTextareaCols : "字符宽度",
DlgTextareaRows : "行数",
// Text Field Dialog
DlgTextName : "名称",
DlgTextValue : "初始值",
DlgTextCharWidth : "字符宽度",
DlgTextMaxChars : "最多字符数",
DlgTextType : "类型",
DlgTextTypeText : "文本",
DlgTextTypePass : "密码",
// Hidden Field Dialog
DlgHiddenName : "名称",
DlgHiddenValue : "初始值",
// Bulleted List Dialog
BulletedListProp : "项目列表属性",
NumberedListProp : "编号列表属性",
DlgLstStart : "开始序号",
DlgLstType : "列表类型",
DlgLstTypeCircle : "圆圈",
DlgLstTypeDisc : "圆点",
DlgLstTypeSquare : "方块",
DlgLstTypeNumbers : "数字 (1, 2, 3)",
DlgLstTypeLCase : "小写字母 (a, b, c)",
DlgLstTypeUCase : "大写字母 (A, B, C)",
DlgLstTypeSRoman : "小写罗马数字 (i, ii, iii)",
DlgLstTypeLRoman : "大写罗马数字 (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "常规",
DlgDocBackTab : "背景",
DlgDocColorsTab : "颜色和边距",
DlgDocMetaTab : "Meta 数据",
DlgDocPageTitle : "页面标题",
DlgDocLangDir : "语言方向",
DlgDocLangDirLTR : "从左到右 (LTR)",
DlgDocLangDirRTL : "从右到左 (RTL)",
DlgDocLangCode : "语言代码",
DlgDocCharSet : "字符编码",
DlgDocCharSetCE : "中欧",
DlgDocCharSetCT : "繁体中文 (Big5)",
DlgDocCharSetCR : "西里尔文",
DlgDocCharSetGR : "希腊文",
DlgDocCharSetJP : "日文",
DlgDocCharSetKR : "韩文",
DlgDocCharSetTR : "土耳其文",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "西欧",
DlgDocCharSetOther : "其它字符编码",
DlgDocDocType : "文档类型",
DlgDocDocTypeOther : "其它文档类型",
DlgDocIncXHTML : "包含 XHTML 声明",
DlgDocBgColor : "背景颜色",
DlgDocBgImage : "背景图像",
DlgDocBgNoScroll : "不滚动背景图像",
DlgDocCText : "文本",
DlgDocCLink : "超链接",
DlgDocCVisited : "已访问的超链接",
DlgDocCActive : "活动超链接",
DlgDocMargins : "页面边距",
DlgDocMaTop : "上",
DlgDocMaLeft : "左",
DlgDocMaRight : "右",
DlgDocMaBottom : "下",
DlgDocMeIndex : "页面索引关键字 (用半角逗号[,]分隔)",
DlgDocMeDescr : "页面说明",
DlgDocMeAuthor : "作者",
DlgDocMeCopy : "版权",
DlgDocPreview : "预览",
// Templates Dialog
Templates : "模板",
DlgTemplatesTitle : "内容模板",
DlgTemplatesSelMsg : "请选择编辑器内容模板<br>(当前内容将会被清除替换):",
DlgTemplatesLoading : "正在加载模板列表,请稍等...",
DlgTemplatesNoTpl : "(没有模板)",
DlgTemplatesReplace : "替换当前内容",
// About Dialog
DlgAboutAboutTab : "关于",
DlgAboutBrowserInfoTab : "浏览器信息",
DlgAboutLicenseTab : "许可证",
DlgAboutVersion : "版本",
DlgAboutInfo : "要获得更多信息请访问 ",
// Div Dialog
DlgDivGeneralTab : "常规",
DlgDivAdvancedTab : "高级",
DlgDivStyle : "样式",
DlgDivInlineStyle : "CSS 样式"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* English language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "Collapse Toolbar",
ToolbarExpand : "Expand Toolbar",
// Toolbar Items and Context Menu
Save : "Save",
NewPage : "New Page",
Preview : "Preview",
Cut : "Cut",
Copy : "Copy",
Paste : "Paste",
PasteText : "Paste as plain text",
PasteWord : "Paste from Word",
Print : "Print",
SelectAll : "Select All",
RemoveFormat : "Remove Format",
InsertLinkLbl : "Link",
InsertLink : "Insert/Edit Link",
RemoveLink : "Remove Link",
VisitLink : "Open Link",
Anchor : "Insert/Edit Anchor",
AnchorDelete : "Remove Anchor",
InsertImageLbl : "Image",
InsertImage : "Insert/Edit Image",
InsertFlashLbl : "Flash",
InsertFlash : "Insert/Edit Flash",
UpFileBtn : "Upload file",
InsertTableLbl : "Table",
InsertTable : "Insert/Edit Table",
InsertLineLbl : "Line",
InsertLine : "Insert Horizontal Line",
InsertSpecialCharLbl: "Special Character",
InsertSpecialChar : "Insert Special Character",
InsertSmileyLbl : "Smiley",
InsertSmiley : "Insert Smiley",
About : "About FCKeditor",
Bold : "Bold",
Italic : "Italic",
Underline : "Underline",
StrikeThrough : "Strike Through",
Subscript : "Subscript",
Superscript : "Superscript",
LeftJustify : "Left Justify",
CenterJustify : "Center Justify",
RightJustify : "Right Justify",
BlockJustify : "Block Justify",
DecreaseIndent : "Decrease Indent",
IncreaseIndent : "Increase Indent",
Blockquote : "Blockquote",
CreateDiv : "Create Div Container",
EditDiv : "Edit Div Container",
DeleteDiv : "Remove Div Container",
Undo : "Undo",
Redo : "Redo",
NumberedListLbl : "Numbered List",
NumberedList : "Insert/Remove Numbered List",
BulletedListLbl : "Bulleted List",
BulletedList : "Insert/Remove Bulleted List",
ShowTableBorders : "Show Table Borders",
ShowDetails : "Show Details",
Style : "Style",
FontFormat : "Format",
Font : "Font",
FontSize : "Size",
TextColor : "Text Color",
BGColor : "Background Color",
Source : "Source",
Find : "Find",
Replace : "Replace",
SpellCheck : "Check Spelling",
UniversalKeyboard : "Universal Keyboard",
PageBreakLbl : "Page Break",
PageBreak : "Insert Page Break",
Form : "Form",
Checkbox : "Checkbox",
RadioButton : "Radio Button",
TextField : "Text Field",
Textarea : "Textarea",
HiddenField : "Hidden Field",
Button : "Button",
SelectionField : "Selection Field",
ImageButton : "Image Button",
FitWindow : "Maximize the editor size",
ShowBlocks : "Show Blocks",
// Context Menu
EditLink : "Edit Link",
CellCM : "Cell",
RowCM : "Row",
ColumnCM : "Column",
InsertRowAfter : "Insert Row After",
InsertRowBefore : "Insert Row Before",
DeleteRows : "Delete Rows",
InsertColumnAfter : "Insert Column After",
InsertColumnBefore : "Insert Column Before",
DeleteColumns : "Delete Columns",
InsertCellAfter : "Insert Cell After",
InsertCellBefore : "Insert Cell Before",
DeleteCells : "Delete Cells",
MergeCells : "Merge Cells",
MergeRight : "Merge Right",
MergeDown : "Merge Down",
HorizontalSplitCell : "Split Cell Horizontally",
VerticalSplitCell : "Split Cell Vertically",
TableDelete : "Delete Table",
CellProperties : "Cell Properties",
TableProperties : "Table Properties",
ImageProperties : "Image Properties",
FlashProperties : "Flash Properties",
AnchorProp : "Anchor Properties",
ButtonProp : "Button Properties",
CheckboxProp : "Checkbox Properties",
HiddenFieldProp : "Hidden Field Properties",
RadioButtonProp : "Radio Button Properties",
ImageButtonProp : "Image Button Properties",
TextFieldProp : "Text Field Properties",
SelectionFieldProp : "Selection Field Properties",
TextareaProp : "Textarea Properties",
FormProp : "Form Properties",
FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)",
// Alerts and Messages
ProcessingXHTML : "Processing XHTML. Please wait...",
Done : "Done",
PasteWordConfirm : "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?",
NotCompatiblePaste : "This command is available for Internet Explorer version 5.5 or more. Do you want to paste without cleaning?",
UnknownToolbarItem : "Unknown toolbar item \"%1\"",
UnknownCommand : "Unknown command name \"%1\"",
NotImplemented : "Command not implemented",
UnknownToolbarSet : "Toolbar set \"%1\" doesn't exist",
NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.",
BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.",
DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.",
VisitLinkBlocked : "It was not possible to open a new window. Make sure all popup blockers are disabled.",
// Dialogs
DlgBtnOK : "OK",
DlgBtnCancel : "Cancel",
DlgBtnClose : "Close",
DlgBtnBrowseServer : "Browse Server",
DlgAdvancedTag : "Advanced",
DlgOpOther : "<Other>",
DlgInfoTab : "Info",
DlgAlertUrl : "Please insert the URL",
// General Dialogs Labels
DlgGenNotSet : "<not set>",
DlgGenId : "Id",
DlgGenLangDir : "Language Direction",
DlgGenLangDirLtr : "Left to Right (LTR)",
DlgGenLangDirRtl : "Right to Left (RTL)",
DlgGenLangCode : "Language Code",
DlgGenAccessKey : "Access Key",
DlgGenName : "Name",
DlgGenTabIndex : "Tab Index",
DlgGenLongDescr : "Long Description URL",
DlgGenClass : "Stylesheet Classes",
DlgGenTitle : "Advisory Title",
DlgGenContType : "Advisory Content Type",
DlgGenLinkCharset : "Linked Resource Charset",
DlgGenStyle : "Style",
// Image Dialog
DlgImgTitle : "Image Properties",
DlgImgInfoTab : "Image Info",
DlgImgBtnUpload : "Send it to the Server",
DlgImgURL : "URL",
DlgImgUpload : "Upload",
DlgImgAlt : "Alternative Text",
DlgImgWidth : "Width",
DlgImgHeight : "Height",
DlgImgLockRatio : "Lock Ratio",
DlgBtnResetSize : "Reset Size",
DlgImgBorder : "Border",
DlgImgHSpace : "HSpace",
DlgImgVSpace : "VSpace",
DlgImgAlign : "Align",
DlgImgAlignLeft : "Left",
DlgImgAlignAbsBottom: "Abs Bottom",
DlgImgAlignAbsMiddle: "Abs Middle",
DlgImgAlignBaseline : "Baseline",
DlgImgAlignBottom : "Bottom",
DlgImgAlignMiddle : "Middle",
DlgImgAlignRight : "Right",
DlgImgAlignTextTop : "Text Top",
DlgImgAlignTop : "Top",
DlgImgPreview : "Preview",
DlgImgAlertUrl : "Please type the image URL",
DlgImgLinkTab : "Link",
// Flash Dialog
DlgFlashTitle : "Flash Properties",
DlgFlashChkPlay : "Auto Play",
DlgFlashChkLoop : "Loop",
DlgFlashChkMenu : "Enable Flash Menu",
DlgFlashScale : "Scale",
DlgFlashScaleAll : "Show all",
DlgFlashScaleNoBorder : "No Border",
DlgFlashScaleFit : "Exact Fit",
// Link Dialog
DlgLnkWindowTitle : "Link",
DlgLnkInfoTab : "Link Info",
DlgLnkTargetTab : "Target",
DlgLnkType : "Link Type",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Link to anchor in the text",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protocol",
DlgLnkProtoOther : "<other>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "Select an Anchor",
DlgLnkAnchorByName : "By Anchor Name",
DlgLnkAnchorById : "By Element Id",
DlgLnkNoAnchors : "(No anchors available in the document)",
DlgLnkEMail : "E-Mail Address",
DlgLnkEMailSubject : "Message Subject",
DlgLnkEMailBody : "Message Body",
DlgLnkUpload : "Upload",
DlgLnkBtnUpload : "Send it to the Server",
DlgLnkTarget : "Target",
DlgLnkTargetFrame : "<frame>",
DlgLnkTargetPopup : "<popup window>",
DlgLnkTargetBlank : "New Window (_blank)",
DlgLnkTargetParent : "Parent Window (_parent)",
DlgLnkTargetSelf : "Same Window (_self)",
DlgLnkTargetTop : "Topmost Window (_top)",
DlgLnkTargetFrameName : "Target Frame Name",
DlgLnkPopWinName : "Popup Window Name",
DlgLnkPopWinFeat : "Popup Window Features",
DlgLnkPopResize : "Resizable",
DlgLnkPopLocation : "Location Bar",
DlgLnkPopMenu : "Menu Bar",
DlgLnkPopScroll : "Scroll Bars",
DlgLnkPopStatus : "Status Bar",
DlgLnkPopToolbar : "Toolbar",
DlgLnkPopFullScrn : "Full Screen (IE)",
DlgLnkPopDependent : "Dependent (Netscape)",
DlgLnkPopWidth : "Width",
DlgLnkPopHeight : "Height",
DlgLnkPopLeft : "Left Position",
DlgLnkPopTop : "Top Position",
DlnLnkMsgNoUrl : "Please type the link URL",
DlnLnkMsgNoEMail : "Please type the e-mail address",
DlnLnkMsgNoAnchor : "Please select an anchor",
DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces",
// Color Dialog
DlgColorTitle : "Select Color",
DlgColorBtnClear : "Clear",
DlgColorHighlight : "Highlight",
DlgColorSelected : "Selected",
// Smiley Dialog
DlgSmileyTitle : "Insert a Smiley",
// Special Character Dialog
DlgSpecialCharTitle : "Select Special Character",
// Table Dialog
DlgTableTitle : "Table Properties",
DlgTableRows : "Rows",
DlgTableColumns : "Columns",
DlgTableBorder : "Border size",
DlgTableAlign : "Alignment",
DlgTableAlignNotSet : "<Not set>",
DlgTableAlignLeft : "Left",
DlgTableAlignCenter : "Center",
DlgTableAlignRight : "Right",
DlgTableWidth : "Width",
DlgTableWidthPx : "pixels",
DlgTableWidthPc : "percent",
DlgTableHeight : "Height",
DlgTableCellSpace : "Cell spacing",
DlgTableCellPad : "Cell padding",
DlgTableCaption : "Caption",
DlgTableSummary : "Summary",
// Table Cell Dialog
DlgCellTitle : "Cell Properties",
DlgCellWidth : "Width",
DlgCellWidthPx : "pixels",
DlgCellWidthPc : "percent",
DlgCellHeight : "Height",
DlgCellWordWrap : "Word Wrap",
DlgCellWordWrapNotSet : "<Not set>",
DlgCellWordWrapYes : "Yes",
DlgCellWordWrapNo : "No",
DlgCellHorAlign : "Horizontal Alignment",
DlgCellHorAlignNotSet : "<Not set>",
DlgCellHorAlignLeft : "Left",
DlgCellHorAlignCenter : "Center",
DlgCellHorAlignRight: "Right",
DlgCellVerAlign : "Vertical Alignment",
DlgCellVerAlignNotSet : "<Not set>",
DlgCellVerAlignTop : "Top",
DlgCellVerAlignMiddle : "Middle",
DlgCellVerAlignBottom : "Bottom",
DlgCellVerAlignBaseline : "Baseline",
DlgCellRowSpan : "Rows Span",
DlgCellCollSpan : "Columns Span",
DlgCellBackColor : "Background Color",
DlgCellBorderColor : "Border Color",
DlgCellBtnSelect : "Select...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "Find and Replace",
// Find Dialog
DlgFindTitle : "Find",
DlgFindFindBtn : "Find",
DlgFindNotFoundMsg : "The specified text was not found.",
// Replace Dialog
DlgReplaceTitle : "Replace",
DlgReplaceFindLbl : "Find what:",
DlgReplaceReplaceLbl : "Replace with:",
DlgReplaceCaseChk : "Match case",
DlgReplaceReplaceBtn : "Replace",
DlgReplaceReplAllBtn : "Replace All",
DlgReplaceWordChk : "Match whole word",
// Paste Operations / Dialog
PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).",
PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).",
PasteAsText : "Paste as Plain Text",
PasteFromWord : "Paste from Word",
DlgPasteMsg2 : "Please paste inside the following box using the keyboard (<strong>Ctrl+V</strong>) and hit <strong>OK</strong>.",
DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.",
DlgPasteIgnoreFont : "Ignore Font Face definitions",
DlgPasteRemoveStyles : "Remove Styles definitions",
// Color Picker
ColorAutomatic : "Automatic",
ColorMoreColors : "More Colors...",
// Document Properties
DocProps : "Document Properties",
// Anchor Dialog
DlgAnchorTitle : "Anchor Properties",
DlgAnchorName : "Anchor Name",
DlgAnchorErrorName : "Please type the anchor name",
// Speller Pages Dialog
DlgSpellNotInDic : "Not in dictionary",
DlgSpellChangeTo : "Change to",
DlgSpellBtnIgnore : "Ignore",
DlgSpellBtnIgnoreAll : "Ignore All",
DlgSpellBtnReplace : "Replace",
DlgSpellBtnReplaceAll : "Replace All",
DlgSpellBtnUndo : "Undo",
DlgSpellNoSuggestions : "- No suggestions -",
DlgSpellProgress : "Spell check in progress...",
DlgSpellNoMispell : "Spell check complete: No misspellings found",
DlgSpellNoChanges : "Spell check complete: No words changed",
DlgSpellOneChange : "Spell check complete: One word changed",
DlgSpellManyChanges : "Spell check complete: %1 words changed",
IeSpellDownload : "Spell checker not installed. Do you want to download it now?",
// Button Dialog
DlgButtonText : "Text (Value)",
DlgButtonType : "Type",
DlgButtonTypeBtn : "Button",
DlgButtonTypeSbm : "Submit",
DlgButtonTypeRst : "Reset",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "Name",
DlgCheckboxValue : "Value",
DlgCheckboxSelected : "Selected",
// Form Dialog
DlgFormName : "Name",
DlgFormAction : "Action",
DlgFormMethod : "Method",
// Select Field Dialog
DlgSelectName : "Name",
DlgSelectValue : "Value",
DlgSelectSize : "Size",
DlgSelectLines : "lines",
DlgSelectChkMulti : "Allow multiple selections",
DlgSelectOpAvail : "Available Options",
DlgSelectOpText : "Text",
DlgSelectOpValue : "Value",
DlgSelectBtnAdd : "Add",
DlgSelectBtnModify : "Modify",
DlgSelectBtnUp : "Up",
DlgSelectBtnDown : "Down",
DlgSelectBtnSetValue : "Set as selected value",
DlgSelectBtnDelete : "Delete",
// Textarea Dialog
DlgTextareaName : "Name",
DlgTextareaCols : "Columns",
DlgTextareaRows : "Rows",
// Text Field Dialog
DlgTextName : "Name",
DlgTextValue : "Value",
DlgTextCharWidth : "Character Width",
DlgTextMaxChars : "Maximum Characters",
DlgTextType : "Type",
DlgTextTypeText : "Text",
DlgTextTypePass : "Password",
// Hidden Field Dialog
DlgHiddenName : "Name",
DlgHiddenValue : "Value",
// Bulleted List Dialog
BulletedListProp : "Bulleted List Properties",
NumberedListProp : "Numbered List Properties",
DlgLstStart : "Start",
DlgLstType : "Type",
DlgLstTypeCircle : "Circle",
DlgLstTypeDisc : "Disc",
DlgLstTypeSquare : "Square",
DlgLstTypeNumbers : "Numbers (1, 2, 3)",
DlgLstTypeLCase : "Lowercase Letters (a, b, c)",
DlgLstTypeUCase : "Uppercase Letters (A, B, C)",
DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)",
DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "General",
DlgDocBackTab : "Background",
DlgDocColorsTab : "Colors and Margins",
DlgDocMetaTab : "Meta Data",
DlgDocPageTitle : "Page Title",
DlgDocLangDir : "Language Direction",
DlgDocLangDirLTR : "Left to Right (LTR)",
DlgDocLangDirRTL : "Right to Left (RTL)",
DlgDocLangCode : "Language Code",
DlgDocCharSet : "Character Set Encoding",
DlgDocCharSetCE : "Central European",
DlgDocCharSetCT : "Chinese Traditional (Big5)",
DlgDocCharSetCR : "Cyrillic",
DlgDocCharSetGR : "Greek",
DlgDocCharSetJP : "Japanese",
DlgDocCharSetKR : "Korean",
DlgDocCharSetTR : "Turkish",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "Western European",
DlgDocCharSetOther : "Other Character Set Encoding",
DlgDocDocType : "Document Type Heading",
DlgDocDocTypeOther : "Other Document Type Heading",
DlgDocIncXHTML : "Include XHTML Declarations",
DlgDocBgColor : "Background Color",
DlgDocBgImage : "Background Image URL",
DlgDocBgNoScroll : "Nonscrolling Background",
DlgDocCText : "Text",
DlgDocCLink : "Link",
DlgDocCVisited : "Visited Link",
DlgDocCActive : "Active Link",
DlgDocMargins : "Page Margins",
DlgDocMaTop : "Top",
DlgDocMaLeft : "Left",
DlgDocMaRight : "Right",
DlgDocMaBottom : "Bottom",
DlgDocMeIndex : "Document Indexing Keywords (comma separated)",
DlgDocMeDescr : "Document Description",
DlgDocMeAuthor : "Author",
DlgDocMeCopy : "Copyright",
DlgDocPreview : "Preview",
// Templates Dialog
Templates : "Templates",
DlgTemplatesTitle : "Content Templates",
DlgTemplatesSelMsg : "Please select the template to open in the editor<br />(the actual contents will be lost):",
DlgTemplatesLoading : "Loading templates list. Please wait...",
DlgTemplatesNoTpl : "(No templates defined)",
DlgTemplatesReplace : "Replace actual contents",
// About Dialog
DlgAboutAboutTab : "About",
DlgAboutBrowserInfoTab : "Browser Info",
DlgAboutLicenseTab : "License",
DlgAboutVersion : "version",
DlgAboutInfo : "For further information go to",
// Div Dialog
DlgDivGeneralTab : "General",
DlgDivAdvancedTab : "Advanced",
DlgDivStyle : "Style",
DlgDivInlineStyle : "Inline Style"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Chinese Traditional language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "隱藏面板",
ToolbarExpand : "顯示面板",
// Toolbar Items and Context Menu
Save : "儲存",
NewPage : "開新檔案",
Preview : "預覽",
Cut : "剪下",
Copy : "複製",
Paste : "貼上",
PasteText : "貼為純文字格式",
PasteWord : "自 Word 貼上",
Print : "列印",
SelectAll : "全選",
RemoveFormat : "清除格式",
InsertLinkLbl : "超連結",
InsertLink : "插入/編輯超連結",
RemoveLink : "移除超連結",
VisitLink : "開啟超連結",
Anchor : "插入/編輯錨點",
AnchorDelete : "移除錨點",
InsertImageLbl : "影像",
InsertImage : "插入/編輯影像",
InsertFlashLbl : "Flash",
InsertFlash : "插入/編輯 Flash",
UpFileBtn : "上傳文件",
InsertTableLbl : "表格",
InsertTable : "插入/編輯表格",
InsertLineLbl : "水平線",
InsertLine : "插入水平線",
InsertSpecialCharLbl: "特殊符號",
InsertSpecialChar : "插入特殊符號",
InsertSmileyLbl : "表情符號",
InsertSmiley : "插入表情符號",
About : "關於 FCKeditor",
Bold : "粗體",
Italic : "斜體",
Underline : "底線",
StrikeThrough : "刪除線",
Subscript : "下標",
Superscript : "上標",
LeftJustify : "靠左對齊",
CenterJustify : "置中",
RightJustify : "靠右對齊",
BlockJustify : "左右對齊",
DecreaseIndent : "減少縮排",
IncreaseIndent : "增加縮排",
Blockquote : "引用文字",
CreateDiv : "新增 Div 標籤",
EditDiv : "變更 Div 標籤",
DeleteDiv : "移除 Div 標籤",
Undo : "復原",
Redo : "重複",
NumberedListLbl : "編號清單",
NumberedList : "插入/移除編號清單",
BulletedListLbl : "項目清單",
BulletedList : "插入/移除項目清單",
ShowTableBorders : "顯示表格邊框",
ShowDetails : "顯示詳細資料",
Style : "樣式",
FontFormat : "格式",
Font : "字體",
FontSize : "大小",
TextColor : "文字顏色",
BGColor : "背景顏色",
Source : "原始碼",
Find : "尋找",
Replace : "取代",
SpellCheck : "拼字檢查",
UniversalKeyboard : "萬國鍵盤",
PageBreakLbl : "分頁符號",
PageBreak : "插入分頁符號",
Form : "表單",
Checkbox : "核取方塊",
RadioButton : "選項按鈕",
TextField : "文字方塊",
Textarea : "文字區域",
HiddenField : "隱藏欄位",
Button : "按鈕",
SelectionField : "清單/選單",
ImageButton : "影像按鈕",
FitWindow : "編輯器最大化",
ShowBlocks : "顯示區塊",
// Context Menu
EditLink : "編輯超連結",
CellCM : "儲存格",
RowCM : "列",
ColumnCM : "欄",
InsertRowAfter : "向下插入列",
InsertRowBefore : "向上插入列",
DeleteRows : "刪除列",
InsertColumnAfter : "向右插入欄",
InsertColumnBefore : "向左插入欄",
DeleteColumns : "刪除欄",
InsertCellAfter : "向右插入儲存格",
InsertCellBefore : "向左插入儲存格",
DeleteCells : "刪除儲存格",
MergeCells : "合併儲存格",
MergeRight : "向右合併儲存格",
MergeDown : "向下合併儲存格",
HorizontalSplitCell : "橫向分割儲存格",
VerticalSplitCell : "縱向分割儲存格",
TableDelete : "刪除表格",
CellProperties : "儲存格屬性",
TableProperties : "表格屬性",
ImageProperties : "影像屬性",
FlashProperties : "Flash 屬性",
AnchorProp : "錨點屬性",
ButtonProp : "按鈕屬性",
CheckboxProp : "核取方塊屬性",
HiddenFieldProp : "隱藏欄位屬性",
RadioButtonProp : "選項按鈕屬性",
ImageButtonProp : "影像按鈕屬性",
TextFieldProp : "文字方塊屬性",
SelectionFieldProp : "清單/選單屬性",
TextareaProp : "文字區域屬性",
FormProp : "表單屬性",
FontFormats : "一般;已格式化;位址;標題 1;標題 2;標題 3;標題 4;標題 5;標題 6;一般 (DIV)",
// Alerts and Messages
ProcessingXHTML : "處理 XHTML 中,請稍候…",
Done : "完成",
PasteWordConfirm : "您想貼上的文字似乎是自 Word 複製而來,請問您是否要先清除 Word 的格式後再行貼上?",
NotCompatiblePaste : "此指令僅在 Internet Explorer 5.5 或以上的版本有效。請問您是否同意不清除格式即貼上?",
UnknownToolbarItem : "未知工具列項目 \"%1\"",
UnknownCommand : "未知指令名稱 \"%1\"",
NotImplemented : "尚未安裝此指令",
UnknownToolbarSet : "工具列設定 \"%1\" 不存在",
NoActiveX : "瀏覽器的安全性設定限制了本編輯器的某些功能。您必須啟用安全性設定中的「執行ActiveX控制項與外掛程式」項目,否則本編輯器將會出現錯誤並缺少某些功能",
BrowseServerBlocked : "無法開啟資源瀏覽器,請確定所有快顯視窗封鎖程式是否關閉",
DialogBlocked : "無法開啟對話視窗,請確定所有快顯視窗封鎖程式是否關閉",
VisitLinkBlocked : "無法開啟新視窗,請確定所有快顯視窗封鎖程式是否關閉",
// Dialogs
DlgBtnOK : "確定",
DlgBtnCancel : "取消",
DlgBtnClose : "關閉",
DlgBtnBrowseServer : "瀏覽伺服器端",
DlgAdvancedTag : "進階",
DlgOpOther : "<其他>",
DlgInfoTab : "資訊",
DlgAlertUrl : "請插入 URL",
// General Dialogs Labels
DlgGenNotSet : "<尚未設定>",
DlgGenId : "ID",
DlgGenLangDir : "語言方向",
DlgGenLangDirLtr : "由左而右 (LTR)",
DlgGenLangDirRtl : "由右而左 (RTL)",
DlgGenLangCode : "語言代碼",
DlgGenAccessKey : "存取鍵",
DlgGenName : "名稱",
DlgGenTabIndex : "定位順序",
DlgGenLongDescr : "詳細 URL",
DlgGenClass : "樣式表類別",
DlgGenTitle : "標題",
DlgGenContType : "內容類型",
DlgGenLinkCharset : "連結資源之編碼",
DlgGenStyle : "樣式",
// Image Dialog
DlgImgTitle : "影像屬性",
DlgImgInfoTab : "影像資訊",
DlgImgBtnUpload : "上傳至伺服器",
DlgImgURL : "URL",
DlgImgUpload : "上傳",
DlgImgAlt : "替代文字",
DlgImgWidth : "寬度",
DlgImgHeight : "高度",
DlgImgLockRatio : "等比例",
DlgBtnResetSize : "重設為原大小",
DlgImgBorder : "邊框",
DlgImgHSpace : "水平距離",
DlgImgVSpace : "垂直距離",
DlgImgAlign : "對齊",
DlgImgAlignLeft : "靠左對齊",
DlgImgAlignAbsBottom: "絕對下方",
DlgImgAlignAbsMiddle: "絕對中間",
DlgImgAlignBaseline : "基準線",
DlgImgAlignBottom : "靠下對齊",
DlgImgAlignMiddle : "置中對齊",
DlgImgAlignRight : "靠右對齊",
DlgImgAlignTextTop : "文字上方",
DlgImgAlignTop : "靠上對齊",
DlgImgPreview : "預覽",
DlgImgAlertUrl : "請輸入影像 URL",
DlgImgLinkTab : "超連結",
// Flash Dialog
DlgFlashTitle : "Flash 屬性",
DlgFlashChkPlay : "自動播放",
DlgFlashChkLoop : "重複",
DlgFlashChkMenu : "開啟選單",
DlgFlashScale : "縮放",
DlgFlashScaleAll : "全部顯示",
DlgFlashScaleNoBorder : "無邊框",
DlgFlashScaleFit : "精確符合",
// Link Dialog
DlgLnkWindowTitle : "超連結",
DlgLnkInfoTab : "超連結資訊",
DlgLnkTargetTab : "目標",
DlgLnkType : "超連接類型",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "本頁錨點",
DlgLnkTypeEMail : "電子郵件",
DlgLnkProto : "通訊協定",
DlgLnkProtoOther : "<其他>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "請選擇錨點",
DlgLnkAnchorByName : "依錨點名稱",
DlgLnkAnchorById : "依元件 ID",
DlgLnkNoAnchors : "(本文件尚無可用之錨點)",
DlgLnkEMail : "電子郵件",
DlgLnkEMailSubject : "郵件主旨",
DlgLnkEMailBody : "郵件內容",
DlgLnkUpload : "上傳",
DlgLnkBtnUpload : "傳送至伺服器",
DlgLnkTarget : "目標",
DlgLnkTargetFrame : "<框架>",
DlgLnkTargetPopup : "<快顯視窗>",
DlgLnkTargetBlank : "新視窗 (_blank)",
DlgLnkTargetParent : "父視窗 (_parent)",
DlgLnkTargetSelf : "本視窗 (_self)",
DlgLnkTargetTop : "最上層視窗 (_top)",
DlgLnkTargetFrameName : "目標框架名稱",
DlgLnkPopWinName : "快顯視窗名稱",
DlgLnkPopWinFeat : "快顯視窗屬性",
DlgLnkPopResize : "可調整大小",
DlgLnkPopLocation : "網址列",
DlgLnkPopMenu : "選單列",
DlgLnkPopScroll : "捲軸",
DlgLnkPopStatus : "狀態列",
DlgLnkPopToolbar : "工具列",
DlgLnkPopFullScrn : "全螢幕 (IE)",
DlgLnkPopDependent : "從屬 (NS)",
DlgLnkPopWidth : "寬",
DlgLnkPopHeight : "高",
DlgLnkPopLeft : "左",
DlgLnkPopTop : "右",
DlnLnkMsgNoUrl : "請輸入欲連結的 URL",
DlnLnkMsgNoEMail : "請輸入電子郵件位址",
DlnLnkMsgNoAnchor : "請選擇錨點",
DlnLnkMsgInvPopName : "快顯名稱必須以「英文字母」為開頭,且不得含有空白",
// Color Dialog
DlgColorTitle : "請選擇顏色",
DlgColorBtnClear : "清除",
DlgColorHighlight : "預覽",
DlgColorSelected : "選擇",
// Smiley Dialog
DlgSmileyTitle : "插入表情符號",
// Special Character Dialog
DlgSpecialCharTitle : "請選擇特殊符號",
// Table Dialog
DlgTableTitle : "表格屬性",
DlgTableRows : "列數",
DlgTableColumns : "欄數",
DlgTableBorder : "邊框",
DlgTableAlign : "對齊",
DlgTableAlignNotSet : "<未設定>",
DlgTableAlignLeft : "靠左對齊",
DlgTableAlignCenter : "置中",
DlgTableAlignRight : "靠右對齊",
DlgTableWidth : "寬度",
DlgTableWidthPx : "像素",
DlgTableWidthPc : "百分比",
DlgTableHeight : "高度",
DlgTableCellSpace : "間距",
DlgTableCellPad : "內距",
DlgTableCaption : "標題",
DlgTableSummary : "摘要",
// Table Cell Dialog
DlgCellTitle : "儲存格屬性",
DlgCellWidth : "寬度",
DlgCellWidthPx : "像素",
DlgCellWidthPc : "百分比",
DlgCellHeight : "高度",
DlgCellWordWrap : "自動換行",
DlgCellWordWrapNotSet : "<尚未設定>",
DlgCellWordWrapYes : "是",
DlgCellWordWrapNo : "否",
DlgCellHorAlign : "水平對齊",
DlgCellHorAlignNotSet : "<尚未設定>",
DlgCellHorAlignLeft : "靠左對齊",
DlgCellHorAlignCenter : "置中",
DlgCellHorAlignRight: "靠右對齊",
DlgCellVerAlign : "垂直對齊",
DlgCellVerAlignNotSet : "<尚未設定>",
DlgCellVerAlignTop : "靠上對齊",
DlgCellVerAlignMiddle : "置中",
DlgCellVerAlignBottom : "靠下對齊",
DlgCellVerAlignBaseline : "基準線",
DlgCellRowSpan : "合併列數",
DlgCellCollSpan : "合併欄数",
DlgCellBackColor : "背景顏色",
DlgCellBorderColor : "邊框顏色",
DlgCellBtnSelect : "請選擇…",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "尋找與取代",
// Find Dialog
DlgFindTitle : "尋找",
DlgFindFindBtn : "尋找",
DlgFindNotFoundMsg : "未找到指定的文字。",
// Replace Dialog
DlgReplaceTitle : "取代",
DlgReplaceFindLbl : "尋找:",
DlgReplaceReplaceLbl : "取代:",
DlgReplaceCaseChk : "大小寫須相符",
DlgReplaceReplaceBtn : "取代",
DlgReplaceReplAllBtn : "全部取代",
DlgReplaceWordChk : "全字相符",
// Paste Operations / Dialog
PasteErrorCut : "瀏覽器的安全性設定不允許編輯器自動執行剪下動作。請使用快捷鍵 (Ctrl+X) 剪下。",
PasteErrorCopy : "瀏覽器的安全性設定不允許編輯器自動執行複製動作。請使用快捷鍵 (Ctrl+C) 複製。",
PasteAsText : "貼為純文字格式",
PasteFromWord : "自 Word 貼上",
DlgPasteMsg2 : "請使用快捷鍵 (<strong>Ctrl+V</strong>) 貼到下方區域中並按下 <strong>確定</strong>",
DlgPasteSec : "因為瀏覽器的安全性設定,本編輯器無法直接存取您的剪貼簿資料,請您自行在本視窗進行貼上動作。",
DlgPasteIgnoreFont : "移除字型設定",
DlgPasteRemoveStyles : "移除樣式設定",
// Color Picker
ColorAutomatic : "自動",
ColorMoreColors : "更多顏色…",
// Document Properties
DocProps : "文件屬性",
// Anchor Dialog
DlgAnchorTitle : "命名錨點",
DlgAnchorName : "錨點名稱",
DlgAnchorErrorName : "請輸入錨點名稱",
// Speller Pages Dialog
DlgSpellNotInDic : "不在字典中",
DlgSpellChangeTo : "更改為",
DlgSpellBtnIgnore : "忽略",
DlgSpellBtnIgnoreAll : "全部忽略",
DlgSpellBtnReplace : "取代",
DlgSpellBtnReplaceAll : "全部取代",
DlgSpellBtnUndo : "復原",
DlgSpellNoSuggestions : "- 無建議值 -",
DlgSpellProgress : "進行拼字檢查中…",
DlgSpellNoMispell : "拼字檢查完成:未發現拼字錯誤",
DlgSpellNoChanges : "拼字檢查完成:未更改任何單字",
DlgSpellOneChange : "拼字檢查完成:更改了 1 個單字",
DlgSpellManyChanges : "拼字檢查完成:更改了 %1 個單字",
IeSpellDownload : "尚未安裝拼字檢查元件。您是否想要現在下載?",
// Button Dialog
DlgButtonText : "顯示文字 (值)",
DlgButtonType : "類型",
DlgButtonTypeBtn : "按鈕 (Button)",
DlgButtonTypeSbm : "送出 (Submit)",
DlgButtonTypeRst : "重設 (Reset)",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "名稱",
DlgCheckboxValue : "選取值",
DlgCheckboxSelected : "已選取",
// Form Dialog
DlgFormName : "名稱",
DlgFormAction : "動作",
DlgFormMethod : "方法",
// Select Field Dialog
DlgSelectName : "名稱",
DlgSelectValue : "選取值",
DlgSelectSize : "大小",
DlgSelectLines : "行",
DlgSelectChkMulti : "可多選",
DlgSelectOpAvail : "可用選項",
DlgSelectOpText : "顯示文字",
DlgSelectOpValue : "值",
DlgSelectBtnAdd : "新增",
DlgSelectBtnModify : "修改",
DlgSelectBtnUp : "上移",
DlgSelectBtnDown : "下移",
DlgSelectBtnSetValue : "設為預設值",
DlgSelectBtnDelete : "刪除",
// Textarea Dialog
DlgTextareaName : "名稱",
DlgTextareaCols : "字元寬度",
DlgTextareaRows : "列數",
// Text Field Dialog
DlgTextName : "名稱",
DlgTextValue : "值",
DlgTextCharWidth : "字元寬度",
DlgTextMaxChars : "最多字元數",
DlgTextType : "類型",
DlgTextTypeText : "文字",
DlgTextTypePass : "密碼",
// Hidden Field Dialog
DlgHiddenName : "名稱",
DlgHiddenValue : "值",
// Bulleted List Dialog
BulletedListProp : "項目清單屬性",
NumberedListProp : "編號清單屬性",
DlgLstStart : "起始編號",
DlgLstType : "清單類型",
DlgLstTypeCircle : "圓圈",
DlgLstTypeDisc : "圓點",
DlgLstTypeSquare : "方塊",
DlgLstTypeNumbers : "數字 (1, 2, 3)",
DlgLstTypeLCase : "小寫字母 (a, b, c)",
DlgLstTypeUCase : "大寫字母 (A, B, C)",
DlgLstTypeSRoman : "小寫羅馬數字 (i, ii, iii)",
DlgLstTypeLRoman : "大寫羅馬數字 (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "一般",
DlgDocBackTab : "背景",
DlgDocColorsTab : "顯色與邊界",
DlgDocMetaTab : "Meta 資料",
DlgDocPageTitle : "頁面標題",
DlgDocLangDir : "語言方向",
DlgDocLangDirLTR : "由左而右 (LTR)",
DlgDocLangDirRTL : "由右而左 (RTL)",
DlgDocLangCode : "語言代碼",
DlgDocCharSet : "字元編碼",
DlgDocCharSetCE : "中歐語系",
DlgDocCharSetCT : "正體中文 (Big5)",
DlgDocCharSetCR : "斯拉夫文",
DlgDocCharSetGR : "希臘文",
DlgDocCharSetJP : "日文",
DlgDocCharSetKR : "韓文",
DlgDocCharSetTR : "土耳其文",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "西歐語系",
DlgDocCharSetOther : "其他字元編碼",
DlgDocDocType : "文件類型",
DlgDocDocTypeOther : "其他文件類型",
DlgDocIncXHTML : "包含 XHTML 定義",
DlgDocBgColor : "背景顏色",
DlgDocBgImage : "背景影像",
DlgDocBgNoScroll : "浮水印",
DlgDocCText : "文字",
DlgDocCLink : "超連結",
DlgDocCVisited : "已瀏覽過的超連結",
DlgDocCActive : "作用中的超連結",
DlgDocMargins : "頁面邊界",
DlgDocMaTop : "上",
DlgDocMaLeft : "左",
DlgDocMaRight : "右",
DlgDocMaBottom : "下",
DlgDocMeIndex : "文件索引關鍵字 (用半形逗號[,]分隔)",
DlgDocMeDescr : "文件說明",
DlgDocMeAuthor : "作者",
DlgDocMeCopy : "版權所有",
DlgDocPreview : "預覽",
// Templates Dialog
Templates : "樣版",
DlgTemplatesTitle : "內容樣版",
DlgTemplatesSelMsg : "請選擇欲開啟的樣版<br> (原有的內容將會被清除):",
DlgTemplatesLoading : "讀取樣版清單中,請稍候…",
DlgTemplatesNoTpl : "(無樣版)",
DlgTemplatesReplace : "取代原有內容",
// About Dialog
DlgAboutAboutTab : "關於",
DlgAboutBrowserInfoTab : "瀏覽器資訊",
DlgAboutLicenseTab : "許可證",
DlgAboutVersion : "版本",
DlgAboutInfo : "想獲得更多資訊請至 ",
// Div Dialog
DlgDivGeneralTab : "一般",
DlgDivAdvancedTab : "進階",
DlgDivStyle : "樣式",
DlgDivInlineStyle : "CSS 樣式"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts for the fck_select.html page.
*/
function Select( combo )
{
var iIndex = combo.selectedIndex ;
oListText.selectedIndex = iIndex ;
oListValue.selectedIndex = iIndex ;
var oTxtText = document.getElementById( "txtText" ) ;
var oTxtValue = document.getElementById( "txtValue" ) ;
oTxtText.value = oListText.value ;
oTxtValue.value = oListValue.value ;
}
function Add()
{
var oTxtText = document.getElementById( "txtText" ) ;
var oTxtValue = document.getElementById( "txtValue" ) ;
AddComboOption( oListText, oTxtText.value, oTxtText.value ) ;
AddComboOption( oListValue, oTxtValue.value, oTxtValue.value ) ;
oListText.selectedIndex = oListText.options.length - 1 ;
oListValue.selectedIndex = oListValue.options.length - 1 ;
oTxtText.value = '' ;
oTxtValue.value = '' ;
oTxtText.focus() ;
}
function Modify()
{
var iIndex = oListText.selectedIndex ;
if ( iIndex < 0 ) return ;
var oTxtText = document.getElementById( "txtText" ) ;
var oTxtValue = document.getElementById( "txtValue" ) ;
oListText.options[ iIndex ].innerHTML = HTMLEncode( oTxtText.value ) ;
oListText.options[ iIndex ].value = oTxtText.value ;
oListValue.options[ iIndex ].innerHTML = HTMLEncode( oTxtValue.value ) ;
oListValue.options[ iIndex ].value = oTxtValue.value ;
oTxtText.value = '' ;
oTxtValue.value = '' ;
oTxtText.focus() ;
}
function Move( steps )
{
ChangeOptionPosition( oListText, steps ) ;
ChangeOptionPosition( oListValue, steps ) ;
}
function Delete()
{
RemoveSelectedOptions( oListText ) ;
RemoveSelectedOptions( oListValue ) ;
}
function SetSelectedValue()
{
var iIndex = oListValue.selectedIndex ;
if ( iIndex < 0 ) return ;
var oTxtValue = document.getElementById( "txtSelValue" ) ;
oTxtValue.value = oListValue.options[ iIndex ].value ;
}
// Moves the selected option by a number of steps (also negative)
function ChangeOptionPosition( combo, steps )
{
var iActualIndex = combo.selectedIndex ;
if ( iActualIndex < 0 )
return ;
var iFinalIndex = iActualIndex + steps ;
if ( iFinalIndex < 0 )
iFinalIndex = 0 ;
if ( iFinalIndex > ( combo.options.length - 1 ) )
iFinalIndex = combo.options.length - 1 ;
if ( iActualIndex == iFinalIndex )
return ;
var oOption = combo.options[ iActualIndex ] ;
var sText = HTMLDecode( oOption.innerHTML ) ;
var sValue = oOption.value ;
combo.remove( iActualIndex ) ;
oOption = AddComboOption( combo, sText, sValue, null, iFinalIndex ) ;
oOption.selected = true ;
}
// Remove all selected options from a SELECT object
function RemoveSelectedOptions(combo)
{
// Save the selected index
var iSelectedIndex = combo.selectedIndex ;
var oOptions = combo.options ;
// Remove all selected options
for ( var i = oOptions.length - 1 ; i >= 0 ; i-- )
{
if (oOptions[i].selected) combo.remove(i) ;
}
// Reset the selection based on the original selected index
if ( combo.options.length > 0 )
{
if ( iSelectedIndex >= combo.options.length ) iSelectedIndex = combo.options.length - 1 ;
combo.selectedIndex = iSelectedIndex ;
}
}
// Add a new option to a SELECT object (combo or list)
function AddComboOption( combo, optionText, optionValue, documentObject, index )
{
var oOption ;
if ( documentObject )
oOption = documentObject.createElement("OPTION") ;
else
oOption = document.createElement("OPTION") ;
if ( index != null )
combo.options.add( oOption, index ) ;
else
combo.options.add( oOption ) ;
oOption.innerHTML = optionText.length > 0 ? HTMLEncode( optionText ) : ' ' ;
oOption.value = optionValue ;
return oOption ;
}
function HTMLEncode( text )
{
if ( !text )
return '' ;
text = text.replace( /&/g, '&' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( />/g, '>' ) ;
return text ;
}
function HTMLDecode( text )
{
if ( !text )
return '' ;
text = text.replace( />/g, '>' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( /&/g, '&' ) ;
return text ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Link dialog window (see fck_link.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKRegexLib = oEditor.FCKRegexLib ;
var FCKTools = oEditor.FCKTools ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', FCKLang.DlgLnkInfoTab ) ;
if ( !FCKConfig.LinkDlgHideTarget )
dialog.AddTab( 'Target', FCKLang.DlgLnkTargetTab, true ) ;
if ( FCKConfig.LinkUpload )
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload, true ) ;
if ( !FCKConfig.LinkDlgHideAdvanced )
dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divInfo' , ( tabCode == 'Info' ) ) ;
ShowE('divTarget' , ( tabCode == 'Target' ) ) ;
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
ShowE('divAttribs' , ( tabCode == 'Advanced' ) ) ;
dialog.SetAutoSize( true ) ;
}
//#### Regular Expressions library.
var oRegex = new Object() ;
oRegex.UriProtocol = /^(((http|https|ftp|news):\/\/)|mailto:)/gi ;
oRegex.UrlOnChangeProtocol = /^(http|https|ftp|news):\/\/(?=.)/gi ;
oRegex.UrlOnChangeTestOther = /^((javascript:)|[#\/\.])/gi ;
oRegex.ReserveTarget = /^_(blank|self|top|parent)$/i ;
oRegex.PopupUri = /^javascript:void\(\s*window.open\(\s*'([^']+)'\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*\)\s*$/ ;
// Accessible popups
oRegex.OnClickPopup = /^\s*on[cC]lick="\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*"$/ ;
oRegex.PopupFeatures = /(?:^|,)([^=]+)=(\d+|yes|no)/gi ;
//#### Parser Functions
var oParser = new Object() ;
// This method simply returns the two inputs in numerical order. You can even
// provide strings, as the method would parseInt() the values.
oParser.SortNumerical = function(a, b)
{
return parseInt( a, 10 ) - parseInt( b, 10 ) ;
}
oParser.ParseEMailParams = function(sParams)
{
// Initialize the oEMailParams object.
var oEMailParams = new Object() ;
oEMailParams.Subject = '' ;
oEMailParams.Body = '' ;
var aMatch = sParams.match( /(^|^\?|&)subject=([^&]+)/i ) ;
if ( aMatch ) oEMailParams.Subject = decodeURIComponent( aMatch[2] ) ;
aMatch = sParams.match( /(^|^\?|&)body=([^&]+)/i ) ;
if ( aMatch ) oEMailParams.Body = decodeURIComponent( aMatch[2] ) ;
return oEMailParams ;
}
// This method returns either an object containing the email info, or FALSE
// if the parameter is not an email link.
oParser.ParseEMailUri = function( sUrl )
{
// Initializes the EMailInfo object.
var oEMailInfo = new Object() ;
oEMailInfo.Address = '' ;
oEMailInfo.Subject = '' ;
oEMailInfo.Body = '' ;
var aLinkInfo = sUrl.match( /^(\w+):(.*)$/ ) ;
if ( aLinkInfo && aLinkInfo[1] == 'mailto' )
{
// This seems to be an unprotected email link.
var aParts = aLinkInfo[2].match( /^([^\?]+)\??(.+)?/ ) ;
if ( aParts )
{
// Set the e-mail address.
oEMailInfo.Address = aParts[1] ;
// Look for the optional e-mail parameters.
if ( aParts[2] )
{
var oEMailParams = oParser.ParseEMailParams( aParts[2] ) ;
oEMailInfo.Subject = oEMailParams.Subject ;
oEMailInfo.Body = oEMailParams.Body ;
}
}
return oEMailInfo ;
}
else if ( aLinkInfo && aLinkInfo[1] == 'javascript' )
{
// This may be a protected email.
// Try to match the url against the EMailProtectionFunction.
var func = FCKConfig.EMailProtectionFunction ;
if ( func != null )
{
try
{
// Escape special chars.
func = func.replace( /([\/^$*+.?()\[\]])/g, '\\$1' ) ;
// Define the possible keys.
var keys = new Array('NAME', 'DOMAIN', 'SUBJECT', 'BODY') ;
// Get the order of the keys (hold them in the array <pos>) and
// the function replaced by regular expression patterns.
var sFunc = func ;
var pos = new Array() ;
for ( var i = 0 ; i < keys.length ; i ++ )
{
var rexp = new RegExp( keys[i] ) ;
var p = func.search( rexp ) ;
if ( p >= 0 )
{
sFunc = sFunc.replace( rexp, '\'([^\']*)\'' ) ;
pos[pos.length] = p + ':' + keys[i] ;
}
}
// Sort the available keys.
pos.sort( oParser.SortNumerical ) ;
// Replace the excaped single quotes in the url, such they do
// not affect the regexp afterwards.
aLinkInfo[2] = aLinkInfo[2].replace( /\\'/g, '###SINGLE_QUOTE###' ) ;
// Create the regexp and execute it.
var rFunc = new RegExp( '^' + sFunc + '$' ) ;
var aMatch = rFunc.exec( aLinkInfo[2] ) ;
if ( aMatch )
{
var aInfo = new Array();
for ( var i = 1 ; i < aMatch.length ; i ++ )
{
var k = pos[i-1].match(/^\d+:(.+)$/) ;
aInfo[k[1]] = aMatch[i].replace(/###SINGLE_QUOTE###/g, '\'') ;
}
// Fill the EMailInfo object that will be returned
oEMailInfo.Address = aInfo['NAME'] + '@' + aInfo['DOMAIN'] ;
oEMailInfo.Subject = decodeURIComponent( aInfo['SUBJECT'] ) ;
oEMailInfo.Body = decodeURIComponent( aInfo['BODY'] ) ;
return oEMailInfo ;
}
}
catch (e)
{
}
}
// Try to match the email against the encode protection.
var aMatch = aLinkInfo[2].match( /^location\.href='mailto:'\+(String\.fromCharCode\([\d,]+\))\+'(.*)'$/ ) ;
if ( aMatch )
{
// The link is encoded
oEMailInfo.Address = eval( aMatch[1] ) ;
if ( aMatch[2] )
{
var oEMailParams = oParser.ParseEMailParams( aMatch[2] ) ;
oEMailInfo.Subject = oEMailParams.Subject ;
oEMailInfo.Body = oEMailParams.Body ;
}
return oEMailInfo ;
}
}
return false;
}
oParser.CreateEMailUri = function( address, subject, body )
{
// Switch for the EMailProtection setting.
switch ( FCKConfig.EMailProtection )
{
case 'function' :
var func = FCKConfig.EMailProtectionFunction ;
if ( func == null )
{
if ( FCKConfig.Debug )
{
alert('EMailProtection alert!\nNo function defined. Please set "FCKConfig.EMailProtectionFunction"') ;
}
return '';
}
// Split the email address into name and domain parts.
var aAddressParts = address.split( '@', 2 ) ;
if ( aAddressParts[1] == undefined )
{
aAddressParts[1] = '' ;
}
// Replace the keys by their values (embedded in single quotes).
func = func.replace(/NAME/g, "'" + aAddressParts[0].replace(/'/g, '\\\'') + "'") ;
func = func.replace(/DOMAIN/g, "'" + aAddressParts[1].replace(/'/g, '\\\'') + "'") ;
func = func.replace(/SUBJECT/g, "'" + encodeURIComponent( subject ).replace(/'/g, '\\\'') + "'") ;
func = func.replace(/BODY/g, "'" + encodeURIComponent( body ).replace(/'/g, '\\\'') + "'") ;
return 'javascript:' + func ;
case 'encode' :
var aParams = [] ;
var aAddressCode = [] ;
if ( subject.length > 0 )
aParams.push( 'subject='+ encodeURIComponent( subject ) ) ;
if ( body.length > 0 )
aParams.push( 'body=' + encodeURIComponent( body ) ) ;
for ( var i = 0 ; i < address.length ; i++ )
aAddressCode.push( address.charCodeAt( i ) ) ;
return 'javascript:location.href=\'mailto:\'+String.fromCharCode(' + aAddressCode.join( ',' ) + ')+\'?' + aParams.join( '&' ) + '\'' ;
}
// EMailProtection 'none'
var sBaseUri = 'mailto:' + address ;
var sParams = '' ;
if ( subject.length > 0 )
sParams = '?subject=' + encodeURIComponent( subject ) ;
if ( body.length > 0 )
{
sParams += ( sParams.length == 0 ? '?' : '&' ) ;
sParams += 'body=' + encodeURIComponent( body ) ;
}
return sBaseUri + sParams ;
}
//#### Initialization Code
// oLink: The actual selected link in the editor.
var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ;
if ( oLink )
FCK.Selection.SelectNode( oLink ) ;
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
// Fill the Anchor Names and Ids combos.
LoadAnchorNamesAndIds() ;
// Load the selected link information (if any).
LoadSelection() ;
// Update the dialog box.
SetLinkType( GetE('cmbLinkType').value ) ;
// Show/Hide the "Browse Server" button.
GetE('divBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ;
// Show the initial dialog content.
GetE('divInfo').style.display = '' ;
// Set the actual uploader URL.
if ( FCKConfig.LinkUpload )
GetE('frmUpload').action = FCKConfig.LinkUploadURL ;
// Set the default target (from configuration).
SetDefaultTarget() ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
// Select the first field.
switch( GetE('cmbLinkType').value )
{
case 'url' :
SelectField( 'txtUrl' ) ;
break ;
case 'email' :
SelectField( 'txtEMailAddress' ) ;
break ;
case 'anchor' :
if ( GetE('divSelAnchor').style.display != 'none' )
SelectField( 'cmbAnchorName' ) ;
else
SelectField( 'cmbLinkType' ) ;
}
}
var bHasAnchors ;
function LoadAnchorNamesAndIds()
{
// Since version 2.0, the anchors are replaced in the DOM by IMGs so the user see the icon
// to edit them. So, we must look for that images now.
var aAnchors = new Array() ;
var i ;
var oImages = oEditor.FCK.EditorDocument.getElementsByTagName( 'IMG' ) ;
for( i = 0 ; i < oImages.length ; i++ )
{
if ( oImages[i].getAttribute('_fckanchor') )
aAnchors[ aAnchors.length ] = oEditor.FCK.GetRealElement( oImages[i] ) ;
}
// Add also real anchors
var oLinks = oEditor.FCK.EditorDocument.getElementsByTagName( 'A' ) ;
for( i = 0 ; i < oLinks.length ; i++ )
{
if ( oLinks[i].name && ( oLinks[i].name.length > 0 ) )
aAnchors[ aAnchors.length ] = oLinks[i] ;
}
var aIds = FCKTools.GetAllChildrenIds( oEditor.FCK.EditorDocument.body ) ;
bHasAnchors = ( aAnchors.length > 0 || aIds.length > 0 ) ;
for ( i = 0 ; i < aAnchors.length ; i++ )
{
var sName = aAnchors[i].name ;
if ( sName && sName.length > 0 )
FCKTools.AddSelectOption( GetE('cmbAnchorName'), sName, sName ) ;
}
for ( i = 0 ; i < aIds.length ; i++ )
{
FCKTools.AddSelectOption( GetE('cmbAnchorId'), aIds[i], aIds[i] ) ;
}
ShowE( 'divSelAnchor' , bHasAnchors ) ;
ShowE( 'divNoAnchor' , !bHasAnchors ) ;
}
function LoadSelection()
{
if ( !oLink ) return ;
var sType = 'url' ;
// Get the actual Link href.
var sHRef = oLink.getAttribute( '_fcksavedurl' ) ;
if ( sHRef == null )
sHRef = oLink.getAttribute( 'href' , 2 ) || '' ;
// Look for a popup javascript link.
var oPopupMatch = oRegex.PopupUri.exec( sHRef ) ;
if( oPopupMatch )
{
GetE('cmbTarget').value = 'popup' ;
sHRef = oPopupMatch[1] ;
FillPopupFields( oPopupMatch[2], oPopupMatch[3] ) ;
SetTarget( 'popup' ) ;
}
// Accessible popups, the popup data is in the onclick attribute
if ( !oPopupMatch )
{
var onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ;
if ( onclick )
{
// Decode the protected string
onclick = decodeURIComponent( onclick ) ;
oPopupMatch = oRegex.OnClickPopup.exec( onclick ) ;
if( oPopupMatch )
{
GetE( 'cmbTarget' ).value = 'popup' ;
FillPopupFields( oPopupMatch[1], oPopupMatch[2] ) ;
SetTarget( 'popup' ) ;
}
}
}
// Search for the protocol.
var sProtocol = oRegex.UriProtocol.exec( sHRef ) ;
// Search for a protected email link.
var oEMailInfo = oParser.ParseEMailUri( sHRef );
if ( oEMailInfo )
{
sType = 'email' ;
GetE('txtEMailAddress').value = oEMailInfo.Address ;
GetE('txtEMailSubject').value = oEMailInfo.Subject ;
GetE('txtEMailBody').value = oEMailInfo.Body ;
}
else if ( sProtocol )
{
sProtocol = sProtocol[0].toLowerCase() ;
GetE('cmbLinkProtocol').value = sProtocol ;
// Remove the protocol and get the remaining URL.
var sUrl = sHRef.replace( oRegex.UriProtocol, '' ) ;
sType = 'url' ;
GetE('txtUrl').value = sUrl ;
}
else if ( sHRef.substr(0,1) == '#' && sHRef.length > 1 ) // It is an anchor link.
{
sType = 'anchor' ;
GetE('cmbAnchorName').value = GetE('cmbAnchorId').value = sHRef.substr(1) ;
}
else // It is another type of link.
{
sType = 'url' ;
GetE('cmbLinkProtocol').value = '' ;
GetE('txtUrl').value = sHRef ;
}
if ( !oPopupMatch )
{
// Get the target.
var sTarget = oLink.target ;
if ( sTarget && sTarget.length > 0 )
{
if ( oRegex.ReserveTarget.test( sTarget ) )
{
sTarget = sTarget.toLowerCase() ;
GetE('cmbTarget').value = sTarget ;
}
else
GetE('cmbTarget').value = 'frame' ;
GetE('txtTargetFrame').value = sTarget ;
}
}
// Get Advances Attributes
GetE('txtAttId').value = oLink.id ;
GetE('txtAttName').value = oLink.name ;
GetE('cmbAttLangDir').value = oLink.dir ;
GetE('txtAttLangCode').value = oLink.lang ;
GetE('txtAttAccessKey').value = oLink.accessKey ;
GetE('txtAttTabIndex').value = oLink.tabIndex <= 0 ? '' : oLink.tabIndex ;
GetE('txtAttTitle').value = oLink.title ;
GetE('txtAttContentType').value = oLink.type ;
GetE('txtAttCharSet').value = oLink.charset ;
var sClass ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
sClass = oLink.getAttribute('className',2) || '' ;
// Clean up temporary classes for internal use:
sClass = sClass.replace( FCKRegexLib.FCK_Class, '' ) ;
GetE('txtAttStyle').value = oLink.style.cssText ;
}
else
{
sClass = oLink.getAttribute('class',2) || '' ;
GetE('txtAttStyle').value = oLink.getAttribute('style',2) || '' ;
}
GetE('txtAttClasses').value = sClass ;
// Update the Link type combo.
GetE('cmbLinkType').value = sType ;
}
//#### Link type selection.
function SetLinkType( linkType )
{
ShowE('divLinkTypeUrl' , (linkType == 'url') ) ;
ShowE('divLinkTypeAnchor' , (linkType == 'anchor') ) ;
ShowE('divLinkTypeEMail' , (linkType == 'email') ) ;
if ( !FCKConfig.LinkDlgHideTarget )
dialog.SetTabVisibility( 'Target' , (linkType == 'url') ) ;
if ( FCKConfig.LinkUpload )
dialog.SetTabVisibility( 'Upload' , (linkType == 'url') ) ;
if ( !FCKConfig.LinkDlgHideAdvanced )
dialog.SetTabVisibility( 'Advanced' , (linkType != 'anchor' || bHasAnchors) ) ;
if ( linkType == 'email' )
dialog.SetAutoSize( true ) ;
}
//#### Target type selection.
function SetTarget( targetType )
{
GetE('tdTargetFrame').style.display = ( targetType == 'popup' ? 'none' : '' ) ;
GetE('tdPopupName').style.display =
GetE('tablePopupFeatures').style.display = ( targetType == 'popup' ? '' : 'none' ) ;
switch ( targetType )
{
case "_blank" :
case "_self" :
case "_parent" :
case "_top" :
GetE('txtTargetFrame').value = targetType ;
break ;
case "" :
GetE('txtTargetFrame').value = '' ;
break ;
}
if ( targetType == 'popup' )
dialog.SetAutoSize( true ) ;
}
//#### Called while the user types the URL.
function OnUrlChange()
{
var sUrl = GetE('txtUrl').value ;
var sProtocol = oRegex.UrlOnChangeProtocol.exec( sUrl ) ;
if ( sProtocol )
{
sUrl = sUrl.substr( sProtocol[0].length ) ;
GetE('txtUrl').value = sUrl ;
GetE('cmbLinkProtocol').value = sProtocol[0].toLowerCase() ;
}
else if ( oRegex.UrlOnChangeTestOther.test( sUrl ) )
{
GetE('cmbLinkProtocol').value = '' ;
}
}
//#### Called while the user types the target name.
function OnTargetNameChange()
{
var sFrame = GetE('txtTargetFrame').value ;
if ( sFrame.length == 0 )
GetE('cmbTarget').value = '' ;
else if ( oRegex.ReserveTarget.test( sFrame ) )
GetE('cmbTarget').value = sFrame.toLowerCase() ;
else
GetE('cmbTarget').value = 'frame' ;
}
// Accessible popups
function BuildOnClickPopup()
{
var sWindowName = "'" + GetE('txtPopupName').value.replace(/\W/gi, "") + "'" ;
var sFeatures = '' ;
var aChkFeatures = document.getElementsByName( 'chkFeature' ) ;
for ( var i = 0 ; i < aChkFeatures.length ; i++ )
{
if ( i > 0 ) sFeatures += ',' ;
sFeatures += aChkFeatures[i].value + '=' + ( aChkFeatures[i].checked ? 'yes' : 'no' ) ;
}
if ( GetE('txtPopupWidth').value.length > 0 ) sFeatures += ',width=' + GetE('txtPopupWidth').value ;
if ( GetE('txtPopupHeight').value.length > 0 ) sFeatures += ',height=' + GetE('txtPopupHeight').value ;
if ( GetE('txtPopupLeft').value.length > 0 ) sFeatures += ',left=' + GetE('txtPopupLeft').value ;
if ( GetE('txtPopupTop').value.length > 0 ) sFeatures += ',top=' + GetE('txtPopupTop').value ;
if ( sFeatures != '' )
sFeatures = sFeatures + ",status" ;
return ( "window.open(this.href," + sWindowName + ",'" + sFeatures + "'); return false" ) ;
}
//#### Fills all Popup related fields.
function FillPopupFields( windowName, features )
{
if ( windowName )
GetE('txtPopupName').value = windowName ;
var oFeatures = new Object() ;
var oFeaturesMatch ;
while( ( oFeaturesMatch = oRegex.PopupFeatures.exec( features ) ) != null )
{
var sValue = oFeaturesMatch[2] ;
if ( sValue == ( 'yes' || '1' ) )
oFeatures[ oFeaturesMatch[1] ] = true ;
else if ( ! isNaN( sValue ) && sValue != 0 )
oFeatures[ oFeaturesMatch[1] ] = sValue ;
}
// Update all features check boxes.
var aChkFeatures = document.getElementsByName('chkFeature') ;
for ( var i = 0 ; i < aChkFeatures.length ; i++ )
{
if ( oFeatures[ aChkFeatures[i].value ] )
aChkFeatures[i].checked = true ;
}
// Update position and size text boxes.
if ( oFeatures['width'] ) GetE('txtPopupWidth').value = oFeatures['width'] ;
if ( oFeatures['height'] ) GetE('txtPopupHeight').value = oFeatures['height'] ;
if ( oFeatures['left'] ) GetE('txtPopupLeft').value = oFeatures['left'] ;
if ( oFeatures['top'] ) GetE('txtPopupTop').value = oFeatures['top'] ;
}
//#### The OK button was hit.
function Ok()
{
var sUri, sInnerHtml ;
oEditor.FCKUndo.SaveUndoStep() ;
switch ( GetE('cmbLinkType').value )
{
case 'url' :
sUri = GetE('txtUrl').value ;
if ( sUri.length == 0 )
{
alert( FCKLang.DlnLnkMsgNoUrl ) ;
return false ;
}
sUri = GetE('cmbLinkProtocol').value + sUri ;
break ;
case 'email' :
sUri = GetE('txtEMailAddress').value ;
if ( sUri.length == 0 )
{
alert( FCKLang.DlnLnkMsgNoEMail ) ;
return false ;
}
sUri = oParser.CreateEMailUri(
sUri,
GetE('txtEMailSubject').value,
GetE('txtEMailBody').value ) ;
break ;
case 'anchor' :
var sAnchor = GetE('cmbAnchorName').value ;
if ( sAnchor.length == 0 ) sAnchor = GetE('cmbAnchorId').value ;
if ( sAnchor.length == 0 )
{
alert( FCKLang.DlnLnkMsgNoAnchor ) ;
return false ;
}
sUri = '#' + sAnchor ;
break ;
}
// If no link is selected, create a new one (it may result in more than one link creation - #220).
var aLinks = oLink ? [ oLink ] : oEditor.FCK.CreateLink( sUri, true ) ;
// If no selection, no links are created, so use the uri as the link text (by dom, 2006-05-26)
var aHasSelection = ( aLinks.length > 0 ) ;
if ( !aHasSelection )
{
sInnerHtml = sUri;
// Built a better text for empty links.
switch ( GetE('cmbLinkType').value )
{
// anchor: use old behavior --> return true
case 'anchor':
sInnerHtml = sInnerHtml.replace( /^#/, '' ) ;
break ;
// url: try to get path
case 'url':
var oLinkPathRegEx = new RegExp("//?([^?\"']+)([?].*)?$") ;
var asLinkPath = oLinkPathRegEx.exec( sUri ) ;
if (asLinkPath != null)
sInnerHtml = asLinkPath[1]; // use matched path
break ;
// mailto: try to get email address
case 'email':
sInnerHtml = GetE('txtEMailAddress').value ;
break ;
}
// Create a new (empty) anchor.
aLinks = [ oEditor.FCK.InsertElement( 'a' ) ] ;
}
for ( var i = 0 ; i < aLinks.length ; i++ )
{
oLink = aLinks[i] ;
if ( aHasSelection )
sInnerHtml = oLink.innerHTML ; // Save the innerHTML (IE changes it if it is like an URL).
oLink.href = sUri ;
SetAttribute( oLink, '_fcksavedurl', sUri ) ;
var onclick;
// Accessible popups
if( GetE('cmbTarget').value == 'popup' )
{
onclick = BuildOnClickPopup() ;
// Encode the attribute
onclick = encodeURIComponent( " onclick=\"" + onclick + "\"" ) ;
SetAttribute( oLink, 'onclick_fckprotectedatt', onclick ) ;
}
else
{
// Check if the previous onclick was for a popup:
// In that case remove the onclick handler.
onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ;
if ( onclick )
{
// Decode the protected string
onclick = decodeURIComponent( onclick ) ;
if( oRegex.OnClickPopup.test( onclick ) )
SetAttribute( oLink, 'onclick_fckprotectedatt', '' ) ;
}
}
oLink.innerHTML = sInnerHtml ; // Set (or restore) the innerHTML
// Target
if( GetE('cmbTarget').value != 'popup' )
SetAttribute( oLink, 'target', GetE('txtTargetFrame').value ) ;
else
SetAttribute( oLink, 'target', null ) ;
// Let's set the "id" only for the first link to avoid duplication.
if ( i == 0 )
SetAttribute( oLink, 'id', GetE('txtAttId').value ) ;
// Advances Attributes
SetAttribute( oLink, 'name' , GetE('txtAttName').value ) ;
SetAttribute( oLink, 'dir' , GetE('cmbAttLangDir').value ) ;
SetAttribute( oLink, 'lang' , GetE('txtAttLangCode').value ) ;
SetAttribute( oLink, 'accesskey', GetE('txtAttAccessKey').value ) ;
SetAttribute( oLink, 'tabindex' , ( GetE('txtAttTabIndex').value > 0 ? GetE('txtAttTabIndex').value : null ) ) ;
SetAttribute( oLink, 'title' , GetE('txtAttTitle').value ) ;
SetAttribute( oLink, 'type' , GetE('txtAttContentType').value ) ;
SetAttribute( oLink, 'charset' , GetE('txtAttCharSet').value ) ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
var sClass = GetE('txtAttClasses').value ;
// If it's also an anchor add an internal class
if ( GetE('txtAttName').value.length != 0 )
sClass += ' FCK__AnchorC' ;
SetAttribute( oLink, 'className', sClass ) ;
oLink.style.cssText = GetE('txtAttStyle').value ;
}
else
{
SetAttribute( oLink, 'class', GetE('txtAttClasses').value ) ;
SetAttribute( oLink, 'style', GetE('txtAttStyle').value ) ;
}
}
// Select the (first) link.
oEditor.FCKSelection.SelectNode( aLinks[0] );
return true ;
}
function BrowseServer()
{
OpenFileBrowser( FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ;
}
function SetUrl( url )
{
GetE('txtUrl').value = url ;
OnUrlChange() ;
dialog.SetSelectedTab( 'Info' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.LinkUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.LinkUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile = GetE('txtUploadFile').value ;
if ( sFile.length == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
if ( ( FCKConfig.LinkUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
( FCKConfig.LinkUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
{
OnUploadCompleted( 202 ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
}
function SetDefaultTarget()
{
var target = FCKConfig.DefaultLinkTarget || '' ;
if ( oLink || target.length == 0 )
return ;
switch ( target )
{
case '_blank' :
case '_self' :
case '_parent' :
case '_top' :
GetE('cmbTarget').value = target ;
break ;
default :
GetE('cmbTarget').value = 'frame' ;
break ;
}
GetE('txtTargetFrame').value = target ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Link dialog window (see fck_link.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKRegexLib = oEditor.FCKRegexLib ;
var FCKTools = oEditor.FCKTools ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
dialog.SetAutoSize( true ) ;
}
// oLink: The actual selected link in the editor.
var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ;
if ( oLink )
FCK.Selection.SelectNode( oLink ) ;
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
// Show the initial dialog content.
GetE('divUpload').style.display = '' ;
// Set the actual uploader URL.
if ( FCKConfig.FilesUploadURL )
GetE('frmUpload').action = FCKConfig.FilesUploadURL ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
}
//#### The OK button was hit.
function Ok()
{
oEditor.FCKUndo.SaveUndoStep() ;
return true ;
}
function BrowseServer()
{
OpenFileBrowser( FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ;
}
function SetUrl( url )
{
dialog.SetSelectedTab( 'Upload' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.LinkUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.LinkUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile;
var sFile_count = 0;
for (var i = 0; i <= 4; i++)
{
var sFile = GetE('txtUploadFile_' + i).value ;
if ( sFile.length == 0 )
{
continue;
}
sFile_count ++;
// if ( ( FCKConfig.LinkUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
// ( FCKConfig.LinkUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
// {
// OnUploadCompleted( 202 ) ;
// return false ;
// }
}
if ( sFile_count == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
} | JavaScript |
////////////////////////////////////////////////////
// wordWindow object
////////////////////////////////////////////////////
function wordWindow() {
// private properties
this._forms = [];
// private methods
this._getWordObject = _getWordObject;
//this._getSpellerObject = _getSpellerObject;
this._wordInputStr = _wordInputStr;
this._adjustIndexes = _adjustIndexes;
this._isWordChar = _isWordChar;
this._lastPos = _lastPos;
// public properties
this.wordChar = /[a-zA-Z]/;
this.windowType = "wordWindow";
this.originalSpellings = new Array();
this.suggestions = new Array();
this.checkWordBgColor = "pink";
this.normWordBgColor = "white";
this.text = "";
this.textInputs = new Array();
this.indexes = new Array();
//this.speller = this._getSpellerObject();
// public methods
this.resetForm = resetForm;
this.totalMisspellings = totalMisspellings;
this.totalWords = totalWords;
this.totalPreviousWords = totalPreviousWords;
//this.getTextObjectArray = getTextObjectArray;
this.getTextVal = getTextVal;
this.setFocus = setFocus;
this.removeFocus = removeFocus;
this.setText = setText;
//this.getTotalWords = getTotalWords;
this.writeBody = writeBody;
this.printForHtml = printForHtml;
}
function resetForm() {
if( this._forms ) {
for( var i = 0; i < this._forms.length; i++ ) {
this._forms[i].reset();
}
}
return true;
}
function totalMisspellings() {
var total_words = 0;
for( var i = 0; i < this.textInputs.length; i++ ) {
total_words += this.totalWords( i );
}
return total_words;
}
function totalWords( textIndex ) {
return this.originalSpellings[textIndex].length;
}
function totalPreviousWords( textIndex, wordIndex ) {
var total_words = 0;
for( var i = 0; i <= textIndex; i++ ) {
for( var j = 0; j < this.totalWords( i ); j++ ) {
if( i == textIndex && j == wordIndex ) {
break;
} else {
total_words++;
}
}
}
return total_words;
}
//function getTextObjectArray() {
// return this._form.elements;
//}
function getTextVal( textIndex, wordIndex ) {
var word = this._getWordObject( textIndex, wordIndex );
if( word ) {
return word.value;
}
}
function setFocus( textIndex, wordIndex ) {
var word = this._getWordObject( textIndex, wordIndex );
if( word ) {
if( word.type == "text" ) {
word.focus();
word.style.backgroundColor = this.checkWordBgColor;
}
}
}
function removeFocus( textIndex, wordIndex ) {
var word = this._getWordObject( textIndex, wordIndex );
if( word ) {
if( word.type == "text" ) {
word.blur();
word.style.backgroundColor = this.normWordBgColor;
}
}
}
function setText( textIndex, wordIndex, newText ) {
var word = this._getWordObject( textIndex, wordIndex );
var beginStr;
var endStr;
if( word ) {
var pos = this.indexes[textIndex][wordIndex];
var oldText = word.value;
// update the text given the index of the string
beginStr = this.textInputs[textIndex].substring( 0, pos );
endStr = this.textInputs[textIndex].substring(
pos + oldText.length,
this.textInputs[textIndex].length
);
this.textInputs[textIndex] = beginStr + newText + endStr;
// adjust the indexes on the stack given the differences in
// length between the new word and old word.
var lengthDiff = newText.length - oldText.length;
this._adjustIndexes( textIndex, wordIndex, lengthDiff );
word.size = newText.length;
word.value = newText;
this.removeFocus( textIndex, wordIndex );
}
}
function writeBody() {
var d = window.document;
var is_html = false;
d.open();
// iterate through each text input.
for( var txtid = 0; txtid < this.textInputs.length; txtid++ ) {
var end_idx = 0;
var begin_idx = 0;
d.writeln( '<form name="textInput'+txtid+'">' );
var wordtxt = this.textInputs[txtid];
this.indexes[txtid] = [];
if( wordtxt ) {
var orig = this.originalSpellings[txtid];
if( !orig ) break;
//!!! plain text, or HTML mode?
d.writeln( '<div class="plainText">' );
// iterate through each occurrence of a misspelled word.
for( var i = 0; i < orig.length; i++ ) {
// find the position of the current misspelled word,
// starting at the last misspelled word.
// and keep looking if it's a substring of another word
do {
begin_idx = wordtxt.indexOf( orig[i], end_idx );
end_idx = begin_idx + orig[i].length;
// word not found? messed up!
if( begin_idx == -1 ) break;
// look at the characters immediately before and after
// the word. If they are word characters we'll keep looking.
var before_char = wordtxt.charAt( begin_idx - 1 );
var after_char = wordtxt.charAt( end_idx );
} while (
this._isWordChar( before_char )
|| this._isWordChar( after_char )
);
// keep track of its position in the original text.
this.indexes[txtid][i] = begin_idx;
// write out the characters before the current misspelled word
for( var j = this._lastPos( txtid, i ); j < begin_idx; j++ ) {
// !!! html mode? make it html compatible
d.write( this.printForHtml( wordtxt.charAt( j )));
}
// write out the misspelled word.
d.write( this._wordInputStr( orig[i] ));
// if it's the last word, write out the rest of the text
if( i == orig.length-1 ){
d.write( printForHtml( wordtxt.substr( end_idx )));
}
}
d.writeln( '</div>' );
}
d.writeln( '</form>' );
}
//for ( var j = 0; j < d.forms.length; j++ ) {
// alert( d.forms[j].name );
// for( var k = 0; k < d.forms[j].elements.length; k++ ) {
// alert( d.forms[j].elements[k].name + ": " + d.forms[j].elements[k].value );
// }
//}
// set the _forms property
this._forms = d.forms;
d.close();
}
// return the character index in the full text after the last word we evaluated
function _lastPos( txtid, idx ) {
if( idx > 0 )
return this.indexes[txtid][idx-1] + this.originalSpellings[txtid][idx-1].length;
else
return 0;
}
function printForHtml( n ) {
return n ; // by FredCK
/*
var htmlstr = n;
if( htmlstr.length == 1 ) {
// do simple case statement if it's just one character
switch ( n ) {
case "\n":
htmlstr = '<br/>';
break;
case "<":
htmlstr = '<';
break;
case ">":
htmlstr = '>';
break;
}
return htmlstr;
} else {
htmlstr = htmlstr.replace( /</g, '<' );
htmlstr = htmlstr.replace( />/g, '>' );
htmlstr = htmlstr.replace( /\n/g, '<br/>' );
return htmlstr;
}
*/
}
function _isWordChar( letter ) {
if( letter.search( this.wordChar ) == -1 ) {
return false;
} else {
return true;
}
}
function _getWordObject( textIndex, wordIndex ) {
if( this._forms[textIndex] ) {
if( this._forms[textIndex].elements[wordIndex] ) {
return this._forms[textIndex].elements[wordIndex];
}
}
return null;
}
function _wordInputStr( word ) {
var str = '<input readonly ';
str += 'class="blend" type="text" value="' + word + '" size="' + word.length + '">';
return str;
}
function _adjustIndexes( textIndex, wordIndex, lengthDiff ) {
for( var i = wordIndex + 1; i < this.originalSpellings[textIndex].length; i++ ) {
this.indexes[textIndex][i] = this.indexes[textIndex][i] + lengthDiff;
}
}
| JavaScript |
////////////////////////////////////////////////////
// controlWindow object
////////////////////////////////////////////////////
function controlWindow( controlForm ) {
// private properties
this._form = controlForm;
// public properties
this.windowType = "controlWindow";
// this.noSuggestionSelection = "- No suggestions -"; // by FredCK
this.noSuggestionSelection = FCKLang.DlgSpellNoSuggestions ;
// set up the properties for elements of the given control form
this.suggestionList = this._form.sugg;
this.evaluatedText = this._form.misword;
this.replacementText = this._form.txtsugg;
this.undoButton = this._form.btnUndo;
// public methods
this.addSuggestion = addSuggestion;
this.clearSuggestions = clearSuggestions;
this.selectDefaultSuggestion = selectDefaultSuggestion;
this.resetForm = resetForm;
this.setSuggestedText = setSuggestedText;
this.enableUndo = enableUndo;
this.disableUndo = disableUndo;
}
function resetForm() {
if( this._form ) {
this._form.reset();
}
}
function setSuggestedText() {
var slct = this.suggestionList;
var txt = this.replacementText;
var str = "";
if( (slct.options[0].text) && slct.options[0].text != this.noSuggestionSelection ) {
str = slct.options[slct.selectedIndex].text;
}
txt.value = str;
}
function selectDefaultSuggestion() {
var slct = this.suggestionList;
var txt = this.replacementText;
if( slct.options.length == 0 ) {
this.addSuggestion( this.noSuggestionSelection );
} else {
slct.options[0].selected = true;
}
this.setSuggestedText();
}
function addSuggestion( sugg_text ) {
var slct = this.suggestionList;
if( sugg_text ) {
var i = slct.options.length;
var newOption = new Option( sugg_text, 'sugg_text'+i );
slct.options[i] = newOption;
}
}
function clearSuggestions() {
var slct = this.suggestionList;
for( var j = slct.length - 1; j > -1; j-- ) {
if( slct.options[j] ) {
slct.options[j] = null;
}
}
}
function enableUndo() {
if( this.undoButton ) {
if( this.undoButton.disabled == true ) {
this.undoButton.disabled = false;
}
}
}
function disableUndo() {
if( this.undoButton ) {
if( this.undoButton.disabled == false ) {
this.undoButton.disabled = true;
}
}
}
| JavaScript |
////////////////////////////////////////////////////
// spellChecker.js
//
// spellChecker object
//
// This file is sourced on web pages that have a textarea object to evaluate
// for spelling. It includes the implementation for the spellCheckObject.
//
////////////////////////////////////////////////////
// constructor
function spellChecker( textObject ) {
// public properties - configurable
// this.popUpUrl = '/speller/spellchecker.html'; // by FredCK
this.popUpUrl = 'fck_spellerpages/spellerpages/spellchecker.html'; // by FredCK
this.popUpName = 'spellchecker';
// this.popUpProps = "menu=no,width=440,height=350,top=70,left=120,resizable=yes,status=yes"; // by FredCK
this.popUpProps = null ; // by FredCK
// this.spellCheckScript = '/speller/server-scripts/spellchecker.php'; // by FredCK
//this.spellCheckScript = '/cgi-bin/spellchecker.pl';
// values used to keep track of what happened to a word
this.replWordFlag = "R"; // single replace
this.ignrWordFlag = "I"; // single ignore
this.replAllFlag = "RA"; // replace all occurances
this.ignrAllFlag = "IA"; // ignore all occurances
this.fromReplAll = "~RA"; // an occurance of a "replace all" word
this.fromIgnrAll = "~IA"; // an occurance of a "ignore all" word
// properties set at run time
this.wordFlags = new Array();
this.currentTextIndex = 0;
this.currentWordIndex = 0;
this.spellCheckerWin = null;
this.controlWin = null;
this.wordWin = null;
this.textArea = textObject; // deprecated
this.textInputs = arguments;
// private methods
this._spellcheck = _spellcheck;
this._getSuggestions = _getSuggestions;
this._setAsIgnored = _setAsIgnored;
this._getTotalReplaced = _getTotalReplaced;
this._setWordText = _setWordText;
this._getFormInputs = _getFormInputs;
// public methods
this.openChecker = openChecker;
this.startCheck = startCheck;
this.checkTextBoxes = checkTextBoxes;
this.checkTextAreas = checkTextAreas;
this.spellCheckAll = spellCheckAll;
this.ignoreWord = ignoreWord;
this.ignoreAll = ignoreAll;
this.replaceWord = replaceWord;
this.replaceAll = replaceAll;
this.terminateSpell = terminateSpell;
this.undo = undo;
// set the current window's "speller" property to the instance of this class.
// this object can now be referenced by child windows/frames.
window.speller = this;
}
// call this method to check all text boxes (and only text boxes) in the HTML document
function checkTextBoxes() {
this.textInputs = this._getFormInputs( "^text$" );
this.openChecker();
}
// call this method to check all textareas (and only textareas ) in the HTML document
function checkTextAreas() {
this.textInputs = this._getFormInputs( "^textarea$" );
this.openChecker();
}
// call this method to check all text boxes and textareas in the HTML document
function spellCheckAll() {
this.textInputs = this._getFormInputs( "^text(area)?$" );
this.openChecker();
}
// call this method to check text boxe(s) and/or textarea(s) that were passed in to the
// object's constructor or to the textInputs property
function openChecker() {
this.spellCheckerWin = window.open( this.popUpUrl, this.popUpName, this.popUpProps );
if( !this.spellCheckerWin.opener ) {
this.spellCheckerWin.opener = window;
}
}
function startCheck( wordWindowObj, controlWindowObj ) {
// set properties from args
this.wordWin = wordWindowObj;
this.controlWin = controlWindowObj;
// reset properties
this.wordWin.resetForm();
this.controlWin.resetForm();
this.currentTextIndex = 0;
this.currentWordIndex = 0;
// initialize the flags to an array - one element for each text input
this.wordFlags = new Array( this.wordWin.textInputs.length );
// each element will be an array that keeps track of each word in the text
for( var i=0; i<this.wordFlags.length; i++ ) {
this.wordFlags[i] = [];
}
// start
this._spellcheck();
return true;
}
function ignoreWord() {
var wi = this.currentWordIndex;
var ti = this.currentTextIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
if( !this.wordWin.getTextVal( ti, wi )) {
alert( 'Error: "Not in dictionary" text is missing.' );
return false;
}
// set as ignored
if( this._setAsIgnored( ti, wi, this.ignrWordFlag )) {
this.currentWordIndex++;
this._spellcheck();
}
return true;
}
function ignoreAll() {
var wi = this.currentWordIndex;
var ti = this.currentTextIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
// get the word that is currently being evaluated.
var s_word_to_repl = this.wordWin.getTextVal( ti, wi );
if( !s_word_to_repl ) {
alert( 'Error: "Not in dictionary" text is missing' );
return false;
}
// set this word as an "ignore all" word.
this._setAsIgnored( ti, wi, this.ignrAllFlag );
// loop through all the words after this word
for( var i = ti; i < this.wordWin.textInputs.length; i++ ) {
for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == ti && j > wi ) || i > ti ) {
// future word: set as "from ignore all" if
// 1) do not already have a flag and
// 2) have the same value as current word
if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl )
&& ( !this.wordFlags[i][j] )) {
this._setAsIgnored( i, j, this.fromIgnrAll );
}
}
}
}
// finally, move on
this.currentWordIndex++;
this._spellcheck();
return true;
}
function replaceWord() {
var wi = this.currentWordIndex;
var ti = this.currentTextIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
if( !this.wordWin.getTextVal( ti, wi )) {
alert( 'Error: "Not in dictionary" text is missing' );
return false;
}
if( !this.controlWin.replacementText ) {
return false ;
}
var txt = this.controlWin.replacementText;
if( txt.value ) {
var newspell = new String( txt.value );
if( this._setWordText( ti, wi, newspell, this.replWordFlag )) {
this.currentWordIndex++;
this._spellcheck();
}
}
return true;
}
function replaceAll() {
var ti = this.currentTextIndex;
var wi = this.currentWordIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
var s_word_to_repl = this.wordWin.getTextVal( ti, wi );
if( !s_word_to_repl ) {
alert( 'Error: "Not in dictionary" text is missing' );
return false;
}
var txt = this.controlWin.replacementText;
if( !txt.value ) return false;
var newspell = new String( txt.value );
// set this word as a "replace all" word.
this._setWordText( ti, wi, newspell, this.replAllFlag );
// loop through all the words after this word
for( var i = ti; i < this.wordWin.textInputs.length; i++ ) {
for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == ti && j > wi ) || i > ti ) {
// future word: set word text to s_word_to_repl if
// 1) do not already have a flag and
// 2) have the same value as s_word_to_repl
if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl )
&& ( !this.wordFlags[i][j] )) {
this._setWordText( i, j, newspell, this.fromReplAll );
}
}
}
}
// finally, move on
this.currentWordIndex++;
this._spellcheck();
return true;
}
function terminateSpell() {
// called when we have reached the end of the spell checking.
var msg = ""; // by FredCK
var numrepl = this._getTotalReplaced();
if( numrepl == 0 ) {
// see if there were no misspellings to begin with
if( !this.wordWin ) {
msg = "";
} else {
if( this.wordWin.totalMisspellings() ) {
// msg += "No words changed."; // by FredCK
msg += FCKLang.DlgSpellNoChanges ; // by FredCK
} else {
// msg += "No misspellings found."; // by FredCK
msg += FCKLang.DlgSpellNoMispell ; // by FredCK
}
}
} else if( numrepl == 1 ) {
// msg += "One word changed."; // by FredCK
msg += FCKLang.DlgSpellOneChange ; // by FredCK
} else {
// msg += numrepl + " words changed."; // by FredCK
msg += FCKLang.DlgSpellManyChanges.replace( /%1/g, numrepl ) ;
}
if( msg ) {
// msg += "\n"; // by FredCK
alert( msg );
}
if( numrepl > 0 ) {
// update the text field(s) on the opener window
for( var i = 0; i < this.textInputs.length; i++ ) {
// this.textArea.value = this.wordWin.text;
if( this.wordWin ) {
if( this.wordWin.textInputs[i] ) {
this.textInputs[i].value = this.wordWin.textInputs[i];
}
}
}
}
// return back to the calling window
// this.spellCheckerWin.close(); // by FredCK
if ( typeof( this.OnFinished ) == 'function' ) // by FredCK
this.OnFinished(numrepl) ; // by FredCK
return true;
}
function undo() {
// skip if this is the first word!
var ti = this.currentTextIndex;
var wi = this.currentWordIndex;
if( this.wordWin.totalPreviousWords( ti, wi ) > 0 ) {
this.wordWin.removeFocus( ti, wi );
// go back to the last word index that was acted upon
do {
// if the current word index is zero then reset the seed
if( this.currentWordIndex == 0 && this.currentTextIndex > 0 ) {
this.currentTextIndex--;
this.currentWordIndex = this.wordWin.totalWords( this.currentTextIndex )-1;
if( this.currentWordIndex < 0 ) this.currentWordIndex = 0;
} else {
if( this.currentWordIndex > 0 ) {
this.currentWordIndex--;
}
}
} while (
this.wordWin.totalWords( this.currentTextIndex ) == 0
|| this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromIgnrAll
|| this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromReplAll
);
var text_idx = this.currentTextIndex;
var idx = this.currentWordIndex;
var preReplSpell = this.wordWin.originalSpellings[text_idx][idx];
// if we got back to the first word then set the Undo button back to disabled
if( this.wordWin.totalPreviousWords( text_idx, idx ) == 0 ) {
this.controlWin.disableUndo();
}
var i, j, origSpell ;
// examine what happened to this current word.
switch( this.wordFlags[text_idx][idx] ) {
// replace all: go through this and all the future occurances of the word
// and revert them all to the original spelling and clear their flags
case this.replAllFlag :
for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) {
for( j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == text_idx && j >= idx ) || i > text_idx ) {
origSpell = this.wordWin.originalSpellings[i][j];
if( origSpell == preReplSpell ) {
this._setWordText ( i, j, origSpell, undefined );
}
}
}
}
break;
// ignore all: go through all the future occurances of the word
// and clear their flags
case this.ignrAllFlag :
for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) {
for( j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == text_idx && j >= idx ) || i > text_idx ) {
origSpell = this.wordWin.originalSpellings[i][j];
if( origSpell == preReplSpell ) {
this.wordFlags[i][j] = undefined;
}
}
}
}
break;
// replace: revert the word to its original spelling
case this.replWordFlag :
this._setWordText ( text_idx, idx, preReplSpell, undefined );
break;
}
// For all four cases, clear the wordFlag of this word. re-start the process
this.wordFlags[text_idx][idx] = undefined;
this._spellcheck();
}
}
function _spellcheck() {
var ww = this.wordWin;
// check if this is the last word in the current text element
if( this.currentWordIndex == ww.totalWords( this.currentTextIndex) ) {
this.currentTextIndex++;
this.currentWordIndex = 0;
// keep going if we're not yet past the last text element
if( this.currentTextIndex < this.wordWin.textInputs.length ) {
this._spellcheck();
return;
} else {
this.terminateSpell();
return;
}
}
// if this is after the first one make sure the Undo button is enabled
if( this.currentWordIndex > 0 ) {
this.controlWin.enableUndo();
}
// skip the current word if it has already been worked on
if( this.wordFlags[this.currentTextIndex][this.currentWordIndex] ) {
// increment the global current word index and move on.
this.currentWordIndex++;
this._spellcheck();
} else {
var evalText = ww.getTextVal( this.currentTextIndex, this.currentWordIndex );
if( evalText ) {
this.controlWin.evaluatedText.value = evalText;
ww.setFocus( this.currentTextIndex, this.currentWordIndex );
this._getSuggestions( this.currentTextIndex, this.currentWordIndex );
}
}
}
function _getSuggestions( text_num, word_num ) {
this.controlWin.clearSuggestions();
// add suggestion in list for each suggested word.
// get the array of suggested words out of the
// three-dimensional array containing all suggestions.
var a_suggests = this.wordWin.suggestions[text_num][word_num];
if( a_suggests ) {
// got an array of suggestions.
for( var ii = 0; ii < a_suggests.length; ii++ ) {
this.controlWin.addSuggestion( a_suggests[ii] );
}
}
this.controlWin.selectDefaultSuggestion();
}
function _setAsIgnored( text_num, word_num, flag ) {
// set the UI
this.wordWin.removeFocus( text_num, word_num );
// do the bookkeeping
this.wordFlags[text_num][word_num] = flag;
return true;
}
function _getTotalReplaced() {
var i_replaced = 0;
for( var i = 0; i < this.wordFlags.length; i++ ) {
for( var j = 0; j < this.wordFlags[i].length; j++ ) {
if(( this.wordFlags[i][j] == this.replWordFlag )
|| ( this.wordFlags[i][j] == this.replAllFlag )
|| ( this.wordFlags[i][j] == this.fromReplAll )) {
i_replaced++;
}
}
}
return i_replaced;
}
function _setWordText( text_num, word_num, newText, flag ) {
// set the UI and form inputs
this.wordWin.setText( text_num, word_num, newText );
// keep track of what happened to this word:
this.wordFlags[text_num][word_num] = flag;
return true;
}
function _getFormInputs( inputPattern ) {
var inputs = new Array();
for( var i = 0; i < document.forms.length; i++ ) {
for( var j = 0; j < document.forms[i].elements.length; j++ ) {
if( document.forms[i].elements[j].type.match( inputPattern )) {
inputs[inputs.length] = document.forms[i].elements[j];
}
}
}
return inputs;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Useful functions used by almost all dialog window pages.
* Dialogs should link to this file as the very first script on the page.
*/
// Automatically detect the correct document.domain (#123).
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.parent.document.domain ;
break ;
}
catch( e ) {}
// Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ...
d = d.replace( /.*?(?:\.|$)/, '' ) ;
if ( d.length == 0 )
break ; // It was not able to detect the domain.
try
{
document.domain = d ;
}
catch (e)
{
break ;
}
}
})() ;
// Attention: FCKConfig must be available in the page.
function GetCommonDialogCss( prefix )
{
// CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see _dev/css_compression.txt).
return FCKConfig.BasePath + 'dialog/common/' + '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}.BtnReset{float:left;background-position:center center;background-image:url(images/reset.gif);width:16px;height:16px;background-repeat:no-repeat;border:1px none;font-size:1px}.BtnLocked,.BtnUnlocked{float:left;background-position:center center;background-image:url(images/locked.gif);width:16px;height:16px;background-repeat:no-repeat;border:none 1px;font-size:1px}.BtnUnlocked{background-image:url(images/unlocked.gif)}.BtnOver{border:outset 1px;cursor:pointer;cursor:hand}' ;
}
// Gets a element by its Id. Used for shorter coding.
function GetE( elementId )
{
return document.getElementById( elementId ) ;
}
function ShowE( element, isVisible )
{
if ( typeof( element ) == 'string' )
element = GetE( element ) ;
element.style.display = isVisible ? '' : 'none' ;
}
function SetAttribute( element, attName, attValue )
{
if ( attValue == null || attValue.length == 0 )
element.removeAttribute( attName, 0 ) ; // 0 : Case Insensitive
else
element.setAttribute( attName, attValue, 0 ) ; // 0 : Case Insensitive
}
function GetAttribute( element, attName, valueIfNull )
{
var oAtt = element.attributes[attName] ;
if ( oAtt == null || !oAtt.specified )
return valueIfNull ? valueIfNull : '' ;
var oValue = element.getAttribute( attName, 2 ) ;
if ( oValue == null )
oValue = oAtt.nodeValue ;
return ( oValue == null ? valueIfNull : oValue ) ;
}
function SelectField( elementId )
{
var element = GetE( elementId ) ;
element.focus() ;
// element.select may not be available for some fields (like <select>).
if ( element.select )
element.select() ;
}
// Functions used by text fields to accept numbers only.
var IsDigit = ( function()
{
var KeyIdentifierMap =
{
End : 35,
Home : 36,
Left : 37,
Right : 39,
'U+00007F' : 46 // Delete
} ;
return function ( e )
{
if ( !e )
e = event ;
var iCode = ( e.keyCode || e.charCode ) ;
if ( !iCode && e.keyIdentifier && ( e.keyIdentifier in KeyIdentifierMap ) )
iCode = KeyIdentifierMap[ e.keyIdentifier ] ;
return (
( iCode >= 48 && iCode <= 57 ) // Numbers
|| (iCode >= 35 && iCode <= 40) // Arrows, Home, End
|| iCode == 8 // Backspace
|| iCode == 46 // Delete
|| iCode == 9 // Tab
) ;
}
} )() ;
String.prototype.Trim = function()
{
return this.replace( /(^\s*)|(\s*$)/g, '' ) ;
}
String.prototype.StartsWith = function( value )
{
return ( this.substr( 0, value.length ) == value ) ;
}
String.prototype.Remove = function( start, length )
{
var s = '' ;
if ( start > 0 )
s = this.substring( 0, start ) ;
if ( start + length < this.length )
s += this.substring( start + length , this.length ) ;
return s ;
}
String.prototype.ReplaceAll = function( searchArray, replaceArray )
{
var replaced = this ;
for ( var i = 0 ; i < searchArray.length ; i++ )
{
replaced = replaced.replace( searchArray[i], replaceArray[i] ) ;
}
return replaced ;
}
function OpenFileBrowser( url, width, height )
{
// oEditor must be defined.
var iLeft = ( oEditor.FCKConfig.ScreenWidth - width ) / 2 ;
var iTop = ( oEditor.FCKConfig.ScreenHeight - height ) / 2 ;
var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes" ;
sOptions += ",width=" + width ;
sOptions += ",height=" + height ;
sOptions += ",left=" + iLeft ;
sOptions += ",top=" + iTop ;
window.open( url, 'FCKBrowseWindow', sOptions ) ;
}
/**
Utility function to create/update an element with a name attribute in IE, so it behaves properly when moved around
It also allows to change the name or other special attributes in an existing node
oEditor : instance of FCKeditor where the element will be created
oOriginal : current element being edited or null if it has to be created
nodeName : string with the name of the element to create
oAttributes : Hash object with the attributes that must be set at creation time in IE
Those attributes will be set also after the element has been
created for any other browser to avoid redudant code
*/
function CreateNamedElement( oEditor, oOriginal, nodeName, oAttributes )
{
var oNewNode ;
// IE doesn't allow easily to change properties of an existing object,
// so remove the old and force the creation of a new one.
var oldNode = null ;
if ( oOriginal && oEditor.FCKBrowserInfo.IsIE )
{
// Force the creation only if some of the special attributes have changed:
var bChanged = false;
for( var attName in oAttributes )
bChanged |= ( oOriginal.getAttribute( attName, 2) != oAttributes[attName] ) ;
if ( bChanged )
{
oldNode = oOriginal ;
oOriginal = null ;
}
}
// If the node existed (and it's not IE), then we just have to update its attributes
if ( oOriginal )
{
oNewNode = oOriginal ;
}
else
{
// #676, IE doesn't play nice with the name or type attribute
if ( oEditor.FCKBrowserInfo.IsIE )
{
var sbHTML = [] ;
sbHTML.push( '<' + nodeName ) ;
for( var prop in oAttributes )
{
sbHTML.push( ' ' + prop + '="' + oAttributes[prop] + '"' ) ;
}
sbHTML.push( '>' ) ;
if ( !oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()] )
sbHTML.push( '</' + nodeName + '>' ) ;
oNewNode = oEditor.FCK.EditorDocument.createElement( sbHTML.join('') ) ;
// Check if we are just changing the properties of an existing node: copy its properties
if ( oldNode )
{
CopyAttributes( oldNode, oNewNode, oAttributes ) ;
oEditor.FCKDomTools.MoveChildren( oldNode, oNewNode ) ;
oldNode.parentNode.removeChild( oldNode ) ;
oldNode = null ;
if ( oEditor.FCK.Selection.SelectionData )
{
// Trick to refresh the selection object and avoid error in
// fckdialog.html Selection.EnsureSelection
var oSel = oEditor.FCK.EditorDocument.selection ;
oEditor.FCK.Selection.SelectionData = oSel.createRange() ; // Now oSel.type will be 'None' reflecting the real situation
}
}
oNewNode = oEditor.FCK.InsertElement( oNewNode ) ;
// FCK.Selection.SelectionData is broken by now since we've
// deleted the previously selected element. So we need to reassign it.
if ( oEditor.FCK.Selection.SelectionData )
{
var range = oEditor.FCK.EditorDocument.body.createControlRange() ;
range.add( oNewNode ) ;
oEditor.FCK.Selection.SelectionData = range ;
}
}
else
{
oNewNode = oEditor.FCK.InsertElement( nodeName ) ;
}
}
// Set the basic attributes
for( var attName in oAttributes )
oNewNode.setAttribute( attName, oAttributes[attName], 0 ) ; // 0 : Case Insensitive
return oNewNode ;
}
// Copy all the attributes from one node to the other, kinda like a clone
// But oSkipAttributes is an object with the attributes that must NOT be copied
function CopyAttributes( oSource, oDest, oSkipAttributes )
{
var aAttributes = oSource.attributes ;
for ( var n = 0 ; n < aAttributes.length ; n++ )
{
var oAttribute = aAttributes[n] ;
if ( oAttribute.specified )
{
var sAttName = oAttribute.nodeName ;
// We can set the type only once, so do it with the proper value, not copying it.
if ( sAttName in oSkipAttributes )
continue ;
var sAttValue = oSource.getAttribute( sAttName, 2 ) ;
if ( sAttValue == null )
sAttValue = oAttribute.nodeValue ;
oDest.setAttribute( sAttName, sAttValue, 0 ) ; // 0 : Case Insensitive
}
}
// The style:
oDest.style.cssText = oSource.style.cssText ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Image dialog window (see fck_image.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKDebug = oEditor.FCKDebug ;
var FCKTools = oEditor.FCKTools ;
var bImageButton = ( document.location.search.length > 0 && document.location.search.substr(1) == 'ImageButton' ) ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', FCKLang.DlgImgInfoTab ) ;
if ( !bImageButton && !FCKConfig.ImageDlgHideLink )
dialog.AddTab( 'Link', FCKLang.DlgImgLinkTab ) ;
if ( FCKConfig.ImageUpload )
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ;
if ( !FCKConfig.ImageDlgHideAdvanced )
dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divInfo' , ( tabCode == 'Info' ) ) ;
ShowE('divLink' , ( tabCode == 'Link' ) ) ;
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ;
}
// Get the selected image (if available).
var oImage = dialog.Selection.GetSelectedElement() ;
if ( oImage && oImage.tagName != 'IMG' && !( oImage.tagName == 'INPUT' && oImage.type == 'image' ) )
oImage = null ;
// Get the active link.
var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ;
var oImageOriginal ;
function UpdateOriginal( resetSize )
{
if ( !eImgPreview )
return ;
if ( GetE('txtUrl').value.length == 0 )
{
oImageOriginal = null ;
return ;
}
oImageOriginal = document.createElement( 'IMG' ) ; // new Image() ;
if ( resetSize )
{
oImageOriginal.onload = function()
{
this.onload = null ;
ResetSizes() ;
}
}
oImageOriginal.src = eImgPreview.src ;
}
var bPreviewInitialized ;
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
GetE('btnLockSizes').title = FCKLang.DlgImgLockRatio ;
GetE('btnResetSize').title = FCKLang.DlgBtnResetSize ;
// Load the selected element information (if any).
LoadSelection() ;
// Show/Hide the "Browse Server" button.
GetE('tdBrowse').style.display = FCKConfig.ImageBrowser ? '' : 'none' ;
GetE('divLnkBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ;
UpdateOriginal() ;
// Set the actual uploader URL.
if ( FCKConfig.ImageUpload )
GetE('frmUpload').action = FCKConfig.ImageUploadURL ;
dialog.SetAutoSize( true ) ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
SelectField( 'txtUrl' ) ;
}
function LoadSelection()
{
if ( ! oImage ) return ;
var sUrl = oImage.getAttribute( '_fcksavedurl' ) ;
if ( sUrl == null )
sUrl = GetAttribute( oImage, 'src', '' ) ;
GetE('txtUrl').value = sUrl ;
GetE('txtAlt').value = GetAttribute( oImage, 'alt', '' ) ;
GetE('txtVSpace').value = GetAttribute( oImage, 'vspace', '' ) ;
GetE('txtHSpace').value = GetAttribute( oImage, 'hspace', '' ) ;
GetE('txtBorder').value = GetAttribute( oImage, 'border', '' ) ;
GetE('cmbAlign').value = GetAttribute( oImage, 'align', '' ) ;
var iWidth, iHeight ;
var regexSize = /^\s*(\d+)px\s*$/i ;
if ( oImage.style.width )
{
var aMatchW = oImage.style.width.match( regexSize ) ;
if ( aMatchW )
{
iWidth = aMatchW[1] ;
oImage.style.width = '' ;
SetAttribute( oImage, 'width' , iWidth ) ;
}
}
if ( oImage.style.height )
{
var aMatchH = oImage.style.height.match( regexSize ) ;
if ( aMatchH )
{
iHeight = aMatchH[1] ;
oImage.style.height = '' ;
SetAttribute( oImage, 'height', iHeight ) ;
}
}
GetE('txtWidth').value = iWidth ? iWidth : GetAttribute( oImage, "width", '' ) ;
GetE('txtHeight').value = iHeight ? iHeight : GetAttribute( oImage, "height", '' ) ;
// Get Advances Attributes
GetE('txtAttId').value = oImage.id ;
GetE('cmbAttLangDir').value = oImage.dir ;
GetE('txtAttLangCode').value = oImage.lang ;
GetE('txtAttTitle').value = oImage.title ;
GetE('txtLongDesc').value = oImage.longDesc ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
GetE('txtAttClasses').value = oImage.className || '' ;
GetE('txtAttStyle').value = oImage.style.cssText ;
}
else
{
GetE('txtAttClasses').value = oImage.getAttribute('class',2) || '' ;
GetE('txtAttStyle').value = oImage.getAttribute('style',2) ;
}
if ( oLink )
{
var sLinkUrl = oLink.getAttribute( '_fcksavedurl' ) ;
if ( sLinkUrl == null )
sLinkUrl = oLink.getAttribute('href',2) ;
GetE('txtLnkUrl').value = sLinkUrl ;
GetE('cmbLnkTarget').value = oLink.target ;
}
UpdatePreview() ;
}
//#### The OK button was hit.
function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
dialog.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( FCKLang.DlgImgAlertUrl ) ;
return false ;
}
var bHasImage = ( oImage != null ) ;
if ( bHasImage && bImageButton && oImage.tagName == 'IMG' )
{
if ( confirm( 'Do you want to transform the selected image on a image button?' ) )
oImage = null ;
}
else if ( bHasImage && !bImageButton && oImage.tagName == 'INPUT' )
{
if ( confirm( 'Do you want to transform the selected image button on a simple image?' ) )
oImage = null ;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !bHasImage )
{
if ( bImageButton )
{
oImage = FCK.EditorDocument.createElement( 'input' ) ;
oImage.type = 'image' ;
oImage = FCK.InsertElement( oImage ) ;
}
else
oImage = FCK.InsertElement( 'img' ) ;
}
UpdateImage( oImage ) ;
var sLnkUrl = GetE('txtLnkUrl').value.Trim() ;
if ( sLnkUrl.length == 0 )
{
if ( oLink )
FCK.ExecuteNamedCommand( 'Unlink' ) ;
}
else
{
if ( oLink ) // Modifying an existent link.
oLink.href = sLnkUrl ;
else // Creating a new link.
{
if ( !bHasImage )
oEditor.FCKSelection.SelectNode( oImage ) ;
oLink = oEditor.FCK.CreateLink( sLnkUrl )[0] ;
if ( !bHasImage )
{
oEditor.FCKSelection.SelectNode( oLink ) ;
oEditor.FCKSelection.Collapse( false ) ;
}
}
SetAttribute( oLink, '_fcksavedurl', sLnkUrl ) ;
SetAttribute( oLink, 'target', GetE('cmbLnkTarget').value ) ;
}
return true ;
}
function UpdateImage( e, skipId )
{
e.src = GetE('txtUrl').value ;
SetAttribute( e, "_fcksavedurl", GetE('txtUrl').value ) ;
SetAttribute( e, "alt" , GetE('txtAlt').value ) ;
SetAttribute( e, "width" , GetE('txtWidth').value ) ;
SetAttribute( e, "height", GetE('txtHeight').value ) ;
SetAttribute( e, "vspace", GetE('txtVSpace').value ) ;
SetAttribute( e, "hspace", GetE('txtHSpace').value ) ;
SetAttribute( e, "border", GetE('txtBorder').value ) ;
SetAttribute( e, "align" , GetE('cmbAlign').value ) ;
// Advances Attributes
if ( ! skipId )
SetAttribute( e, 'id', GetE('txtAttId').value ) ;
SetAttribute( e, 'dir' , GetE('cmbAttLangDir').value ) ;
SetAttribute( e, 'lang' , GetE('txtAttLangCode').value ) ;
SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ;
SetAttribute( e, 'longDesc' , GetE('txtLongDesc').value ) ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
e.className = GetE('txtAttClasses').value ;
e.style.cssText = GetE('txtAttStyle').value ;
}
else
{
SetAttribute( e, 'class' , GetE('txtAttClasses').value ) ;
SetAttribute( e, 'style', GetE('txtAttStyle').value ) ;
}
}
var eImgPreview ;
var eImgPreviewLink ;
function SetPreviewElements( imageElement, linkElement )
{
eImgPreview = imageElement ;
eImgPreviewLink = linkElement ;
UpdatePreview() ;
UpdateOriginal() ;
bPreviewInitialized = true ;
}
function UpdatePreview()
{
if ( !eImgPreview || !eImgPreviewLink )
return ;
if ( GetE('txtUrl').value.length == 0 )
eImgPreviewLink.style.display = 'none' ;
else
{
UpdateImage( eImgPreview, true ) ;
if ( GetE('txtLnkUrl').value.Trim().length > 0 )
eImgPreviewLink.href = 'javascript:void(null);' ;
else
SetAttribute( eImgPreviewLink, 'href', '' ) ;
eImgPreviewLink.style.display = '' ;
}
}
var bLockRatio = true ;
function SwitchLock( lockButton )
{
bLockRatio = !bLockRatio ;
lockButton.className = bLockRatio ? 'BtnLocked' : 'BtnUnlocked' ;
lockButton.title = bLockRatio ? 'Lock sizes' : 'Unlock sizes' ;
if ( bLockRatio )
{
if ( GetE('txtWidth').value.length > 0 )
OnSizeChanged( 'Width', GetE('txtWidth').value ) ;
else
OnSizeChanged( 'Height', GetE('txtHeight').value ) ;
}
}
// Fired when the width or height input texts change
function OnSizeChanged( dimension, value )
{
// Verifies if the aspect ration has to be maintained
if ( oImageOriginal && bLockRatio )
{
var e = dimension == 'Width' ? GetE('txtHeight') : GetE('txtWidth') ;
if ( value.length == 0 || isNaN( value ) )
{
e.value = '' ;
return ;
}
if ( dimension == 'Width' )
value = value == 0 ? 0 : Math.round( oImageOriginal.height * ( value / oImageOriginal.width ) ) ;
else
value = value == 0 ? 0 : Math.round( oImageOriginal.width * ( value / oImageOriginal.height ) ) ;
if ( !isNaN( value ) )
e.value = value ;
}
UpdatePreview() ;
}
// Fired when the Reset Size button is clicked
function ResetSizes()
{
if ( ! oImageOriginal ) return ;
if ( oEditor.FCKBrowserInfo.IsGecko && !oImageOriginal.complete )
{
setTimeout( ResetSizes, 50 ) ;
return ;
}
GetE('txtWidth').value = oImageOriginal.width ;
GetE('txtHeight').value = oImageOriginal.height ;
UpdatePreview() ;
}
function BrowseServer()
{
OpenServerBrowser(
'Image',
FCKConfig.ImageBrowserURL,
FCKConfig.ImageBrowserWindowWidth,
FCKConfig.ImageBrowserWindowHeight ) ;
}
function LnkBrowseServer()
{
OpenServerBrowser(
'Link',
FCKConfig.LinkBrowserURL,
FCKConfig.LinkBrowserWindowWidth,
FCKConfig.LinkBrowserWindowHeight ) ;
}
function OpenServerBrowser( type, url, width, height )
{
sActualBrowser = type ;
OpenFileBrowser( url, width, height ) ;
}
var sActualBrowser ;
function SetUrl( url, width, height, alt )
{
if ( sActualBrowser == 'Link' )
{
GetE('txtLnkUrl').value = url ;
UpdatePreview() ;
}
else
{
GetE('txtUrl').value = url ;
GetE('txtWidth').value = width ? width : '' ;
GetE('txtHeight').value = height ? height : '' ;
if ( alt )
GetE('txtAlt').value = alt;
UpdatePreview() ;
UpdateOriginal( true ) ;
}
dialog.SetSelectedTab( 'Info' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
sActualBrowser = '' ;
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.ImageUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.ImageUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile = GetE('txtUploadFile').value ;
if ( sFile.length == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
if ( ( FCKConfig.ImageUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
( FCKConfig.ImageUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
{
OnUploadCompleted( 202 ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Flash dialog window (see fck_flash.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKTools = oEditor.FCKTools ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ;
if ( FCKConfig.FlashUpload )
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ;
if ( !FCKConfig.FlashDlgHideAdvanced )
dialog.AddTab( 'Advanced', oEditor.FCKLang.DlgAdvancedTag ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divInfo' , ( tabCode == 'Info' ) ) ;
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ;
}
// Get the selected flash embed (if available).
var oFakeImage = dialog.Selection.GetSelectedElement() ;
var oEmbed ;
if ( oFakeImage )
{
if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckflash') )
oEmbed = FCK.GetRealElement( oFakeImage ) ;
else
oFakeImage = null ;
}
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
// Load the selected element information (if any).
LoadSelection() ;
// Show/Hide the "Browse Server" button.
GetE('tdBrowse').style.display = FCKConfig.FlashBrowser ? '' : 'none' ;
// Set the actual uploader URL.
if ( FCKConfig.FlashUpload )
GetE('frmUpload').action = FCKConfig.FlashUploadURL ;
dialog.SetAutoSize( true ) ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
SelectField( 'txtUrl' ) ;
}
function LoadSelection()
{
if ( ! oEmbed ) return ;
GetE('txtUrl').value = GetAttribute( oEmbed, 'src', '' ) ;
GetE('txtWidth').value = GetAttribute( oEmbed, 'width', '' ) ;
GetE('txtHeight').value = GetAttribute( oEmbed, 'height', '' ) ;
// Get Advances Attributes
GetE('txtAttId').value = oEmbed.id ;
GetE('chkAutoPlay').checked = GetAttribute( oEmbed, 'play', 'true' ) == 'true' ;
GetE('chkLoop').checked = GetAttribute( oEmbed, 'loop', 'true' ) == 'true' ;
GetE('chkMenu').checked = GetAttribute( oEmbed, 'menu', 'true' ) == 'true' ;
GetE('cmbScale').value = GetAttribute( oEmbed, 'scale', '' ).toLowerCase() ;
GetE('txtAttTitle').value = oEmbed.title ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
GetE('txtAttClasses').value = oEmbed.getAttribute('className') || '' ;
GetE('txtAttStyle').value = oEmbed.style.cssText ;
}
else
{
GetE('txtAttClasses').value = oEmbed.getAttribute('class',2) || '' ;
GetE('txtAttStyle').value = oEmbed.getAttribute('style',2) || '' ;
}
UpdatePreview() ;
}
//#### The OK button was hit.
function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
dialog.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( oEditor.FCKLang.DlgAlertUrl ) ;
return false ;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !oEmbed )
{
oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ;
oFakeImage = null ;
}
UpdateEmbed( oEmbed ) ;
if ( !oFakeImage )
{
oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ;
oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ;
oFakeImage = FCK.InsertElement( oFakeImage ) ;
}
oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ;
return true ;
}
function UpdateEmbed( e )
{
SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ;
SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ;
SetAttribute( e, 'src', GetE('txtUrl').value ) ;
SetAttribute( e, "width" , GetE('txtWidth').value ) ;
SetAttribute( e, "height", GetE('txtHeight').value ) ;
// Advances Attributes
SetAttribute( e, 'id' , GetE('txtAttId').value ) ;
SetAttribute( e, 'scale', GetE('cmbScale').value ) ;
SetAttribute( e, 'play', GetE('chkAutoPlay').checked ? 'true' : 'false' ) ;
SetAttribute( e, 'loop', GetE('chkLoop').checked ? 'true' : 'false' ) ;
SetAttribute( e, 'menu', GetE('chkMenu').checked ? 'true' : 'false' ) ;
SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
SetAttribute( e, 'className', GetE('txtAttClasses').value ) ;
e.style.cssText = GetE('txtAttStyle').value ;
}
else
{
SetAttribute( e, 'class', GetE('txtAttClasses').value ) ;
SetAttribute( e, 'style', GetE('txtAttStyle').value ) ;
}
}
var ePreview ;
function SetPreviewElement( previewEl )
{
ePreview = previewEl ;
if ( GetE('txtUrl').value.length > 0 )
UpdatePreview() ;
}
function UpdatePreview()
{
if ( !ePreview )
return ;
while ( ePreview.firstChild )
ePreview.removeChild( ePreview.firstChild ) ;
if ( GetE('txtUrl').value.length == 0 )
ePreview.innerHTML = ' ' ;
else
{
var oDoc = ePreview.ownerDocument || ePreview.document ;
var e = oDoc.createElement( 'EMBED' ) ;
SetAttribute( e, 'src', GetE('txtUrl').value ) ;
SetAttribute( e, 'type', 'application/x-shockwave-flash' ) ;
SetAttribute( e, 'width', '100%' ) ;
SetAttribute( e, 'height', '100%' ) ;
ePreview.appendChild( e ) ;
}
}
// <embed id="ePreview" src="fck_flash/claims.swf" width="100%" height="100%" style="visibility:hidden" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
function BrowseServer()
{
OpenFileBrowser( FCKConfig.FlashBrowserURL, FCKConfig.FlashBrowserWindowWidth, FCKConfig.FlashBrowserWindowHeight ) ;
}
function SetUrl( url, width, height )
{
GetE('txtUrl').value = url ;
if ( width )
GetE('txtWidth').value = width ;
if ( height )
GetE('txtHeight').value = height ;
UpdatePreview() ;
dialog.SetSelectedTab( 'Info' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.FlashUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.FlashUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile = GetE('txtUploadFile').value ;
if ( sFile.length == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
if ( ( FCKConfig.FlashUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
( FCKConfig.FlashUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
{
OnUploadCompleted( 202 ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
}
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.