code stringlengths 1 2.08M | language stringclasses 1
value |
|---|---|
(function ($) {
Drupal.behaviors.commentFieldsetSummaries = {
attach: function (context) {
$('fieldset.comment-node-settings-form', context).drupalSetSummary(function (context) {
return Drupal.checkPlain($('.form-item-comment input:checked', context).next('label').text());
});
// Provide the summary for the node type form.
$('fieldset.comment-node-type-settings-form', context).drupalSetSummary(function(context) {
var vals = [];
// Default comment setting.
vals.push($(".form-item-comment select option:selected", context).text());
// Threading.
var threading = $(".form-item-comment-default-mode input:checked", context).next('label').text();
if (threading) {
vals.push(threading);
}
// Comments per page.
var number = $(".form-item-comment-default-per-page select option:selected", context).val();
vals.push(Drupal.t('@number comments per page', {'@number': number}));
return Drupal.checkPlain(vals.join(', '));
});
}
};
})(jQuery);
| JavaScript |
(function ($) {
Drupal.behaviors.openid = {
attach: function (context) {
var loginElements = $('.form-item-name, .form-item-pass, li.openid-link');
var openidElements = $('.form-item-openid-identifier, li.user-link');
var cookie = $.cookie('Drupal.visitor.openid_identifier');
// This behavior attaches by ID, so is only valid once on a page.
if (!$('#edit-openid-identifier.openid-processed').length) {
if (cookie) {
$('#edit-openid-identifier').val(cookie);
}
if ($('#edit-openid-identifier').val() || location.hash == '#openid-login') {
$('#edit-openid-identifier').addClass('openid-processed');
loginElements.hide();
// Use .css('display', 'block') instead of .show() to be Konqueror friendly.
openidElements.css('display', 'block');
}
}
$('li.openid-link:not(.openid-processed)', context)
.addClass('openid-processed')
.click(function () {
loginElements.hide();
openidElements.css('display', 'block');
// Remove possible error message.
$('#edit-name, #edit-pass').removeClass('error');
$('div.messages.error').hide();
// Set focus on OpenID Identifier field.
$('#edit-openid-identifier')[0].focus();
return false;
});
$('li.user-link:not(.openid-processed)', context)
.addClass('openid-processed')
.click(function () {
openidElements.hide();
loginElements.css('display', 'block');
// Clear OpenID Identifier field and remove possible error message.
$('#edit-openid-identifier').val('').removeClass('error');
$('div.messages.error').css('display', 'block');
// Set focus on username field.
$('#edit-name')[0].focus();
return false;
});
}
};
})(jQuery);
| JavaScript |
/**
* @file
* Attaches the behaviors for the Overlay parent pages.
*/
(function ($) {
/**
* Open the overlay, or load content into it, when an admin link is clicked.
*/
Drupal.behaviors.overlayParent = {
attach: function (context, settings) {
if (Drupal.overlay.isOpen) {
Drupal.overlay.makeDocumentUntabbable(context);
}
if (this.processed) {
return;
}
this.processed = true;
$(window)
// When the hash (URL fragment) changes, open the overlay if needed.
.bind('hashchange.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOperateByURLFragment'))
// Trigger the hashchange handler once, after the page is loaded, so that
// permalinks open the overlay.
.triggerHandler('hashchange.drupal-overlay');
$(document)
// Instead of binding a click event handler to every link we bind one to
// the document and only handle events that bubble up. This allows other
// scripts to bind their own handlers to links and also to prevent
// overlay's handling.
.bind('click.drupal-overlay mouseup.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOverrideLink'));
}
};
/**
* Overlay object for parent windows.
*
* Events
* Overlay triggers a number of events that can be used by other scripts.
* - drupalOverlayOpen: This event is triggered when the overlay is opened.
* - drupalOverlayBeforeClose: This event is triggered when the overlay attempts
* to close. If an event handler returns false, the close will be prevented.
* - drupalOverlayClose: This event is triggered when the overlay is closed.
* - drupalOverlayBeforeLoad: This event is triggered right before a new URL
* is loaded into the overlay.
* - drupalOverlayReady: This event is triggered when the DOM of the overlay
* child document is fully loaded.
* - drupalOverlayLoad: This event is triggered when the overlay is finished
* loading.
* - drupalOverlayResize: This event is triggered when the overlay is being
* resized to match the parent window.
*/
Drupal.overlay = Drupal.overlay || {
isOpen: false,
isOpening: false,
isClosing: false,
isLoading: false
};
Drupal.overlay.prototype = {};
/**
* Open the overlay.
*
* @param url
* The URL of the page to open in the overlay.
*
* @return
* TRUE if the overlay was opened, FALSE otherwise.
*/
Drupal.overlay.open = function (url) {
// Just one overlay is allowed.
if (this.isOpen || this.isOpening) {
return this.load(url);
}
this.isOpening = true;
// Store the original document title.
this.originalTitle = document.title;
// Create the dialog and related DOM elements.
this.create();
this.isOpening = false;
this.isOpen = true;
$(document.documentElement).addClass('overlay-open');
this.makeDocumentUntabbable();
// Allow other scripts to respond to this event.
$(document).trigger('drupalOverlayOpen');
return this.load(url);
};
/**
* Create the underlying markup and behaviors for the overlay.
*/
Drupal.overlay.create = function () {
this.$container = $(Drupal.theme('overlayContainer'))
.appendTo(document.body);
// Overlay uses transparent iframes that cover the full parent window.
// When the overlay is open the scrollbar of the parent window is hidden.
// Because some browsers show a white iframe background for a short moment
// while loading a page into an iframe, overlay uses two iframes. By loading
// the page in a hidden (inactive) iframe the user doesn't see the white
// background. When the page is loaded the active and inactive iframes
// are switched.
this.activeFrame = this.$iframeA = $(Drupal.theme('overlayElement'))
.appendTo(this.$container);
this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement'))
.appendTo(this.$container);
this.$iframeA.bind('load.drupal-overlay', { self: this.$iframeA[0], sibling: this.$iframeB }, $.proxy(this, 'loadChild'));
this.$iframeB.bind('load.drupal-overlay', { self: this.$iframeB[0], sibling: this.$iframeA }, $.proxy(this, 'loadChild'));
// Add a second class "drupal-overlay-open" to indicate these event handlers
// should only be bound when the overlay is open.
var eventClass = '.drupal-overlay.drupal-overlay-open';
$(window)
.bind('resize' + eventClass, $.proxy(this, 'eventhandlerOuterResize'));
$(document)
.bind('drupalOverlayLoad' + eventClass, $.proxy(this, 'eventhandlerOuterResize'))
.bind('drupalOverlayReady' + eventClass +
' drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerSyncURLFragment'))
.bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRefreshPage'))
.bind('drupalOverlayBeforeClose' + eventClass +
' drupalOverlayBeforeLoad' + eventClass +
' drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerDispatchEvent'));
if ($('.overlay-displace-top, .overlay-displace-bottom').length) {
$(document)
.bind('drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerAlterDisplacedElements'))
.bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRestoreDisplacedElements'));
}
};
/**
* Load the given URL into the overlay iframe.
*
* Use this method to change the URL being loaded in the overlay if it is
* already open.
*
* @return
* TRUE if URL is loaded into the overlay, FALSE otherwise.
*/
Drupal.overlay.load = function (url) {
if (!this.isOpen) {
return false;
}
// Allow other scripts to respond to this event.
$(document).trigger('drupalOverlayBeforeLoad');
$(document.documentElement).addClass('overlay-loading');
// The contentDocument property is not supported in IE until IE8.
var iframeDocument = this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document;
// location.replace doesn't create a history entry. location.href does.
// In this case, we want location.replace, as we're creating the history
// entry using URL fragments.
iframeDocument.location.replace(url);
return true;
};
/**
* Close the overlay and remove markup related to it from the document.
*
* @return
* TRUE if the overlay was closed, FALSE otherwise.
*/
Drupal.overlay.close = function () {
// Prevent double execution when close is requested more than once.
if (!this.isOpen || this.isClosing) {
return false;
}
// Allow other scripts to respond to this event.
var event = $.Event('drupalOverlayBeforeClose');
$(document).trigger(event);
// If a handler returned false, the close will be prevented.
if (event.isDefaultPrevented()) {
return false;
}
this.isClosing = true;
this.isOpen = false;
$(document.documentElement).removeClass('overlay-open');
// Restore the original document title.
document.title = this.originalTitle;
this.makeDocumentTabbable();
// Allow other scripts to respond to this event.
$(document).trigger('drupalOverlayClose');
// When the iframe is still loading don't destroy it immediately but after
// the content is loaded (see Drupal.overlay.loadChild).
if (!this.isLoading) {
this.destroy();
this.isClosing = false;
}
return true;
};
/**
* Destroy the overlay.
*/
Drupal.overlay.destroy = function () {
$([document, window]).unbind('.drupal-overlay-open');
this.$container.remove();
this.$container = null;
this.$iframeA = null;
this.$iframeB = null;
this.iframeWindow = null;
};
/**
* Redirect the overlay parent window to the given URL.
*
* @param url
* Can be an absolute URL or a relative link to the domain root.
*/
Drupal.overlay.redirect = function (url) {
// Create a native Link object, so we can use its object methods.
var link = $(url.link(url)).get(0);
// If the link is already open, force the hashchange event to simulate reload.
if (window.location.href == link.href) {
$(window).triggerHandler('hashchange.drupal-overlay');
}
window.location.href = link.href;
return true;
};
/**
* Bind the child window.
*
* Note that this function is fired earlier than Drupal.overlay.loadChild.
*/
Drupal.overlay.bindChild = function (iframeWindow, isClosing) {
this.iframeWindow = iframeWindow;
// We are done if the child window is closing.
if (isClosing || this.isClosing || !this.isOpen) {
return;
}
// Allow other scripts to respond to this event.
$(document).trigger('drupalOverlayReady');
};
/**
* Event handler: load event handler for the overlay iframe.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: load
* - event.currentTarget: iframe
*/
Drupal.overlay.loadChild = function (event) {
var iframe = event.data.self;
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var iframeWindow = iframeDocument.defaultView || iframeDocument.parentWindow;
if (iframeWindow.location == 'about:blank') {
return;
}
this.isLoading = false;
$(document.documentElement).removeClass('overlay-loading');
event.data.sibling.removeClass('overlay-active').attr({ 'tabindex': -1 });
// Only continue when overlay is still open and not closing.
if (this.isOpen && !this.isClosing) {
// And child document is an actual overlayChild.
if (iframeWindow.Drupal && iframeWindow.Drupal.overlayChild) {
// Replace the document title with title of iframe.
document.title = iframeWindow.document.title;
this.activeFrame = $(iframe)
.addClass('overlay-active')
// Add a title attribute to the iframe for accessibility.
.attr('title', Drupal.t('@title dialog', { '@title': iframeWindow.jQuery('#overlay-title').text() })).removeAttr('tabindex');
this.inactiveFrame = event.data.sibling;
// Load an empty document into the inactive iframe.
(this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document).location.replace('about:blank');
// Move the focus to just before the "skip to main content" link inside
// the overlay.
this.activeFrame.focus();
var skipLink = iframeWindow.jQuery('a:first');
Drupal.overlay.setFocusBefore(skipLink, iframeWindow.document);
// Allow other scripts to respond to this event.
$(document).trigger('drupalOverlayLoad');
}
else {
window.location = iframeWindow.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, '');
}
}
else {
this.destroy();
}
};
/**
* Creates a placeholder element to receive document focus.
*
* Setting the document focus to a link will make it visible, even if it's a
* "skip to main content" link that should normally be visible only when the
* user tabs to it. This function can be used to set the document focus to
* just before such an invisible link.
*
* @param $element
* The jQuery element that should receive focus on the next tab press.
* @param document
* The iframe window element to which the placeholder should be added. The
* placeholder element has to be created inside the same iframe as the element
* it precedes, to keep IE happy. (http://bugs.jquery.com/ticket/4059)
*/
Drupal.overlay.setFocusBefore = function ($element, document) {
// Create an anchor inside the placeholder document.
var placeholder = document.createElement('a');
var $placeholder = $(placeholder).addClass('element-invisible').attr('href', '#');
// Put the placeholder where it belongs, and set the document focus to it.
$placeholder.insertBefore($element);
$placeholder.focus();
// Make the placeholder disappear as soon as it loses focus, so that it
// doesn't appear in the tab order again.
$placeholder.one('blur', function () {
$(this).remove();
});
};
/**
* Check if the given link is in the administrative section of the site.
*
* @param url
* The URL to be tested.
*
* @return boolean
* TRUE if the URL represents an administrative link, FALSE otherwise.
*/
Drupal.overlay.isAdminLink = function (url) {
if (Drupal.overlay.isExternalLink(url)) {
return false;
}
var path = this.getPath(url);
// Turn the list of administrative paths into a regular expression.
if (!this.adminPathRegExp) {
var prefix = '';
if (Drupal.settings.overlay.pathPrefixes.length) {
// Allow path prefixes used for language negatiation followed by slash,
// and the empty string.
prefix = '(' + Drupal.settings.overlay.pathPrefixes.join('/|') + '/|)';
}
var adminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.admin.replace(/\s+/g, '|') + ')$';
var nonAdminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.non_admin.replace(/\s+/g, '|') + ')$';
adminPaths = adminPaths.replace(/\*/g, '.*');
nonAdminPaths = nonAdminPaths.replace(/\*/g, '.*');
this.adminPathRegExp = new RegExp(adminPaths);
this.nonAdminPathRegExp = new RegExp(nonAdminPaths);
}
return this.adminPathRegExp.exec(path) && !this.nonAdminPathRegExp.exec(path);
};
/**
* Determine whether a link is external to the site.
*
* @param url
* The URL to be tested.
*
* @return boolean
* TRUE if the URL is external to the site, FALSE otherwise.
*/
Drupal.overlay.isExternalLink = function (url) {
var re = RegExp('^((f|ht)tps?:)?//(?!' + window.location.host + ')');
return re.test(url);
};
/**
* Event handler: resizes overlay according to the size of the parent window.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: any
* - event.currentTarget: any
*/
Drupal.overlay.eventhandlerOuterResize = function (event) {
// Proceed only if the overlay still exists.
if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
return;
}
// IE6 uses position:absolute instead of position:fixed.
if (typeof document.body.style.maxHeight != 'string') {
this.activeFrame.height($(window).height());
}
// Allow other scripts to respond to this event.
$(document).trigger('drupalOverlayResize');
};
/**
* Event handler: resizes displaced elements so they won't overlap the scrollbar
* of overlay's iframe.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: any
* - event.currentTarget: any
*/
Drupal.overlay.eventhandlerAlterDisplacedElements = function (event) {
// Proceed only if the overlay still exists.
if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
return;
}
$(this.iframeWindow.document.body).css({
marginTop: Drupal.overlay.getDisplacement('top'),
marginBottom: Drupal.overlay.getDisplacement('bottom')
})
// IE7 isn't reflowing the document immediately.
// @todo This might be fixed in a cleaner way.
.addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow');
var documentHeight = this.iframeWindow.document.body.clientHeight;
var documentWidth = this.iframeWindow.document.body.clientWidth;
// IE6 doesn't support maxWidth, use width instead.
var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width';
if (Drupal.overlay.leftSidedScrollbarOffset === undefined && $(document.documentElement).attr('dir') === 'rtl') {
// We can't use element.clientLeft to detect whether scrollbars are placed
// on the left side of the element when direction is set to "rtl" as most
// browsers dont't support it correctly.
// http://www.gtalbot.org/BugzillaSection/DocumentAllDHTMLproperties.html
// There seems to be absolutely no way to detect whether the scrollbar
// is on the left side in Opera; always expect scrollbar to be on the left.
if ($.browser.opera) {
Drupal.overlay.leftSidedScrollbarOffset = document.documentElement.clientWidth - this.iframeWindow.document.documentElement.clientWidth + this.iframeWindow.document.documentElement.clientLeft;
}
else if (this.iframeWindow.document.documentElement.clientLeft) {
Drupal.overlay.leftSidedScrollbarOffset = this.iframeWindow.document.documentElement.clientLeft;
}
else {
var el1 = $('<div style="direction: rtl; overflow: scroll;"></div>').appendTo(document.body);
var el2 = $('<div></div>').appendTo(el1);
Drupal.overlay.leftSidedScrollbarOffset = parseInt(el2[0].offsetLeft - el1[0].offsetLeft);
el1.remove();
}
}
// Consider any element that should be visible above the overlay (such as
// a toolbar).
$('.overlay-displace-top, .overlay-displace-bottom').each(function () {
var data = $(this).data();
var maxWidth = documentWidth;
// In IE, Shadow filter makes element to overlap the scrollbar with 1px.
if (this.filters && this.filters.length && this.filters.item('DXImageTransform.Microsoft.Shadow')) {
maxWidth -= 1;
}
if (Drupal.overlay.leftSidedScrollbarOffset) {
$(this).css('left', Drupal.overlay.leftSidedScrollbarOffset);
}
// Prevent displaced elements overlapping window's scrollbar.
var currentMaxWidth = parseInt($(this).css(maxWidthName));
if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) {
$(this).css(maxWidthName, maxWidth);
(data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true;
}
// Use a more rigorous approach if the displaced element still overlaps
// window's scrollbar; clip the element on the right.
var offset = $(this).offset();
var offsetRight = offset.left + $(this).outerWidth();
if ((data.drupalOverlay && data.drupalOverlay.clip) || offsetRight > maxWidth) {
if (Drupal.overlay.leftSidedScrollbarOffset) {
$(this).css('clip', 'rect(auto, auto, ' + (documentHeight - offset.top) + 'px, ' + (Drupal.overlay.leftSidedScrollbarOffset + 2) + 'px)');
}
else {
$(this).css('clip', 'rect(auto, ' + (maxWidth - offset.left) + 'px, ' + (documentHeight - offset.top) + 'px, auto)');
}
(data.drupalOverlay = data.drupalOverlay || {}).clip = true;
}
});
};
/**
* Event handler: restores size of displaced elements as they were before
* overlay was opened.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: any
* - event.currentTarget: any
*/
Drupal.overlay.eventhandlerRestoreDisplacedElements = function (event) {
var $displacedElements = $('.overlay-displace-top, .overlay-displace-bottom');
try {
$displacedElements.css({ maxWidth: '', clip: '' });
}
// IE bug that doesn't allow unsetting style.clip (http://dev.jquery.com/ticket/6512).
catch (err) {
$displacedElements.attr('style', function (index, attr) {
return attr.replace(/clip\s*:\s*rect\([^)]+\);?/i, '');
});
}
};
/**
* Event handler: overrides href of administrative links to be opened in
* the overlay.
*
* This click event handler should be bound to any document (for example the
* overlay iframe) of which you want links to open in the overlay.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: click, mouseup
* - event.currentTarget: document
*
* @see Drupal.overlayChild.behaviors.addClickHandler
*/
Drupal.overlay.eventhandlerOverrideLink = function (event) {
// In some browsers the click event isn't fired for right-clicks. Use the
// mouseup event for right-clicks and the click event for everything else.
if ((event.type == 'click' && event.button == 2) || (event.type == 'mouseup' && event.button != 2)) {
return;
}
var $target = $(event.target);
// Only continue if clicked target (or one of its parents) is a link.
if (!$target.is('a')) {
$target = $target.closest('a');
if (!$target.length) {
return;
}
}
// Never open links in the overlay that contain the overlay-exclude class.
if ($target.hasClass('overlay-exclude')) {
return;
}
// Close the overlay when the link contains the overlay-close class.
if ($target.hasClass('overlay-close')) {
// Clearing the overlay URL fragment will close the overlay.
$.bbq.removeState('overlay');
return;
}
var target = $target[0];
var href = target.href;
// Only handle links that have an href attribute and use the HTTP(S) protocol.
if (href != undefined && href != '' && target.protocol.match(/^https?\:/)) {
var anchor = href.replace(target.ownerDocument.location.href, '');
// Skip anchor links.
if (anchor.length == 0 || anchor.charAt(0) == '#') {
return;
}
// Open admin links in the overlay.
else if (this.isAdminLink(href)) {
// If the link contains the overlay-restore class and the overlay-context
// state is set, also update the parent window's location.
var parentLocation = ($target.hasClass('overlay-restore') && typeof $.bbq.getState('overlay-context') == 'string')
? Drupal.settings.basePath + $.bbq.getState('overlay-context')
: null;
href = this.fragmentizeLink($target.get(0), parentLocation);
// Only override default behavior when left-clicking and user is not
// pressing the ALT, CTRL, META (Command key on the Macintosh keyboard)
// or SHIFT key.
if (event.button == 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
// Redirect to a fragmentized href. This will trigger a hashchange event.
this.redirect(href);
// Prevent default action and further propagation of the event.
return false;
}
// Otherwise alter clicked link's href. This is being picked up by
// the default action handler.
else {
$target
// Restore link's href attribute on blur or next click.
.one('blur mousedown', { target: target, href: target.href }, function (event) { $(event.data.target).attr('href', event.data.href); })
.attr('href', href);
}
}
// Non-admin links should close the overlay and open in the main window,
// which is the default action for a link. We only need to handle them
// if the overlay is open and the clicked link is inside the overlay iframe.
else if (this.isOpen && target.ownerDocument === this.iframeWindow.document) {
// Open external links in the immediate parent of the frame, unless the
// link already has a different target.
if (target.hostname != window.location.hostname) {
if (!$target.attr('target')) {
$target.attr('target', '_parent');
}
}
else {
// Add the overlay-context state to the link, so "overlay-restore" links
// can restore the context.
if ($target[0].hash) {
// Leave links with an existing fragment alone. Adding an extra
// parameter to a link like "node/1#section-1" breaks the link.
}
else {
// For links with no existing fragment, add the overlay context.
$target.attr('href', $.param.fragment(href, { 'overlay-context': this.getPath(window.location) + window.location.search }));
}
// When the link has a destination query parameter and that destination
// is an admin link we need to fragmentize it. This will make it reopen
// in the overlay.
var params = $.deparam.querystring(href);
if (params.destination && this.isAdminLink(params.destination)) {
var fragmentizedDestination = $.param.fragment(this.getPath(window.location), { overlay: params.destination });
$target.attr('href', $.param.querystring(href, { destination: fragmentizedDestination }));
}
// Make the link open in the immediate parent of the frame, unless the
// link already has a different target.
if (!$target.attr('target')) {
$target.attr('target', '_parent');
}
}
}
}
};
/**
* Event handler: opens or closes the overlay based on the current URL fragment.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: hashchange
* - event.currentTarget: document
*/
Drupal.overlay.eventhandlerOperateByURLFragment = function (event) {
// If we changed the hash to reflect an internal redirect in the overlay,
// its location has already been changed, so don't do anything.
if ($.data(window.location, window.location.href) === 'redirect') {
$.data(window.location, window.location.href, null);
return;
}
// Get the overlay URL from the current URL fragment.
var state = $.bbq.getState('overlay');
if (state) {
// Append render variable, so the server side can choose the right
// rendering and add child frame code to the page if needed.
var url = $.param.querystring(Drupal.settings.basePath + state, { render: 'overlay' });
this.open(url);
this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
}
// If there is no overlay URL in the fragment and the overlay is (still)
// open, close the overlay.
else if (this.isOpen && !this.isClosing) {
this.close();
this.resetActiveClass(this.getPath(window.location));
}
};
/**
* Event handler: makes sure the internal overlay URL is reflected in the parent
* URL fragment.
*
* Normally the parent URL fragment determines the overlay location. However, if
* the overlay redirects internally, the parent doesn't get informed, and the
* parent URL fragment will be out of date. This is a sanity check to make
* sure we're in the right place.
*
* The parent URL fragment is also not updated automatically when overlay's
* open, close or load functions are used directly (instead of through
* eventhandlerOperateByURLFragment).
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: drupalOverlayReady, drupalOverlayClose
* - event.currentTarget: document
*/
Drupal.overlay.eventhandlerSyncURLFragment = function (event) {
if (this.isOpen) {
var expected = $.bbq.getState('overlay');
// This is just a sanity check, so we're comparing paths, not query strings.
if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) {
// There may have been a redirect inside the child overlay window that the
// parent wasn't aware of. Update the parent URL fragment appropriately.
var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location);
// Set a 'redirect' flag on the new location so the hashchange event handler
// knows not to change the overlay's content.
$.data(window.location, newLocation, 'redirect');
// Use location.replace() so we don't create an extra history entry.
window.location.replace(newLocation);
}
}
else {
$.bbq.removeState('overlay');
}
};
/**
* Event handler: if the child window suggested that the parent refresh on
* close, force a page refresh.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: drupalOverlayClose
* - event.currentTarget: document
*/
Drupal.overlay.eventhandlerRefreshPage = function (event) {
if (Drupal.overlay.refreshPage) {
window.location.reload(true);
}
};
/**
* Event handler: dispatches events to the overlay document.
*
* @param event
* Event being triggered, with the following restrictions:
* - event.type: any
* - event.currentTarget: any
*/
Drupal.overlay.eventhandlerDispatchEvent = function (event) {
if (this.iframeWindow && this.iframeWindow.document) {
this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event);
}
};
/**
* Make a regular admin link into a URL that will trigger the overlay to open.
*
* @param link
* A JavaScript Link object (i.e. an <a> element).
* @param parentLocation
* (optional) URL to override the parent window's location with.
*
* @return
* A URL that will trigger the overlay (in the form
* /node/1#overlay=admin/config).
*/
Drupal.overlay.fragmentizeLink = function (link, parentLocation) {
// Don't operate on links that are already overlay-ready.
var params = $.deparam.fragment(link.href);
if (params.overlay) {
return link.href;
}
// Determine the link's original destination. Set ignorePathFromQueryString to
// true to prevent transforming this link into a clean URL while clean URLs
// may be disabled.
var path = this.getPath(link, true);
// Preserve existing query and fragment parameters in the URL, except for
// "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment.
var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash;
// Assemble and return the overlay-ready link.
return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
};
/**
* Refresh any regions of the page that are displayed outside the overlay.
*
* @param data
* An array of objects with information on the page regions to be refreshed.
* For each object, the key is a CSS class identifying the region to be
* refreshed, and the value represents the section of the Drupal $page array
* corresponding to this region.
*/
Drupal.overlay.refreshRegions = function (data) {
$.each(data, function () {
var region_info = this;
$.each(region_info, function (regionClass) {
var regionName = region_info[regionClass];
var regionSelector = '.' + regionClass;
// Allow special behaviors to detach.
Drupal.detachBehaviors($(regionSelector));
$.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) {
$(regionSelector).replaceWith($(newElement));
Drupal.attachBehaviors($(regionSelector), Drupal.settings);
});
});
});
};
/**
* Reset the active class on links in displaced elements according to
* given path.
*
* @param activePath
* Path to match links against.
*/
Drupal.overlay.resetActiveClass = function(activePath) {
var self = this;
var windowDomain = window.location.protocol + window.location.hostname;
$('.overlay-displace-top, .overlay-displace-bottom')
.find('a[href]')
// Remove active class from all links in displaced elements.
.removeClass('active')
// Add active class to links that match activePath.
.each(function () {
var linkDomain = this.protocol + this.hostname;
var linkPath = self.getPath(this);
// A link matches if it is part of the active trail of activePath, except
// for frontpage links.
if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
$(this).addClass('active');
}
});
};
/**
* Helper function to get the (corrected) Drupal path of a link.
*
* @param link
* Link object or string to get the Drupal path from.
* @param ignorePathFromQueryString
* Boolean whether to ignore path from query string if path appears empty.
*
* @return
* The Drupal path.
*/
Drupal.overlay.getPath = function (link, ignorePathFromQueryString) {
if (typeof link == 'string') {
// Create a native Link object, so we can use its object methods.
link = $(link.link(link)).get(0);
}
var path = link.pathname;
// Ensure a leading slash on the path, omitted in some browsers.
if (path.charAt(0) != '/') {
path = '/' + path;
}
path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), '');
if (path == '' && !ignorePathFromQueryString) {
// If the path appears empty, it might mean the path is represented in the
// query string (clean URLs are not used).
var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search);
if (match && match.length == 4) {
path = match[2];
}
}
return path;
};
/**
* Get the total displacement of given region.
*
* @param region
* Region name. Either "top" or "bottom".
*
* @return
* The total displacement of given region in pixels.
*/
Drupal.overlay.getDisplacement = function (region) {
var displacement = 0;
var lastDisplaced = $('.overlay-displace-' + region + ':last');
if (lastDisplaced.length) {
displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight();
// In modern browsers (including IE9), when box-shadow is defined, use the
// normal height.
var cssBoxShadowValue = lastDisplaced.css('box-shadow');
var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
// In IE8 and below, we use the shadow filter to apply box-shadow styles to
// the toolbar. It adds some extra height that we need to remove.
if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) {
displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength;
displacement = Math.max(0, displacement);
}
}
return displacement;
};
/**
* Makes elements outside the overlay unreachable via the tab key.
*
* @param context
* The part of the DOM that should have its tabindexes changed. Defaults to
* the entire page.
*/
Drupal.overlay.makeDocumentUntabbable = function (context) {
// Manipulating tabindexes for the entire document is unacceptably slow in IE6
// and IE7, so in those browsers, the underlying page will still be reachable
// via the tab key. However, we still make the links within the Disable
// message unreachable, because the same message also exists within the
// child document. The duplicate copy in the underlying document is only for
// assisting screen-reader users navigating the document with reading commands
// that follow markup order rather than tab order.
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
$('#overlay-disable-message a', context).attr('tabindex', -1);
return;
}
context = context || document.body;
var $overlay, $tabbable, $hasTabindex;
// Determine which elements on the page already have a tabindex.
$hasTabindex = $('[tabindex] :not(.overlay-element)', context);
// Record the tabindex for each element, so we can restore it later.
$hasTabindex.each(Drupal.overlay._recordTabindex);
// Add the tabbable elements from the current context to any that we might
// have previously recorded.
Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex);
// Set tabindex to -1 on everything outside the overlay and toolbars, so that
// the underlying page is unreachable.
// By default, browsers make a, area, button, input, object, select, textarea,
// and iframe elements reachable via the tab key.
$tabbable = $('a, area, button, input, object, select, textarea, iframe');
// If another element (like a div) has a tabindex, it's also tabbable.
$tabbable = $tabbable.add($hasTabindex);
// Leave links inside the overlay and toolbars alone.
$overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*');
$tabbable = $tabbable.not($overlay);
// We now have a list of everything in the underlying document that could
// possibly be reachable via the tab key. Make it all unreachable.
$tabbable.attr('tabindex', -1);
};
/**
* Restores the original tabindex value of a group of elements.
*
* @param context
* The part of the DOM that should have its tabindexes restored. Defaults to
* the entire page.
*/
Drupal.overlay.makeDocumentTabbable = function (context) {
// Manipulating tabindexes is unacceptably slow in IE6 and IE7. In those
// browsers, the underlying page was never made unreachable via tab, so
// there is no work to be done here.
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
return;
}
var $needsTabindex;
context = context || document.body;
// Make the underlying document tabbable again by removing all existing
// tabindex attributes.
var $tabindex = $('[tabindex]', context);
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
// removeAttr('tabindex') is broken in IE6-7, but the DOM function
// removeAttribute works.
var i;
var length = $tabindex.length;
for (i = 0; i < length; i++) {
$tabindex[i].removeAttribute('tabIndex');
}
}
else {
$tabindex.removeAttr('tabindex');
}
// Restore the tabindex attributes that existed before the overlay was opened.
$needsTabindex = $(Drupal.overlay._hasTabindex, context);
$needsTabindex.each(Drupal.overlay._restoreTabindex);
Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex);
};
/**
* Record the tabindex for an element, using $.data.
*
* Meant to be used as a jQuery.fn.each callback.
*/
Drupal.overlay._recordTabindex = function () {
var $element = $(this);
var tabindex = $(this).attr('tabindex');
$element.data('drupalOverlayOriginalTabIndex', tabindex);
};
/**
* Restore an element's original tabindex.
*
* Meant to be used as a jQuery.fn.each callback.
*/
Drupal.overlay._restoreTabindex = function () {
var $element = $(this);
var tabindex = $element.data('drupalOverlayOriginalTabIndex');
$element.attr('tabindex', tabindex);
};
/**
* Theme function to create the overlay iframe element.
*/
Drupal.theme.prototype.overlayContainer = function () {
return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
};
/**
* Theme function to create an overlay iframe element.
*/
Drupal.theme.prototype.overlayElement = function (url) {
return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
};
})(jQuery);
| JavaScript |
/**
* @file
* Attaches the behaviors for the Overlay child pages.
*/
(function ($) {
/**
* Attach the child dialog behavior to new content.
*/
Drupal.behaviors.overlayChild = {
attach: function (context, settings) {
// Make sure this behavior is not processed more than once.
if (this.processed) {
return;
}
this.processed = true;
// If we cannot reach the parent window, break out of the overlay.
if (!parent.Drupal || !parent.Drupal.overlay) {
window.location = window.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, '');
}
var settings = settings.overlayChild || {};
// If the entire parent window should be refreshed when the overlay is
// closed, pass that information to the parent window.
if (settings.refreshPage) {
parent.Drupal.overlay.refreshPage = true;
}
// If a form has been submitted successfully, then the server side script
// may have decided to tell the parent window to close the popup dialog.
if (settings.closeOverlay) {
parent.Drupal.overlay.bindChild(window, true);
// Use setTimeout to close the child window from a separate thread,
// because the current one is busy processing Drupal behaviors.
setTimeout(function () {
if (typeof settings.redirect == 'string') {
parent.Drupal.overlay.redirect(settings.redirect);
}
else {
parent.Drupal.overlay.close();
}
}, 1);
return;
}
// If one of the regions displaying outside the overlay needs to be
// reloaded immediately, let the parent window know.
if (settings.refreshRegions) {
parent.Drupal.overlay.refreshRegions(settings.refreshRegions);
}
// Ok, now we can tell the parent window we're ready.
parent.Drupal.overlay.bindChild(window);
// IE8 crashes on certain pages if this isn't called; reason unknown.
window.scrollTo(window.scrollX, window.scrollY);
// Attach child related behaviors to the iframe document.
Drupal.overlayChild.attachBehaviors(context, settings);
// There are two links within the message that informs people about the
// overlay and how to disable it. Make sure both links are visible when
// either one has focus and add a class to the wrapper for styling purposes.
$('#overlay-disable-message', context)
.focusin(function () {
$(this).addClass('overlay-disable-message-focused');
$('a.element-focusable', this).removeClass('element-invisible');
})
.focusout(function () {
$(this).removeClass('overlay-disable-message-focused');
$('a.element-focusable', this).addClass('element-invisible');
});
}
};
/**
* Overlay object for child windows.
*/
Drupal.overlayChild = Drupal.overlayChild || {
behaviors: {}
};
Drupal.overlayChild.prototype = {};
/**
* Attach child related behaviors to the iframe document.
*/
Drupal.overlayChild.attachBehaviors = function (context, settings) {
$.each(this.behaviors, function () {
this(context, settings);
});
};
/**
* Capture and handle clicks.
*
* Instead of binding a click event handler to every link we bind one to the
* document and handle events that bubble up. This also allows other scripts
* to bind their own handlers to links and also to prevent overlay's handling.
*/
Drupal.overlayChild.behaviors.addClickHandler = function (context, settings) {
$(document).bind('click.drupal-overlay mouseup.drupal-overlay', $.proxy(parent.Drupal.overlay, 'eventhandlerOverrideLink'));
};
/**
* Modify forms depending on their relation to the overlay.
*
* By default, forms are assumed to keep the flow in the overlay. Thus their
* action attribute get a ?render=overlay suffix.
*/
Drupal.overlayChild.behaviors.parseForms = function (context, settings) {
$('form', context).once('overlay', function () {
// Obtain the action attribute of the form.
var action = $(this).attr('action');
// Keep internal forms in the overlay.
if (action == undefined || (action.indexOf('http') != 0 && action.indexOf('https') != 0)) {
action += (action.indexOf('?') > -1 ? '&' : '?') + 'render=overlay';
$(this).attr('action', action);
}
// Submit external forms into a new window.
else {
$(this).attr('target', '_new');
}
});
};
/**
* Replace the overlay title with a message while loading another page.
*/
Drupal.overlayChild.behaviors.loading = function (context, settings) {
var $title;
var text = Drupal.t('Loading');
var dots = '';
$(document).bind('drupalOverlayBeforeLoad.drupal-overlay.drupal-overlay-child-loading', function () {
$title = $('#overlay-title').text(text);
var id = setInterval(function () {
dots = (dots.length > 10) ? '' : dots + '.';
$title.text(text + dots);
}, 500);
});
};
/**
* Switch active tab immediately.
*/
Drupal.overlayChild.behaviors.tabs = function (context, settings) {
var $tabsLinks = $('#overlay-tabs > li > a');
$('#overlay-tabs > li > a').bind('click.drupal-overlay', function () {
var active_tab = Drupal.t('(active tab)');
$tabsLinks.parent().siblings().removeClass('active').find('element-invisible:contains(' + active_tab + ')').appendTo(this);
$(this).parent().addClass('active');
});
};
/**
* If the shortcut add/delete button exists, move it to the overlay titlebar.
*/
Drupal.overlayChild.behaviors.shortcutAddLink = function (context, settings) {
// Remove any existing shortcut button markup from the titlebar.
$('#overlay-titlebar').find('.add-or-remove-shortcuts').remove();
// If the shortcut add/delete button exists, move it to the titlebar.
var $addToShortcuts = $('.add-or-remove-shortcuts');
if ($addToShortcuts.length) {
$addToShortcuts.insertAfter('#overlay-title');
}
$(document).bind('drupalOverlayBeforeLoad.drupal-overlay.drupal-overlay-child-loading', function () {
$('#overlay-titlebar').find('.add-or-remove-shortcuts').remove();
});
};
/**
* Use displacement from parent window.
*/
Drupal.overlayChild.behaviors.alterTableHeaderOffset = function (context, settings) {
if (Drupal.settings.tableHeaderOffset) {
Drupal.overlayChild.prevTableHeaderOffset = Drupal.settings.tableHeaderOffset;
}
Drupal.settings.tableHeaderOffset = 'Drupal.overlayChild.tableHeaderOffset';
};
/**
* Callback for Drupal.settings.tableHeaderOffset.
*/
Drupal.overlayChild.tableHeaderOffset = function () {
var topOffset = Drupal.overlayChild.prevTableHeaderOffset ? eval(Drupal.overlayChild.prevTableHeaderOffset + '()') : 0;
return topOffset + parseInt($(document.body).css('marginTop'));
};
})(jQuery);
| JavaScript |
(function ($) {
Drupal.behaviors.filterStatus = {
attach: function (context, settings) {
$('#filters-status-wrapper input.form-checkbox', context).once('filter-status', function () {
var $checkbox = $(this);
// Retrieve the tabledrag row belonging to this filter.
var $row = $('#' + $checkbox.attr('id').replace(/-status$/, '-weight'), context).closest('tr');
// Retrieve the vertical tab belonging to this filter.
var tab = $('#' + $checkbox.attr('id').replace(/-status$/, '-settings'), context).data('verticalTab');
// Bind click handler to this checkbox to conditionally show and hide the
// filter's tableDrag row and vertical tab pane.
$checkbox.bind('click.filterUpdate', function () {
if ($checkbox.is(':checked')) {
$row.show();
if (tab) {
tab.tabShow().updateSummary();
}
}
else {
$row.hide();
if (tab) {
tab.tabHide().updateSummary();
}
}
// Restripe table after toggling visibility of table row.
Drupal.tableDrag['filter-order'].restripeTable();
});
// Attach summary for configurable filters (only for screen-readers).
if (tab) {
tab.fieldset.drupalSetSummary(function (tabContext) {
return $checkbox.is(':checked') ? Drupal.t('Enabled') : Drupal.t('Disabled');
});
}
// Trigger our bound click handler to update elements to initial state.
$checkbox.triggerHandler('click.filterUpdate');
});
}
};
})(jQuery);
| JavaScript |
(function ($) {
/**
* Automatically display the guidelines of the selected text format.
*/
Drupal.behaviors.filterGuidelines = {
attach: function (context) {
$('.filter-guidelines', context).once('filter-guidelines')
.find(':header').hide()
.closest('.filter-wrapper').find('select.filter-list')
.bind('change', function () {
$(this).closest('.filter-wrapper')
.find('.filter-guidelines-item').hide()
.siblings('.filter-guidelines-' + this.value).show();
})
.change();
}
};
})(jQuery);
| JavaScript |
/**
* @file
* Attaches behaviors for the Dashboard module.
*/
(function ($) {
/**
* Implements Drupal.behaviors for the Dashboard module.
*/
Drupal.behaviors.dashboard = {
attach: function (context, settings) {
$('#dashboard', context).once(function () {
$(this).prepend('<div class="customize clearfix"><ul class="action-links"><li><a href="#">' + Drupal.t('Customize dashboard') + '</a></li></ul><div class="canvas"></div></div>');
$('.customize .action-links a', this).click(Drupal.behaviors.dashboard.enterCustomizeMode);
});
Drupal.behaviors.dashboard.addPlaceholders();
if (Drupal.settings.dashboard.launchCustomize) {
Drupal.behaviors.dashboard.enterCustomizeMode();
}
},
addPlaceholders: function() {
$('#dashboard .dashboard-region .region').each(function () {
var empty_text = "";
// If the region is empty
if ($('.block', this).length == 0) {
// Check if we are in customize mode and grab the correct empty text
if ($('#dashboard').hasClass('customize-mode')) {
empty_text = Drupal.settings.dashboard.emptyRegionTextActive;
} else {
empty_text = Drupal.settings.dashboard.emptyRegionTextInactive;
}
// We need a placeholder.
if ($('.placeholder', this).length == 0) {
$(this).append('<div class="placeholder"></div>');
}
$('.placeholder', this).html(empty_text);
}
else {
$('.placeholder', this).remove();
}
});
},
/**
* Enters "customize" mode by displaying disabled blocks.
*/
enterCustomizeMode: function () {
$('#dashboard').addClass('customize-mode customize-inactive');
Drupal.behaviors.dashboard.addPlaceholders();
// Hide the customize link
$('#dashboard .customize .action-links').hide();
// Load up the disabled blocks
$('div.customize .canvas').load(Drupal.settings.dashboard.drawer, Drupal.behaviors.dashboard.setupDrawer);
},
/**
* Exits "customize" mode by simply forcing a page refresh.
*/
exitCustomizeMode: function () {
$('#dashboard').removeClass('customize-mode customize-inactive');
Drupal.behaviors.dashboard.addPlaceholders();
location.href = Drupal.settings.dashboard.dashboard;
},
/**
* Sets up the drag-and-drop behavior and the 'close' button.
*/
setupDrawer: function () {
$('div.customize .canvas-content input').click(Drupal.behaviors.dashboard.exitCustomizeMode);
$('div.customize .canvas-content').append('<a class="button" href="' + Drupal.settings.dashboard.dashboard + '">' + Drupal.t('Done') + '</a>');
// Initialize drag-and-drop.
var regions = $('#dashboard div.region');
regions.sortable({
connectWith: regions,
cursor: 'move',
cursorAt: {top:0},
dropOnEmpty: true,
items: '> div.block, > div.disabled-block',
placeholder: 'block-placeholder clearfix',
tolerance: 'pointer',
start: Drupal.behaviors.dashboard.start,
over: Drupal.behaviors.dashboard.over,
sort: Drupal.behaviors.dashboard.sort,
update: Drupal.behaviors.dashboard.update
});
},
/**
* Makes the block appear as a disabled block while dragging.
*
* This function is called on the jQuery UI Sortable "start" event.
*
* @param event
* The event that triggered this callback.
* @param ui
* An object containing information about the item that is being dragged.
*/
start: function (event, ui) {
$('#dashboard').removeClass('customize-inactive');
var item = $(ui.item);
// If the block is already in disabled state, don't do anything.
if (!item.hasClass('disabled-block')) {
item.css({height: 'auto'});
}
},
/**
* Adapts block's width to the region it is moved into while dragging.
*
* This function is called on the jQuery UI Sortable "over" event.
*
* @param event
* The event that triggered this callback.
* @param ui
* An object containing information about the item that is being dragged.
*/
over: function (event, ui) {
var item = $(ui.item);
// If the block is in disabled state, remove width.
if ($(this).closest('#disabled-blocks').length) {
item.css('width', '');
}
else {
item.css('width', $(this).width());
}
},
/**
* Adapts a block's position to stay connected with the mouse pointer.
*
* This function is called on the jQuery UI Sortable "sort" event.
*
* @param event
* The event that triggered this callback.
* @param ui
* An object containing information about the item that is being dragged.
*/
sort: function (event, ui) {
var item = $(ui.item);
if (event.pageX > ui.offset.left + item.width()) {
item.css('left', event.pageX);
}
},
/**
* Sends block order to the server, and expand previously disabled blocks.
*
* This function is called on the jQuery UI Sortable "update" event.
*
* @param event
* The event that triggered this callback.
* @param ui
* An object containing information about the item that was just dropped.
*/
update: function (event, ui) {
$('#dashboard').addClass('customize-inactive');
var item = $(ui.item);
// If the user dragged a disabled block, load the block contents.
if (item.hasClass('disabled-block')) {
var module, delta, itemClass;
itemClass = item.attr('class');
// Determine the block module and delta.
module = itemClass.match(/\bmodule-(\S+)\b/)[1];
delta = itemClass.match(/\bdelta-(\S+)\b/)[1];
// Load the newly enabled block's content.
$.get(Drupal.settings.dashboard.blockContent + '/' + module + '/' + delta, {},
function (block) {
if (block) {
item.html(block);
}
if (item.find('div.content').is(':empty')) {
item.find('div.content').html(Drupal.settings.dashboard.emptyBlockText);
}
Drupal.attachBehaviors(item);
},
'html'
);
// Remove the "disabled-block" class, so we don't reload its content the
// next time it's dragged.
item.removeClass("disabled-block");
}
Drupal.behaviors.dashboard.addPlaceholders();
// Let the server know what the new block order is.
$.post(Drupal.settings.dashboard.updatePath, {
'form_token': Drupal.settings.dashboard.formToken,
'regions': Drupal.behaviors.dashboard.getOrder
}
);
},
/**
* Returns the current order of the blocks in each of the sortable regions.
*
* @return
* The current order of the blocks, in query string format.
*/
getOrder: function () {
var order = [];
$('#dashboard div.region').each(function () {
var region = $(this).parent().attr('id').replace(/-/g, '_');
var blocks = $(this).sortable('toArray');
$.each(blocks, function() {
order.push(region + '[]=' + this);
});
});
order = order.join('&');
return order;
}
};
})(jQuery);
| JavaScript |
(function ($) {
Drupal.color = {
logoChanged: false,
callback: function(context, settings, form, farb, height, width) {
// Change the logo to be the real one.
if (!this.logoChanged) {
$('#preview #preview-logo img').attr('src', Drupal.settings.color.logo);
this.logoChanged = true;
}
// Remove the logo if the setting is toggled off.
if (Drupal.settings.color.logo == null) {
$('div').remove('#preview-logo');
}
// Solid background.
$('#preview', form).css('backgroundColor', $('#palette input[name="palette[bg]"]', form).val());
// Text preview.
$('#preview #preview-main h2, #preview .preview-content', form).css('color', $('#palette input[name="palette[text]"]', form).val());
$('#preview #preview-content a', form).css('color', $('#palette input[name="palette[link]"]', form).val());
// Sidebar block.
$('#preview #preview-sidebar #preview-block', form).css('background-color', $('#palette input[name="palette[sidebar]"]', form).val());
$('#preview #preview-sidebar #preview-block', form).css('border-color', $('#palette input[name="palette[sidebarborders]"]', form).val());
// Footer wrapper background.
$('#preview #preview-footer-wrapper', form).css('background-color', $('#palette input[name="palette[footer]"]', form).val());
// CSS3 Gradients.
var gradient_start = $('#palette input[name="palette[top]"]', form).val();
var gradient_end = $('#palette input[name="palette[bottom]"]', form).val();
$('#preview #preview-header', form).attr('style', "background-color: " + gradient_start + "; background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(" + gradient_start + "), to(" + gradient_end + ")); background-image: -moz-linear-gradient(-90deg, " + gradient_start + ", " + gradient_end + ");");
$('#preview #preview-site-name', form).css('color', $('#palette input[name="palette[titleslogan]"]', form).val());
}
};
})(jQuery);
| JavaScript |
jQuery(document).ready(function() {
jQuery('#klantenreactieFotoUploader .actionBrowse').click(function() {
var itemLocator = jQuery(jQuery(this)).parent().parent();
window.send_to_editor = function(html) {
imgurlInput = jQuery('img',html).attr('src');
imgurl = imgurlInput.replace("http://"+window.location.hostname, "");
// alert(imgurl);
// alert(window.location.hostname);
tb_remove();
jQuery(itemLocator).find("input").val(imgurl);
jQuery(itemLocator).find("img").attr("src", imgurl)
}
// alert(imgurl);
tb_show('', 'media-upload.php?post_id=1&type=image&TB_iframe=true');
jQuery(itemLocator).find("a").addClass("visible");
return false;
});
jQuery('#klantenreactieFotoUploader .actionDelete').click(function() {
jQuery(jQuery(this)).parent().parent().find("div img").attr("src", "/wp-content/plugins/42A-klantenreacties/images/42Autos-img-noauto.jpg")
jQuery(jQuery(this)).parent().parent().find("input").val("");
jQuery(jQuery(this)).parent().parent().find("a").removeClass("visible");
return false;
});
}); | JavaScript |
$(document).ready(function()
{
$('#dateLastVisitMin').datepicker();
$('#dateLastVisitMax').datepicker();
$('#dateLastVisit').datepicker();
$('#DoB').datepicker();
$('#divDoB').hide();
$('#divDateLastVisit').hide();
// add click event to btnShowDoB
$('#btnShowDoB').click(function()
{
$('#divDoBRange').hide();
$('#divDoB').show().animate({ backgroundColor: "#4186D3"}, "fast").animate({backgroundColor: "#FFFFFF"}, "fast");
$('#minAge').val(''); // clear out unused fields
$('#maxAge').val('');
});
// add click event to btnShowDoBRange
$('#btnShowDoBRange').click(function()
{
$('#divDoBRange').show().animate({ backgroundColor: "#4186D3"}, "fast").animate({backgroundColor: "#FFFFFF"}, "fast");
$('#divDoB').hide();
$('#DoB').val(''); // clear out unused field
});
// add click event to btnShowDateLastVisit
$('#btnShowDateLastVisit').click(function()
{
$('#divDateLastVisitRange').hide();
$('#divDateLastVisit').show().animate({ backgroundColor: "#4186D3"}, "fast").animate({backgroundColor: "#FFFFFF"}, "fast");
$('#dateLastVisitMin').val(''); // clear out unused field
$('#dateLastVisitMax').val(''); // clear out unused field
});
// add click event to btnShowDateLastVisitRange
$('#btnShowDateLastVisitRange').click(function()
{
$('#divDateLastVisitRange').show().animate({ backgroundColor: "#4186D3"}, "fast").animate({backgroundColor: "#FFFFFF"}, "fast");
$('#divDateLastVisit').hide();
$('#dateLastVisit').val(''); // clear out unused field
});
// when clicked, this adds a new row for medications after the first medications row
$('#btnAddMedication').click(function()
{
$("<tr><td></td><td><input name='medications' type='text' /></td>").insertAfter('#trMedications').animate({ backgroundColor: "#4186D3"}, "fast").animate({backgroundColor: "#FFFFFF"}, "fast");
//$('#trMedications').after(
//"<tr><td></td><td><input name='medications' type='text' /></td>"
//);
});
// when clicked, this adds a new row for allergies after the first allergy row
$('#btnAddAllergy').click(function()
{
$("<tr><td></td><td><input name='allergies' type='text' /></td>").insertAfter('#trAllergies').animate({ backgroundColor: "#4186D3"}, "fast").animate({backgroundColor: "#FFFFFF"}, "fast");
//$('#trAllergies').after(
//"<tr><td></td><td><input name='allergies' type='text' /></td>"
//);
});
// load jQuery Validation
$("#criteria").validationEngine('attach');
// clear fields because the browser will cache old fields
clearValues();
});
// clear all fields because the browser will cache fields
function clearValues()
{
$('#firstName').val('');
$('#lastName').val('');
$('#minAge').val('');
$('#maxAge').val('');
$('#race').val('--');
$('#gender').val('--');
$('#insurance').val('');
$('#city').val('');
$('#state').val('');
$('#country').val('');
$('#drLastName').val('');
$('#religion').val('');
$('#bloodType').val('--');
$('#postalCode').val('');
$('.medications').val('');
$('.allergies').val('');
$('#dateLastVisitMin').val('');
$('#dateLastVisitMax').val('');
$('#reason').val('');
$('#DoB').val('');
$('#dateLastVisit').val('');
document.getElementById("defaultAllergiesCombinationType").checked = true;
document.getElementById("defaultMedicationsCombinationType").checked = true;
//$('#').val('');
} | JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* This field is required",
"alertTextCheckboxMultiple": "* Please select an option",
"alertTextCheckboxe": "* This checkbox is required",
"alertTextDateRange": "* Both date range fields are required"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() == "test") ? true : false;
},
"alertText": "* Field must equal test"
},
"dateRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Range"
},
"dateTimeRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Time Range"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " characters required"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " characters allowed"
},
"groupRequired": {
"regex": "none",
"alertText": "* You must fill one of the following fields"
},
"min": {
"regex": "none",
"alertText": "* Minimum value is "
},
"max": {
"regex": "none",
"alertText": "* Maximum value is "
},
"past": {
"regex": "none",
"alertText": "* Date prior to "
},
"future": {
"regex": "none",
"alertText": "* Date past "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " options allowed"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Please select ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
"creditCard": {
"regex": "none",
"alertText": "* Invalid credit card number"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/,
"alertText": "* Invalid phone number"
},
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Not a valid integer"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* Invalid floating decimal number"
},
"date": {
// Check if date is valid by leap year
"func": function (field) {
var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
var year = match[1];
var month = match[2]*1;
var day = match[3]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Invalid IP address"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Numbers only"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Letters only"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* No special characters allowed"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* This name is already taken",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* Please input HELLO"
},
//tls warning:homegrown not fielded
"dateFormat":{
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
"alertText": "* Invalid Date"
},
//tls warning:homegrown not fielded
"dateTimeFormat": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
"alertText": "* Invalid Date or Date Format",
"alertText2": "Expected Format: ",
"alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ",
"alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery); | JavaScript |
/*
* Inline Form Validation Engine 2.6.2, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
"use strict";
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (!form.data('jqv') || form.data('jqv') == null ) {
options = methods._saveOptions(form, options);
// bind all formError elements to close on click
$(document).on("click", ".formError", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
});
}
return this;
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class";
if (options.binded) {
// delegate fields
form.on(options.validationEventTrigger, "["+options.validateAttribute+"*=validate]:not([type=checkbox]):not([type=radio]):not(.datepicker)", methods._onFieldEvent);
form.on("click", "["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]", methods._onFieldEvent);
form.on(options.validationEventTrigger,"["+options.validateAttribute+"*=validate][class*=datepicker]", {"delay": 300}, methods._onFieldEvent);
}
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
form.on("click","a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick);
form.removeData('jqv_submitButton');
// bind form.submit
form.on("submit", methods._onSubmitEvent);
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
var form = this;
var options = form.data('jqv');
// unbind fields
form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").off(options.validationEventTrigger, methods._onFieldEvent);
form.find("["+options.validateAttribute+"*=validate][type=checkbox],[class*=validate][type=radio]").off("click", methods._onFieldEvent);
// unbind form.submit
form.off("submit", methods._onSubmitEvent);
form.removeData('jqv');
form.off("click", "a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick);
form.removeData('jqv_submitButton');
if (options.autoPositionUpdate)
$(window).off("resize", methods.updatePromptsPosition);
return this;
},
/**
* Validates either a form or a list of fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function() {
var element = $(this);
var valid = null;
if (element.is("form") || element.hasClass("validationEngineContainer")) {
if (element.hasClass('validating')) {
// form is already validating.
// Should abort old validation and start new one. I don't know how to implement it.
return false;
} else {
element.addClass('validating');
var options = element.data('jqv');
var valid = methods._validateFields(this);
// If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again
setTimeout(function(){
element.removeClass('validating');
}, 100);
if (valid && options.onSuccess) {
options.onSuccess();
} else if (!valid && options.onFailure) {
options.onFailure();
}
}
} else if (element.is('form') || element.hasClass('validationEngineContainer')) {
element.removeClass('validating');
} else {
// field validation
var form = element.closest('form, .validationEngineContainer'),
options = (form.data('jqv')) ? form.data('jqv') : $.validationEngine.defaults,
valid = methods._validateField(element, options);
if (valid && options.onFieldSuccess)
options.onFieldSuccess();
else if (options.onFieldFailure && options.InvalidFields.length > 0) {
options.onFieldFailure();
}
}
if(options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, valid);
}
return valid;
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window) {
var form = event.data.formElem;
var noAnimation = event.data.noAnimation;
}
else
var form = $(this.closest('form, .validationEngineContainer'));
var options = form.data('jqv');
// No option, take default one
form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each(function(){
var field = $(this);
if (options.prettySelect && field.is(":hidden"))
field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix);
var prompt = methods._getPrompt(field);
var promptText = $(prompt).find(".formErrorContent").html();
if(prompt)
methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation);
});
return this;
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form, .validationEngineContainer');
var options = form.data('jqv');
// No option, take default one
if(!options)
options = methods._saveOptions(this, options);
if(promptPosition)
options.promptPosition=promptPosition;
options.showArrow = showArrow==true;
methods._showPrompt(this, promptText, type, false, options);
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var form = $(this).closest('form, .validationEngineContainer');
var options = form.data('jqv');
var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3;
var closingtag;
if($(this).is("form") || $(this).hasClass("validationEngineContainer")) {
closingtag = "parentForm"+methods._getClassName($(this).attr("id"));
} else {
closingtag = methods._getClassName($(this).attr("id")) +"formError";
}
$('.'+closingtag).fadeTo(fadeDuration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
var form = this;
var options = form.data('jqv');
var duration = options ? options.fadeDuration:300;
$('.formError').fadeTo(duration, 300, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function(event) {
var field = $(this);
var form = field.closest('form, .validationEngineContainer');
var options = form.data('jqv');
options.eventTrigger = "field";
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
if (options.InvalidFields.length == 0 && options.onFieldSuccess) {
options.onFieldSuccess();
} else if (options.InvalidFields.length > 0 && options.onFieldFailure) {
options.onFieldFailure();
}
}, (event.data) ? event.data.delay : 0);
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
var options = form.data('jqv');
//check if it is trigger from skipped button
if (form.data("jqv_submitButton")){
var submitButton = $("#" + form.data("jqv_submitButton"));
if (submitButton){
if (submitButton.length > 0){
if (submitButton.hasClass("validate-skip") || submitButton.attr("data-validation-engine-skip") == "true")
return true;
}
}
}
options.eventTrigger = "submit";
// validate each field
// (- skip field ajax validation, not necessary IF we will perform an ajax form validation)
var r=methods._validateFields(form);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
// cancel form auto-submission - process with async call onAjaxFormComplete
return false;
}
if(options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, r);
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (!value) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Return true if the ajax field is validated
* @param {String} fieldid
* @param {Object} options
* @return true, if validation passed, false if false or doesn't exist
*/
_checkAjaxFieldStatus: function(fieldid, options) {
return options.ajaxValidCache[fieldid] == true;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// Trigger hook, start validation
form.trigger("jqv.form.validating");
// first, evaluate status of non ajax fields
var first_err=null;
form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each( function() {
var field = $(this);
var names = [];
if ($.inArray(field.attr('name'), names) < 0) {
errorFound |= methods._validateField(field, options);
if (errorFound && first_err==null)
if (field.is(":hidden") && options.prettySelect)
first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
else {
//Check if we need to adjust what element to show the prompt on
//and and such scroll to instead
if(field.data('jqv-prompt-at') instanceof jQuery ){
field = field.data('jqv-prompt-at');
} else if(field.data('jqv-prompt-at')) {
field = $(field.data('jqv-prompt-at'));
}
first_err=field;
}
if (options.doNotShowAllErrosOnSubmit)
return false;
names.push(field.attr('name'));
//if option set, stop checking validation rules after one error is found
if(options.showOneMessage == true && errorFound){
return false;
}
}
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// third, check status and scroll the container accordingly
form.trigger("jqv.form.result", [errorFound]);
if (errorFound) {
if (options.scroll) {
var destination=first_err.offset().top;
var fixleft = first_err.offset().left;
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType=options.promptPosition;
if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1)
positionType=positionType.substring(0,positionType.indexOf(":"));
if (positionType!="bottomRight" && positionType!="bottomLeft") {
var prompt_err= methods._getPrompt(first_err);
if (prompt_err) {
destination=prompt_err.offset().top;
}
}
// Offset the amount the page scrolls by an amount in px to accomodate fixed elements at top of page
if (options.scrollOffset) {
destination -= options.scrollOffset;
}
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
if (options.isOverflown) {
var overflowDIV = $(options.overflownDIV);
if(!overflowDIV.length) return false;
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV + ":not(:animated)");
scrollContainer.animate({ scrollTop: destination }, 1100, function(){
if(options.focusFirstField) first_err.focus();
});
} else {
$("html, body").animate({
scrollTop: destination
}, 1100, function(){
if(options.focusFirstField) first_err.focus();
});
$("html, body").animate({scrollLeft: fixleft},1100)
}
} else if(options.focusFirstField)
first_err.focus();
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
var type = (options.ajaxFormValidationMethod) ? options.ajaxFormValidationMethod : "GET";
var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
var dataType = (options.dataType) ? options.dataType : "json";
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.)
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id")) {
field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter);
++$.validationEngine.fieldIdCounter;
}
if (!options.validateNonVisibleFields && (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden")))
return false;
var rulesParsing = field.attr(options.validateAttribute);
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (!getRules)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var promptType = "";
var required = false;
var limitErrors = false;
options.isError = false;
options.showArrow = true;
// If the programmer wants to limit the amount of error messages per field,
if (options.maxErrorsPerField > 0) {
limitErrors = true;
}
var form = $(field.closest("form, .validationEngineContainer"));
// Fix for adding spaces in the rules
for (var i = 0; i < rules.length; i++) {
rules[i] = rules[i].replace(" ", "");
// Remove any parsing errors
if (rules[i] === '') {
delete rules[i];
}
}
for (var i = 0, field_errors = 0; i < rules.length; i++) {
// If we are limiting errors, and have hit the max, break
if (limitErrors && field_errors >= options.maxErrorsPerField) {
// If we haven't hit a required yet, check to see if there is one in the validation rules for this
// field and that it's index is greater or equal to our current index
if (!required) {
var have_required = $.inArray('required', rules);
required = (have_required != -1 && have_required >= i);
}
break;
}
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required);
break;
case "custom":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom);
break;
case "groupRequired":
// Check is its the first of group, if not, reload validation with first field
// AND continue normal validation on present field
var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]";
var firstOfGroup = form.find(classGroup).eq(0);
if(firstOfGroup[0] != field[0]){
methods._validateField(firstOfGroup, options, skipAjaxValidation);
options.showArrow = true;
}
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired);
if(errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// AJAX defaults to returning it's loading message
errorMsg = methods._ajax(field, rules, i, options);
if (errorMsg) {
promptType = "load";
}
break;
case "minSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize);
break;
case "maxSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize);
break;
case "min":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min);
break;
case "max":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max);
break;
case "past":
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._past);
break;
case "future":
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._future);
break;
case "dateRange":
var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateTimeRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox);
break;
case "minCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox);
break;
case "equals":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals);
break;
case "funcCall":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall);
break;
case "creditCard":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard);
break;
case "condRequired":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired);
if (errorMsg !== undefined) {
required = true;
}
break;
default:
}
var end_validation = false;
// If we were passed back an message object, check what the status was to determine what to do
if (typeof errorMsg == "object") {
switch (errorMsg.status) {
case "_break":
end_validation = true;
break;
// If we have an error message, set errorMsg to the error message
case "_error":
errorMsg = errorMsg.message;
break;
// If we want to throw an error, but not show a prompt, return early with true
case "_error_no_prompt":
return true;
break;
// Anything else we continue on
default:
break;
}
}
// If it has been specified that validation should end now, break
if (end_validation) {
break;
}
// If we have a string, that means that we have an error, so add it to the error message.
if (typeof errorMsg == 'string') {
promptText += errorMsg + "<br/>";
options.isError = true;
field_errors++;
}
}
// If the rules required is not added, an empty field is not validated
if(!required && !(field.val()) && field.val().length < 1) options.isError = false;
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.prop("type");
var positionType=field.data("promptPosition") || options.promptPosition;
if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) {
if(positionType === 'inline') {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:last"));
} else {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
}
options.showArrow = false;
}
if(field.is(":hidden") && options.prettySelect) {
field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
}
if (options.isError && options.showPrompts){
methods._showPrompt(field, promptText, promptType, false, options);
}else{
if (!isAjaxValidator) methods._closePrompt(field);
}
if (!isAjaxValidator) {
field.trigger("jqv.field.result", [field, options.isError, promptText]);
}
/* Record error */
var errindex = $.inArray(field[0], options.InvalidFields);
if (errindex == -1) {
if (options.isError)
options.InvalidFields.push(field[0]);
} else if (!options.isError) {
options.InvalidFields.splice(errindex, 1);
}
methods._handleStatusCssClasses(field, options);
/* run callback function for each field */
if (options.isError && options.onFieldFailure)
options.onFieldFailure(field);
if (!options.isError && options.onFieldSuccess)
options.onFieldSuccess(field);
return options.isError;
},
/**
* Handling css classes of fields indicating result of validation
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @private
*/
_handleStatusCssClasses: function(field, options) {
/* remove all classes */
if(options.addSuccessCssClassToField)
field.removeClass(options.addSuccessCssClassToField);
if(options.addFailureCssClassToField)
field.removeClass(options.addFailureCssClassToField);
/* Add classes */
if (options.addSuccessCssClassToField && !options.isError)
field.addClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField && options.isError)
field.addClass(options.addFailureCssClassToField);
},
/********************
* _getErrorMessage
*
* @param form
* @param field
* @param rule
* @param rules
* @param i
* @param options
* @param originalValidationMethod
* @return {*}
* @private
*/
_getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) {
// If we are using the custon validation type, build the index for the rule.
// Otherwise if we are doing a function call, make the call and return the object
// that is passed back.
var rule_index = jQuery.inArray(rule, rules);
if (rule === "custom" || rule === "funcCall") {
var custom_validation_type = rules[rule_index + 1];
rule = rule + "[" + custom_validation_type + "]";
// Delete the rule from the rules array so that it doesn't try to call the
// same rule over again
delete(rules[rule_index]);
}
// Change the rule to the composite rule, if it was different from the original
var alteredRule = rule;
var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class");
var element_classes_array = element_classes.split(" ");
// Call the original validation method. If we are dealing with dates or checkboxes, also pass the form
var errorMsg;
if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") {
errorMsg = originalValidationMethod(form, field, rules, i, options);
} else {
errorMsg = originalValidationMethod(field, rules, i, options);
}
// If the original validation method returned an error and we have a custom error message,
// return the custom message instead. Otherwise return the original error message.
if (errorMsg != undefined) {
var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, alteredRule, options);
if (custom_message) errorMsg = custom_message;
}
return errorMsg;
},
_getCustomErrorMessage:function (field, classes, rule, options) {
var custom_message = false;
var validityProp = /^custom\[.*\]$/.test(rule) ? methods._validityProp["custom"] : methods._validityProp[rule];
// If there is a validityProp for this rule, check to see if the field has an attribute for it
if (validityProp != undefined) {
custom_message = field.attr("data-errormessage-"+validityProp);
// If there was an error message for it, return the message
if (custom_message != undefined)
return custom_message;
}
custom_message = field.attr("data-errormessage");
// If there is an inline custom error message, return it
if (custom_message != undefined)
return custom_message;
var id = '#' + field.attr("id");
// If we have custom messages for the element's id, get the message for the rule from the id.
// Otherwise, if we have custom messages for the element's classes, use the first class message we find instead.
if (typeof options.custom_error_messages[id] != "undefined" &&
typeof options.custom_error_messages[id][rule] != "undefined" ) {
custom_message = options.custom_error_messages[id][rule]['message'];
} else if (classes.length > 0) {
for (var i = 0; i < classes.length && classes.length > 0; i++) {
var element_class = "." + classes[i];
if (typeof options.custom_error_messages[element_class] != "undefined" &&
typeof options.custom_error_messages[element_class][rule] != "undefined") {
custom_message = options.custom_error_messages[element_class][rule]['message'];
break;
}
}
}
if (!custom_message &&
typeof options.custom_error_messages[rule] != "undefined" &&
typeof options.custom_error_messages[rule]['message'] != "undefined"){
custom_message = options.custom_error_messages[rule]['message'];
}
return custom_message;
},
_validityProp: {
"required": "value-missing",
"custom": "custom-error",
"groupRequired": "value-missing",
"ajax": "custom-error",
"minSize": "range-underflow",
"maxSize": "range-overflow",
"min": "range-underflow",
"max": "range-overflow",
"past": "type-mismatch",
"future": "type-mismatch",
"dateRange": "type-mismatch",
"dateTimeRange": "type-mismatch",
"maxCheckbox": "range-overflow",
"minCheckbox": "range-underflow",
"equals": "pattern-mismatch",
"funcCall": "custom-error",
"creditCard": "pattern-mismatch",
"condRequired": "value-missing"
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @param {bool} condRequired flag when method is used for internal purpose in condRequired check
* @return an error string if validation failed
*/
_required: function(field, rules, i, options, condRequired) {
switch (field.prop("type")) {
case "text":
case "password":
case "textarea":
case "file":
case "select-one":
case "select-multiple":
default:
var field_val = $.trim( field.val() );
var dv_placeholder = $.trim( field.attr("data-validation-placeholder") );
var placeholder = $.trim( field.attr("placeholder") );
if (
( !field_val )
|| ( dv_placeholder && field_val == dv_placeholder )
|| ( placeholder && field_val == placeholder )
) {
return options.allrules[rules[i]].alertText;
}
break;
case "radio":
case "checkbox":
// new validation style to only check dependent field
if (condRequired) {
if (!field.attr('checked')) {
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
}
// old validation style
var form = field.closest("form, .validationEngineContainer");
var name = field.attr("name");
if (form.find("input[name='" + name + "']:checked").size() == 0) {
if (form.find("input[name='" + name + "']:visible").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
}
},
/**
* Validate that 1 from the group field is required
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_groupRequired: function(field, rules, i, options) {
var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]";
var isValid = false;
// Check all fields from the group
field.closest("form, .validationEngineContainer").find(classGroup).each(function(){
if(!methods._required($(this), rules, i, options)){
isValid = true;
return false;
}
});
if(!isValid) {
return options.allrules[rules[i]].alertText;
}
},
/**
* Validate rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_custom: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
var fn;
if(!rule) {
alert("jqv:custom rule not found - "+customRule);
return;
}
if(rule["regex"]) {
var ex=rule.regex;
if(!ex) {
alert("jqv:custom regex not found - "+customRule);
return;
}
var pattern = new RegExp(ex);
if (!pattern.test(field.val())) return options.allrules[customRule].alertText;
} else if(rule["func"]) {
fn = rule["func"];
if (typeof(fn) !== "function") {
alert("jqv:custom parameter 'function' is no function - "+customRule);
return;
}
if (!fn(field, rules, i, options))
return options.allrules[customRule].alertText;
} else {
alert("jqv:custom type not allowed "+customRule);
return;
}
},
/**
* Validate custom function outside of the engine scope
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_funcCall: function(field, rules, i, options) {
var functionName = rules[i + 1];
var fn;
if(functionName.indexOf('.') >-1)
{
var namespaces = functionName.split('.');
var scope = window;
while(namespaces.length)
{
scope = scope[namespaces.shift()];
}
fn = scope;
}
else
fn = window[functionName] || options.customFunctions[functionName];
if (typeof(fn) == 'function')
return fn(field, rules, i, options);
},
/**
* Field match
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_equals: function(field, rules, i, options) {
var equalsField = rules[i + 1];
if (field.val() != $("#" + equalsField).val())
return options.allrules.equals.alertText;
},
/**
* Check the maximum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxSize: function(field, rules, i, options) {
var max = rules[i + 1];
var len = field.val().length;
if (len > max) {
var rule = options.allrules.maxSize;
return rule.alertText + max + rule.alertText2;
}
},
/**
* Check the minimum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minSize: function(field, rules, i, options) {
var min = rules[i + 1];
var len = field.val().length;
if (len < min) {
var rule = options.allrules.minSize;
return rule.alertText + min + rule.alertText2;
}
},
/**
* Check number minimum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_min: function(field, rules, i, options) {
var min = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len < min) {
var rule = options.allrules.min;
if (rule.alertText2) return rule.alertText + min + rule.alertText2;
return rule.alertText + min;
}
},
/**
* Check number maximum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_max: function(field, rules, i, options) {
var max = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len >max ) {
var rule = options.allrules.max;
if (rule.alertText2) return rule.alertText + max + rule.alertText2;
//orefalo: to review, also do the translations
return rule.alertText + max;
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_past: function(form, field, rules, i, options) {
var p=rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate > pdate ) {
var rule = options.allrules.past;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks date is in the future
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_future: function(form, field, rules, i, options) {
var p=rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate < pdate ) {
var rule = options.allrules.future;
if (rule.alertText2)
return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks if valid date
*
* @param {string} date string
* @return a bool based on determination of valid date
*/
_isDate: function (value) {
var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);
return dateRegEx.test(value);
},
/**
* Checks if valid date time
*
* @param {string} date string
* @return a bool based on determination of valid date time
*/
_isDateTime: function (value){
var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/);
return dateTimeRegEx.test(value);
},
//Checks if the start date is before the end date
//returns true if end is later than start
_dateCompare: function (start, end) {
return (new Date(start.toString()) < new Date(end.toString()));
},
/**
* Checks date range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateRange: function (field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Checks date time range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateTimeRange: function (field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Max number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize > nbCheck) {
options.showArrow = false;
if (options.allrules.maxCheckbox.alertText2)
return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2;
return options.allrules.maxCheckbox.alertText;
}
},
/**
* Min number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize < nbCheck) {
options.showArrow = false;
return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2;
}
},
/**
* Checks that it is a valid credit card number according to the
* Luhn checksum algorithm.
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_creditCard: function(field, rules, i, options) {
//spaces and dashes may be valid characters, but must be stripped to calculate the checksum.
var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, '');
var numDigits = cardNumber.length;
if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) {
var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String();
do {
digit = parseInt(cardNumber.charAt(i));
luhn += (pos++ % 2 == 0) ? digit * 2 : digit;
} while (--i >= 0)
for (i = 0; i < luhn.length; i++) {
sum += parseInt(luhn.charAt(i));
}
valid = sum % 10 == 0;
}
if (!valid) return options.allrules.creditCard.alertText;
},
/**
* Ajax field validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return nothing! the ajax validator handles the prompts itself
*/
_ajax: function(field, rules, i, options) {
var errorSelector = rules[i + 1];
var rule = options.allrules[errorSelector];
var extraData = rule.extraData;
var extraDataDynamic = rule.extraDataDynamic;
var data = {
"fieldId" : field.attr("id"),
"fieldValue" : field.val()
};
if (typeof extraData === "object") {
$.extend(data, extraData);
} else if (typeof extraData === "string") {
var tempData = extraData.split("&");
for(var i = 0; i < tempData.length; i++) {
var values = tempData[i].split("=");
if (values[0] && values[0]) {
data[values[0]] = values[1];
}
}
}
if (extraDataDynamic) {
var tmpData = [];
var domIds = String(extraDataDynamic).split(",");
for (var i = 0; i < domIds.length; i++) {
var id = domIds[i];
if ($(id).length) {
var inputValue = field.closest("form, .validationEngineContainer").find(id).val();
var keyValue = id.replace('#', '') + '=' + escape(inputValue);
data[id.replace('#', '')] = inputValue;
}
}
}
// If a field change event triggered this we want to clear the cache for this ID
if (options.eventTrigger == "field") {
delete(options.ajaxValidCache[field.attr("id")]);
}
// If there is an error or if the the field is already validated, do not re-execute AJAX
if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) {
$.ajax({
type: options.ajaxFormValidationMethod,
url: rule.url,
cache: false,
dataType: "json",
data: data,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() {},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
// asynchronously called on success, data is the json answer from the server
var errorFieldId = json[0];
//var errorField = $($("#" + errorFieldId)[0]);
var errorField = $("#"+ errorFieldId).eq(0);
// make sure we found the element
if (errorField.length == 1) {
var status = json[1];
// read the optional msg from the server
var msg = json[2];
if (!status) {
// Houston we got a problem - display an red prompt
options.ajaxValidCache[errorFieldId] = false;
options.isError = true;
// resolve the msg prompt
if(msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertText;
if (options.showPrompts) methods._showPrompt(errorField, msg, "", true, options);
} else {
options.ajaxValidCache[errorFieldId] = true;
// resolves the msg prompt
if(msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertTextOk;
if (options.showPrompts) {
// see if we should display a green prompt
if (msg)
methods._showPrompt(errorField, msg, "pass", true, options);
else
methods._closePrompt(errorField);
}
// If a submit form triggered this, we want to re-submit the form
if (options.eventTrigger == "submit")
field.closest("form").submit();
}
}
errorField.trigger("jqv.field.result", [errorField, options.isError, msg]);
}
});
return rule.alertTextLoad;
}
},
/**
* Common method to handle ajax errors
*
* @param {Object} data
* @param {Object} transport
*/
_ajaxError: function(data, transport) {
if(data.status == 0 && transport == null)
alert("The page is not served from a server! ajax call failed");
else if(typeof console != "undefined")
console.log("Ajax error: " + data.status + " " + transport);
},
/**
* date -> string
*
* @param {Object} date
*/
_dateToString: function(date) {
return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
},
/**
* Parses an ISO date
* @param {String} d
*/
_parseDate: function(d) {
var dateParts = d.split("-");
if(dateParts==d)
dateParts = d.split("/");
if(dateParts==d) {
dateParts = d.split(".");
return new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
}
return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]);
},
/**
* Builds or updates a prompt with the given information
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) {
//Check if we need to adjust what element to show the prompt on
if(field.data('jqv-prompt-at') instanceof jQuery ){
field = field.data('jqv-prompt-at');
} else if(field.data('jqv-prompt-at')) {
field = $(field.data('jqv-prompt-at'));
}
var prompt = methods._getPrompt(field);
// The ajax submit errors are not see has an error in the form,
// When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time
// Because no error was found befor submitting
if(ajaxform) prompt = false;
// Check that there is indded text
if($.trim(promptText)){
if (prompt)
methods._updatePrompt(field, prompt, promptText, type, ajaxed, options);
else
methods._buildPrompt(field, promptText, type, ajaxed, options);
}
},
/**
* Builds and shades a prompt for the given field.
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_buildPrompt: function(field, promptText, type, ajaxed, options) {
// create the prompt
var prompt = $('<div>');
prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
// add a class name to identify the parent form of the prompt
prompt.addClass("parentForm"+methods._getClassName(field.closest('form, .validationEngineContainer').attr("id")));
prompt.addClass("formError");
switch (type) {
case "pass":
prompt.addClass("greenPopup");
break;
case "load":
prompt.addClass("blackPopup");
break;
default:
/* it has error */
//alert("unknown popup type:"+type);
}
if (ajaxed)
prompt.addClass("ajaxed");
// create the prompt content
var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);
// determine position type
var positionType=field.data("promptPosition") || options.promptPosition;
// create the css arrow pointing at the field
// note that there is no triangle on max-checkbox and radio
if (options.showArrow) {
var arrow = $('<div>').addClass("formErrorArrow");
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
if (typeof(positionType)=='string')
{
var pos=positionType.indexOf(":");
if(pos!=-1)
positionType=positionType.substring(0,pos);
}
switch (positionType) {
case "bottomLeft":
case "bottomRight":
prompt.find(".formErrorContent").before(arrow);
arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
break;
case "topLeft":
case "topRight":
arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
prompt.append(arrow);
break;
}
}
// Add custom prompt class
if (options.addPromptClass)
prompt.addClass(options.addPromptClass);
// Add custom prompt class defined in element
var requiredOverride = field.attr('data-required-class');
if(requiredOverride !== undefined) {
prompt.addClass(requiredOverride);
} else {
if(options.prettySelect) {
if($('#' + field.attr('id')).next().is('select')) {
var prettyOverrideClass = $('#' + field.attr('id').substr(options.usePrefix.length).substring(options.useSuffix.length)).attr('data-required-class');
if(prettyOverrideClass !== undefined) {
prompt.addClass(prettyOverrideClass);
}
}
}
}
prompt.css({
"opacity": 0
});
if(positionType === 'inline') {
prompt.addClass("inline");
if(typeof field.attr('data-prompt-target') !== 'undefined' && $('#'+field.attr('data-prompt-target')).length > 0) {
prompt.appendTo($('#'+field.attr('data-prompt-target')));
} else {
field.after(prompt);
}
} else {
field.before(prompt);
}
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
'position': positionType === 'inline' ? 'relative' : 'absolute',
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
}).data("callerField", field);
if (options.autoHidePrompt) {
setTimeout(function(){
prompt.animate({
"opacity": 0
},function(){
prompt.closest('.formErrorOuter').remove();
prompt.remove();
});
}, options.autoHideDelay);
}
return prompt.animate({
"opacity": 0.87
});
},
/**
* Updates the prompt text field - the field for which the prompt
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) {
if (prompt) {
if (typeof type !== "undefined") {
if (type == "pass")
prompt.addClass("greenPopup");
else
prompt.removeClass("greenPopup");
if (type == "load")
prompt.addClass("blackPopup");
else
prompt.removeClass("blackPopup");
}
if (ajaxed)
prompt.addClass("ajaxed");
else
prompt.removeClass("ajaxed");
prompt.find(".formErrorContent").html(promptText);
var pos = methods._calculatePosition(field, prompt, options);
var css = {"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize};
if (noAnimation)
prompt.css(css);
else
prompt.animate(css);
}
},
/**
* Closes the prompt associated with the given field
*
* @param {jqObject}
* field
*/
_closePrompt: function(field) {
var prompt = methods._getPrompt(field);
if (prompt)
prompt.fadeTo("fast", 0, function() {
prompt.parent('.formErrorOuter').remove();
prompt.remove();
});
},
closePrompt: function(field) {
return methods._closePrompt(field);
},
/**
* Returns the error prompt matching the field if any
*
* @param {jqObject}
* field
* @return undefined or the error prompt (jqObject)
*/
_getPrompt: function(field) {
var formId = $(field).closest('form, .validationEngineContainer').attr('id');
var className = methods._getClassName(field.attr("id")) + "formError";
var match = $("." + methods._escapeExpression(className) + '.parentForm' + methods._getClassName(formId))[0];
if (match)
return $(match);
},
/**
* Returns the escapade classname
*
* @param {selector}
* className
*/
_escapeExpression: function (selector) {
return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1");
},
/**
* returns true if we are in a RTLed document
*
* @param {jqObject} field
*/
isRTL: function(field)
{
var $document = $(document);
var $body = $('body');
var rtl =
(field && field.hasClass('rtl')) ||
(field && (field.attr('dir') || '').toLowerCase()==='rtl') ||
$document.hasClass('rtl') ||
($document.attr('dir') || '').toLowerCase()==='rtl' ||
$body.hasClass('rtl') ||
($body.attr('dir') || '').toLowerCase()==='rtl';
return Boolean(rtl);
},
/**
* Calculates prompt position
*
* @param {jqObject}
* field
* @param {jqObject}
* the prompt
* @param {Map}
* options
* @return positions
*/
_calculatePosition: function (field, promptElmt, options) {
var promptTopPosition, promptleftPosition, marginTopSize;
var fieldWidth = field.width();
var fieldLeft = field.position().left;
var fieldTop = field.position().top;
var fieldHeight = field.height();
var promptHeight = promptElmt.height();
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
//prompt positioning adjustment support
//now you can adjust prompt position
//usage: positionType:Xshift,Yshift
//for example:
// bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally
// topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top
//You can use +pixels, - pixels. If no sign is provided than + is default.
var positionType=field.data("promptPosition") || options.promptPosition;
var shift1="";
var shift2="";
var shiftX=0;
var shiftY=0;
if (typeof(positionType)=='string') {
//do we have any position adjustments ?
if (positionType.indexOf(":")!=-1) {
shift1=positionType.substring(positionType.indexOf(":")+1);
positionType=positionType.substring(0,positionType.indexOf(":"));
//if any advanced positioning will be needed (percents or something else) - parser should be added here
//for now we use simple parseInt()
//do we have second parameter?
if (shift1.indexOf(",") !=-1) {
shift2=shift1.substring(shift1.indexOf(",") +1);
shift1=shift1.substring(0,shift1.indexOf(","));
shiftY=parseInt(shift2);
if (isNaN(shiftY)) shiftY=0;
};
shiftX=parseInt(shift1);
if (isNaN(shift1)) shift1=0;
};
};
switch (positionType) {
default:
case "topRight":
promptleftPosition += fieldLeft + fieldWidth - 30;
promptTopPosition += fieldTop;
break;
case "topLeft":
promptTopPosition += fieldTop;
promptleftPosition += fieldLeft;
break;
case "centerRight":
promptTopPosition = fieldTop+4;
marginTopSize = 0;
promptleftPosition= fieldLeft + field.outerWidth(true)+5;
break;
case "centerLeft":
promptleftPosition = fieldLeft - (promptElmt.width() + 2);
promptTopPosition = fieldTop+4;
marginTopSize = 0;
break;
case "bottomLeft":
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
promptleftPosition = fieldLeft;
break;
case "bottomRight":
promptleftPosition = fieldLeft + fieldWidth - 30;
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
break;
case "inline":
promptleftPosition = 0;
promptTopPosition = 0;
marginTopSize = 0;
};
//apply adjusments if any
promptleftPosition += shiftX;
promptTopPosition += shiftY;
return {
"callerTopPosition": promptTopPosition + "px",
"callerleftPosition": promptleftPosition + "px",
"marginTopSize": marginTopSize + "px"
};
},
/**
* Saves the user options and variables in the form.data
*
* @param {jqObject}
* form - the form where the user option should be saved
* @param {Map}
* options - the user options
* @return the user options (extended from the defaults)
*/
_saveOptions: function(form, options) {
// is there a language localisation ?
if ($.validationEngineLanguage)
var allRules = $.validationEngineLanguage.allRules;
else
$.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page");
// --- Internals DO NOT TOUCH or OVERLOAD ---
// validation rules and i18
$.validationEngine.defaults.allrules = allRules;
var userOptions = $.extend(true,{},$.validationEngine.defaults,options);
form.data('jqv', userOptions);
return userOptions;
},
/**
* Removes forbidden characters from class name
* @param {String} className
*/
_getClassName: function(className) {
if(className)
return className.replace(/:/g, "_").replace(/\./g, "_");
},
/**
* Escape special character for jQuery selector
* http://totaldev.com/content/escaping-characters-get-valid-jquery-id
* @param {String} selector
*/
_jqSelector: function(str){
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
},
/**
* Conditionally required field
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_condRequired: function(field, rules, i, options) {
var idx, dependingField;
for(idx = (i + 1); idx < rules.length; idx++) {
dependingField = jQuery("#" + rules[idx]).first();
/* Use _required for determining wether dependingField has a value.
* There is logic there for handling all field types, and default value; so we won't replicate that here
* Indicate this special use by setting the last parameter to true so we only validate the dependingField on chackboxes and radio buttons (#462)
*/
if (dependingField.length && methods._required(dependingField, ["required"], 0, options, true) == undefined) {
/* We now know any of the depending fields has a value,
* so we can validate this field as per normal required code
*/
return methods._required(field, ["required"], 0, options);
}
}
},
_submitButtonClick: function(event) {
var button = $(this);
var form = button.closest('form, .validationEngineContainer');
form.data("jqv_submitButton", button.attr("id"));
}
};
/**
* Plugin entry point.
* You may pass an action as a parameter or a list of options.
* if none, the init and attach methods are being called.
* Remember: if you pass options, the attached method is NOT called automatically
*
* @param {String}
* method (optional) action
*/
$.fn.validationEngine = function(method) {
var form = $(this);
if(!form[0]) return form; // stop here if the form does not exist
if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) {
// make sure init is called once
if(method != "showPrompt" && method != "hide" && method != "hideAll")
methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));
} else if (typeof method == 'object' || !method) {
// default constructor with or without arguments
methods.init.apply(form, arguments);
return methods.attach.apply(form);
} else {
$.error('Method ' + method + ' does not exist in jQuery.validationEngine');
}
};
// LEAK GLOBAL OPTIONS
$.validationEngine= {fieldIdCounter: 0,defaults:{
// Name of the event triggering field validation
validationEventTrigger: "blur",
// Automatically scroll viewport to the first error
scroll: true,
// Focus on the first input
focusFirstField:true,
// Show prompts, set to false to disable prompts
showPrompts: true,
// Should we attempt to validate non-visible input fields contained in the form? (Useful in cases of tabbed containers, e.g. jQuery-UI tabs)
validateNonVisibleFields: false,
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight, inline
// inline gets inserted after the validated field or into an element specified in data-prompt-target
promptPosition: "topRight",
bindMethod:"bind",
// internal, automatically set to true when it parse a _ajax rule
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action)
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// Object where you store custom messages to override the default error messages
custom_error_messages:{},
// true if you want to vind the input fields
binded: true,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Limit how many displayed errors a field can have
maxErrorsPerField: false,
// Caches field validation status, typically only bad status are created.
// the array is used during ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {},
// Auto update prompt position after window resize
autoPositionUpdate: false,
InvalidFields: [],
onFieldSuccess: false,
onFieldFailure: false,
onSuccess: false,
onFailure: false,
validateAttribute: "class",
addSuccessCssClassToField: "",
addFailureCssClassToField: "",
// Auto-hide prompt
autoHidePrompt: false,
// Delay before auto-hide
autoHideDelay: 10000,
// Fade out duration while hiding the validations
fadeDuration: 0.3,
// Use Prettify select library
prettySelect: false,
// Add css class on prompt
addPromptClass : "",
// Custom ID uses prefix
usePrefix: "",
// Custom ID uses suffix
useSuffix: "",
// Only show one message per error prompt
showOneMessage: false
}};
$(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"});
})(jQuery);
| 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.
var fs = require('fs');
var puts = require('util').puts;
// The "Schema" constructor lets you load a protocol schema definition
// (a compiled .proto file).
var Schema = require('protobuf_for_node').Schema;
// "schema" contains all message types defined in feeds.proto|desc.
var schema = new Schema(fs.readFileSync('example/feeds.desc'));
// The "Feed" message.
var Feed = schema['feeds.Feed'];
// Serializes a JS object to a protocol message in a node buffer
// according to the protocol message schema.
var serialized = Feed.serialize({ title: 'Title', ignored: 42 });
// Parses a protocol message in a node buffer into a JS object
// according to the protocol message schema.
var aFeed = Feed.parse(serialized);
// The "ignored" field has been dropped.
puts("Message after roundtrip: " + JSON.stringify(aFeed, null, 2));
// Each protocol message type has its own prototype. You can attach
// methods to parsed protocol messages.
Feed.prototype.numEntries = function() {
return this.entry.length;
};
var aFeed = Feed.parse(Feed.serialize({ entry: [{}, {}] }));
puts("Number of entries: " + aFeed.numEntries());
// Performance is (only) on par with builtin JSON serialization.
var t = Date.now();
for (var i = 0; i < 100000; i++)
Feed.parse(Feed.serialize({ entry: [{}, {}] }));
puts("Proto: " + (Date.now() - t)/100 + " us / object");
var t = Date.now();
for (var i = 0; i < 100000; i++)
JSON.parse(JSON.stringify({ entry: [{}, {}] }));
puts("JSON: " + (Date.now() - t)/100 + " us / object");
| 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.
var puts = require('util').puts;
var pwd = require('protoservice');
// Synchronous service call. This is only possible if the service
// implementation is synchronous, too, i.e. invokes the Done closure
// before returning. Otherwise this will fail.
var entries = pwd.sync.GetEntries({});
puts(entries.entry.length + " users");
// Synchronous implementations can be called callback style, too.
// They will automatically be placed on the eio thred pool. This is
// good for blocking or CPU-consuming tasks.
pwd.sync.GetEntries({}, function(entries) {
// This will print last.
puts("sync: " + entries.entry.length + " users");
});
puts("Getting entries asynchronously from sync service ...");
// Invocations of async services (ones that call "Done" only after the
// initial service call returns) must be called callback-style.
pwd.async.GetEntries({}, function(entries) {
// This will print last.
puts("async: " + entries.entry.length + " users");
});
puts("Getting entries asynchronously from async service ...");
| JavaScript |
var assert = require('assert'),
puts = require('util').puts,
read = require('fs').readFileSync,
Schema = require('protobuf_for_node').Schema;
/* hack to make the tests pass with node v0.3.0's new Buffer model */
/* copied from http://github.com/bnoordhuis/node-iconv/blob/master/test.js */
assert.bufferEqual = function(a, b, c) {
assert.equal(
a.inspect().replace(/^<SlowBuffer/, '<Buffer'),
b.inspect().replace(/^<SlowBuffer/, '<Buffer'),
c);
};
var T = new Schema(read('test/unittest.desc'))['protobuf_unittest.TestAllTypes'];
assert.ok(T, 'type in schema');
var golden = read('test/golden_message');
var message = T.parse(golden);
assert.ok(message, 'parses message'); // currently rather crashes
assert.bufferEqual(T.serialize(message), golden, 'roundtrip');
message.ignored = 42;
assert.bufferEqual(T.serialize(message), golden, 'ignored field');
assert.throws(function() {
T.parse(new Buffer('invalid'));
}, Error, 'Should not parse');
assert.strictEqual(T.parse(
T.serialize({
optionalInt32: '3'
})
).optionalInt32, 3, 'Number conversion');
assert.strictEqual(T.parse(
T.serialize({
optionalInt32: ''
})
).optionalInt32, 0, 'Number conversion');
assert.strictEqual(T.parse(
T.serialize({
optionalInt32: 'foo'
})
).optionalInt32, 0, 'Number conversion');
assert.strictEqual(T.parse(
T.serialize({
optionalInt32: {}
})
).optionalInt32, 0, 'Number conversion');
assert.strictEqual(T.parse(
T.serialize({
optionalInt32: null
})
).optionalInt32, undefined, 'null');
assert.throws(function() {
T.serialize({
optionalNestedEnum: 'foo'
});
}, Error, 'Unknown enum');
assert.throws(function() {
T.serialize({
optionalNestedMessage: 3
});
}, Error, 'Not an object');
assert.throws(function() {
T.serialize({
repeatedNestedMessage: ''
});
}, Error, 'Not an array');
assert.bufferEqual(T.parse(
T.serialize({
optionalBytes: new Buffer('foo')
})
).optionalBytes, new Buffer('foo'));
assert.bufferEqual(T.parse(
T.serialize({
optionalBytes: 'foo'
})
).optionalBytes, new Buffer('foo'));
assert.bufferEqual(T.parse(
T.serialize({
optionalBytes: '\u20ac'
})
).optionalBytes, new Buffer('\u00e2\u0082\u00ac', 'binary'));
assert.bufferEqual(T.parse(
T.serialize({
optionalBytes: '\u0000'
})
).optionalBytes, new Buffer('\u0000', 'binary'));
assert.equal(T.parse(
T.serialize({
optionalString: new Buffer('f\u0000o')
})
).optionalString, 'f\u0000o');
puts('Success');
| JavaScript |
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var page = {
startX: 150,
startY: 150,
endX: 400,
endY: 300,
moveX: 0,
moveY: 0,
pageWidth: 0,
pageHeight: 0,
visibleWidth: 0,
visibleHeight: 0,
dragging: false,
moving: false,
resizing: false,
isMouseDown: false,
scrollXCount: 0,
scrollYCount: 0,
scrollX: 0,
scrollY: 0,
captureWidth: 0,
captureHeight: 0,
isSelectionAreaTurnOn: false,
fixedElements_ : [],
marginTop: 0,
marginLeft: 0,
modifiedBottomRightFixedElements: [],
originalViewPortWidth: document.documentElement.clientWidth,
defaultScrollBarWidth: 17, // Default scroll bar width on windows platform.
hookBodyScrollValue: function(needHook) {
document.documentElement.setAttribute(
"__screen_capture_need_hook_scroll_value__", needHook);
var event = document.createEvent('Event');
event.initEvent('__screen_capture_check_hook_status_event__', true, true);
document.documentElement.dispatchEvent(event);
},
/**
* Determine if the page scrolled to bottom or right.
*/
isScrollToPageEnd: function(coordinate) {
var body = document.body;
var docElement = document.documentElement;
if (coordinate == 'x')
return docElement.clientWidth + body.scrollLeft == body.scrollWidth;
else if (coordinate == 'y')
return docElement.clientHeight + body.scrollTop == body.scrollHeight;
},
/**
* Detect if the view port is located to the corner of page.
*/
detectPagePosition: function() {
var body = document.body;
var pageScrollTop = body.scrollTop;
var pageScrollLeft = body.scrollLeft;
if (pageScrollTop == 0 && pageScrollLeft == 0) {
return 'top_left';
} else if (pageScrollTop == 0 && this.isScrollToPageEnd('x')) {
return 'top_right';
} else if (this.isScrollToPageEnd('y') && pageScrollLeft == 0) {
return 'bottom_left';
} else if (this.isScrollToPageEnd('y') && this.isScrollToPageEnd('x')) {
return 'bottom_right';
}
return null;
},
/**
* Detect fixed-positioned element's position in the view port.
* @param {Element} elem
* @return {String|Object} Return position of the element in the view port:
* top_left, top_right, bottom_left, bottom_right, or null.
*/
detectCapturePositionOfFixedElement: function(elem) {
var docElement = document.documentElement;
var viewPortWidth = docElement.clientWidth;
var viewPortHeight = docElement.clientHeight;
var offsetWidth = elem.offsetWidth;
var offsetHeight = elem.offsetHeight;
var offsetTop = elem.offsetTop;
var offsetLeft = elem.offsetLeft;
var result = [];
// Compare distance between element and the edge of view port to determine
// the capture position of element.
if (offsetTop <= viewPortHeight - offsetTop - offsetHeight) {
result.push('top');
} else if (offsetTop < viewPortHeight) {
result.push('bottom');
}
if (offsetLeft <= viewPortWidth - offsetLeft - offsetWidth) {
result.push('left');
} else if (offsetLeft < viewPortWidth) {
result.push('right');
}
// If the element is out of view port, then ignore.
if (result.length != 2)
return null;
return result.join('_');
},
restoreFixedElements: function() {
this.fixedElements_.forEach(function(element) {
element[1].style.visibility = "visible";
});
this.fixedElements_ = [];
},
/**
* Iterate DOM tree and cache visible fixed-position elements.
*/
cacheVisibleFixedPositionedElements: function() {
var nodeIterator = document.createNodeIterator(
document.documentElement,
NodeFilter.SHOW_ELEMENT,
null,
false
);
var currentNode;
while (currentNode = nodeIterator.nextNode()) {
var nodeComputedStyle =
document.defaultView.getComputedStyle(currentNode, "");
// Skip nodes which don't have computeStyle or are invisible.
if (!nodeComputedStyle)
continue;
if (nodeComputedStyle.position == "fixed" &&
nodeComputedStyle.display != 'none' &&
nodeComputedStyle.visibility != 'hidden') {
var position =
this.detectCapturePositionOfFixedElement(currentNode);
if (position)
this.fixedElements_.push([position, currentNode]);
}
}
},
// Handle fixed-position elements for capture.
handleFixedElements: function(capturePosition) {
var docElement = document.documentElement;
var body = document.body;
// If page has no scroll bar, then return directly.
if (docElement.clientHeight == body.scrollHeight &&
docElement.clientWidth == body.scrollWidth)
return;
if (!this.fixedElements_.length) {
this.cacheVisibleFixedPositionedElements();
}
this.fixedElements_.forEach(function(element) {
if (element[0] == capturePosition)
element[1].style.visibility = 'visible';
else
element[1].style.visibility= 'hidden';
});
},
handleSecondToLastCapture: function() {
var docElement = document.documentElement;
var body = document.body;
var bottomPositionElements = [];
var rightPositionElements = [];
var that = this;
this.fixedElements_.forEach(function(element) {
var position = element[0];
if (position == 'bottom_left' || position == 'bottom_right') {
bottomPositionElements.push(element[1]);
} else if (position == 'bottom_right' || position == 'top_right') {
rightPositionElements.push(element[1]);
}
});
// Determine if the current capture is last but one.
var remainingCaptureHeight = body.scrollHeight - docElement.clientHeight -
body.scrollTop;
if (remainingCaptureHeight > 0 &&
remainingCaptureHeight < docElement.clientHeight) {
bottomPositionElements.forEach(function(element) {
if (element.offsetHeight > remainingCaptureHeight) {
element.css('visibility', 'visible');
var originalBottom = window.getComputedStyle(element).bottom;
that.modifiedBottomRightFixedElements.push(
['bottom', element, originalBottom]);
element.css('bottom', -remainingCaptureHeight + 'px');
}
});
}
var remainingCaptureWidth = body.scrollWidth - docElement.clientWidth -
body.scrollLeft;
if (remainingCaptureWidth > 0 &&
remainingCaptureWidth < docElement.clientWidth) {
rightPositionElements.forEach(function(element) {
if (element.offsetWidth > remainingCaptureWidth) {
element.css('visibility','visible');
var originalRight = window.getComputedStyle(element).right;
that.modifiedBottomRightFixedElements.push(
['right', element, originalRight]);
element.css('right',-remainingCaptureWidth + 'px');
}
});
}
},
restoreBottomRightOfFixedPositionElements: function() {
this.modifiedBottomRightFixedElements.forEach(function(data) {
var property = data[0];
var element = data[1];
var originalValue = data[2];
element.css(property,originalValue);
});
this.modifiedBottomRightFixedElements = [];
},
hideAllFixedPositionedElements: function() {
this.fixedElements_.forEach(function(element) {
element[1].css('visibility', 'hidden');
});
},
hasScrollBar: function(axis) {
var body = document.body;
var docElement = document.documentElement;
if (axis == 'x') {
if (window.getComputedStyle(body).overflowX == 'scroll')
return true;
return Math.abs(body.scrollWidth - docElement.clientWidth) >=
page.defaultScrollBarWidth;
} else if (axis == 'y') {
if (window.getComputedStyle(body).overflowY == 'scroll')
return true;
return Math.abs(body.scrollHeight - docElement.clientHeight) >=
page.defaultScrollBarWidth;
}
},
getOriginalViewPortWidth: function() {
chrome.extension.sendRequest({ msg: 'original_view_port_width'},
function(originalViewPortWidth) {
if (originalViewPortWidth) {
page.originalViewPortWidth = page.hasScrollBar('y') ?
originalViewPortWidth - page.defaultScrollBarWidth : originalViewPortWidth;
} else {
page.originalViewPortWidth = document.documentElement.clientWidth;
}
});
},
calculateSizeAfterZooming: function(originalSize) {
var originalViewPortWidth = page.originalViewPortWidth;
var currentViewPortWidth = document.documentElement.clientWidth;
if (originalViewPortWidth == currentViewPortWidth)
return originalSize;
return Math.round(
originalViewPortWidth * originalSize / currentViewPortWidth);
},
getZoomLevel: function() {
return page.originalViewPortWidth / document.documentElement.clientWidth;
},
handleRightFloatBoxInGmail: function() {
var mainframe = $('#canvas_frame');
var boxContainer = $('body > .dw');
var fBody = mainframe.contentDocument.body;
if (fBody.clientHeight + fBody.scrollTop == fBody.scrollHeight) {
boxContainer.css('display', 'block');
} else {
boxContainer.css('display', 'none');
}
},
/**
* Check if the page is only made of invisible embed elements.
*/
checkPageIsOnlyEmbedElement: function() {
var bodyNode = document.body.children;
var isOnlyEmbed = false;
for (var i = 0; i < bodyNode.length; i++) {
var tagName = bodyNode[i].tagName;
if (tagName == 'OBJECT' || tagName == 'EMBED' || tagName == 'VIDEO' ||
tagName == 'SCRIPT' || tagName == 'LINK') {
isOnlyEmbed = true;
} else if (bodyNode[i].style.display != 'none'){
isOnlyEmbed = false;
break;
}
}
return isOnlyEmbed;
},
isGMailPage: function(){
var hostName = window.location.hostname;
if (hostName == 'mail.google.com' &&
document.getElementById('canvas_frame')) {
return true;
}
return false;
},
/**
* Receive messages from background page, and then decide what to do next
*/
addMessageListener : function() {
chrome.extension.onRequest.addListener(function(request, sender, response) {
if( request.msg ){
if (page.isSelectionAreaTurnOn) {
page.removeSelectionArea();
}
switch (request.msg) {
case 'capture_window': response(page.getWindowSize()); break;
case 'show_selection_area': page.showSelectionArea(); break;
case 'scroll_init': // Capture whole page.
response(page.scrollInit(0, 0, document.width, document.height, 'captureWhole'));
break;
case 'scroll_next':
page.visibleWidth = request.visibleWidth;
page.visibleHeight = request.visibleHeight;
response(page.scrollNext());
break;
case 'capture_selected':
response(page.scrollInit(
page.startX, page.startY,
page.calculateSizeAfterZooming(page.endX - page.startX),
page.calculateSizeAfterZooming(page.endY - page.startY), 'captureSelected'));
break;
case 'is_page_capturable':
var resp = {};
try {
if (isPageCapturable()) {
resp = {msg: 'capturable'};
} else {
resp = {msg: 'uncapturable'};
}
chrome.extension.sendRequest(resp);
} catch(e) {
chrome.extension.sendRequest({msg: 'loading'});
}
}
}
});
},
/**
* Send Message to background page
*/
sendMessage: function(message) {
chrome.extension.sendRequest(message);
},
/**
* Initialize scrollbar position, and get the data browser
*/
scrollInit : function(startX, startY, canvasWidth, canvasHeight, type) {
this.hookBodyScrollValue(true);
page.captureHeight = canvasHeight;
page.captureWidth = canvasWidth;
var docWidth = document.documentElement.scrollWidth;
var docHeight = document.documentElement.scrollHeight;
window.scrollTo(startX, startY);
this.handleFixedElements('top_left');
this.handleSecondToLastCapture();
if (page.isGMailPage() && type == 'captureWhole') {
var frame = document.getElementById('canvas_frame');
docHeight = page.captureHeight = canvasHeight =
frame.contentDocument.height;
docWidth = page.captureWidth = canvasWidth = frame.contentDocument.width;
frame.contentDocument.body.scrollTop = 0;
frame.contentDocument.body.scrollLeft = 0;
page.handleRightFloatBoxInGmail();
}
page.scrollXCount = 0;
page.scrollYCount = 1;
page.scrollX = window.scrollX; // document.body.scrollLeft
page.scrollY = window.scrollY;
return {
'msg': 'scroll_init_done',
'startX': page.calculateSizeAfterZooming(startX),
'startY': page.calculateSizeAfterZooming(startY),
'scrollX': window.scrollX,
'scrollY': window.scrollY,
'docHeight': docHeight,
'docWidth': docWidth,
'visibleWidth': document.documentElement.clientWidth,
'visibleHeight': document.documentElement.clientHeight,
'canvasWidth': canvasWidth,
'canvasHeight': canvasHeight,
'scrollXCount': 0,
'scrollYCount': 0,
'zoom': page.getZoomLevel()
};
},
/**
* Calculate the next position of the scrollbar
*/
scrollNext: function() {
if (page.scrollYCount * page.visibleWidth >= page.captureWidth) {
page.scrollXCount++;
page.scrollYCount = 0;
}
if (page.scrollXCount * page.visibleHeight < page.captureHeight) {
this.restoreBottomRightOfFixedPositionElements();
var doc = document.documentElement;
window.scrollTo(
page.scrollYCount * doc.clientWidth + page.scrollX,
page.scrollXCount * doc.clientHeight + page.scrollY);
var pagePosition = this.detectPagePosition();
if (pagePosition) {
this.handleFixedElements(pagePosition);
} else {
this.hideAllFixedPositionedElements();
}
this.handleSecondToLastCapture();
if (page.isGMailPage()) {
var frame = document.getElementById('canvas_frame');
frame.contentDocument.body.scrollLeft =
page.scrollYCount * doc.clientWidth;
frame.contentDocument.body.scrollTop =
page.scrollXCount * doc.clientHeight;
page.handleRightFloatBoxInGmail();
}
var x = page.scrollXCount;
var y = page.scrollYCount;
page.scrollYCount++;
return { msg: 'scroll_next_done',scrollXCount: x, scrollYCount: y };
} else {
window.scrollTo(page.startX, page.startY);
this.restoreFixedElements();
this.hookBodyScrollValue(false);
return {'msg': 'scroll_finished'};
}
},
/**
* Show the selection Area
*/
showSelectionArea : function() {
page.createFloatLayer();
setTimeout(page.createSelectionArea, 100);
},
getWindowSize: function() {
var docWidth = document.width;
var docHeight = document.height;
if (page.isGMailPage()) {
var frame = document.getElementById('canvas_frame');
docHeight = frame.contentDocument.height;
docWidth = frame.contentDocument.width;
}
return {'msg':'capture_window',
'docWidth': docWidth,
'docHeight': docHeight};
},
getSelectionSize: function() {
page.removeSelectionArea();
setTimeout(function() {
page.sendMessage({
'msg': 'capture_selected',
'x': page.startX,
'y': page.startY,
'width': page.endX - page.startX,
'height': page.endY - page.startY,
'visibleWidth': document.documentElement.clientWidth,
'visibleHeight': document.documentElement.clientHeight,
'docWidth': document.width,
'docHeight': document.height
})}, 100);
},
/**
* Create a float layer on the webpage
*/
createFloatLayer: function() {
var fl = page.createDiv($('body'), 'f2qu_sc_drag_area_protector');
fl.css('height', (document.body.offsetHeight || document.documentElement.offsetHeight ) + 'px')
},
matchMarginValue: function(str) {
return str.match(/\d+/);
},
/**
* Load the screenshot area interface
*/
createSelectionArea : function() {
var areaProtector = $('#f2qu_sc_drag_area_protector');
var zoom = page.getZoomLevel();
var bodyStyle = window.getComputedStyle(document.body, null);
if ('relative' == bodyStyle['position']) {
page.marginTop = page.matchMarginValue(bodyStyle['marginTop']);
page.marginLeft = page.matchMarginValue(bodyStyle['marginLeft']);
areaProtector.css('top', - parseInt(page.marginTop) + 'px');
areaProtector.css('left', - parseInt(page.marginLeft) + 'px');
}
areaProtector.css('width', Math.round((document.width + parseInt(page.marginLeft)) / zoom) + 'px');
areaProtector.css('height', Math.round((document.height + parseInt(page.marginTop)) / zoom) + 'px');
areaProtector.click(function() {
event.stopPropagation();
return false;
});
// Create elements for area capture.
page.createDiv(areaProtector, 'f2qu_sc_drag_shadow_top');
page.createDiv(areaProtector, 'f2qu_sc_drag_shadow_bottom');
page.createDiv(areaProtector, 'f2qu_sc_drag_shadow_left');
page.createDiv(areaProtector, 'f2qu_sc_drag_shadow_right');
var areaElement = page.createDiv(areaProtector, 'f2qu_sc_drag_area');
page.createDiv(areaElement, 'f2qu_sc_drag_container');
page.createDiv(areaElement, 'f2qu_sc_drag_size');
// Add event listener for 'cancel' and 'capture' button.
var cancel = page.createDiv(areaElement, 'f2qu_sc_drag_cancel');
cancel[0].addEventListener('mousedown', function () {
// Remove area capture containers and event listeners.
page.removeSelectionArea();
}, true);
cancel.html("取消");
var crop = page.createDiv(areaElement, 'f2qu_sc_drag_crop');
crop[0].addEventListener('mousedown', page.onDblClick, false);
crop.html('确定');
page.createDiv(areaElement, 'f2qu_sc_drag_north_west');
page.createDiv(areaElement, 'f2qu_sc_drag_north_east');
page.createDiv(areaElement, 'f2qu_sc_drag_south_east');
page.createDiv(areaElement, 'f2qu_sc_drag_south_west');
areaProtector[0].addEventListener('mousedown', page.onMouseDown, false);
document.addEventListener('mousemove', page.onMouseMove, false);
document.addEventListener('mouseup', page.onMouseUp, false);
$('#f2qu_sc_drag_container')[0].addEventListener('dblclick', page.onDblClick, false);
page.pageHeight = $('#f2qu_sc_drag_area_protector')[0].clientHeight;
page.pageWidth = $('#f2qu_sc_drag_area_protector')[0].clientWidth;
var areaElement = $('#f2qu_sc_drag_area');
areaElement.css('left', page.getElementLeft(areaElement) + 'px');
areaElement.css('top', page.getElementTop(areaElement) + 'px');
page.startX = page.getElementLeft(areaElement);
page.startY = page.getElementTop(areaElement);
page.endX = page.getElementLeft(areaElement) + 250;
page.endY = page.getElementTop(areaElement) + 150;
areaElement.css('width','250px');
areaElement.css('height','150px');
page.isSelectionAreaTurnOn = true;
page.updateShadow(areaElement);
page.updateSize();
},
getElementLeft: function(obj) {
return (document.body.scrollLeft +
(document.documentElement.clientWidth -
obj[0].offsetWidth) / 2);
},
getElementTop: function(obj) {
return (document.body.scrollTop +
(document.documentElement.clientHeight - 200 -
obj[0].offsetHeight) / 2);
},
/**
* Init selection area due to the position of the mouse when mouse down
*/
onMouseDown: function() {
if (event.button != 2) {
var element = event.target;
if (element) {
var elementName = element.tagName;
if (elementName && document) {
page.isMouseDown = true;
var areaElement = $('#f2qu_sc_drag_area');
var xPosition = event.pageX;
var yPosition = event.pageY;
if (areaElement[0]) {
if (element == $('#f2qu_sc_drag_container')[0]) {
page.moving = true;
page.moveX = xPosition - areaElement[0].offsetLeft;
page.moveY = yPosition - areaElement[0].offsetTop;
} else if (element == $('#f2qu_sc_drag_north_east')[0]) {
page.resizing = true;
page.startX = areaElement[0].offsetLeft;
page.startY = areaElement[0].offsetTop + areaElement[0].clientHeight;
} else if (element == $('#f2qu_sc_drag_north_west')[0]) {
page.resizing = true;
page.startX = areaElement[0].offsetLeft + areaElement[0].clientWidth;
page.startY = areaElement[0].offsetTop + areaElement[0].clientHeight;
} else if (element == $('#f2qu_sc_drag_south_east')[0]) {
page.resizing = true;
page.startX = areaElement[0].offsetLeft;
page.startY = areaElement[0].offsetTop;
} else if (element == $('#f2qu_sc_drag_south_west')[0]) {
page.resizing = true;
page.startX = areaElement[0].offsetLeft + areaElement[0].clientWidth;
page.startY = areaElement[0].offsetTop;
} else {
page.dragging = true;
page.endX = 0;
page.endY = 0;
page.endX = page.startX = xPosition;
page.endY = page.startY = yPosition;
}
}
event.preventDefault();
}
}
}
},
/**
* Change selection area position when mouse moved
*/
onMouseMove: function() {
var element = event.target;
if (element && page.isMouseDown) {
var areaElement = $('#f2qu_sc_drag_area');
if (areaElement[0]) {
var xPosition = event.pageX;
var yPosition = event.pageY;
if (page.dragging || page.resizing) {
var width = 0;
var height = 0;
var zoom = page.getZoomLevel();
var viewWidth = Math.round(document.width / zoom);
var viewHeight = Math.round(document.height / zoom);
if (xPosition > viewWidth) {
xPosition = viewWidth;
} else if (xPosition < 0) {
xPosition = 0;
}
if (yPosition > viewHeight) {
yPosition = viewHeight;
} else if (yPosition < 0) {
yPosition = 0;
}
page.endX = xPosition;
page.endY = yPosition;
if (page.startX > page.endX) {
width = page.startX - page.endX;
areaElement.css('left', xPosition + 'px');
} else {
width = page.endX - page.startX;
areaElement.css('left', page.startX + 'px');
}
if (page.startY > page.endY) {
height = page.startY - page.endY;
areaElement.css('top', page.endY + 'px');
} else {
height = page.endY - page.startY;
areaElement.css('top', page.startY + 'px');
}
areaElement.css('height', height + 'px');
areaElement.css('width', width + 'px');
if (window.innerWidth < xPosition) {
document.body.scrollLeft = xPosition - window.innerWidth;
}
if (document.body.scrollTop + window.innerHeight < yPosition + 25) {
document.body.scrollTop = yPosition - window.innerHeight + 25;
}
if (yPosition < document.body.scrollTop) {
document.body.scrollTop -= 25;
}
} else if (page.moving) {
var newXPosition = xPosition - page.moveX;
var newYPosition = yPosition - page.moveY;
if (newXPosition < 0) {
newXPosition = 0;
} else if (newXPosition + areaElement[0].clientWidth > page.pageWidth) {
newXPosition = page.pageWidth - areaElement[0].clientWidth;
}
if (newYPosition < 0) {
newYPosition = 0;
} else if (newYPosition + areaElement[0].clientHeight >
page.pageHeight) {
newYPosition = page.pageHeight - areaElement[0].clientHeight;
}
areaElement.css('left', newXPosition + 'px');
areaElement.css('top', newYPosition + 'px');
page.endX = newXPosition + areaElement[0].clientWidth;
page.startX = newXPosition;
page.endY = newYPosition + areaElement[0].clientHeight;
page.startY = newYPosition;
}
var crop = $('#f2qu_sc_drag_crop');
var cancel = $('#f2qu_sc_drag_cancel');
if (event.pageY + 25 > document.height) {
crop.css('bottom', 0);
cancel.css('bottom', 0)
} else {
crop.css('bottom', '-25px');
cancel.css('bottom', '-25px');
}
var dragSizeContainer = $('#f2qu_sc_drag_size');
if (event.pageY < 18) {
dragSizeContainer.css('top', 0);
} else {
dragSizeContainer.css('top','-18px');
}
page.updateShadow(areaElement);
page.updateSize();
}
}
},
/**
* Fix the selection area position when mouse up
*/
onMouseUp: function()
{
page.isMouseDown = false;
if (event.button != 2) {
page.resizing = false;
page.dragging = false;
page.moving = false;
page.moveX = 0;
page.moveY = 0;
var temp;
if (page.endX < page.startX) {
temp = page.endX;
page.endX = page.startX;
page.startX = temp;
}
if (page.endY < page.startY) {
temp = page.endY;
page.endY = page.startY;
page.startY = temp;
}
}
},
/**
* Update the location of the shadow layer
*/
updateShadow: function(areaElement) {
$('#f2qu_sc_drag_shadow_top').css('height',
parseInt(areaElement.css('top')) + 'px');
$('#f2qu_sc_drag_shadow_top').css('width',(parseInt(areaElement.css('left')) +
parseInt(areaElement.css('width')) + 1) + 'px');
$('#f2qu_sc_drag_shadow_left').css('height',
(page.pageHeight - parseInt(areaElement.css('top'))) + 'px');
$('#f2qu_sc_drag_shadow_left').css('width',
parseInt(areaElement.css('left')) + 'px');
var height = (parseInt(areaElement.css('top')) +
parseInt(areaElement.css('height')) + 1);
height = (height < 0) ? 0 : height;
var width = (page.pageWidth) - 1 - (parseInt(areaElement.css('left')) +
parseInt(areaElement.css('width')));
width = (width < 0) ? 0 : width;
$('#f2qu_sc_drag_shadow_right').css('height', height + 'px');
$('#f2qu_sc_drag_shadow_right').css('width', width + 'px');
height = (page.pageHeight - 1 - (parseInt(areaElement.css('top')) +
parseInt(areaElement.css('height'))));
height = (height < 0) ? 0 : height;
width = (page.pageWidth) - parseInt(areaElement.css('left'));
width = (width < 0) ? 0 : width;
$('#f2qu_sc_drag_shadow_bottom').css('height', height + 'px');
$('#f2qu_sc_drag_shadow_bottom').css('width', width + 'px');
},
//do crop the selected area;
onDblClick : function (){
//此全局变量联系 content.js 截屏过程标记
document.f2qu_capturing = true;
var fixdom =$('#pl_content_top');
if( fixdom[0] ){
fixdom.css('opacity', 0);
}
//截屏过程处理
page.removeSelectionArea();
page.sendMessage({msg: 'capture_selected'});
},
/**
* Remove selection area
*/
removeSelectionArea: function() {
document.removeEventListener('mousedown', page.onMouseDown, false);
document.removeEventListener('mousemove', page.onMouseMove, false);
document.removeEventListener('mouseup', page.onMouseUp, false);
$('#f2qu_sc_drag_container')[0].removeEventListener('dblclick',page.onDblClick, false);
page.removeElement('f2qu_sc_drag_area_protector');
page.removeElement('f2qu_sc_drag_area');
page.isSelectionAreaTurnOn = false;
},
/**
* Refresh the size info
*/
updateSize: function() {
var width = Math.abs(page.endX - page.startX);
var height = Math.abs(page.endY - page.startY);
$('#f2qu_sc_drag_size')[0].innerText = page.calculateSizeAfterZooming(width) +
' x ' + page.calculateSizeAfterZooming(height);
},
/**
* create div
*/
createDiv: function(parent, id) {
var divElement = $('<div id='+id+'></div>');
parent.append(divElement);
return divElement;
},
/**
* Remove an element
*/
removeElement: function(id) {
if($('#'+id)) {
$('#'+id).remove();
}
},
injectCssResource: function(cssResource) {
var css = document.createElement('LINK');
css.type = 'text/css';
css.rel = 'stylesheet';
css.href = chrome.extension.getURL(cssResource);
(document.head || document.body || document.documentElement).
appendChild(css);
},
injectJavaScriptResource: function(scriptResource) {
var script = document.createElement("script");
script.type = "text/javascript";
script.charset = "utf-8";
script.src = chrome.extension.getURL(scriptResource);
(document.head || document.body || document.documentElement).
appendChild(script);
},
/**
* Remove an element
*/
init: function() {
if (document.body.hasAttribute('f2qu_screen_capture_injected')) {
return;
}
if (isPageCapturable()) {
chrome.extension.sendRequest({msg: 'page_capturable'});
} else {
chrome.extension.sendRequest({msg: 'page_uncapturable'});
}
this.injectCssResource('style.css');
this.addMessageListener();
this.injectJavaScriptResource("page_context.js");
//Retrieve original width of view port and cache.
page.getOriginalViewPortWidth();
}
};
/**
* Indicate if the current page can be captured.
*/
var isPageCapturable = function() {
return !page.checkPageIsOnlyEmbedElement();
};
function $(id) {
return document.getElementById(id);
}
page.init();
window.onresize = function() {
if (page.isSelectionAreaTurnOn) {
page.removeSelectionArea();
page.showSelectionArea();
}
// Reget original width of view port if browser window resized or page zoomed.
page.getOriginalViewPortWidth();
};
// Send page url for retriving and parsing access token for facebook and picasa.
page.sendMessage({
msg: 'url_for_access_token',
url: window.location.href
});
| JavaScript |
var __screenCapturePageContext__ = {
clone: function(object) {
function StubObj() { }
StubObj.prototype = object;
var newObj = new StubObj();
newObj.getInternalObject = function() {
return this.__proto__;
}
newObj.toString = function() {
try {
return this.__proto__.toString();
} catch (e) {
return 'object Object';
}
}
return newObj;
},
bind: function(newThis, func) {
var args = [];
for(var i = 2;i < arguments.length; i++) {
args.push(arguments[i]);
}
return function() {
return func.apply(newThis, args);
}
},
bodyWrapperDelegate_: null,
currentHookStatus_: false,
scrollValueHooker: function(oldValue, newValue, reason) {
// When we hook the value of scrollLeft/Top of body, it always returns 0.
return 0;
},
toggleBodyScrollValueHookStatus: function() {
this.currentHookStatus_ = !this.currentHookStatus_;
if (this.currentHookStatus_) {
var This = this;
try {
document.__defineGetter__('body', function() {
return This.bodyWrapperDelegate_.getWrapper();
});
} catch (e) {
window.console.log('error' + e);
}
this.bodyWrapperDelegate_.watch('scrollLeft', this.scrollValueHooker);
this.bodyWrapperDelegate_.watch('scrollTop', this.scrollValueHooker);
} else {
this.bodyWrapperDelegate_.unwatch('scrollLeft', this.scrollValueHooker);
this.bodyWrapperDelegate_.unwatch('scrollTop', this.scrollValueHooker);
var This = this;
try {
document.__defineGetter__('body', function() {
return This.bodyWrapperDelegate_.getWrapper().getInternalObject();
});
} catch (e) {
window.console.log('error' + e);
}
}
},
checkHookStatus: function() {
var needHookScrollValue = document.documentElement.getAttributeNode(
'__screen_capture_need_hook_scroll_value__');
needHookScrollValue =
!!(needHookScrollValue && needHookScrollValue.nodeValue == 'true');
if (this.currentHookStatus_ != needHookScrollValue)
this.toggleBodyScrollValueHookStatus();
},
init: function() {
if (!this.bodyWrapperDelegate_) {
this.bodyWrapperDelegate_ =
new __screenCapturePageContext__.ObjectWrapDelegate(
document.body, '^(DOCUMENT_[A-Z_]+|[A-Z_]+_NODE)$');
document.documentElement.addEventListener(
'__screen_capture_check_hook_status_event__',
__screenCapturePageContext__.bind(this, this.checkHookStatus));
}
}
};
// ObjectWrapDelegate class will create a empty object(wrapper), map its
// prototype to the 'originalObject', then search all non-function properties
// (except those properties which match the propertyNameFilter) of the
// 'orginalObject' and set corresponding getter/setter to the wrapper.
// Then you can manipulate the wrapper as 'originalObject' because the wrapper
// use the corresponding getter/setter to access the corresponding properties in
// 'originalObject' and the all function calls can be call through the prototype
// inherit.
// After createing the wrapper object, you can use watch method to monitor any
// property which you want to know when it has been read(get) or change(set).
// Please see the detail comment on method watch.
// Remember the ObjectWrapDelegate returns the wrapDelegateObject instead of
// really wrapper object. You have to use ObjectWrapDelegate.getWrapper to get
// real wrapper object.
// parameter @originalObject, object which you want to wrap
// parameter @propertyNameFilter, string, regular expression pattern string for
// those properties you don't put in the wrap object.
__screenCapturePageContext__.ObjectWrapDelegate = function(
originalObject, propertyNameFilter) {
this.window_ = window;
// The wrapper is the object we use to wrap the 'originalObject'.
this.wrapper_ = __screenCapturePageContext__.clone(originalObject);
// This array saves all properties we set our getter/setter for them.
this.properties_ = [];
// This object to save all watch handlers. Each watch handler is bind to one
// certain property which is in properties_.
this.watcherTable_ = {};
// Check the propertyNameFilter parameter.
if (typeof propertyNameFilter == 'undefined') {
propertyNameFilter = '';
} else if (typeof propertyNameFilter != 'string') {
try {
propertyNameFilter = propertyNameFilter.toString();
} catch (e) {
propertyNameFilter = '';
}
}
if (propertyNameFilter.length) {
this.propertyNameFilter_ = new RegExp('');
this.propertyNameFilter_.compile(propertyNameFilter);
} else {
this.propertyNameFilter_ = null;
}
// For closure to access the private data of class.
var This = this;
// Set the getter object.
function setGetterAndSetter(wrapper, propertyName) {
wrapper.__defineGetter__(propertyName, function() {
var internalObj = this.getInternalObject();
var originalReturnValue = internalObj[propertyName];
var returnValue = originalReturnValue;
// See whether this property has been watched.
var watchers = This.watcherTable_[propertyName];
if (watchers) {
// copy the watcher to a cache in case someone call unwatch inside the
// watchHandler.
var watchersCache = watchers.concat();
for (var i = 0, l = watchersCache.length; i < l; ++i) {
var watcher = watchersCache[i];
if (!watcher) {
window.console.log('wrapper\'s watch for ' + propertyName +
' is unavailable!');
continue; // should never happend
}
originalReturnValue = returnValue;
try {
returnValue = watcher(returnValue, returnValue, 'get');
} catch (e) {
returnValue = originalReturnValue;
}
}
}
return returnValue;
});
// Set the setter object.
wrapper.__defineSetter__(propertyName, function(value) {
var internalObj = this.getInternalObject();
var originalValue = value;
var userValue = originalValue;
var oldValue;
try {
oldValue = internalObj[propertyName];
} catch (e) {
oldValue = null;
}
// See whether this property has been watched.
var watchers = This.watcherTable_[propertyName];
if (watchers) {
// copy the watcher to a cache in case someone call unwatch inside the
// watchHandler.
var watchersCache = watchers.concat();
for (var i = 0, l = watchersCache.length; i < l; ++i) {
var watcher = watchersCache[i];
if (!watcher) {
window.console.log('wrapper\'s watch for ' + propertyName +
' is unavailable!');
continue; // should never happend
}
originalValue = userValue;
try {
userValue = watcher(oldValue, userValue, 'set');
} catch (e) {
userValue = originalValue;
}
}
}
internalObj[propertyName] = userValue;
});
};
this.cleanUp_ = function() {
This.window_.removeEventListener('unload', This.cleanUp_, false);
// Delete all properties
for (var i = 0, l = This.properties_.length; i < l; ++i) {
delete This.wrapper_[This.properties_[i]];
}
This.window_ = null;
This.wrapper_ = null;
This.properties_ = null;
This.watcherTable_ = null;
This.propertyNameFilter_ = null;
This = null;
}
// We only bridge the non-function properties.
for (var prop in originalObject) {
if (this.propertyNameFilter_ && this.propertyNameFilter_.test(prop)) {
this.propertyNameFilter_.test('');
continue;
}
if (typeof originalObject[prop] != 'function') {
this.properties_.push(prop);
setGetterAndSetter(this.wrapper_, prop);
}
}
// Listen the unload event.
this.window_.addEventListener('unload', this.cleanUp_, false);
};
__screenCapturePageContext__.ObjectWrapDelegate.prototype.getWrapper =
function() {
return this.wrapper_;
}
// Check whether a property is in the wrapper or not. If yes, return true.
// Otherwise return false.
__screenCapturePageContext__.ObjectWrapDelegate.prototype.hasProperty =
function(propertyName) {
for (var i = 0, l = this.properties_.length; i < l; ++i) {
if (propertyName == this.properties_[i])
return true;
}
return false;
}
// Watches for a property to be accessed or be assigned a value and runs a
// function when that occurs.
// Watches for accessing a property or assignment to a property named prop in
// this object, calling handler(oldval, newval, reason) whenever prop is
// get/set and storing the return value in that property.
// A watchpoint can filter (or nullify) the value assignment, by returning a
// modified newval (or by returning oldval).
// When watchpoint is trigering by get opeartor, the oldval is equal with
// newval. The reason will be 'get'.
// When watchpoint is trigering by set opeartor, The reason will be 'set'.
// If you delete a property for which a watchpoint has been set,
// that watchpoint does not disappear. If you later recreate the property,
// the watchpoint is still in effect.
// To remove a watchpoint, use the unwatch method.
// If register the watchpoint successfully, return true. Otherwise return false.
__screenCapturePageContext__.ObjectWrapDelegate.prototype.watch = function(
propertyName, watchHandler) {
if (!this.hasProperty(propertyName))
return false;
var watchers = this.watcherTable_[propertyName];
if (watchers) {
for (var i = 0, l = watchers.length; i < l; ++i) {
if (watchHandler == watchers[i])
return true;
}
} else {
watchers = new Array();
this.watcherTable_[propertyName] = watchers;
}
watchers.push(watchHandler);
return true;
}
// Removes a watchpoint set with the watch method.
__screenCapturePageContext__.ObjectWrapDelegate.prototype.unwatch = function(
propertyName, watchHandler) {
if (!this.hasProperty(propertyName))
return false;
var watchers = this.watcherTable_[propertyName];
if (watchers) {
for (var i = 0, l = watchers.length; i < l; ++i) {
if (watchHandler == watchers[i]) {
watchers.splice(i, 1);
return true;
}
}
}
return false;
}
__screenCapturePageContext__.init();
| JavaScript |
(function(){
/**
* ajax is a encapsulated function that used to send data to server
* asynchronously. It uses XMLHttpRequest object to send textual or binary
* data through HTTP method GET, POST etc. It can custom request method,
* request header. Response can be parsed automatically by MIME type of
* response's Content-type, and it can handle success, error or progress event
* in course of sending request and retrieving response.
* @param {Object} option
*/
function ajax(option) {
if (arguments.length < 1 || option.constructor != Object)
throw new Error('Bad parameter.');
var url = option.url;
var success = option.success;
var complete = option.complete;
if (!url || !(success || complete))
throw new Error('Parameter url and success or complete are required.');
var parameters = option.parameters || {};
var method = option.method || 'GET';
var status = option.status;
var headers = option.headers || {};
var data = option.data || null;
var multipartData = option.multipartData;
var queryString = constructQueryString(parameters);
if (multipartData) {
var boundary = multipartData.boundary || 'XMLHttpRequest2';
method = 'POST';
var multipartDataString;
var contentType = headers['Content-Type'] || 'multipart/form-data';
if (contentType.indexOf('multipart/form-data') == 0) {
headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
multipartDataString = constructMultipartFormData(multipartData, boundary,
parameters);
} else if (contentType.indexOf('multipart/related') == 0) {
headers['Content-Type'] = 'multipart/related; boundary=' + boundary;
multipartDataString = constructMultipartRelatedData(boundary,
multipartData.dataList);
}
data = constructBlobData(multipartDataString);
} else {
if (queryString)
url += '?' + queryString;
}
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var statusCode = xhr.status;
var parsedResponse = parseResponse(xhr);
if (complete)
complete(statusCode, parsedResponse);
if (success && (statusCode == 200 || statusCode == 304)) {
success(parsedResponse);
} else if (status) {
if (status[statusCode]) {
// Call specified status code handler
status[statusCode](parsedResponse);
} else if (status['others']) {
// Call others status code handler
status['others'](parsedResponse, statusCode);
}
}
}
};
// Handle request progress
var progress = option.progress;
if (progress) {
xhr.upload.addEventListener('progress', function(e) {
// lengthComputable return true when the length of the progress is known
if (e.lengthComputable) {
progress(e.loaded, e.total);
}
}, false);
}
// Set request header
for (var headerKey in headers) {
xhr.setRequestHeader(headerKey, headers[headerKey]);
}
xhr.send(data);
}
function constructQueryString(parameters) {
var tmpParameter = [];
for(var name in parameters) {
var value = parameters[name];
if (value.constructor == Array) {
value.forEach(function(val) {
tmpParameter.push(name + '=' + val);
});
} else {
tmpParameter.push(name + '=' + value);
}
}
return tmpParameter.join('&');
}
// Parse response data according to content type of response
function parseResponse(xhr) {
var ct = xhr.getResponseHeader("content-type");
if (typeof ct == 'string') {
if (ct.indexOf('xml') >= 0)
return xhr.responseXML;
else if (ct.indexOf('json') >= 0)
return JSON.parse(xhr.responseText);
}
return xhr.responseText;
}
function constructBlobData(dataString, contentType) {
// Create a BlobBuilder instance to constrct a Blob object
var bb;
if (window.BlobBuilder) {
bb = new BlobBuilder();
} else if (window.WebKitBlobBuilder) {
bb = new WebKitBlobBuilder();
}
var len = dataString.length;
// Create a 8-bit unsigned integer ArrayBuffer view
var data = new Uint8Array(len);
for (var i = 0; i < len; i++) {
data[i] = dataString.charCodeAt(i);
}
// Convert to ArrayBuffer and appended to BlobBuilder
bb.append(data.buffer);
// Return a Blob object from builder
return bb.getBlob(contentType);
}
/**
* Construct multipart/form-data formatted data string.
* @param {Object} binaryData binary data
* @param {String} boundary boundary of parts
* @param {Object} otherParameters other text parameters
*/
function constructMultipartFormData(binaryData, boundary, otherParameters) {
var commonHeader = 'Content-Disposition: form-data; ';
var data = [];
for (var key in otherParameters) {
// Add boundary of one header part
data.push('--' + boundary + '\r\n');
// Add same Content-Disposition information
data.push(commonHeader);
data.push('name="' + key + '"\r\n\r\n' + otherParameters[key] + '\r\n');
}
// Construct file data header
data.push('--' + boundary + '\r\n');
data.push(commonHeader);
data.push('name="' + (binaryData.name || 'binaryfilename') + '"; ');
data.push('filename=\"' + binaryData.value + '\"\r\n');
data.push('Content-type: ' + binaryData.type + '\r\n\r\n');
data.push(binaryData.data + '\r\n');
data.push('--' + boundary + '--\r\n');
return data.join('');
}
function constructMultipartRelatedData(boundary, dataList) {
var result = [];
dataList.forEach(function(data) {
result.push('--' + boundary + '\r\n');
result.push('Content-Type: ' + data.contentType + '\r\n\r\n');
result.push(data.data + '\r\n');
});
result.push('--' + boundary + '--\r\n');
return result.join('');
}
ajax.encodeForBinary = function(string) {
string = encodeURI(string).replace(/%([A-Z0-9]{2})/g, '%u00$1');
return unescape(string);
};
ajax.convertEntityString = function(string) {
var entitychars = ['<', '>', '&', '"', '\''];
var entities = ['<', '>', '&', '"', '''];
entitychars.forEach(function(character, index) {
string = string.replace(character, entities[index]);
});
return string;
};
window.ajax = ajax;
})(); | JavaScript |
// Import the needed java packages and classes
importPackage(java.util);
importClass(javax.swing.JOptionPane)
function putDate() {
TARGET.replaceSelection("This is a dummy proc that inserts the Current Date:\n" + new Date());
TARGET.replaceSelection("\nTab Size of doc = " + AU.getTabSize(TARGET));
} | JavaScript |
// =============== GLOBALS ==============
// to identify differnt tab
var tab;
// Bookmarked page database
var SearchMarkDB = {};
// History page database
var SearchHistoryDB = {};
//timer
var startTime;
var endTime;
// Communicate with extension UI
var gPort;
var keywords;
// Used to highlight searched keywords in results
var uiHighlightStart = '<span class=highlight>';
var uiHighlightEnd = '</span>';
var uiEllipses = '<b>...</b>';
var uiContextLen = -30;
// ======================== DATABASE API ==================
// Open the mark database
SearchMarkDB.db = null;
SearchMarkDB.open = function()
{
var dbSize = 200 * 1024 * 1024; // 200 MB
SearchMarkDB.db =
openDatabase('SearchMarkDB', '1.0', 'Bookmark Page Storage', dbSize);
}
//Open the history database
SearchHistoryDB.db = null;
SearchHistoryDB.open = function()
{
var dbSize = 200 * 1024 * 1024; // 200 MB
SearchHistoryDB.db =
openDatabase('SearchHistoryDB', '1.0', 'Historymark Page Storage', dbSize);
}
// create the table that stores all the bookmark
// info, including the associated pages.
SearchMarkDB.createTable =
function()
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('CREATE VIRTUAL TABLE pages ' +
'USING fts3(id INTEGER PRIMARY KEY, ' +
'url TEXT, title TEXT, page TEXT, time INTEGER)',
[],
getCallback("create table", "pages", 1,1),
getCallback("create table", "pages", 0,1));
tx.executeSql('CREATE TABLE IF NOT EXISTS ' +
'rawpages (id INTEGER PRIMARY KEY, htmlpage TEXT)',
[],
getCallback("create table", "rawpages", 1,1),
getCallback("create table", "rawpages", 0,1));
});
}
// create the table that stores all the history pages
// info, including the associated pages.
SearchHistoryDB.createTable =
function()
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('CREATE VIRTUAL TABLE pages ' +
'USING fts3(id INTEGER PRIMARY KEY, ' +
'url TEXT, title TEXT, page TEXT, time INTEGER)',
[],
getCallback("create table", "pages", 1,2),
getCallback("create table", "pages", 0,2));
tx.executeSql('CREATE TABLE IF NOT EXISTS ' +
'rawpages (id INTEGER PRIMARY KEY, htmlpage TEXT)',
[],
getCallback("create table", "rawpages", 1,2),
getCallback("create table", "rawpages", 0,2));
});
}
// add a bookmark and associated page to the database
SearchMarkDB.addBookmarkedPage =
function(newId, newUrl, newTitle, newPlainPage, newTime, newHtmlPage)
{
SearchMarkDB.db.transaction(
function(tx)
{
// html-free page for searching
tx.executeSql('INSERT INTO pages(id, url, title, page, ' +
'time) VALUES (?,?,?,?,?)',
[ newId, newUrl, newTitle, newPlainPage,
newTime ],
getCallback("insert page", newId + " " +
newUrl, 1,1),
getCallback("insert page", newId + " " +
newUrl, 0,1));
// html page for showing cached version
tx.executeSql('INSERT INTO rawpages(id, htmlpage) ' +
'VALUES (?,?)',
[newId, newHtmlPage ],
getCallback("insert page raw", newId +
" " + newUrl, 1,1),
getCallback("insert page raw", newId +
" " + newUrl, 0,1));
});
}
// add a history page and associated page to the database
SearchHistoryDB.addHistoryPage =
function(newId, newUrl, newTitle, newPlainPage, newTime, newHtmlPage)
{
SearchHistoryDB.db.transaction(
function(tx)
{
// html-free page for searching
tx.executeSql('INSERT INTO pages(id, url, title, page, ' +
'time) VALUES (?,?,?,?,?)',
[ newId, newUrl, newTitle, newPlainPage,
newTime ],
getCallback("insert page", newId + " " +
newUrl, 1,2),
getCallback("insert page", newId + " " +
newUrl, 0,2));
// html page for showing cached version
tx.executeSql('INSERT INTO rawpages(id, htmlpage) ' +
'VALUES (?,?)',
[newId, newHtmlPage ],
getCallback("insert page raw", newId +
" " + newUrl, 1,2),
getCallback("insert page raw", newId +
" " + newUrl, 0,2));
});
}
// remove a bookmarked page from the database
SearchMarkDB.removeBookmarkedPage =
function(theId)
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('DELETE FROM pages WHERE id=?', [ theId ],
getCallback("remove page", theId, 1,1),
getCallback("remove page", theId, 0,1));
tx.executeSql('DELETE FROM rawpages WHERE id=?', [ theId ],
getCallback("remove page raw", theId, 1,1),
getCallback("remove page raw", theId, 0,1));
});
}
// remove a history page from the database
SearchHistoryDB.removeHistoryPage =
function(theurl)
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('DELETE FROM pages WHERE url=?', [ theurl ],
getCallback("remove page", theurl, 1,2),
getCallback("remove page", theurl, 0,2));
tx.executeSql('DELETE FROM rawpages WHERE url=?', [ theurl ],
getCallback("remove page raw", theurl, 1,2),
getCallback("remove page raw", theurl, 0,2));
});
}
// update an already stored bookmarked page
SearchMarkDB.updateBookmarkedPage =
function(theId, theUrl, theTitle, thePlainPage, theTime,
theHtmlPage)
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('UPDATE pages SET url=?, ' +
'title=?, page=? WHERE id=?',
[ theUrl, theTitle, thePlainPage, theId ],
getCallback("update bookmark", theUrl, 1,1),
getCallback("update bookmark", theUrl, 0,1));
tx.executeSql('UPDATE rawpages SET htmlpage=? WHERE id=?',
[ theHtmlPage, theId ],
getCallback("update bookmark", "raw " + theUrl, 1,1),
getCallback("update bookmark", "raw " + theUrl, 0,1));
});
}
// update an already stored history page, this will cover the original page
SearchHistoryDB.updateHistoryPage =
function(theId, theUrl, theTitle, thePlainPage, theTime,
theHtmlPage)
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('UPDATE pages SET url=?, ' +
'title=?, page=? WHERE id=?',
[ theUrl, theTitle, thePlainPage, theId ],
getCallback("update historypage", theUrl, 1,2),
getCallback("update historypage", theUrl, 0,2));
tx.executeSql('UPDATE rawpages SET htmlpage=? WHERE id=?',
[ theHtmlPage, theId ],
getCallback("update historypage", "raw " + theUrl, 1,2),
getCallback("update historypage", "raw " + theUrl, 0,2));
});
}
// get all bookmark URLs. Callback function can
// be provided use the results as necessary.
SearchMarkDB.getStoredBookmarks =
function()
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('SELECT id,url,title FROM pages',
[],
getCallback("show db", "pages", 1,1),
getCallback("show db", "pages", 0,1));
tx.executeSql('SELECT id FROM rawpages',
[],
getCallback("show db", "raw", 1,1),
getCallback("show db", "raw", 0,1));
});
}
// get all history URLs. Callback function can
// be provided use the results as necessary.
SearchHistoryDB.getStoredHistory =
function()
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('SELECT id,url,title FROM pages',
[],
getCallback("show db", "pages", 1, 2),
getCallback("show db", "pages", 0, 2));
tx.executeSql('SELECT id FROM rawpages',
[],
getCallback("show db", "raw", 1, 2),
getCallback("show db", "raw", 0, 2));
});
}
// Supports the cached page feature. Returns cached raw html page, for SearchMarkDB
SearchMarkDB.getRawHtmlPage =
function (id, callback)
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('SELECT htmlpage FROM rawpages ' +
'WHERE id = ?',
[id],
callback,
getCallback("get page", "raw", 0,1));
});
}
SearchMarkDB.doSearch =
function(callback, keywords)
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('SELECT id,url,title, ' +
'snippet(pages, "' + uiHighlightStart +
'", "' + uiHighlightEnd +
'", "' + uiEllipses +
'", -1, ' + uiContextLen + ') ' +
'as snippet FROM pages WHERE ' +
'pages MATCH ' + keywords + ' ' +
'ORDER BY time DESC',
[],
callback,
getCallback("search pages", "malformed input", 0, 1));
});
}
// Supports the cached page feature. Returns cached raw html page, for SearchHistoryDB
SearchHistoryDB.getRawHtmlPage =
function (id, callback)
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('SELECT htmlpage FROM rawpages ' +
'WHERE id = ?',
[id],
callback,
getCallback("get page", "raw", 0,2));
});
}
SearchHistoryDB.doSearch =
function(callback, keywords)
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('SELECT id,url,title, ' +
'snippet(pages, "' + uiHighlightStart +
'", "' + uiHighlightEnd +
'", "' + uiEllipses +
'", -1, ' + uiContextLen + ') ' +
'as snippet FROM pages WHERE ' +
'pages MATCH ' + keywords + ' ' ,
// 'ORDER BY score DESC',
[],
callback,
getCallback("search pages", "malformed input", 0,2));
});
}
// clear all stored information.
SearchMarkDB.clear =
function()
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('DELETE FROM pages', [],
getCallback("clear table", "pages", 1,1),
getCallback("clear table", "pages", 0,1));
tx.executeSql('DELETE FROM rawpages', [],
getCallback("clear table", "rawpages", 1,1),
getCallback("clear table", "rawpages", 0,1));
});
}
SearchHistoryDB.clear =
function()
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('DELETE FROM pages', [],
getCallback("clear table", "pages", 1,2),
getCallback("clear table", "pages", 0,2));
tx.executeSql('DELETE FROM rawpages', [],
getCallback("clear table", "rawpages", 1,2),
getCallback("clear table", "rawpages", 0,2));
});
}
// remove the table and all stored information
SearchMarkDB.purge =
function()
{
SearchMarkDB.db.transaction(
function(tx)
{
tx.executeSql('DROP TABLE pages', [],
getCallback("delete table", "pages", 1,1),
getCallback("delete table", "pages", 0,1));
tx.executeSql('DROP TABLE rawpages', [],
getCallback("delete table", "rawpages", 1,1),
getCallback("delete table", "rawpages", 0,1));
});
}
SearchHistoryDB.purge =
function()
{
SearchHistoryDB.db.transaction(
function(tx)
{
tx.executeSql('DROP TABLE pages', [],
getCallback("delete table", "pages", 1,2),
getCallback("delete table", "pages", 0,2));
tx.executeSql('DROP TABLE rawpages', [],
getCallback("delete table", "rawpages", 1 ,2),
getCallback("delete table", "rawpages", 0), 2);
});
}
// ========================== CORE ===============
// prepare to initialize
// open the database each time extension loads.
SearchMarkDB.open();
//console.debug("Opened SearchMark database.");
SearchHistoryDB.open();
//console.debug("Opened SearchHistory database.");
localStorage['newversion'] = 2.5; // what is the meaning of this ???
// Important for new installs
if(!localStorage['oldversion'])
{ // not defined
// set to a version before upgrade functionality ever existed
localStorage['oldversion'] = 1.1;
}
if(localStorage['newversion'] > localStorage['oldversion'])
{
// will not be true for new installs
if(localStorage['initialized'])
{ // already installed. Do upgrade.
// console.log("Upgrading to version " +
// localStorage['newversion']);
doUpgrade();
}
localStorage['oldversion'] = localStorage['newversion'];
}
init();
chrome.browserAction.onClicked.addListener(
function(tab)
{
chrome.tabs.create(
{'url' : 'SearchMarkUI.html'},
function(newTab) {});
});
chrome.extension.onRequest.addListener(handleRequest);
chrome.bookmarks.onChanged.addListener(
function(id, changeInfo)
{
if (!localStorage['initialized'])
return;
getAndStoreBookmarkContent(
{id : id,
url : changeInfo.url,
title : changeInfo.title,
time : 0},
SearchMarkDB.updateBookmarkedPage);
});
chrome.bookmarks.onCreated.addListener(
function(id, newBookmark)
{
localStorage['totalbookmarks']++;
if (!localStorage['initialized'])
return;
getAndStoreBookmarkContent(
{id : id,
url : newBookmark.url,
title : newBookmark.title,
time : newBookmark.dateAdded},
SearchMarkDB.addBookmarkedPage);
});
chrome.bookmarks.onRemoved.addListener(
function(id, removeInfo)
{
localStorage['totalbookmarks']--;
if (!localStorage['initialized'])
return;
SearchMarkDB.removeBookmarkedPage(id);
});
// add links to history
chrome.history.onVisited.addListener(
function(newHistoryItem)
{
localStorage['totalhistory']++;
if (!localStorage['initialized'])
return;
getAndStoreHistoryContent(
{id : newHistoryItem.id,
url : newHistoryItem.url,
title : newHistoryItem.title,
time : newHistoryItem.lastVisitTime},
SearchHistoryDB.addHistoryPage);
});
// add listener to history's on remove
chrome.history.onVisitRemoved.addListener(
function(empty, removeurls) //empty is a boolean variable
//removeurls is an array of String
{
localStorage['totalhistory']--;
if (!localStorage['initialized'])
return;
if(empty){
// delete all data in the history database
SearchHistoryDB.purge();
return;
}
for(var i = 0; i< removeurls.length; i++)
SearchHistoryDB.removeHistoryPage(removeurls[i]);
});
// experimental APIs require user to start chrome with a specific option
// flag from the command line. So, not using for now.
// chrome.experimental.omnibox.onInputEntered.addListener(
// function(keywords) {
// handleRequest({method: 'search', keywords: keywords},
// background, function() {});
// }
// );
// ================= CORE API ===================
function init()
{
// console.log("Initializing...");
localStorage['added'] = 0;
var bookmarkdb = "bookmarkdb";
var historydb = "historydb";
// if bookmarks in DB not in sync with actual bookmarks
if(localStorage['added'] && localStorage['totalbookmarks'] &&
localStorage['added'] != localStorage['totalbookmarks'])
cleanupStorage(bookmarkdb);
if(localStorage['historyadded'] && localStorage['totalhistory'] &&
localStorage['historyadded'] != localStorage['totalhistory'])
cleanupStorage(historydb);
// initialize once only. Populate the database
// by retrieving and storing bookmarked pages, and
// URLs.
if (!localStorage['initialized'] ||
localStorage['initialized'] == 0)
{
SearchMarkDB.createTable();
SearchHistoryDB.createTable();
var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
var oneWeekAgo = (new Date).getTime() - microsecondsPerWeek;
chrome.bookmarks.getTree(
function(bookmarks)
{
localStorage['added'] = 0;
localStorage['totalbookmarks'] = 0;
initBookmarkDatabase(bookmarks);
});
//populate the history database
chrome.history.search({
'text':'',
'startTime': oneWeekAgo
},
function(historyItems)
{
//alert("test");
localStorage['historyadded'] = 0;
localStorage['totalhistory'] = 0;
initHistoryDatabase(historyItems);
});
// number of times the welcome page was opened
localStorage['uivisits'] = 0;
localStorage['initialized'] = 1;
} else {
localStorage['initialized']++;
}
}
// any upgrade functionality should be placed here
function doUpgrade()
{
if(localStorage['oldversion'] < 2.4)
cleanupStorage("bothdb");
}
// clean up stored configuration variables
// clean type: clean both database , clean bookmark database, or clean history database
// bothdb,bookmarkdb,historydb
function cleanupStorage(cleantype)
{
// console.log("Cleaning up...");
if(cleantype == "bothdb"){
// console.log("Clearing database tables");
SearchMarkDB.clear();
SearchHistoryDB.clear();
// console.log("Removing the tables");
SearchMarkDB.purge();
SearchHistoryDB.purge();
}
else if(cleantype == "bookmarkdb"){
// console.log("Clearing database tables");
SearchMarkDB.clear();
// console.log("Removing the tables");
SearchHistoryDB.purge();
}
else if(cleantype == "historydb"){
// console.log("Clearing database tables");
SearchHistoryDB.clear();
// console.log("Removing the tables");
SearchHistoryDB.purge();
}
// console.log("Setting to 'not initialized'");
localStorage['initialized'] = 0;
}
function handleRequest(request, sender, callback)
{
if (request.method == 'search') {
startTime=new Date();
tab=request.tab;
speak("Please wait for a moment, we are searching for you.");
keywords = request.keywords;
gPort = chrome.extension.connect( {name : "uiToBackend"});
// console.debug("search " + request.keywords);
if(request.searchtype == 1)
SearchMarkDB.doSearch(searchPagesCb,
"'" + request.keywords + "'");
// this is to do test
if(request.searchtype == 2)
SearchHistoryDB.doSearch(searchPagesCb,
"'" + request.keywords + "'");
callback();
} else if (request.method == 'cached') {
if(request.searchtype == 1)
SearchMarkDB.getRawHtmlPage(request.pageid, displayRawPage);
if(request.searchtype == 2)
SearchHistoryDB.getRawHtmlPage(request.pageid, displayRawPage);
// console.debug("cache request " + request.pageid);
callback();
} else {
callback();
}
}
function displayRawPage(tx, r)
{
if(r.rows.length) {
chrome.tabs.create(
{url: 'rawPageView.html', selected: true},
function (tab)
{
// connect to tab that will show the raw page
var port = chrome.extension.connect({name:
"rawPageView"});
// send the raw page
port.postMessage(r.rows.item(0).htmlpage);
// done.
port.disconnect();
});
} else {
//console.log("Unexpected error: this page should have " +
// "been cached. Please file a bug report " +
// "at <todo:put github url here>");
}
}
/*
function quickSort(copyresult) {
if (copyresult.length <= 1) { return copyresult; }
var pivotIndex = Math.floor(copyresult.length / 2);
var pivot = copyresult.splice(pivotIndex, 1)[0].times;
var left = [];
var right = [];
for (var i = 0; i < copyresult.length; i++){
if (copyresult[i].times < pivot) {
left.push(copyresult[i]);
} else {
right.push(copyresult[i]);
}
}
return quickSort(left).concat(copyresult[pivotIndex], quickSort(right));
};
*/
function searchPagesCb(tx, r)
{
endTime=new Date();
var result = {};
if(r.rows.length==0){
result.matchType = "nopage|"+tab;
gPort.postMessage(result);
}else{
var reg = new RegExp(keywords,"gi");
var copyresult = new Array();
var sortedresult = new Array();
for ( var i = 0; i < r.rows.length; i++) {
sortedresult[i] = new Object();
// sortedresult[i] = new Object();
var c = String(r.rows.item(i).snippet).match(reg);
sortedresult[i].times = c.length;
sortedresult[i].id = r.rows.item(i).id;
sortedresult[i].url = r.rows.item(i).url;
//alert(copyresult[i].url);
sortedresult[i].title = r.rows.item(i).title;
sortedresult[i].text = r.rows.item(i).snippet;
// sortedresult[i].matchType = "page";
}
for (var i = 0; i < sortedresult.length - 1; i++) {
for (var j = 0; j < sortedresult.length - 1 - i; j++) {
if (sortedresult[j].times > sortedresult[j + 1].times) {
var tmp = new Object();
tmp = sortedresult[j];
sortedresult[j] = sortedresult[j + 1];
sortedresult[j + 1] = tmp;
}
}
}
for ( var i = r.rows.length-1 ; i >= 0; i--) {
result.id = sortedresult[i].id;
result.url = sortedresult[i].url;
result.title = sortedresult[i].title;
result.text = sortedresult[i].text;
result.matchType = "page|"+tab;
gPort.postMessage(result);
result = {};
}
/* for ( var i = 0; i < r.rows.length; i++) {
result.id = r.rows.item(i).id;
result.url = r.rows.item(i).url;
result.title = r.rows.item(i).title;
result.text = r.rows.item(i).snippet;
result.matchType = "page";
gPort.postMessage(result);
result = {};
} */
}
result.matchType = "DONE|"+tab;
gPort.postMessage(result);
var time=endTime.getTime()-startTime.getTime();
speak("we spend "+time+" millisecond to get "+r.rows.length+" entries of search results!");
}
function removeHTMLfromPage(page)
{
// reduce spaces, remove new lines
var pagetxt = page.replace(/\s+/gm, " ");
// remove 'script', 'head', 'style' tags
pagetxt = pagetxt.replace(/<\s*?head.*?>.*?<\s*?\/\s*?head\s*?>/i, " ");
pagetxt = pagetxt.replace(/<\s*?script.*?>.*?<\s*?\/\s*?script\s*?>/gi, " ");
pagetxt = pagetxt.replace(/<\s*?style.*?>.*?<\s*?\/\s*?style\s*?>/gi, " ");
// Now remove other tags
pagetxt = pagetxt.replace(/<.*?\/?>/g, " ");
// Remove symbols
pagetxt = pagetxt.replace(/&.*?;/g, " ");
// Remove comment markers
pagetxt = pagetxt.replace(/(<!--|-->)/g, " ");
// Remove stop words
//pagetxt = pagetxt.replace(/(am|are|is|be|was|were|of|the|he|she|they|them|I|in|on|to|at|and|or|for)/g, " ");
// After all the filtering, need to fix up spaces again
pagetxt = pagetxt.replace(/\s+/gm, " ");
return pagetxt;
}
function getAndStoreBookmarkContent(bookmark, storeInDB)
{
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", bookmark.url, true);
xhr.onreadystatechange = function()
{
try {
if (this.readyState == 4) {
var pageNoHtml = removeHTMLfromPage(this.responseText);
// add page to database
storeInDB(bookmark.id, bookmark.url,
bookmark.title, pageNoHtml,
bookmark.dateAdded, this.responseText);
this.abort();
}
} catch (e) {
// console.log(e.message);
storeInDB(bookmark.id, bookmark.url, bookmark.title,
"", "");
}
}
xhr.send();
} catch (e) {
// console.log(e.message + bookmark.url);
storeInDB(bookmark.id, bookmark.url, bookmark.title, "", "");
}
}
// get and store history page content
function getAndStoreHistoryContent(historyItem, storeInDB)
{
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", historyItem.url, true);
xhr.onreadystatechange = function()
{
try {
if (this.readyState == 4) {
var pageNoHtml = removeHTMLfromPage(this.responseText);
// add page to database
storeInDB(historyItem.id, historyItem.url,
historyItem.title, pageNoHtml,
historyItem.lastVisitTime, this.responseText);
this.abort();
}
} catch (e) {
// console.log(e.message);
storeInDB(historyItem.id, historyItem.url, historyItem.title,
"", "");
}
}
xhr.send();
} catch (e) {
// console.log(e.message + historyItem.url);
storeInDB(historyItem.id, historyItem.url, historyItem.title, "", "");
}
}
function initBookmarkDatabase(bookmarks)
{
bookmarks.forEach(
function(bookmark)
{
if (bookmark.url &&
bookmark.url.match("^https?://*"))
{ // url exists and is well formed
// console.debug("Adding " + bookmark.url);
localStorage['totalbookmarks']++;
getAndStoreBookmarkContent(bookmark,
SearchMarkDB.addBookmarkedPage);
} else {
// console.debug("Skipping. " + bookmark.url);
}
if (bookmark.children)
initBookmarkDatabase(bookmark.children);
});
}
//initialize history database
function initHistoryDatabase(historyItems)
{
for(var i = 0; i < historyItems.length; i++){
if (historyItems[i].url && historyItems[i].url.match("^https?://*"))
{ // url exists and is well formed
// console.debug("Adding " + historyItems[i].url);
localStorage['totalhistorymarks']++;
getAndStoreHistoryContent(historyItems[i],
SearchHistoryDB.addHistoryPage);
} else {
// console.debug("Skipping. " + historyItems[i].url);
}
};
// alert(historyItems[0].url);
}
function getCallback(cbname, msg, type, dbtype)
{
switch (cbname) {
case "show db":
if (type == 1)
return function(tx, r)
{
for ( var i = 0; i < r.rows.length; i++) {
// console.log("Stored. " + msg + " " +
// r.rows.item(i).url);
}
}
else
return function(tx, r)
{
// console.debug("failed: " + cbname + " " + msg);
// console.log(" " + e.message);
}
break;
case "search pages":
if (type == 1) // success callback
return function(tx, r)
{
// console.debug("succeeded: " + cbname + " " + msg);
}
else
return function(tx, e)
{
// console.debug("failed: " + cbname + " " + msg);
// console.log(" " + e.message);
// search pages failed, tell user
var result = {};
result.matchType = "DONE";
result.error = 'Sorry, I am not sure what you are ' +
'looking for. Could you be missing a quote (") ' +
'while searching for a phrase?';
gPort.postMessage(result);
}
break;
case "insert page raw":
if (type == 1) // success callback
return function(tx, r)
{
// console.debug("succeded: " + cbname + " " + msg);
if(dbtype==1)localStorage['added']++;
if(dbtype==2)localStorage['historyadded']++;
}
else
// failure callback
return function(tx, e)
{
// console.debug("failed: " + cbname + " " + msg);
// console.log(" " + e.message);
}
break;
case "remove page raw":
if (type == 1) // success callback
return function(tx, r)
{
// console.debug("succeeded: " + cbname + " " + msg);
if(dbtype==1)localStorage['added']--;
if(dbtype==2)localStorage['historyadded']--;
}
else
// failure callback
return function(tx, e)
{
// console.debug("failed: " + cbname + " " + msg);
// console.log(" " + e.message);
}
break;
default:
if (type == 1) // success callback
return function(tx, r)
{
// console.debug("succeeded: " + cbname + " " + msg);
}
else
// failure callback
return function(tx, e)
{
// console.debug("failed: " + cbname + " " + msg);
// console.log(" " + e.message);
}
}
}
//======================== SPEAK SECTION ==================
var lastUtterance = '';
var speaking = false;
var globalUtteranceIndex = 0;
if (localStorage['lastVersionUsed'] != '1') {
localStorage['lastVersionUsed'] = '1';
chrome.tabs.create({
url: chrome.extension.getURL('options.html')
});
}
function speak(utterance) {
if (speaking && utterance == lastUtterance) {
chrome.tts.stop();
return;
}
speaking = true;
lastUtterance = utterance;
globalUtteranceIndex++;
var utteranceIndex = globalUtteranceIndex;
var rate = localStorage['rate'] || 1.0;
var pitch = localStorage['pitch'] || 1.0;
var volume = localStorage['volume'] || 1.0;
var voice = localStorage['voice'];
chrome.tts.speak(
utterance,
{voiceName: voice,
rate: parseFloat(rate),
pitch: parseFloat(pitch),
volume: parseFloat(volume),
onEvent: function(evt) {
if (evt.type == 'end' ||
evt.type == 'interrupted' ||
evt.type == 'cancelled' ||
evt.type == 'error') {
if (utteranceIndex == globalUtteranceIndex) {
speaking = false;
}
}
}
});
}
| JavaScript |
/*
* angular-ui-bootstrap
* http://angular-ui.github.io/bootstrap/
* Version: 0.12.0 - 2014-11-16
* License: MIT
*/
angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]);
angular.module("ui.bootstrap.tpls", ["template/accordion/accordion-group.html","template/accordion/accordion.html","template/alert/alert.html","template/carousel/carousel.html","template/carousel/slide.html","template/datepicker/datepicker.html","template/datepicker/day.html","template/datepicker/month.html","template/datepicker/popup.html","template/datepicker/year.html","template/modal/backdrop.html","template/modal/window.html","template/pagination/pager.html","template/pagination/pagination.html","template/tooltip/tooltip-html-unsafe-popup.html","template/tooltip/tooltip-popup.html","template/popover/popover.html","template/progressbar/bar.html","template/progressbar/progress.html","template/progressbar/progressbar.html","template/rating/rating.html","template/tabs/tab.html","template/tabs/tabset.html","template/timepicker/timepicker.html","template/typeahead/typeahead-match.html","template/typeahead/typeahead-popup.html"]);
angular.module('ui.bootstrap.transition', [])
/**
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
* @param {DOMElement} element The DOMElement that will be animated.
* @param {string|object|function} trigger The thing that will cause the transition to start:
* - As a string, it represents the css class to be added to the element.
* - As an object, it represents a hash of style attributes to be applied to the element.
* - As a function, it represents a function to be called that will cause the transition to occur.
* @return {Promise} A promise that is resolved when the transition finishes.
*/
.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) {
var $transition = function(element, trigger, options) {
options = options || {};
var deferred = $q.defer();
var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];
var transitionEndHandler = function(event) {
$rootScope.$apply(function() {
element.unbind(endEventName, transitionEndHandler);
deferred.resolve(element);
});
};
if (endEventName) {
element.bind(endEventName, transitionEndHandler);
}
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
$timeout(function() {
if ( angular.isString(trigger) ) {
element.addClass(trigger);
} else if ( angular.isFunction(trigger) ) {
trigger(element);
} else if ( angular.isObject(trigger) ) {
element.css(trigger);
}
//If browser does not support transitions, instantly resolve
if ( !endEventName ) {
deferred.resolve(element);
}
});
// Add our custom cancel function to the promise that is returned
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
// i.e. it will therefore never raise a transitionEnd event for that transition
deferred.promise.cancel = function() {
if ( endEventName ) {
element.unbind(endEventName, transitionEndHandler);
}
deferred.reject('Transition cancelled');
};
return deferred.promise;
};
// Work out the name of the transitionEnd event
var transElement = document.createElement('trans');
var transitionEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'transition': 'transitionend'
};
var animationEndEventNames = {
'WebkitTransition': 'webkitAnimationEnd',
'MozTransition': 'animationend',
'OTransition': 'oAnimationEnd',
'transition': 'animationend'
};
function findEndEventName(endEventNames) {
for (var name in endEventNames){
if (transElement.style[name] !== undefined) {
return endEventNames[name];
}
}
}
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
$transition.animationEndEventName = findEndEventName(animationEndEventNames);
return $transition;
}]);
angular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition'])
.directive('collapse', ['$transition', function ($transition) {
return {
link: function (scope, element, attrs) {
var initialAnimSkip = true;
var currentTransition;
function doTransition(change) {
var newTransition = $transition(element, change);
if (currentTransition) {
currentTransition.cancel();
}
currentTransition = newTransition;
newTransition.then(newTransitionDone, newTransitionDone);
return newTransition;
function newTransitionDone() {
// Make sure it's this transition, otherwise, leave it alone.
if (currentTransition === newTransition) {
currentTransition = undefined;
}
}
}
function expand() {
if (initialAnimSkip) {
initialAnimSkip = false;
expandDone();
} else {
element.removeClass('collapse').addClass('collapsing');
doTransition({ height: element[0].scrollHeight + 'px' }).then(expandDone);
}
}
function expandDone() {
element.removeClass('collapsing');
element.addClass('collapse in');
element.css({height: 'auto'});
}
function collapse() {
if (initialAnimSkip) {
initialAnimSkip = false;
collapseDone();
element.css({height: 0});
} else {
// CSS transitions don't work with height: auto, so we have to manually change the height to a specific value
element.css({ height: element[0].scrollHeight + 'px' });
//trigger reflow so a browser realizes that height was updated from auto to a specific value
var x = element[0].offsetWidth;
element.removeClass('collapse in').addClass('collapsing');
doTransition({ height: 0 }).then(collapseDone);
}
}
function collapseDone() {
element.removeClass('collapsing');
element.addClass('collapse');
}
scope.$watch(attrs.collapse, function (shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
.constant('accordionConfig', {
closeOthers: true
})
.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {
// This array keeps track of the accordion groups
this.groups = [];
// Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
this.closeOthers = function(openGroup) {
var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
if ( closeOthers ) {
angular.forEach(this.groups, function (group) {
if ( group !== openGroup ) {
group.isOpen = false;
}
});
}
};
// This is called from the accordion-group directive to add itself to the accordion
this.addGroup = function(groupScope) {
var that = this;
this.groups.push(groupScope);
groupScope.$on('$destroy', function (event) {
that.removeGroup(groupScope);
});
};
// This is called from the accordion-group directive when to remove itself
this.removeGroup = function(group) {
var index = this.groups.indexOf(group);
if ( index !== -1 ) {
this.groups.splice(index, 1);
}
};
}])
// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('accordion', function () {
return {
restrict:'EA',
controller:'AccordionController',
transclude: true,
replace: false,
templateUrl: 'template/accordion/accordion.html'
};
})
// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('accordionGroup', function() {
return {
require:'^accordion', // We need this directive to be inside an accordion
restrict:'EA',
transclude:true, // It transcludes the contents of the directive into the template
replace: true, // The element containing the directive will be replaced with the template
templateUrl:'template/accordion/accordion-group.html',
scope: {
heading: '@', // Interpolate the heading attribute onto this scope
isOpen: '=?',
isDisabled: '=?'
},
controller: function() {
this.setHeading = function(element) {
this.heading = element;
};
},
link: function(scope, element, attrs, accordionCtrl) {
accordionCtrl.addGroup(scope);
scope.$watch('isOpen', function(value) {
if ( value ) {
accordionCtrl.closeOthers(scope);
}
});
scope.toggleOpen = function() {
if ( !scope.isDisabled ) {
scope.isOpen = !scope.isOpen;
}
};
}
};
})
// Use accordion-heading below an accordion-group to provide a heading containing HTML
// <accordion-group>
// <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading>
// </accordion-group>
.directive('accordionHeading', function() {
return {
restrict: 'EA',
transclude: true, // Grab the contents to be used as the heading
template: '', // In effect remove this element!
replace: true,
require: '^accordionGroup',
link: function(scope, element, attr, accordionGroupCtrl, transclude) {
// Pass the heading to the accordion-group controller
// so that it can be transcluded into the right place in the template
// [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
accordionGroupCtrl.setHeading(transclude(scope, function() {}));
}
};
})
// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
// <div class="accordion-group">
// <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div>
// ...
// </div>
.directive('accordionTransclude', function() {
return {
require: '^accordionGroup',
link: function(scope, element, attr, controller) {
scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {
if ( heading ) {
element.html('');
element.append(heading);
}
});
}
};
});
angular.module('ui.bootstrap.alert', [])
.controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {
$scope.closeable = 'close' in $attrs;
this.close = $scope.close;
}])
.directive('alert', function () {
return {
restrict:'EA',
controller:'AlertController',
templateUrl:'template/alert/alert.html',
transclude:true,
replace:true,
scope: {
type: '@',
close: '&'
}
};
})
.directive('dismissOnTimeout', ['$timeout', function($timeout) {
return {
require: 'alert',
link: function(scope, element, attrs, alertCtrl) {
$timeout(function(){
alertCtrl.close();
}, parseInt(attrs.dismissOnTimeout, 10));
}
};
}]);
angular.module('ui.bootstrap.bindHtml', [])
.directive('bindHtmlUnsafe', function () {
return function (scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
});
angular.module('ui.bootstrap.buttons', [])
.constant('buttonConfig', {
activeClass: 'active',
toggleEvent: 'click'
})
.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {
this.activeClass = buttonConfig.activeClass || 'active';
this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])
.directive('btnRadio', function () {
return {
require: ['btnRadio', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
var isActive = element.hasClass(buttonsCtrl.activeClass);
if (!isActive || angular.isDefined(attrs.uncheckable)) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));
ngModelCtrl.$render();
});
}
});
}
};
})
.directive('btnCheckbox', function () {
return {
require: ['btnCheckbox', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
function getTrueValue() {
return getCheckboxValue(attrs.btnCheckboxTrue, true);
}
function getFalseValue() {
return getCheckboxValue(attrs.btnCheckboxFalse, false);
}
function getCheckboxValue(attributeValue, defaultValue) {
var val = scope.$eval(attributeValue);
return angular.isDefined(val) ? val : defaultValue;
}
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
ngModelCtrl.$render();
});
});
}
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.carousel
*
* @description
* AngularJS version of an image carousel.
*
*/
angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
.controller('CarouselController', ['$scope', '$timeout', '$interval', '$transition', function ($scope, $timeout, $interval, $transition) {
var self = this,
slides = self.slides = $scope.slides = [],
currentIndex = -1,
currentInterval, isPlaying;
self.currentSlide = null;
var destroyed = false;
/* direction: "prev" or "next" */
self.select = $scope.select = function(nextSlide, direction) {
var nextIndex = slides.indexOf(nextSlide);
//Decide direction if it's not given
if (direction === undefined) {
direction = nextIndex > currentIndex ? 'next' : 'prev';
}
if (nextSlide && nextSlide !== self.currentSlide) {
if ($scope.$currentTransition) {
$scope.$currentTransition.cancel();
//Timeout so ng-class in template has time to fix classes for finished slide
$timeout(goNext);
} else {
goNext();
}
}
function goNext() {
// Scope has been destroyed, stop here.
if (destroyed) { return; }
//If we have a slide to transition from and we have a transition type and we're allowed, go
if (self.currentSlide && angular.isString(direction) && !$scope.noTransition && nextSlide.$element) {
//We shouldn't do class manip in here, but it's the same weird thing bootstrap does. need to fix sometime
nextSlide.$element.addClass(direction);
var reflow = nextSlide.$element[0].offsetWidth; //force reflow
//Set all other slides to stop doing their stuff for the new transition
angular.forEach(slides, function(slide) {
angular.extend(slide, {direction: '', entering: false, leaving: false, active: false});
});
angular.extend(nextSlide, {direction: direction, active: true, entering: true});
angular.extend(self.currentSlide||{}, {direction: direction, leaving: true});
$scope.$currentTransition = $transition(nextSlide.$element, {});
//We have to create new pointers inside a closure since next & current will change
(function(next,current) {
$scope.$currentTransition.then(
function(){ transitionDone(next, current); },
function(){ transitionDone(next, current); }
);
}(nextSlide, self.currentSlide));
} else {
transitionDone(nextSlide, self.currentSlide);
}
self.currentSlide = nextSlide;
currentIndex = nextIndex;
//every time you change slides, reset the timer
restartTimer();
}
function transitionDone(next, current) {
angular.extend(next, {direction: '', active: true, leaving: false, entering: false});
angular.extend(current||{}, {direction: '', active: false, leaving: false, entering: false});
$scope.$currentTransition = null;
}
};
$scope.$on('$destroy', function () {
destroyed = true;
});
/* Allow outside people to call indexOf on slides array */
self.indexOfSlide = function(slide) {
return slides.indexOf(slide);
};
$scope.next = function() {
var newIndex = (currentIndex + 1) % slides.length;
//Prevent this user-triggered transition from occurring if there is already one in progress
if (!$scope.$currentTransition) {
return self.select(slides[newIndex], 'next');
}
};
$scope.prev = function() {
var newIndex = currentIndex - 1 < 0 ? slides.length - 1 : currentIndex - 1;
//Prevent this user-triggered transition from occurring if there is already one in progress
if (!$scope.$currentTransition) {
return self.select(slides[newIndex], 'prev');
}
};
$scope.isActive = function(slide) {
return self.currentSlide === slide;
};
$scope.$watch('interval', restartTimer);
$scope.$on('$destroy', resetTimer);
function restartTimer() {
resetTimer();
var interval = +$scope.interval;
if (!isNaN(interval) && interval > 0) {
currentInterval = $interval(timerFn, interval);
}
}
function resetTimer() {
if (currentInterval) {
$interval.cancel(currentInterval);
currentInterval = null;
}
}
function timerFn() {
var interval = +$scope.interval;
if (isPlaying && !isNaN(interval) && interval > 0) {
$scope.next();
} else {
$scope.pause();
}
}
$scope.play = function() {
if (!isPlaying) {
isPlaying = true;
restartTimer();
}
};
$scope.pause = function() {
if (!$scope.noPause) {
isPlaying = false;
resetTimer();
}
};
self.addSlide = function(slide, element) {
slide.$element = element;
slides.push(slide);
//if this is the first slide or the slide is set to active, select it
if(slides.length === 1 || slide.active) {
self.select(slides[slides.length-1]);
if (slides.length == 1) {
$scope.play();
}
} else {
slide.active = false;
}
};
self.removeSlide = function(slide) {
//get the index of the slide inside the carousel
var index = slides.indexOf(slide);
slides.splice(index, 1);
if (slides.length > 0 && slide.active) {
if (index >= slides.length) {
self.select(slides[index-1]);
} else {
self.select(slides[index]);
}
} else if (currentIndex > index) {
currentIndex--;
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:carousel
* @restrict EA
*
* @description
* Carousel is the outer container for a set of image 'slides' to showcase.
*
* @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
* @param {boolean=} noTransition Whether to disable transitions on the carousel.
* @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<carousel>
<slide>
<img src="http://placekitten.com/150/150" style="margin:auto;">
<div class="carousel-caption">
<p>Beautiful!</p>
</div>
</slide>
<slide>
<img src="http://placekitten.com/100/150" style="margin:auto;">
<div class="carousel-caption">
<p>D'aww!</p>
</div>
</slide>
</carousel>
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('carousel', [function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
controller: 'CarouselController',
require: 'carousel',
templateUrl: 'template/carousel/carousel.html',
scope: {
interval: '=',
noTransition: '=',
noPause: '='
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:slide
* @restrict EA
*
* @description
* Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.
*
* @param {boolean=} active Model binding, whether or not this slide is currently active.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="CarouselDemoCtrl">
<carousel>
<slide ng-repeat="slide in slides" active="slide.active">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
Interval, in milliseconds: <input type="number" ng-model="myInterval">
<br />Enter a negative number to stop the interval.
</div>
</file>
<file name="script.js">
function CarouselDemoCtrl($scope) {
$scope.myInterval = 5000;
}
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('slide', function() {
return {
require: '^carousel',
restrict: 'EA',
transclude: true,
replace: true,
templateUrl: 'template/carousel/slide.html',
scope: {
active: '=?'
},
link: function (scope, element, attrs, carouselCtrl) {
carouselCtrl.addSlide(scope, element);
//when the scope is destroyed then remove the slide from the current slides array
scope.$on('$destroy', function() {
carouselCtrl.removeSlide(scope);
});
scope.$watch('active', function(active) {
if (active) {
carouselCtrl.select(scope);
}
});
}
};
});
angular.module('ui.bootstrap.dateparser', [])
.service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) {
this.parsers = {};
var formatCodeToRegex = {
'yyyy': {
regex: '\\d{4}',
apply: function(value) { this.year = +value; }
},
'yy': {
regex: '\\d{2}',
apply: function(value) { this.year = +value + 2000; }
},
'y': {
regex: '\\d{1,4}',
apply: function(value) { this.year = +value; }
},
'MMMM': {
regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }
},
'MMM': {
regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }
},
'MM': {
regex: '0[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; }
},
'M': {
regex: '[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; }
},
'dd': {
regex: '[0-2][0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; }
},
'd': {
regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; }
},
'EEEE': {
regex: $locale.DATETIME_FORMATS.DAY.join('|')
},
'EEE': {
regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')
}
};
function createParser(format) {
var map = [], regex = format.split('');
angular.forEach(formatCodeToRegex, function(data, code) {
var index = format.indexOf(code);
if (index > -1) {
format = format.split('');
regex[index] = '(' + data.regex + ')';
format[index] = '$'; // Custom symbol to define consumed part of format
for (var i = index + 1, n = index + code.length; i < n; i++) {
regex[i] = '';
format[i] = '$';
}
format = format.join('');
map.push({ index: index, apply: data.apply });
}
});
return {
regex: new RegExp('^' + regex.join('') + '$'),
map: orderByFilter(map, 'index')
};
}
this.parse = function(input, format) {
if ( !angular.isString(input) || !format ) {
return input;
}
format = $locale.DATETIME_FORMATS[format] || format;
if ( !this.parsers[format] ) {
this.parsers[format] = createParser(format);
}
var parser = this.parsers[format],
regex = parser.regex,
map = parser.map,
results = input.match(regex);
if ( results && results.length ) {
var fields = { year: 1900, month: 0, date: 1, hours: 0 }, dt;
for( var i = 1, n = results.length; i < n; i++ ) {
var mapper = map[i-1];
if ( mapper.apply ) {
mapper.apply.call(fields, results[i]);
}
}
if ( isValid(fields.year, fields.month, fields.date) ) {
dt = new Date( fields.year, fields.month, fields.date, fields.hours);
}
return dt;
}
};
// Check if date is valid for specific month (and year for February).
// Month: 0 = Jan, 1 = Feb, etc
function isValid(year, month, date) {
if ( month === 1 && date > 28) {
return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
}
if ( month === 3 || month === 5 || month === 8 || month === 10) {
return date < 31;
}
return true;
}
}]);
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in
* relation to other, existing elements (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$position', ['$document', '$window', function ($document, $window) {
function getStyle(el, cssprop) {
if (el.currentStyle) { //IE
return el.currentStyle[cssprop];
} else if ($window.getComputedStyle) {
return $window.getComputedStyle(el)[cssprop];
}
// finally try and get inline style
return el.style[cssprop];
}
/**
* Checks if a given element is statically positioned
* @param element - raw DOM element
*/
function isStaticPositioned(element) {
return (getStyle(element, 'position') || 'static' ) === 'static';
}
/**
* returns the closest, non-statically positioned parentOffset of a given element
* @param element
*/
var parentOffsetEl = function (element) {
var docDomEl = $document[0];
var offsetParent = element.offsetParent || docDomEl;
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docDomEl;
};
return {
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/
*/
position: function (element) {
var elBCR = this.offset(element);
var offsetParentBCR = { top: 0, left: 0 };
var offsetParentEl = parentOffsetEl(element[0]);
if (offsetParentEl != $document[0]) {
offsetParentBCR = this.offset(angular.element(offsetParentEl));
offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
}
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: elBCR.top - offsetParentBCR.top,
left: elBCR.left - offsetParentBCR.left
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/
*/
offset: function (element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
};
},
/**
* Provides coordinates for the targetEl in relation to hostEl
*/
positionElements: function (hostEl, targetEl, positionStr, appendToBody) {
var positionStrParts = positionStr.split('-');
var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';
var hostElPos,
targetElWidth,
targetElHeight,
targetElPos;
hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);
targetElWidth = targetEl.prop('offsetWidth');
targetElHeight = targetEl.prop('offsetHeight');
var shiftWidth = {
center: function () {
return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
},
left: function () {
return hostElPos.left;
},
right: function () {
return hostElPos.left + hostElPos.width;
}
};
var shiftHeight = {
center: function () {
return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
},
top: function () {
return hostElPos.top;
},
bottom: function () {
return hostElPos.top + hostElPos.height;
}
};
switch (pos0) {
case 'right':
targetElPos = {
top: shiftHeight[pos1](),
left: shiftWidth[pos0]()
};
break;
case 'left':
targetElPos = {
top: shiftHeight[pos1](),
left: hostElPos.left - targetElWidth
};
break;
case 'bottom':
targetElPos = {
top: shiftHeight[pos0](),
left: shiftWidth[pos1]()
};
break;
default:
targetElPos = {
top: hostElPos.top - targetElHeight,
left: shiftWidth[pos1]()
};
break;
}
return targetElPos;
}
};
}]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])
.constant('datepickerConfig', {
formatDay: 'dd',
formatMonth: 'MMMM',
formatYear: 'yyyy',
formatDayHeader: 'EEE',
formatDayTitle: 'MMMM yyyy',
formatMonthTitle: 'yyyy',
datepickerMode: 'day',
minMode: 'day',
maxMode: 'year',
showWeeks: true,
startingDay: 0,
yearRange: 20,
minDate: null,
maxDate: null
})
.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$timeout', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $timeout, $log, dateFilter, datepickerConfig) {
var self = this,
ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;
// Modes chain
this.modes = ['day', 'month', 'year'];
// Configuration attributes
angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange'], function( key, index ) {
self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
});
// Watchable date attributes
angular.forEach(['minDate', 'maxDate'], function( key ) {
if ( $attrs[key] ) {
$scope.$parent.$watch($parse($attrs[key]), function(value) {
self[key] = value ? new Date(value) : null;
self.refreshView();
});
} else {
self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
}
});
$scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
$scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
this.activeDate = angular.isDefined($attrs.initDate) ? $scope.$parent.$eval($attrs.initDate) : new Date();
$scope.isActive = function(dateObject) {
if (self.compare(dateObject.date, self.activeDate) === 0) {
$scope.activeDateId = dateObject.uid;
return true;
}
return false;
};
this.init = function( ngModelCtrl_ ) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = function() {
self.render();
};
};
this.render = function() {
if ( ngModelCtrl.$modelValue ) {
var date = new Date( ngModelCtrl.$modelValue ),
isValid = !isNaN(date);
if ( isValid ) {
this.activeDate = date;
} else {
$log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
}
ngModelCtrl.$setValidity('date', isValid);
}
this.refreshView();
};
this.refreshView = function() {
if ( this.element ) {
this._refreshView();
var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));
}
};
this.createDateObject = function(date, format) {
var model = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
return {
date: date,
label: dateFilter(date, format),
selected: model && this.compare(date, model) === 0,
disabled: this.isDisabled(date),
current: this.compare(date, new Date()) === 0
};
};
this.isDisabled = function( date ) {
return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
};
// Split array into smaller arrays
this.split = function(arr, size) {
var arrays = [];
while (arr.length > 0) {
arrays.push(arr.splice(0, size));
}
return arrays;
};
$scope.select = function( date ) {
if ( $scope.datepickerMode === self.minMode ) {
var dt = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );
ngModelCtrl.$setViewValue( dt );
ngModelCtrl.$render();
} else {
self.activeDate = date;
$scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ];
}
};
$scope.move = function( direction ) {
var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
month = self.activeDate.getMonth() + direction * (self.step.months || 0);
self.activeDate.setFullYear(year, month, 1);
self.refreshView();
};
$scope.toggleMode = function( direction ) {
direction = direction || 1;
if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
return;
}
$scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ];
};
// Key event mapper
$scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' };
var focusElement = function() {
$timeout(function() {
self.element[0].focus();
}, 0 , false);
};
// Listen for focus requests from popup directive
$scope.$on('datepicker.focus', focusElement);
$scope.keydown = function( evt ) {
var key = $scope.keys[evt.which];
if ( !key || evt.shiftKey || evt.altKey ) {
return;
}
evt.preventDefault();
evt.stopPropagation();
if (key === 'enter' || key === 'space') {
if ( self.isDisabled(self.activeDate)) {
return; // do nothing
}
$scope.select(self.activeDate);
focusElement();
} else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
$scope.toggleMode(key === 'up' ? 1 : -1);
focusElement();
} else {
self.handleKeyDown(key, evt);
self.refreshView();
}
};
}])
.directive( 'datepicker', function () {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/datepicker.html',
scope: {
datepickerMode: '=?',
dateDisabled: '&'
},
require: ['datepicker', '?^ngModel'],
controller: 'DatepickerController',
link: function(scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if ( ngModelCtrl ) {
datepickerCtrl.init( ngModelCtrl );
}
}
};
})
.directive('daypicker', ['dateFilter', function (dateFilter) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/day.html',
require: '^datepicker',
link: function(scope, element, attrs, ctrl) {
scope.showWeeks = ctrl.showWeeks;
ctrl.step = { months: 1 };
ctrl.element = element;
var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function getDaysInMonth( year, month ) {
return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
}
function getDates(startDate, n) {
var dates = new Array(n), current = new Date(startDate), i = 0;
current.setHours(12); // Prevent repeated dates because of timezone bug
while ( i < n ) {
dates[i++] = new Date(current);
current.setDate( current.getDate() + 1 );
}
return dates;
}
ctrl._refreshView = function() {
var year = ctrl.activeDate.getFullYear(),
month = ctrl.activeDate.getMonth(),
firstDayOfMonth = new Date(year, month, 1),
difference = ctrl.startingDay - firstDayOfMonth.getDay(),
numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
firstDate = new Date(firstDayOfMonth);
if ( numDisplayedFromPreviousMonth > 0 ) {
firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );
}
// 42 is the number of days on a six-month calendar
var days = getDates(firstDate, 42);
for (var i = 0; i < 42; i ++) {
days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {
secondary: days[i].getMonth() !== month,
uid: scope.uniqueId + '-' + i
});
}
scope.labels = new Array(7);
for (var j = 0; j < 7; j++) {
scope.labels[j] = {
abbr: dateFilter(days[j].date, ctrl.formatDayHeader),
full: dateFilter(days[j].date, 'EEEE')
};
}
scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);
scope.rows = ctrl.split(days, 7);
if ( scope.showWeeks ) {
scope.weekNumbers = [];
var weekNumber = getISO8601WeekNumber( scope.rows[0][0].date ),
numWeeks = scope.rows.length;
while( scope.weekNumbers.push(weekNumber++) < numWeeks ) {}
}
};
ctrl.compare = function(date1, date2) {
return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );
};
function getISO8601WeekNumber(date) {
var checkDate = new Date(date);
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
ctrl.handleKeyDown = function( key, evt ) {
var date = ctrl.activeDate.getDate();
if (key === 'left') {
date = date - 1; // up
} else if (key === 'up') {
date = date - 7; // down
} else if (key === 'right') {
date = date + 1; // down
} else if (key === 'down') {
date = date + 7;
} else if (key === 'pageup' || key === 'pagedown') {
var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
ctrl.activeDate.setMonth(month, 1);
date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);
} else if (key === 'home') {
date = 1;
} else if (key === 'end') {
date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());
}
ctrl.activeDate.setDate(date);
};
ctrl.refreshView();
}
};
}])
.directive('monthpicker', ['dateFilter', function (dateFilter) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/month.html',
require: '^datepicker',
link: function(scope, element, attrs, ctrl) {
ctrl.step = { years: 1 };
ctrl.element = element;
ctrl._refreshView = function() {
var months = new Array(12),
year = ctrl.activeDate.getFullYear();
for ( var i = 0; i < 12; i++ ) {
months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), {
uid: scope.uniqueId + '-' + i
});
}
scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);
scope.rows = ctrl.split(months, 3);
};
ctrl.compare = function(date1, date2) {
return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );
};
ctrl.handleKeyDown = function( key, evt ) {
var date = ctrl.activeDate.getMonth();
if (key === 'left') {
date = date - 1; // up
} else if (key === 'up') {
date = date - 3; // down
} else if (key === 'right') {
date = date + 1; // down
} else if (key === 'down') {
date = date + 3;
} else if (key === 'pageup' || key === 'pagedown') {
var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
ctrl.activeDate.setFullYear(year);
} else if (key === 'home') {
date = 0;
} else if (key === 'end') {
date = 11;
}
ctrl.activeDate.setMonth(date);
};
ctrl.refreshView();
}
};
}])
.directive('yearpicker', ['dateFilter', function (dateFilter) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/year.html',
require: '^datepicker',
link: function(scope, element, attrs, ctrl) {
var range = ctrl.yearRange;
ctrl.step = { years: range };
ctrl.element = element;
function getStartingYear( year ) {
return parseInt((year - 1) / range, 10) * range + 1;
}
ctrl._refreshView = function() {
var years = new Array(range);
for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) {
years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), {
uid: scope.uniqueId + '-' + i
});
}
scope.title = [years[0].label, years[range - 1].label].join(' - ');
scope.rows = ctrl.split(years, 5);
};
ctrl.compare = function(date1, date2) {
return date1.getFullYear() - date2.getFullYear();
};
ctrl.handleKeyDown = function( key, evt ) {
var date = ctrl.activeDate.getFullYear();
if (key === 'left') {
date = date - 1; // up
} else if (key === 'up') {
date = date - 5; // down
} else if (key === 'right') {
date = date + 1; // down
} else if (key === 'down') {
date = date + 5;
} else if (key === 'pageup' || key === 'pagedown') {
date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;
} else if (key === 'home') {
date = getStartingYear( ctrl.activeDate.getFullYear() );
} else if (key === 'end') {
date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1;
}
ctrl.activeDate.setFullYear(date);
};
ctrl.refreshView();
}
};
}])
.constant('datepickerPopupConfig', {
datepickerPopup: 'yyyy-MM-dd',
currentText: 'Today',
clearText: 'Clear',
closeText: 'Done',
closeOnDateSelection: true,
appendToBody: false,
showButtonBar: true
})
.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',
function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
isOpen: '=?',
currentText: '@',
clearText: '@',
closeText: '@',
dateDisabled: '&'
},
link: function(scope, element, attrs, ngModel) {
var dateFormat,
closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;
scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;
scope.getText = function( key ) {
return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
};
attrs.$observe('datepickerPopup', function(value) {
dateFormat = value || datepickerPopupConfig.datepickerPopup;
ngModel.$render();
});
// popup element used to display calendar
var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>');
popupEl.attr({
'ng-model': 'date',
'ng-change': 'dateSelection()'
});
function cameltoDash( string ){
return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
}
// datepicker element
var datepickerEl = angular.element(popupEl.children()[0]);
if ( attrs.datepickerOptions ) {
angular.forEach(scope.$parent.$eval(attrs.datepickerOptions), function( value, option ) {
datepickerEl.attr( cameltoDash(option), value );
});
}
scope.watchData = {};
angular.forEach(['minDate', 'maxDate', 'datepickerMode'], function( key ) {
if ( attrs[key] ) {
var getAttribute = $parse(attrs[key]);
scope.$parent.$watch(getAttribute, function(value){
scope.watchData[key] = value;
});
datepickerEl.attr(cameltoDash(key), 'watchData.' + key);
// Propagate changes from datepicker to outside
if ( key === 'datepickerMode' ) {
var setAttribute = getAttribute.assign;
scope.$watch('watchData.' + key, function(value, oldvalue) {
if ( value !== oldvalue ) {
setAttribute(scope.$parent, value);
}
});
}
}
});
if (attrs.dateDisabled) {
datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
}
function parseDate(viewValue) {
if (!viewValue) {
ngModel.$setValidity('date', true);
return null;
} else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
ngModel.$setValidity('date', true);
return viewValue;
} else if (angular.isString(viewValue)) {
var date = dateParser.parse(viewValue, dateFormat) || new Date(viewValue);
if (isNaN(date)) {
ngModel.$setValidity('date', false);
return undefined;
} else {
ngModel.$setValidity('date', true);
return date;
}
} else {
ngModel.$setValidity('date', false);
return undefined;
}
}
ngModel.$parsers.unshift(parseDate);
// Inner change
scope.dateSelection = function(dt) {
if (angular.isDefined(dt)) {
scope.date = dt;
}
ngModel.$setViewValue(scope.date);
ngModel.$render();
if ( closeOnDateSelection ) {
scope.isOpen = false;
element[0].focus();
}
};
element.bind('input change keyup', function() {
scope.$apply(function() {
scope.date = ngModel.$modelValue;
});
});
// Outter change
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
scope.date = parseDate( ngModel.$modelValue );
};
var documentClickBind = function(event) {
if (scope.isOpen && event.target !== element[0]) {
scope.$apply(function() {
scope.isOpen = false;
});
}
};
var keydown = function(evt, noApply) {
scope.keydown(evt);
};
element.bind('keydown', keydown);
scope.keydown = function(evt) {
if (evt.which === 27) {
evt.preventDefault();
evt.stopPropagation();
scope.close();
} else if (evt.which === 40 && !scope.isOpen) {
scope.isOpen = true;
}
};
scope.$watch('isOpen', function(value) {
if (value) {
scope.$broadcast('datepicker.focus');
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
$document.bind('click', documentClickBind);
} else {
$document.unbind('click', documentClickBind);
}
});
scope.select = function( date ) {
if (date === 'today') {
var today = new Date();
if (angular.isDate(ngModel.$modelValue)) {
date = new Date(ngModel.$modelValue);
date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
} else {
date = new Date(today.setHours(0, 0, 0, 0));
}
}
scope.dateSelection( date );
};
scope.close = function() {
scope.isOpen = false;
element[0].focus();
};
var $popup = $compile(popupEl)(scope);
// Prevent jQuery cache memory leak (template is now redundant after linking)
popupEl.remove();
if ( appendToBody ) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
scope.$on('$destroy', function() {
$popup.remove();
element.unbind('keydown', keydown);
$document.unbind('click', documentClickBind);
});
}
};
}])
.directive('datepickerPopupWrap', function() {
return {
restrict:'EA',
replace: true,
transclude: true,
templateUrl: 'template/datepicker/popup.html',
link:function (scope, element, attrs) {
element.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
};
});
angular.module('ui.bootstrap.dropdown', [])
.constant('dropdownConfig', {
openClass: 'open'
})
.service('dropdownService', ['$document', function($document) {
var openScope = null;
this.open = function( dropdownScope ) {
if ( !openScope ) {
$document.bind('click', closeDropdown);
$document.bind('keydown', escapeKeyBind);
}
if ( openScope && openScope !== dropdownScope ) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function( dropdownScope ) {
if ( openScope === dropdownScope ) {
openScope = null;
$document.unbind('click', closeDropdown);
$document.unbind('keydown', escapeKeyBind);
}
};
var closeDropdown = function( evt ) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) { return; }
var toggleElement = openScope.getToggleElement();
if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
return;
}
openScope.$apply(function() {
openScope.isOpen = false;
});
};
var escapeKeyBind = function( evt ) {
if ( evt.which === 27 ) {
openScope.focusToggleElement();
closeDropdown();
}
};
}])
.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;
this.init = function( element ) {
self.$element = element;
if ( $attrs.isOpen ) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
};
this.toggle = function( open ) {
return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function() {
return scope.isOpen;
};
scope.getToggleElement = function() {
return self.toggleElement;
};
scope.focusToggleElement = function() {
if ( self.toggleElement ) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function( isOpen, wasOpen ) {
$animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);
if ( isOpen ) {
scope.focusToggleElement();
dropdownService.open( scope );
} else {
dropdownService.close( scope );
}
setIsOpen($scope, isOpen);
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, { open: !!isOpen });
}
});
$scope.$on('$locationChangeSuccess', function() {
scope.isOpen = false;
});
$scope.$on('$destroy', function() {
scope.$destroy();
});
}])
.directive('dropdown', function() {
return {
controller: 'DropdownController',
link: function(scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init( element );
}
};
})
.directive('dropdownToggle', function() {
return {
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if ( !dropdownCtrl ) {
return;
}
dropdownCtrl.toggleElement = element;
var toggleDropdown = function(event) {
event.preventDefault();
if ( !element.hasClass('disabled') && !attrs.disabled ) {
scope.$apply(function() {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function() {
element.unbind('click', toggleDropdown);
});
}
};
});
angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', ['$timeout', function ($timeout) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
link: function (scope, element, attrs) {
scope.backdropClass = attrs.backdropClass || '';
scope.animate = false;
//trigger CSS transitions
$timeout(function () {
scope.animate = true;
});
}
};
}])
.directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
return {
restrict: 'EA',
scope: {
index: '@',
animate: '='
},
replace: true,
transclude: true,
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl || 'template/modal/window.html';
},
link: function (scope, element, attrs) {
element.addClass(attrs.windowClass || '');
scope.size = attrs.size;
$timeout(function () {
// trigger CSS transitions
scope.animate = true;
/**
* Auto-focusing of a freshly-opened modal element causes any child elements
* with the autofocus attribute to lose focus. This is an issue on touch
* based devices which will show and then hide the onscreen keyboard.
* Attempts to refocus the autofocus element via JavaScript will not reopen
* the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
* the modal element if the modal does not contain an autofocus element.
*/
if (!element[0].querySelectorAll('[autofocus]').length) {
element[0].focus();
}
});
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
}
};
}])
.directive('modalTransclude', function () {
return {
link: function($scope, $element, $attrs, controller, $transclude) {
$transclude($scope.$parent, function(clone) {
$element.empty();
$element.append(clone);
});
}
};
})
.factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap',
function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var $modalStack = {};
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex){
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance) {
var body = $document.find('body').eq(0);
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
//remove window DOM element
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() {
modalWindow.modalScope.$destroy();
body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
checkRemoveBackdrop();
});
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() == -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, 150, function () {
backdropScopeRef.$destroy();
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, emulateTime, done) {
// Closing animation
scope.animate = false;
var transitionEndEventName = $transition.transitionEndEventName;
if (transitionEndEventName) {
// transition out
var timeout = $timeout(afterAnimating, emulateTime);
domEl.bind(transitionEndEventName, function () {
$timeout.cancel(timeout);
afterAnimating();
scope.$apply();
});
} else {
// Ensure this call is async
$timeout(afterAnimating);
}
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
domEl.remove();
if (done) {
done();
}
}
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
evt.preventDefault();
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key, 'escape key press');
});
}
}
});
$modalStack.open = function (modalInstance, modal) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard
});
var body = $document.find('body').eq(0),
currBackdropIndex = backdropIndex();
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.index = currBackdropIndex;
var angularBackgroundDomEl = angular.element('<div modal-backdrop></div>');
angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
body.append(backdropDomEl);
}
var angularDomEl = angular.element('<div modal-window></div>');
angularDomEl.attr({
'template-url': modal.windowTemplateUrl,
'window-class': modal.windowClass,
'size': modal.size,
'index': openedWindows.length() - 1,
'animate': 'animate'
}).html(modal.content);
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
body.append(modalDomEl);
body.addClass(OPENED_MODAL_CLASS);
};
$modalStack.close = function (modalInstance, result) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.deferred.resolve(result);
removeModalWindow(modalInstance);
}
};
$modalStack.dismiss = function (modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.deferred.reject(reason);
removeModalWindow(modalInstance);
}
};
$modalStack.dismissAll = function (reason) {
var topModal = this.getTop();
while (topModal) {
this.dismiss(topModal.key, reason);
topModal = this.getTop();
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
backdrop: true, //can be also false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$http.get(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl,
{cache: $templateCache}).then(function (result) {
return result.data;
});
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
close: function (result) {
$modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
$modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
if (modalOptions.controllerAs) {
modalScope[modalOptions.controllerAs] = ctrlInstance;
}
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
content: tplAndVars[0],
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
backdropClass: modalOptions.backdropClass,
windowClass: modalOptions.windowClass,
windowTemplateUrl: modalOptions.windowTemplateUrl,
size: modalOptions.size
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
templateAndResolvePromise.then(function () {
modalOpenedDeferred.resolve(true);
}, function () {
modalOpenedDeferred.reject(false);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
});
angular.module('ui.bootstrap.pagination', [])
.controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) {
var self = this,
ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
this.init = function(ngModelCtrl_, config) {
ngModelCtrl = ngModelCtrl_;
this.config = config;
ngModelCtrl.$render = function() {
self.render();
};
if ($attrs.itemsPerPage) {
$scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
self.itemsPerPage = parseInt(value, 10);
$scope.totalPages = self.calculateTotalPages();
});
} else {
this.itemsPerPage = config.itemsPerPage;
}
};
this.calculateTotalPages = function() {
var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
return Math.max(totalPages || 0, 1);
};
this.render = function() {
$scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
};
$scope.selectPage = function(page) {
if ( $scope.page !== page && page > 0 && page <= $scope.totalPages) {
ngModelCtrl.$setViewValue(page);
ngModelCtrl.$render();
}
};
$scope.getText = function( key ) {
return $scope[key + 'Text'] || self.config[key + 'Text'];
};
$scope.noPrevious = function() {
return $scope.page === 1;
};
$scope.noNext = function() {
return $scope.page === $scope.totalPages;
};
$scope.$watch('totalItems', function() {
$scope.totalPages = self.calculateTotalPages();
});
$scope.$watch('totalPages', function(value) {
setNumPages($scope.$parent, value); // Readonly variable
if ( $scope.page > value ) {
$scope.selectPage(value);
} else {
ngModelCtrl.$render();
}
});
}])
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
directionLinks: true,
firstText: 'First',
previousText: 'Previous',
nextText: 'Next',
lastText: 'Last',
rotate: true
})
.directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {
return {
restrict: 'EA',
scope: {
totalItems: '=',
firstText: '@',
previousText: '@',
nextText: '@',
lastText: '@'
},
require: ['pagination', '?ngModel'],
controller: 'PaginationController',
templateUrl: 'template/pagination/pagination.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (!ngModelCtrl) {
return; // do nothing if no ng-model
}
// Setup configuration parameters
var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
paginationCtrl.init(ngModelCtrl, paginationConfig);
if (attrs.maxSize) {
scope.$parent.$watch($parse(attrs.maxSize), function(value) {
maxSize = parseInt(value, 10);
paginationCtrl.render();
});
}
// Create page object used in template
function makePage(number, text, isActive) {
return {
number: number,
text: text,
active: isActive
};
}
function getPages(currentPage, totalPages) {
var pages = [];
// Default page limits
var startPage = 1, endPage = totalPages;
var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );
// recompute if maxSize
if ( isMaxSized ) {
if ( rotate ) {
// Current page is displayed in the middle of the visible ones
startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
endPage = startPage + maxSize - 1;
// Adjust if limit is exceeded
if (endPage > totalPages) {
endPage = totalPages;
startPage = endPage - maxSize + 1;
}
} else {
// Visible pages are paginated with maxSize
startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
// Adjust last page if limit is exceeded
endPage = Math.min(startPage + maxSize - 1, totalPages);
}
}
// Add page number links
for (var number = startPage; number <= endPage; number++) {
var page = makePage(number, number, number === currentPage);
pages.push(page);
}
// Add links to move between page sets
if ( isMaxSized && ! rotate ) {
if ( startPage > 1 ) {
var previousPageSet = makePage(startPage - 1, '...', false);
pages.unshift(previousPageSet);
}
if ( endPage < totalPages ) {
var nextPageSet = makePage(endPage + 1, '...', false);
pages.push(nextPageSet);
}
}
return pages;
}
var originalRender = paginationCtrl.render;
paginationCtrl.render = function() {
originalRender();
if (scope.page > 0 && scope.page <= scope.totalPages) {
scope.pages = getPages(scope.page, scope.totalPages);
}
};
}
};
}])
.constant('pagerConfig', {
itemsPerPage: 10,
previousText: '« Previous',
nextText: 'Next »',
align: true
})
.directive('pager', ['pagerConfig', function(pagerConfig) {
return {
restrict: 'EA',
scope: {
totalItems: '=',
previousText: '@',
nextText: '@'
},
require: ['pager', '?ngModel'],
controller: 'PaginationController',
templateUrl: 'template/pagination/pager.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (!ngModelCtrl) {
return; // do nothing if no ng-model
}
scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
paginationCtrl.init(ngModelCtrl, pagerConfig);
}
};
}]);
/**
* The following features are still outstanding: animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html tooltips, and selector delegation.
*/
angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )
/**
* The $tooltip service creates tooltip- and popover-like directives as well as
* houses global options for them.
*/
.provider( '$tooltip', function () {
// The default options tooltip and popover.
var defaultOptions = {
placement: 'top',
animation: true,
popupDelay: 0
};
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur'
};
// The options specified to the provider globally.
var globalOptions = {};
/**
* `options({})` allows global configuration of all tooltips in the
* application.
*
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
* // place tooltips left instead of top by default
* $tooltipProvider.options( { placement: 'left' } );
* });
*/
this.options = function( value ) {
angular.extend( globalOptions, value );
};
/**
* This allows you to extend the set of trigger mappings available. E.g.:
*
* $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
*/
this.setTriggers = function setTriggers ( triggers ) {
angular.extend( triggerMap, triggers );
};
/**
* This is a helper function for translating camel-case to snake-case.
*/
function snake_case(name){
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) {
return function $tooltip ( type, prefix, defaultTriggerShow ) {
var options = angular.extend( {}, defaultOptions, globalOptions );
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers ( trigger ) {
var show = trigger || options.trigger || defaultTriggerShow;
var hide = triggerMap[show] || show;
return {
show: show,
hide: hide
};
}
var directiveName = snake_case( type );
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div '+ directiveName +'-popup '+
'title="'+startSym+'title'+endSym+'" '+
'content="'+startSym+'content'+endSym+'" '+
'placement="'+startSym+'placement'+endSym+'" '+
'animation="animation" '+
'is-open="isOpen"'+
'>'+
'</div>';
return {
restrict: 'EA',
compile: function (tElem, tAttrs) {
var tooltipLinker = $compile( template );
return function link ( scope, element, attrs ) {
var tooltip;
var tooltipLinkedScope;
var transitionTimeout;
var popupTimeout;
var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
var triggers = getTriggers( undefined );
var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
var ttScope = scope.$new(true);
var positionTooltip = function () {
var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
ttPosition.top += 'px';
ttPosition.left += 'px';
// Now set the calculated positioning.
tooltip.css( ttPosition );
};
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
ttScope.isOpen = false;
function toggleTooltipBind () {
if ( ! ttScope.isOpen ) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
return;
}
prepareTooltip();
if ( ttScope.popupDelay ) {
// Do nothing if the tooltip was already scheduled to pop-up.
// This happens if show is triggered multiple times before any hide is triggered.
if (!popupTimeout) {
popupTimeout = $timeout( show, ttScope.popupDelay, false );
popupTimeout.then(function(reposition){reposition();});
}
} else {
show()();
}
}
function hideTooltipBind () {
scope.$apply(function () {
hide();
});
}
// Show the tooltip popup element.
function show() {
popupTimeout = null;
// If there is a pending remove transition, we must cancel it, lest the
// tooltip be mysteriously removed.
if ( transitionTimeout ) {
$timeout.cancel( transitionTimeout );
transitionTimeout = null;
}
// Don't show empty tooltips.
if ( ! ttScope.content ) {
return angular.noop;
}
createTooltip();
// Set the initial positioning.
tooltip.css({ top: 0, left: 0, display: 'block' });
// Now we add it to the DOM because need some info about it. But it's not
// visible yet anyway.
if ( appendToBody ) {
$document.find( 'body' ).append( tooltip );
} else {
element.after( tooltip );
}
positionTooltip();
// And show the tooltip.
ttScope.isOpen = true;
ttScope.$digest(); // digest required as $apply is not called
// Return positioning function as promise callback for correct
// positioning after draw.
return positionTooltip;
}
// Hide the tooltip popup element.
function hide() {
// First things first: we don't show it anymore.
ttScope.isOpen = false;
//if tooltip is going to be shown after delay, we must cancel this
$timeout.cancel( popupTimeout );
popupTimeout = null;
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
if ( ttScope.animation ) {
if (!transitionTimeout) {
transitionTimeout = $timeout(removeTooltip, 500);
}
} else {
removeTooltip();
}
}
function createTooltip() {
// There can only be one tooltip element per directive shown at once.
if (tooltip) {
removeTooltip();
}
tooltipLinkedScope = ttScope.$new();
tooltip = tooltipLinker(tooltipLinkedScope, angular.noop);
}
function removeTooltip() {
transitionTimeout = null;
if (tooltip) {
tooltip.remove();
tooltip = null;
}
if (tooltipLinkedScope) {
tooltipLinkedScope.$destroy();
tooltipLinkedScope = null;
}
}
function prepareTooltip() {
prepPlacement();
prepPopupDelay();
}
/**
* Observe the relevant attributes.
*/
attrs.$observe( type, function ( val ) {
ttScope.content = val;
if (!val && ttScope.isOpen ) {
hide();
}
});
attrs.$observe( prefix+'Title', function ( val ) {
ttScope.title = val;
});
function prepPlacement() {
var val = attrs[ prefix + 'Placement' ];
ttScope.placement = angular.isDefined( val ) ? val : options.placement;
}
function prepPopupDelay() {
var val = attrs[ prefix + 'PopupDelay' ];
var delay = parseInt( val, 10 );
ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
}
var unregisterTriggers = function () {
element.unbind(triggers.show, showTooltipBind);
element.unbind(triggers.hide, hideTooltipBind);
};
function prepTriggers() {
var val = attrs[ prefix + 'Trigger' ];
unregisterTriggers();
triggers = getTriggers( val );
if ( triggers.show === triggers.hide ) {
element.bind( triggers.show, toggleTooltipBind );
} else {
element.bind( triggers.show, showTooltipBind );
element.bind( triggers.hide, hideTooltipBind );
}
}
prepTriggers();
var animation = scope.$eval(attrs[prefix + 'Animation']);
ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
// if a tooltip is attached to <body> we need to remove it on
// location change as its parent scope will probably not be destroyed
// by the change.
if ( appendToBody ) {
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
if ( ttScope.isOpen ) {
hide();
}
});
}
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
$timeout.cancel( transitionTimeout );
$timeout.cancel( popupTimeout );
unregisterTriggers();
removeTooltip();
ttScope = null;
});
};
}
};
};
}];
})
.directive( 'tooltipPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-popup.html'
};
})
.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
}])
.directive( 'tooltipHtmlUnsafePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
};
})
.directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
}]);
/**
* The following features are still outstanding: popup delay, animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html popovers, and selector delegatation.
*/
angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )
.directive( 'popoverPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
})
.directive( 'popover', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'popover', 'popover', 'click' );
}]);
angular.module('ui.bootstrap.progressbar', [])
.constant('progressConfig', {
animate: true,
max: 100
})
.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {
var self = this,
animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
this.bars = [];
$scope.max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max;
this.addBar = function(bar, element) {
if ( !animate ) {
element.css({'transition': 'none'});
}
this.bars.push(bar);
bar.$watch('value', function( value ) {
bar.percent = +(100 * value / $scope.max).toFixed(2);
});
bar.$on('$destroy', function() {
element = null;
self.removeBar(bar);
});
};
this.removeBar = function(bar) {
this.bars.splice(this.bars.indexOf(bar), 1);
};
}])
.directive('progress', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
require: 'progress',
scope: {},
templateUrl: 'template/progressbar/progress.html'
};
})
.directive('bar', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
require: '^progress',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/bar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, element);
}
};
})
.directive('progressbar', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/progressbar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, angular.element(element.children()[0]));
}
};
});
angular.module('ui.bootstrap.rating', [])
.constant('ratingConfig', {
max: 5,
stateOn: null,
stateOff: null
})
.controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {
var ngModelCtrl = { $setViewValue: angular.noop };
this.init = function(ngModelCtrl_) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = this.render;
this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) :
new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max );
$scope.range = this.buildTemplateObjects(ratingStates);
};
this.buildTemplateObjects = function(states) {
for (var i = 0, n = states.length; i < n; i++) {
states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]);
}
return states;
};
$scope.rate = function(value) {
if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) {
ngModelCtrl.$setViewValue(value);
ngModelCtrl.$render();
}
};
$scope.enter = function(value) {
if ( !$scope.readonly ) {
$scope.value = value;
}
$scope.onHover({value: value});
};
$scope.reset = function() {
$scope.value = ngModelCtrl.$viewValue;
$scope.onLeave();
};
$scope.onKeydown = function(evt) {
if (/(37|38|39|40)/.test(evt.which)) {
evt.preventDefault();
evt.stopPropagation();
$scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) );
}
};
this.render = function() {
$scope.value = ngModelCtrl.$viewValue;
};
}])
.directive('rating', function() {
return {
restrict: 'EA',
require: ['rating', 'ngModel'],
scope: {
readonly: '=?',
onHover: '&',
onLeave: '&'
},
controller: 'RatingController',
templateUrl: 'template/rating/rating.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if ( ngModelCtrl ) {
ratingCtrl.init( ngModelCtrl );
}
}
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.tabs
*
* @description
* AngularJS version of the tabs directive.
*/
angular.module('ui.bootstrap.tabs', [])
.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
var ctrl = this,
tabs = ctrl.tabs = $scope.tabs = [];
ctrl.select = function(selectedTab) {
angular.forEach(tabs, function(tab) {
if (tab.active && tab !== selectedTab) {
tab.active = false;
tab.onDeselect();
}
});
selectedTab.active = true;
selectedTab.onSelect();
};
ctrl.addTab = function addTab(tab) {
tabs.push(tab);
// we can't run the select function on the first tab
// since that would select it twice
if (tabs.length === 1) {
tab.active = true;
} else if (tab.active) {
ctrl.select(tab);
}
};
ctrl.removeTab = function removeTab(tab) {
var index = tabs.indexOf(tab);
//Select a new tab if the tab to be removed is selected and not destroyed
if (tab.active && tabs.length > 1 && !destroyed) {
//If this is the last tab, select the previous tab. else, the next tab.
var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
ctrl.select(tabs[newActiveIndex]);
}
tabs.splice(index, 1);
};
var destroyed;
$scope.$on('$destroy', function() {
destroyed = true;
});
}])
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabset
* @restrict EA
*
* @description
* Tabset is the outer container for the tabs directive
*
* @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
* @param {boolean=} justified Whether or not to use justified styling for the tabs.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab heading="Tab 1"><b>First</b> Content!</tab>
<tab heading="Tab 2"><i>Second</i> Content!</tab>
</tabset>
<hr />
<tabset vertical="true">
<tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
<tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
</tabset>
<tabset justified="true">
<tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
<tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
</tabset>
</file>
</example>
*/
.directive('tabset', function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
scope: {
type: '@'
},
controller: 'TabsetController',
templateUrl: 'template/tabs/tabset.html',
link: function(scope, element, attrs) {
scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
}
};
})
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tab
* @restrict EA
*
* @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
* @param {string=} select An expression to evaluate when the tab is selected.
* @param {boolean=} active A binding, telling whether or not this tab is selected.
* @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
*
* @description
* Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="TabsDemoCtrl">
<button class="btn btn-small" ng-click="items[0].active = true">
Select item 1, using active binding
</button>
<button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
Enable/disable item 2, using disabled binding
</button>
<br />
<tabset>
<tab heading="Tab 1">First Tab</tab>
<tab select="alertMe()">
<tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
Second Tab, with alert callback and html heading!
</tab>
<tab ng-repeat="item in items"
heading="{{item.title}}"
disabled="item.disabled"
active="item.active">
{{item.content}}
</tab>
</tabset>
</div>
</file>
<file name="script.js">
function TabsDemoCtrl($scope) {
$scope.items = [
{ title:"Dynamic Title 1", content:"Dynamic Item 0" },
{ title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
];
$scope.alertMe = function() {
setTimeout(function() {
alert("You've selected the alert tab!");
});
};
};
</file>
</example>
*/
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabHeading
* @restrict EA
*
* @description
* Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab>
<tab-heading><b>HTML</b> in my titles?!</tab-heading>
And some content, too!
</tab>
<tab>
<tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
That's right.
</tab>
</tabset>
</file>
</example>
*/
.directive('tab', ['$parse', function($parse) {
return {
require: '^tabset',
restrict: 'EA',
replace: true,
templateUrl: 'template/tabs/tab.html',
transclude: true,
scope: {
active: '=?',
heading: '@',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
controller: function() {
//Empty controller so other directives can require being 'under' a tab
},
compile: function(elm, attrs, transclude) {
return function postLink(scope, elm, attrs, tabsetCtrl) {
scope.$watch('active', function(active) {
if (active) {
tabsetCtrl.select(scope);
}
});
scope.disabled = false;
if ( attrs.disabled ) {
scope.$parent.$watch($parse(attrs.disabled), function(value) {
scope.disabled = !! value;
});
}
scope.select = function() {
if ( !scope.disabled ) {
scope.active = true;
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function() {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
};
}
};
}])
.directive('tabHeadingTransclude', [function() {
return {
restrict: 'A',
require: '^tab',
link: function(scope, elm, attrs, tabCtrl) {
scope.$watch('headingElement', function updateHeadingElement(heading) {
if (heading) {
elm.html('');
elm.append(heading);
}
});
}
};
}])
.directive('tabContentTransclude', function() {
return {
restrict: 'A',
require: '^tabset',
link: function(scope, elm, attrs) {
var tab = scope.$eval(attrs.tabContentTransclude);
//Now our tab is ready to be transcluded: both the tab heading area
//and the tab content area are loaded. Transclude 'em both.
tab.$transcludeFn(tab.$parent, function(contents) {
angular.forEach(contents, function(node) {
if (isTabHeading(node)) {
//Let tabHeadingTransclude know.
tab.headingElement = node;
} else {
elm.append(node);
}
});
});
}
};
function isTabHeading(node) {
return node.tagName && (
node.hasAttribute('tab-heading') ||
node.hasAttribute('data-tab-heading') ||
node.tagName.toLowerCase() === 'tab-heading' ||
node.tagName.toLowerCase() === 'data-tab-heading'
);
}
})
;
angular.module('ui.bootstrap.timepicker', [])
.constant('timepickerConfig', {
hourStep: 1,
minuteStep: 1,
showMeridian: true,
meridians: null,
readonlyInput: false,
mousewheel: true
})
.controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {
var selected = new Date(),
ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
this.init = function( ngModelCtrl_, inputs ) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = this.render;
var hoursInputEl = inputs.eq(0),
minutesInputEl = inputs.eq(1);
var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
if ( mousewheel ) {
this.setupMousewheelEvents( hoursInputEl, minutesInputEl );
}
$scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
this.setupInputEvents( hoursInputEl, minutesInputEl );
};
var hourStep = timepickerConfig.hourStep;
if ($attrs.hourStep) {
$scope.$parent.$watch($parse($attrs.hourStep), function(value) {
hourStep = parseInt(value, 10);
});
}
var minuteStep = timepickerConfig.minuteStep;
if ($attrs.minuteStep) {
$scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
minuteStep = parseInt(value, 10);
});
}
// 12H / 24H mode
$scope.showMeridian = timepickerConfig.showMeridian;
if ($attrs.showMeridian) {
$scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
$scope.showMeridian = !!value;
if ( ngModelCtrl.$error.time ) {
// Evaluate from template
var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
selected.setHours( hours );
refresh();
}
} else {
updateTemplate();
}
});
}
// Get $scope.hours in 24H mode if valid
function getHoursFromTemplate ( ) {
var hours = parseInt( $scope.hours, 10 );
var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
if ( !valid ) {
return undefined;
}
if ( $scope.showMeridian ) {
if ( hours === 12 ) {
hours = 0;
}
if ( $scope.meridian === meridians[1] ) {
hours = hours + 12;
}
}
return hours;
}
function getMinutesFromTemplate() {
var minutes = parseInt($scope.minutes, 10);
return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
}
function pad( value ) {
return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
}
// Respond on mousewheel spin
this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {
var isScrollingUp = function(e) {
if (e.originalEvent) {
e = e.originalEvent;
}
//pick correct delta variable depending on event
var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
return (e.detail || delta > 0);
};
hoursInputEl.bind('mousewheel wheel', function(e) {
$scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );
e.preventDefault();
});
minutesInputEl.bind('mousewheel wheel', function(e) {
$scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );
e.preventDefault();
});
};
this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {
if ( $scope.readonlyInput ) {
$scope.updateHours = angular.noop;
$scope.updateMinutes = angular.noop;
return;
}
var invalidate = function(invalidHours, invalidMinutes) {
ngModelCtrl.$setViewValue( null );
ngModelCtrl.$setValidity('time', false);
if (angular.isDefined(invalidHours)) {
$scope.invalidHours = invalidHours;
}
if (angular.isDefined(invalidMinutes)) {
$scope.invalidMinutes = invalidMinutes;
}
};
$scope.updateHours = function() {
var hours = getHoursFromTemplate();
if ( angular.isDefined(hours) ) {
selected.setHours( hours );
refresh( 'h' );
} else {
invalidate(true);
}
};
hoursInputEl.bind('blur', function(e) {
if ( !$scope.invalidHours && $scope.hours < 10) {
$scope.$apply( function() {
$scope.hours = pad( $scope.hours );
});
}
});
$scope.updateMinutes = function() {
var minutes = getMinutesFromTemplate();
if ( angular.isDefined(minutes) ) {
selected.setMinutes( minutes );
refresh( 'm' );
} else {
invalidate(undefined, true);
}
};
minutesInputEl.bind('blur', function(e) {
if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {
$scope.$apply( function() {
$scope.minutes = pad( $scope.minutes );
});
}
});
};
this.render = function() {
var date = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : null;
if ( isNaN(date) ) {
ngModelCtrl.$setValidity('time', false);
$log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else {
if ( date ) {
selected = date;
}
makeValid();
updateTemplate();
}
};
// Call internally when we know that model is valid.
function refresh( keyboardChange ) {
makeValid();
ngModelCtrl.$setViewValue( new Date(selected) );
updateTemplate( keyboardChange );
}
function makeValid() {
ngModelCtrl.$setValidity('time', true);
$scope.invalidHours = false;
$scope.invalidMinutes = false;
}
function updateTemplate( keyboardChange ) {
var hours = selected.getHours(), minutes = selected.getMinutes();
if ( $scope.showMeridian ) {
hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
}
$scope.hours = keyboardChange === 'h' ? hours : pad(hours);
$scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
$scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
}
function addMinutes( minutes ) {
var dt = new Date( selected.getTime() + minutes * 60000 );
selected.setHours( dt.getHours(), dt.getMinutes() );
refresh();
}
$scope.incrementHours = function() {
addMinutes( hourStep * 60 );
};
$scope.decrementHours = function() {
addMinutes( - hourStep * 60 );
};
$scope.incrementMinutes = function() {
addMinutes( minuteStep );
};
$scope.decrementMinutes = function() {
addMinutes( - minuteStep );
};
$scope.toggleMeridian = function() {
addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
};
}])
.directive('timepicker', function () {
return {
restrict: 'EA',
require: ['timepicker', '?^ngModel'],
controller:'TimepickerController',
replace: true,
scope: {},
templateUrl: 'template/timepicker/timepicker.html',
link: function(scope, element, attrs, ctrls) {
var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if ( ngModelCtrl ) {
timepickerCtrl.init( ngModelCtrl, element.find('input') );
}
}
};
});
angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
/**
* A helper service that can parse typeahead's syntax (string provided by users)
* Extracted to a separate service for ease of unit testing
*/
.factory('typeaheadParser', ['$parse', function ($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
return {
parse:function (input) {
var match = input.match(TYPEAHEAD_REGEXP);
if (!match) {
throw new Error(
'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
' but got "' + input + '".');
}
return {
itemName:match[3],
source:$parse(match[4]),
viewMapper:$parse(match[2] || match[1]),
modelMapper:$parse(match[1])
};
}
};
}])
.directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser',
function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
return {
require:'ngModel',
link:function (originalScope, element, attrs, modelCtrl) {
//SUPPORTED ATTRIBUTES (OPTIONS)
//minimal no of characters that needs to be entered before typeahead kicks-in
var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
//minimal wait time after last character typed before typehead kicks-in
var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
//should it restrict model values to the ones selected from the popup only?
var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
//binding to a variable that indicates if matches are being retrieved asynchronously
var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.typeaheadOnSelect);
var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
//INTERNAL VARIABLES
//model setter executed upon match selection
var $setModelValue = $parse(attrs.ngModel).assign;
//expressions used by typeahead
var parserResult = typeaheadParser.parse(attrs.typeahead);
var hasFocus;
//create a child scope for the typeahead directive so we are not polluting original scope
//with typeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
originalScope.$on('$destroy', function(){
scope.$destroy();
});
// WAI-ARIA
var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
element.attr({
'aria-autocomplete': 'list',
'aria-expanded': false,
'aria-owns': popupId
});
//pop-up element used to display matches
var popUpEl = angular.element('<div typeahead-popup></div>');
popUpEl.attr({
id: popupId,
matches: 'matches',
active: 'activeIdx',
select: 'select(activeIdx)',
query: 'query',
position: 'position'
});
//custom item template
if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
}
var resetMatches = function() {
scope.matches = [];
scope.activeIdx = -1;
element.attr('aria-expanded', false);
};
var getMatchId = function(index) {
return popupId + '-option-' + index;
};
// Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
// This attribute is added or removed automatically when the `activeIdx` changes.
scope.$watch('activeIdx', function(index) {
if (index < 0) {
element.removeAttr('aria-activedescendant');
} else {
element.attr('aria-activedescendant', getMatchId(index));
}
});
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest && hasFocus) {
if (matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};
resetMatches();
//we need to propagate user's query so we can higlight matches
scope.query = undefined;
//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;
var scheduleSearchWithTimeout = function(inputValue) {
timeoutPromise = $timeout(function () {
getMatchesAsync(inputValue);
}, waitTime);
};
var cancelPreviousTimeout = function() {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
};
//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.unshift(function (inputValue) {
hasFocus = true;
if (inputValue && inputValue.length >= minSearch) {
if (waitTime > 0) {
cancelPreviousTimeout();
scheduleSearchWithTimeout(inputValue);
} else {
getMatchesAsync(inputValue);
}
} else {
isLoadingSetter(originalScope, false);
cancelPreviousTimeout();
resetMatches();
}
if (isEditable) {
return inputValue;
} else {
if (!inputValue) {
// Reset in case user had typed something previously.
modelCtrl.$setValidity('editable', true);
return inputValue;
} else {
modelCtrl.$setValidity('editable', false);
return undefined;
}
}
});
modelCtrl.$formatters.push(function (modelValue) {
var candidateViewValue, emptyViewValue;
var locals = {};
if (inputFormatter) {
locals.$model = modelValue;
return inputFormatter(originalScope, locals);
} else {
//it might happen that we don't have enough info to properly render input value
//we need to check for this situation and simply return model value if we can't apply custom formatting
locals[parserResult.itemName] = modelValue;
candidateViewValue = parserResult.viewMapper(originalScope, locals);
locals[parserResult.itemName] = undefined;
emptyViewValue = parserResult.viewMapper(originalScope, locals);
return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;
}
});
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
var model, item;
locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
model = parserResult.modelMapper(originalScope, locals);
$setModelValue(originalScope, model);
modelCtrl.$setValidity('editable', true);
onSelectCallback(originalScope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(originalScope, locals)
});
resetMatches();
//return focus to the input element if a match was selected via a mouse click event
// use timeout to avoid $rootScope:inprog error
$timeout(function() { element[0].focus(); }, 0, false);
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
element.bind('keydown', function (evt) {
//typeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
// if there's nothing selected (i.e. focusFirst) and enter is hit, don't do anything
if (scope.activeIdx == -1 && (evt.which === 13 || evt.which === 9)) {
return;
}
evt.preventDefault();
if (evt.which === 40) {
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
} else if (evt.which === 38) {
scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
} else if (evt.which === 13 || evt.which === 9) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
} else if (evt.which === 27) {
evt.stopPropagation();
resetMatches();
scope.$digest();
}
});
element.bind('blur', function (evt) {
hasFocus = false;
});
// Keep reference to click handler to unbind it.
var dismissClickHandler = function (evt) {
if (element[0] !== evt.target) {
resetMatches();
scope.$digest();
}
};
$document.bind('click', dismissClickHandler);
originalScope.$on('$destroy', function(){
$document.unbind('click', dismissClickHandler);
if (appendToBody) {
$popup.remove();
}
});
var $popup = $compile(popUpEl)(scope);
if (appendToBody) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('typeaheadPopup', function () {
return {
restrict:'EA',
scope:{
matches:'=',
query:'=',
active:'=',
position:'=',
select:'&'
},
replace:true,
templateUrl:'template/typeahead/typeahead-popup.html',
link:function (scope, element, attrs) {
scope.templateUrl = attrs.templateUrl;
scope.isOpen = function () {
return scope.matches.length > 0;
};
scope.isActive = function (matchIdx) {
return scope.active == matchIdx;
};
scope.selectActive = function (matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function (activeIdx) {
scope.select({activeIdx:activeIdx});
};
}
};
})
.directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {
return {
restrict:'EA',
scope:{
index:'=',
match:'=',
query:'='
},
link:function (scope, element, attrs) {
var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
$http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){
element.replaceWith($compile(tplContent.trim())(scope));
});
}
};
}])
.filter('typeaheadHighlight', function() {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function(matchItem, query) {
return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
};
});
angular.module("template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/accordion/accordion-group.html",
"<div class=\"panel panel-default\">\n" +
" <div class=\"panel-heading\">\n" +
" <h4 class=\"panel-title\">\n" +
" <a href class=\"accordion-toggle\" ng-click=\"toggleOpen()\" accordion-transclude=\"heading\"><span ng-class=\"{'text-muted': isDisabled}\">{{heading}}</span></a>\n" +
" </h4>\n" +
" </div>\n" +
" <div class=\"panel-collapse\" collapse=\"!isOpen\">\n" +
" <div class=\"panel-body\" ng-transclude></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/accordion/accordion.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/accordion/accordion.html",
"<div class=\"panel-group\" ng-transclude></div>");
}]);
angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/alert/alert.html",
"<div class=\"alert\" ng-class=\"['alert-' + (type || 'warning'), closeable ? 'alert-dismissable' : null]\" role=\"alert\">\n" +
" <button ng-show=\"closeable\" type=\"button\" class=\"close\" ng-click=\"close()\">\n" +
" <span aria-hidden=\"true\">×</span>\n" +
" <span class=\"sr-only\">Close</span>\n" +
" </button>\n" +
" <div ng-transclude></div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/carousel/carousel.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/carousel/carousel.html",
"<div ng-mouseenter=\"pause()\" ng-mouseleave=\"play()\" class=\"carousel\" ng-swipe-right=\"prev()\" ng-swipe-left=\"next()\">\n" +
" <ol class=\"carousel-indicators\" ng-show=\"slides.length > 1\">\n" +
" <li ng-repeat=\"slide in slides track by $index\" ng-class=\"{active: isActive(slide)}\" ng-click=\"select(slide)\"></li>\n" +
" </ol>\n" +
" <div class=\"carousel-inner\" ng-transclude></div>\n" +
" <a class=\"left carousel-control\" ng-click=\"prev()\" ng-show=\"slides.length > 1\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a>\n" +
" <a class=\"right carousel-control\" ng-click=\"next()\" ng-show=\"slides.length > 1\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a>\n" +
"</div>\n" +
"");
}]);
angular.module("template/carousel/slide.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/carousel/slide.html",
"<div ng-class=\"{\n" +
" 'active': leaving || (active && !entering),\n" +
" 'prev': (next || active) && direction=='prev',\n" +
" 'next': (next || active) && direction=='next',\n" +
" 'right': direction=='prev',\n" +
" 'left': direction=='next'\n" +
" }\" class=\"item text-center\" ng-transclude></div>\n" +
"");
}]);
angular.module("template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/datepicker.html",
"<div ng-switch=\"datepickerMode\" role=\"application\" ng-keydown=\"keydown($event)\">\n" +
" <daypicker ng-switch-when=\"day\" tabindex=\"0\"></daypicker>\n" +
" <monthpicker ng-switch-when=\"month\" tabindex=\"0\"></monthpicker>\n" +
" <yearpicker ng-switch-when=\"year\" tabindex=\"0\"></yearpicker>\n" +
"</div>");
}]);
angular.module("template/datepicker/day.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/day.html",
"<table role=\"grid\" aria-labelledby=\"{{uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th colspan=\"{{5 + showWeeks}}\"><button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th ng-show=\"showWeeks\" class=\"text-center\"></th>\n" +
" <th ng-repeat=\"label in labels track by $index\" class=\"text-center\"><small aria-label=\"{{label.full}}\">{{label.abbr}}</small></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr ng-repeat=\"row in rows track by $index\">\n" +
" <td ng-show=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" +
" <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{dt.uid}}\" aria-disabled=\"{{!!dt.disabled}}\">\n" +
" <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default btn-sm\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"{'text-muted': dt.secondary, 'text-info': dt.current}\">{{dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("template/datepicker/month.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/month.html",
"<table role=\"grid\" aria-labelledby=\"{{uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th><button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr ng-repeat=\"row in rows track by $index\">\n" +
" <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{dt.uid}}\" aria-disabled=\"{{!!dt.disabled}}\">\n" +
" <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"{'text-info': dt.current}\">{{dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/popup.html",
"<ul class=\"dropdown-menu\" ng-style=\"{display: (isOpen && 'block') || 'none', top: position.top+'px', left: position.left+'px'}\" ng-keydown=\"keydown($event)\">\n" +
" <li ng-transclude></li>\n" +
" <li ng-if=\"showButtonBar\" style=\"padding:10px 9px 2px\">\n" +
" <span class=\"btn-group pull-left\">\n" +
" <button type=\"button\" class=\"btn btn-sm btn-info\" ng-click=\"select('today')\">{{ getText('current') }}</button>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-danger\" ng-click=\"select(null)\">{{ getText('clear') }}</button>\n" +
" </span>\n" +
" <button type=\"button\" class=\"btn btn-sm btn-success pull-right\" ng-click=\"close()\">{{ getText('close') }}</button>\n" +
" </li>\n" +
"</ul>\n" +
"");
}]);
angular.module("template/datepicker/year.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/datepicker/year.html",
"<table role=\"grid\" aria-labelledby=\"{{uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
" <th colspan=\"3\"><button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
" <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr ng-repeat=\"row in rows track by $index\">\n" +
" <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{dt.uid}}\" aria-disabled=\"{{!!dt.disabled}}\">\n" +
" <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"{'text-info': dt.current}\">{{dt.label}}</span></button>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/modal/backdrop.html",
"<div class=\"modal-backdrop fade {{ backdropClass }}\"\n" +
" ng-class=\"{in: animate}\"\n" +
" ng-style=\"{'z-index': 1040 + (index && 1 || 0) + index*10}\"\n" +
"></div>\n" +
"");
}]);
angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/modal/window.html",
"<div tabindex=\"-1\" role=\"dialog\" class=\"modal fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" +
" <div class=\"modal-dialog\" ng-class=\"{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}\"><div class=\"modal-content\" modal-transclude></div></div>\n" +
"</div>");
}]);
angular.module("template/pagination/pager.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/pagination/pager.html",
"<ul class=\"pager\">\n" +
" <li ng-class=\"{disabled: noPrevious(), previous: align}\"><a href ng-click=\"selectPage(page - 1)\">{{getText('previous')}}</a></li>\n" +
" <li ng-class=\"{disabled: noNext(), next: align}\"><a href ng-click=\"selectPage(page + 1)\">{{getText('next')}}</a></li>\n" +
"</ul>");
}]);
angular.module("template/pagination/pagination.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/pagination/pagination.html",
"<ul class=\"pagination\">\n" +
" <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noPrevious()}\"><a href ng-click=\"selectPage(1)\">{{getText('first')}}</a></li>\n" +
" <li ng-if=\"directionLinks\" ng-class=\"{disabled: noPrevious()}\"><a href ng-click=\"selectPage(page - 1)\">{{getText('previous')}}</a></li>\n" +
" <li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active}\"><a href ng-click=\"selectPage(page.number)\">{{page.text}}</a></li>\n" +
" <li ng-if=\"directionLinks\" ng-class=\"{disabled: noNext()}\"><a href ng-click=\"selectPage(page + 1)\">{{getText('next')}}</a></li>\n" +
" <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noNext()}\"><a href ng-click=\"selectPage(totalPages)\">{{getText('last')}}</a></li>\n" +
"</ul>");
}]);
angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html",
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" bind-html-unsafe=\"content\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tooltip/tooltip-popup.html",
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/popover/popover.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-bind=\"content\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/progressbar/bar.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/progressbar/bar.html",
"<div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: percent + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" ng-transclude></div>");
}]);
angular.module("template/progressbar/progress.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/progressbar/progress.html",
"<div class=\"progress\" ng-transclude></div>");
}]);
angular.module("template/progressbar/progressbar.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/progressbar/progressbar.html",
"<div class=\"progress\">\n" +
" <div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: percent + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" ng-transclude></div>\n" +
"</div>");
}]);
angular.module("template/rating/rating.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/rating/rating.html",
"<span ng-mouseleave=\"reset()\" ng-keydown=\"onKeydown($event)\" tabindex=\"0\" role=\"slider\" aria-valuemin=\"0\" aria-valuemax=\"{{range.length}}\" aria-valuenow=\"{{value}}\">\n" +
" <i ng-repeat=\"r in range track by $index\" ng-mouseenter=\"enter($index + 1)\" ng-click=\"rate($index + 1)\" class=\"glyphicon\" ng-class=\"$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')\">\n" +
" <span class=\"sr-only\">({{ $index < value ? '*' : ' ' }})</span>\n" +
" </i>\n" +
"</span>");
}]);
angular.module("template/tabs/tab.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tabs/tab.html",
"<li ng-class=\"{active: active, disabled: disabled}\">\n" +
" <a href ng-click=\"select()\" tab-heading-transclude>{{heading}}</a>\n" +
"</li>\n" +
"");
}]);
angular.module("template/tabs/tabset.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tabs/tabset.html",
"<div>\n" +
" <ul class=\"nav nav-{{type || 'tabs'}}\" ng-class=\"{'nav-stacked': vertical, 'nav-justified': justified}\" ng-transclude></ul>\n" +
" <div class=\"tab-content\">\n" +
" <div class=\"tab-pane\" \n" +
" ng-repeat=\"tab in tabs\" \n" +
" ng-class=\"{active: tab.active}\"\n" +
" tab-content-transclude=\"tab\">\n" +
" </div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/timepicker/timepicker.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/timepicker/timepicker.html",
"<table>\n" +
" <tbody>\n" +
" <tr class=\"text-center\">\n" +
" <td><a ng-click=\"incrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td> </td>\n" +
" <td><a ng-click=\"incrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
" <td ng-show=\"showMeridian\"></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td style=\"width:50px;\" class=\"form-group\" ng-class=\"{'has-error': invalidHours}\">\n" +
" <input type=\"text\" ng-model=\"hours\" ng-change=\"updateHours()\" class=\"form-control text-center\" ng-mousewheel=\"incrementHours()\" ng-readonly=\"readonlyInput\" maxlength=\"2\">\n" +
" </td>\n" +
" <td>:</td>\n" +
" <td style=\"width:50px;\" class=\"form-group\" ng-class=\"{'has-error': invalidMinutes}\">\n" +
" <input type=\"text\" ng-model=\"minutes\" ng-change=\"updateMinutes()\" class=\"form-control text-center\" ng-readonly=\"readonlyInput\" maxlength=\"2\">\n" +
" </td>\n" +
" <td ng-show=\"showMeridian\"><button type=\"button\" class=\"btn btn-default text-center\" ng-click=\"toggleMeridian()\">{{meridian}}</button></td>\n" +
" </tr>\n" +
" <tr class=\"text-center\">\n" +
" <td><a ng-click=\"decrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td> </td>\n" +
" <td><a ng-click=\"decrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
" <td ng-show=\"showMeridian\"></td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"");
}]);
angular.module("template/typeahead/typeahead-match.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/typeahead/typeahead-match.html",
"<a tabindex=\"-1\" bind-html-unsafe=\"match.label | typeaheadHighlight:query\"></a>");
}]);
angular.module("template/typeahead/typeahead-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/typeahead/typeahead-popup.html",
"<ul class=\"dropdown-menu\" ng-show=\"isOpen()\" ng-style=\"{top: position.top+'px', left: position.left+'px'}\" style=\"display: block;\" role=\"listbox\" aria-hidden=\"{{!isOpen()}}\">\n" +
" <li ng-repeat=\"match in matches track by $index\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index)\" role=\"option\" id=\"{{match.id}}\">\n" +
" <div typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
" </li>\n" +
"</ul>\n" +
"");
}]); | JavaScript |
function G() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
var guid = (G() + G() + "-" + G() + "-" + G() + "-" + G() + "-" + G() + G() + G())
.toUpperCase();
function init() {
// Listen for search results from backend
chrome.extension.onConnect.addListener(function(port) {
if (port.name != "uiToBackend") {
console.log("Invalid port name: " + port.name);
return;
}
port.onMessage.addListener(function(result) {
processSearchResult(result);
});
});
localStorage['uivisits']++;
/* stop showing tip after 2 UI visits */
// if (localStorage['uivisits'] < 4)
// $('#welcomesearchbox').append(
// '<div id="tiparea"><p><b>Tip:</b> Use the "*". '
// + 'For example, to search for words beginning '
// + 'with "mar", simply type "mar*".</div>');
if (localStorage['uivisits'] == 3)
$('#tiparea').delay(3000).fadeOut('slow', function() {
});
$('#searchbox').focus();
$('#searchbox').keyup(function(e) {
if (e.keyCode == 13) {
leavePage('#welcomepage');
}
});
}
function initfromCr() { //init directly from Chrome Omnibox
chrome.extension.onConnect.addListener(function(port) {
if (port.name != "uiToBackend") {
console.log("Invalid port name:" + port.name);
return;
}
port.onMessage.addListener(function(result) {
processSearchResult(result);
});
});
}
// Send request to backend for displaying a cached bookmark page
function requestCachedPage(id) {
chrome.extension.sendRequest({
method : 'cached',
pageid : id
}, function() {
});
}
var type = 1;
var extensionid = chrome.runtime.id;
var dst_url = "chrome-extension://" + extensionid + "/SearchMarkUI.html";
var searchbtnid = "'#searchbutton'";
var searchbtneffect = "'searchbuttonpressed'";
var resultspagename = "'#resultspage'";
// Take keywords from text box and send to
// backend for searching.
function doSearch(searchwords) {
//empty body
if (type == 1) {
var results_page_top_html = '<div id="topsearch">'
+ '<table><tr>'
//+ '<th id = "thlogo"><img src="images/logotext-results.png"/></th>'
+ '<!-- search box -->'
+ '<th id = "thsearchbox"><input type="text" id="searchbox"'
+ 'class="searchboxresult" style="float:center"/>'
+ '<!-- search button -->'
+ '<button type="button" id= "searchbutton" class="searchbutton"'
+ '>' + "Search in Bookmark" + '</button></th>'
+ '</tr></table>' + '</div>';
}
else if (type == 2) {
var results_page_top_html = '<div id="topsearch">'
+ '<table><tr>'
//+ '<th id = "thlogo"><img src="images/logotext-results.png"/></th>'
+ '<!-- search box -->'
+ '<th id = "thsearchbox"><input type="text" id="searchbox"'
+ 'class="searchboxresult"/>'
+ '<!-- search button -->'
+ '<button type="button" id= "searchbutton" class="searchbutton"'
+ '>' + "Search in History" + '</button></th>'
+ '</tr></table>' + '</div>';
}
//alert(results_page_top_html);
$('body').empty();
$('body').append('<div id = "resultspage"></div>');
$('#resultspage').append(results_page_top_html);
var iconUrl = chrome.extension.getURL("images/loading_gif.gif");
var img = '<div align="center" id="resultLoading"><img src="' + iconUrl
+ '" /></div>';
$('#resultspage').append('<div id="resultspagebtm">').append(img).append(
'</div>');
chrome.extension.sendRequest({
method : 'search',
keywords : searchwords,
searchtype : type,
tab : guid
}, function() {
});
var sb = document.getElementById('searchbutton');
if (type == 1) {
sb.addEventListener('mousedown', mousedown);
sb.addEventListener('mouseup', mouseup);
} else if (type == 2) {
sb.addEventListener('mousedown', mousedownsettype);
sb.addEventListener('mouseup', mouseup);
}
}
function leavePage(pagename) {
var searchwords = $('#searchbox').val();
$(pagename).remove();
$('body').css('cursor', 'wait');
doSearch(searchwords);
}
// Each search result will be delivered here.
// result object has fields,
// result.url: page URL
// result.text: formatted page text, or URL
// result.title: page title
// result.matchType: 'title', 'url', or 'page'
// If the title matched, then result.text will be
// empty. if URL matched, then result.text will be
// a formatted URL (keyword is in bold face), if
// page text matched, then result.text will contain
// textual context.
function processSearchResult(result) {
$('#resultLoading').remove();
var nopage = "nopage|" + guid;
var resultString = "";
if (result.matchType == nopage) {
var iconUrl = chrome.extension.getURL("images/failed_search.png");
resultString = '<div align="center"><img src="' + iconUrl
+ '" /></div>';
} else if (result.matchType == ("DONE|" + guid)) {
$('body').css('cursor', 'auto');
// search error?
if (result.error) {
resultString = result.error;
} else {
resultString = " ";
}
$('#searchbox').focus();
$('#searchbox').keyup(function(e) {
if (e.keyCode == 13) {
leavePage('#resultspage');
}
});
} else if (result.matchType == ("page|" + guid)) {
if (result.title == "")
result.title = result.url;
resultString = '<a href="'
+ result.url
+ '" target="_blank">'
+ result.title
+ '</a>'
+ '<br/>'
+ result.text
+ '<br/>'
+ '<span class="resulturl">'
+ result.url
+ '</span> '
+ '<a href="#" class="resultactions" onclick="requestCachedPage('
+ result.id + ');">(Offline Version)</a><p><br/>';
}
$('#resultspagebtm').append(resultString);
}
document.addEventListener('DOMContentLoaded', function() {
var sb1 = document.getElementById('searchbutton1');
sb1.addEventListener('mousedown', mousedown);
sb1.addEventListener('mouseup', mouseup);
var sb2 = document.getElementById('searchbutton2');
sb2.addEventListener('mousedown', mousedownsettype);
sb2.addEventListener('mouseup', mouseup);
if (dst_url != window.location.href) {
getOmnixboxUrl();
} else {
init();
}
});
function getOmnixboxUrl() {
var url = window.location.href;
var regUrl = new RegExp(dst_url + "?[^\s]");
if (url.match(regUrl)) {
var index = url.indexOf("?");
var typekeyword = url.substr(index + 1);
var index_tk = typekeyword.indexOf(":");
type = typekeyword.substr(0, index_tk);
var keyword = typekeyword.substr(index_tk + 1);
initfromCr();
doSearch(keyword);
}
}
function mouseup() {
$('#searchbutton').removeClass('searchbuttonpressed');
leavePage('#welcomepage');
}
function mousedown() {
type = 1;
$('#searchbutton').addClass('searchbuttonpressed');
}
function mousedownsettype() {
type = 2;
$('#searchbutton').addClass('searchbuttonpressed');
}
| JavaScript |
function load() {
//var selectedElement = document.getElementById('selected');
//var sel = window.getSelection();
//sel.removeAllRanges();
//var range = document.createRange();
//range.selectNode(selectedElement);
//sel.addRange(range);
var rateElement = document.getElementById('rate');
var pitchElement = document.getElementById('pitch');
var volumeElement = document.getElementById('volume');
var rate = localStorage['rate'] || 1.0;
var pitch = localStorage['pitch'] || 1.0;
var volume = localStorage['volume'] || 1.0;
rateElement.value = rate;
pitchElement.value = pitch;
volumeElement.value = volume;
function listener(evt) {
rate = rateElement.value;
localStorage['rate'] = rate;
pitch = pitchElement.value;
localStorage['pitch'] = pitch;
volume = volumeElement.value;
localStorage['volume'] = volume;
}
rateElement.addEventListener('keyup', listener, false);
pitchElement.addEventListener('keyup', listener, false);
volumeElement.addEventListener('keyup', listener, false);
rateElement.addEventListener('mouseup', listener, false);
pitchElement.addEventListener('mouseup', listener, false);
volumeElement.addEventListener('mouseup', listener, false);
var defaultsButton = document.getElementById('defaults');
defaultsButton.addEventListener('click', function(evt) {
rate = 1.0;
pitch = 1.0;
volume = 1.0;
localStorage['rate'] = rate;
localStorage['pitch'] = pitch;
localStorage['volume'] = volume;
rateElement.value = rate;
pitchElement.value = pitch;
volumeElement.value = volume;
}, false);
var testButton = document.getElementById('test');
testButton.addEventListener('click', function(evt) {
chrome.tts.speak(
'Testing speech synthesis',
{voiceName: localStorage['voice'],
rate: parseFloat(rate),
pitch: parseFloat(pitch),
volume: parseFloat(volume)});
});
}
document.addEventListener('DOMContentLoaded', load);
| JavaScript |
$("#login").submit(
var self=$(this),
mail = self.find('input[name=mail]'),
password = self.find('input[name=password]'),
mail_val = ma il.val(),
password_val = password.val()
;
if(!mail_val){
mail.focus();
return false
}
if(!password_val){
password.focus()
return false
}
$.phone(
this.action,
{
password:password,
mail:mail
},function (o){
if(o.error)
alert(o.error);
mail.focus().select()
}
)
return false;
) | JavaScript |
$(document).ready(function(){
//welcome page
setTimeout(function(){
$('#welcomePage').fadeOut(500,function(){
$('#phoneIndex').show();
});
},1500);
//从Index进入AccountList
$('#phoneIndexFooter').click(function(){
$('#phoneIndex').fadeOut(800,function(){
$('#phoneAccountList').fadeIn(500);
});
});
//从AccountList 返回 Index
$('span.accountListTopBarBack').click(function(){
$('#phoneAccountList').fadeOut(800,function(){
$('#phoneIndex').fadeIn(500);
});
});
//从AccountList进入Login
$('.accountList').click(function(){
var rel = $(this).attr('rel');
var tit = $(this).children('.accountListTit').html();
$("#loginForm").attr('action', $("#loginForm").attr('action') + rel + '/' );
$('#phoneAccountList').fadeOut(500,function(){
$('#phoneLogin').fadeIn(400);
$('.phoneLoginTopBarTit').html( tit );
});
});
//从Login 返回 AccountList
$('span.phoneLoginTopBarBack').click(function(){
$('#phoneLogin').fadeOut(500,function(){
$('#phoneAccountList').fadeIn(400);
});
});
//form label
$('.inputList label').click(function(){
$(this).fadeOut();
$(this).next().focus();
});
$('.inputList input').keyup(function(){
if( $.trim( $(this).val() ) != ''){
$(this).prev().fadeOut();
}else{
$(this).prev().fadeIn();
}
});
$('.inputList input').blur(function(){
if($.trim( $(this).val() )==''){
$(this).prev().fadeIn();
}
});
//提交表单
$("#loginForm").submit(function(){
var self=$(this),
mail = self.find('input[name=phoneEmail]'),
password = self.find('input[name=phonePwd]'),
mail_val = mail.val(),
password_val = password.val()
;
if(!mail_val){
mail.focus();
return false
}
if(!password_val){
password.focus()
return false
}
$.phone(
this.action,
{
password:password,
mail:mail
},function (o){
if(o.error)
alert(o.error);
mail.focus().select()
}
)
return false;
});
});
| JavaScript |
var mClassify = null,
sClassify = null;
$(document).ready(function(){
$('.container div.taskList').mousedown(function(){
$(this).css('background','orange');
});
$('.container div.taskList').mouseup(function(){
$(this).css('background','');
});
})
| JavaScript |
$(document).ready(function(){
document.onclick = function (event){
var e = event || window.event;
var elem = e.srcElement||e.target;
while(elem){
if(elem.id == "more"){
return;
}
elem = elem.parentNode;
}
//隐藏account下拉菜单
$('.more').animate({
marginLeft: '0px'
}, 500,function(){
$(this).removeClass('moreClose');
});
}
$('.navBarList').click(function(){
//alert($(this).attr('rel'))
//如果点击的是current导航直接无视
if( $(this).children('.navBarStation').hasClass('navOn') ){
return false;
}
//切换显示导航条底部 current 标识
$('.navBarStation').removeClass('navOn');
$(this).children('.navBarStation').addClass('navOn');
});
//more
$('.more').click(function(){
if( $(this).css('margin-left') == '0px' ){
$(this).animate({
marginLeft: '100px'
}, 500,function(){
$(this).addClass('moreClose');
});
}else{
$(this).animate({
marginLeft: '0px'
}, 500,function(){
$(this).removeClass('moreClose');
});
}
});
});
| JavaScript |
__PHONE_CALLBACK = {}
$.extend({
phone : function(url, data, callback){
if ( jQuery.isFunction( data ) ) {
callback = data;
data = undefined;
}
if(callback){
var __callback = data['__callback'] = (""+ Math.random()).slice(2)+$.now();
__PHONE_CALLBACK[__callback] = function(response){
callback(response)
delete __PHONE_CALLBACK[__callback];
}
}
document.location = "$://"+url+'?'+JSON.stringify(data);
}
})
| JavaScript |
document.createElement('header');
document.createElement('nav');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');
document.createElement('hgroup');
$(document).ready(function () {
$('.section-content,#status-container').addClass('ie8-background');
$('.category-separator').hide();
}); | JavaScript |
(function () {
//var host = "192.168.0.100",
var host = window.location.hostname,
// Encapsulation of the vlc plugin
Stream = function (object,type,callbacks) {
var restarting = false, starting = false, error = false, restartTimer, startTimer,
// Register an event listener
registerEvent = function (object, event, handler) {
if (object.attachEvent) {
object.attachEvent (event, handler);
} else if (object.addEventListener) {
object.addEventListener (event, handler, false);
} else {
object["on" + event] = handler;
}
},
// Indicates if the camera/microphone is currently being used
inUse = function (callback) {
$.post('request.json',JSON.stringify({'action':'state'}),function (json) {
if (type==='audio') callback(json.state.microphoneInUse==='true');
else callback(json.state.cameraInUse==='true');
});
};
registerEvent(object,'MediaPlayerEncounteredError',function (event) {
error = true;
if (restarting) {
clearInterval(restartTimer);
restarting = false;
}
if (starting) {
clearInterval(startTimer);
starting = false;
}
callbacks.onError(type);
});
return {
restart: function () {
if (!restarting) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
// We wait 2 secs and restart the stream
restarting = true;
restartTimer = setInterval(function () {
inUse(function (b) {
if (!b) {
this.start();
clearInterval(restartTimer);
}
}.bind(this));
}.bind(this),1000);
}
},
start: function () {
if (!object.playlist.isPlaying) {
starting = true;
error = false;
startTimer = setInterval(function () {
if (object.playlist.isPlaying) {
console.log("STARTED !");
restarting = false;
starting = false;
clearInterval(startTimer);
}
},300);
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
var item = generateURI(host,type);
object.playlist.add(type==='video'?item.uriv:item.uria,'',item.params);
object.playlist.playItem(0);
}
},
stop: function () {
error = false;
if (restarting) {
clearInterval(restartTimer);
restarting = false;
}
if (starting) {
clearInterval(startTimer);
starting = false;
}
if (object.playlist.isPlaying) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
}
},
getState: function() {
if (restarting) return 'restarting';
else if (starting) return 'starting'
else if (object.playlist.isPlaying) return 'streaming';
else if (error) return 'error';
else return 'idle';
},
isStreaming: function () {
return object.playlist.isPlaying;
}
}
},
generateURI = function (h,type) {
var audioEncoder, videoEncoder, cache, rotation, flash, camera, res;
// Audio conf
if ($('#audioEnabled').prop('checked')) {
audioEncoder = $('#audioEncoder').val()=='AMR-NB'?'amr':'aac';
} else {
audioEncoder = "nosound";
}
// Resolution
res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
// Video conf
if ($('#videoEnabled').prop('checked')) {
videoEncoder = ($('#videoEncoder').val()=='H.263'?'h263':'h264')+'='+
/[0-9]+/.exec($('#bitrate').val())[0]+'-'+
/[0-9]+/.exec($('#framerate').val())[0]+'-';
videoEncoder += res[1]+'-'+res[2];
} else {
videoEncoder = "novideo";
}
// Flash
if ($('#flashEnabled').val()==='1') flash = 'on'; else flash = 'off';
// Camera
camera = $('#cameraId').val();
// Params
cache = /[0-9]+/.exec($('#cache').val())[0];
return {
uria:"rtsp://"+h+":"+8086+"?"+audioEncoder,
uriv:"rtsp://"+h+":"+8086+"?"+videoEncoder+'&flash='+flash+'&camera='+camera,
params:[':network-caching='+cache]
}
},
testActivxAndMozillaPlugin = function () {
// TODO: console.log(object.VersionInfo);
// Test if the activx plugin is installed
if (typeof $('#xvlcv')[0].playlist != "undefined") {
return 1;
} else {
$('#xvlcv').css('display','none');
$('#vlcv').css('display','block');
}
// Test if the mozilla plugin is installed
if (typeof $('#vlca')[0].playlist == "undefined") {
// Plugin not detected, alert user !
$('#glass').fadeIn(1000);
$('#error-noplugin').fadeIn(1000);
return 0;
} else {
return 2;
}
},
loadSoundsList = function (sounds) {
var list = $('#soundslist'), category, name;
sounds.forEach(function (e) {
category = e.match(/([a-z0-9]+)_/)[1];
name = e.match(/[a-z0-9]+_([a-z0-9_]+)/)[1];
if ($('.category.'+category).length==0) list.append(
'<div class="category '+category+'"><span class="category-name">'+category+'</span><div class="category-separator"></div></div>'
);
$('.category.'+category).append('<div class="sound" id="'+e+'"><a>'+name.replace(/_/g,' ')+'</a></div>');
});
},
testScreenState = function (screenState) {
if (screenState==0) {
$('#error-screenoff').fadeIn(1000);
$('#glass').fadeIn(1000);
}
},
updateTooltip = function (title) {
$('#tooltip>div').hide();
$('#tooltip #'+title).show();
},
videoStream, videoPlugin, audioStream, oldVideoState = 'idle',oldAudioState = 'idle', lastError = 0,
updateStatus = function () {
var status = $('#status'), button = $('#connect>div>h1'), cover = $('#vlc-container #upper-layer'), error;
if (videoStream.getState()===oldVideoState && audioStream.getState()===oldAudioState && lastError===0) return;
// STATUS
if (videoStream.getState()==='starting' || videoStream.getState()==='restarting' ||
audioStream.getState()==='starting' || audioStream.getState()==='restarting') {
status.html(__('Trying to connect...'))
} else {
if (!videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('NOT CONNECTED'));
else if (videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('Streaming video but not audio'));
else if (!videoStream.isStreaming() && audioStream.isStreaming()) status.html(__('Streaming audio but not video'));
else status.html(__('Streaming audio and video'));
}
// BUTTON
if ((videoStream.getState()==='idle' || videoStream.getState()==='error') &&
(audioStream.getState()==='idle' || audioStream.getState()==='error')) {
button.html(__('Connect !!'));
} else button.text(__('Disconnect ?!'));
// WINDOW
if (lastError!==0) {
videoPlugin.css('visibility','hidden');
if (lastError===1) error = __('Retrieving error message...');
else if (lastError===2) error = __('Connection timed out !');
else if (lastError===0 || lastError===undefined) error = "";
else error = lastError;
lastError = 0;
cover.html('<div id="wrapper"><h1>'+__('An error occurred')+' :(</h1><p>'+error+'</p></div>');
} else if (videoStream.getState()==='restarting' || audioStream.getState()==='restarting') {
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('UPDATING SETTINGS')+'</h1></div>').show();
} else if (videoStream.getState()==='streaming') {
videoPlugin.css('visibility','inherit');
cover.hide();
}
if (videoStream.getState()==='idle') {
if (audioStream.getState()==='streaming') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/speaker.png") center no-repeat').show();
} else if (audioStream.getState()==='idle') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/eye.png") center no-repeat').show();
}
}
oldVideoState = videoStream.getState();
oldAudioState = audioStream.getState();
},
// Called when an error occurs in spydroid
onError = function (type) {
lastError = 1;
$.ajax({type: 'POST', url: 'request.json',data: "[{'action':'state'},{'action':'clear'}]",
success: function (json) {
lastError = json.state.lastError;
try {
if (json.lastStackTrace.match("RuntimeException.+MediaStream.start")) {
// If a start failed happened we display additional information
lastError += "<br /><br />"+__("This generally happens when you are trying to use settings that are not supported by your phone.");
$("#quality").click();
}
} catch (ignore) {}
if (json.activityPaused==='0' && type==='video') {
testScreenState(0);
}
},
error: function () {
lastError = 2;
},
timeout: 1500
});
if (videoStream.getState()!=='error') videoStream.stop();
if (audioStream.getState()!=='error') audioStream.stop();
},
refreshBatteryLevel = function (level) {
$('#battery>#level').text(level);
setTimeout(function () {
$.ajax({type: 'POST', url: 'request.json',data: "[{'action':'battery'}]",
success: function (json) {
refreshBatteryLevel(json.battery);
},
error: function () {
refreshBatteryLevel('?');
}
});
},50000);
},
fetchSettings = function (config) {
$('#resolution,#framerate,#bitrate,#audioEncoder,#videoEncoder').children().each(function (c) {
if ($(this).val()===config.videoResolution ||
$(this).val()===config.videoFramerate ||
$(this).val()===config.videoBitrate ||
$(this).val()===config.audioEncoder ||
$(this).val()===config.videoEncoder ) {
$(this).parent().children().prop('selected',false);
$(this).prop('selected',true);
}
});
if (config.streamAudio===false) $('#audioEnabled').prop('checked',false);
if (config.streamVideo===false) $('#videoEnabled').prop('checked',false);
},
saveSettings = function () {
var res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
var videoQuality = /[0-9]+/.exec($('#bitrate').val())[0]+'-'+/[0-9]+/.exec($('#framerate').val())[0]+'-'+res[1]+'-'+res[2];
var settings = {
'stream_video': $('#videoEnabled').prop('checked')===true,
'stream_audio': $('#audioEnabled').prop('checked')===true,
'video_encoder': $('#videoEncoder').val(),
'audio_encoder': $('#audioEncoder').val(),
'video_quality': videoQuality
};
$.post('request.json',JSON.stringify({'action':'set','settings':settings}));
},
// Disable input for one sec to prevent user from flooding the RTSP server by clicking around too quickly
disableAndEnable = function (input) {
input.prop('disabled',true);
setTimeout(function () {
input.prop('disabled',false);
},1000);
},
setupEvents = function () {
var audioPlugin, test,
cover = $('#vlc-container #upper-layer'),
status = $('#status'),
button = $('#connect>div>h1');
$('.popup').each(function () {
$(this).css({'top':($(window).height()-$(this).height())/2,'left':($(window).width()-$(this).width())/2});
});
$('.popup #close').click(function (){
$('#glass').fadeOut();
$('.popup').fadeOut();
});
test = testActivxAndMozillaPlugin();
if (test===1) {
// Activx plugin detected
videoPlugin = $('#xvlcv');
audioPlugin = $('#xvlca');
} else if (test===2) {
// Mozilla plugin detected
videoPlugin = $('#vlcv');
audioPlugin = $('#vlca');
} else {
// No plugin installed, spydroid probably won't work
// We assume the Mozilla plugin is installed, just in case :/
videoPlugin = $('#vlcv');
audioPlugin = $('#vlca');
}
videoStream = Stream(videoPlugin[0],'video',{onError:function (type) {
onError(type);
}});
audioStream = Stream(audioPlugin[0],'audio',{onError:function (type) {
onError(type);
}});
setInterval(function () {updateStatus();},400);
$('#connect').click(function () {
if ($(this).prop('disabled')===true) return;
disableAndEnable($(this));
if ((videoStream.getState()!=='idle' && videoStream.getState()!=='error') ||
(audioStream.getState()!=='idle' && audioStream.getState()!=='error')) {
videoStream.stop();
audioStream.stop();
} else {
if (!$('#videoEnabled').prop('checked') && !$('#audioEnabled').prop('checked')) return;
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('CONNECTION')+'</h1></div>').show();
if ($('#videoEnabled').prop('checked')) videoStream.start(); else videoStream.stop();
if ($('#audioEnabled').prop('checked')) audioStream.start();
updateStatus();
}
});
$('#torch-button').click(function () {
if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return;
disableAndEnable($(this));
if ($('#flashEnabled').val()=='0') {
$('#flashEnabled').val('1');
$(this).addClass('torch-on');
} else {
$('#flashEnabled').val('0');
$(this).removeClass('torch-on');
}
if (videoStream.getState()==='streaming') videoStream.restart();
});
$('#buzz-button').click(function () {
$(this).animate({'padding-left':'+=10'}, 40, 'linear')
.animate({'padding-left':'-=20'}, 80, 'linear')
.animate({'padding-left':'+=10'}, 40, 'linear');
$.post('request.json',"[{'action':'buzz'}]");
});
$(document).on('click', '.camera-not-selected', function () {
if ($(this).prop('disabled')!==true || videoStream.getState()==='starting') return;
$('#cameras span').addClass('camera-not-selected');
$(this).removeClass('camera-not-selected');
disableAndEnable($('.camera-not-selected'));
$('#cameraId').val($(this).attr('data-id'));
if (videoStream.getState()==='streaming') videoStream.restart();
})
$('.audio select').change(function () {
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('.audio input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#audioEnabled').prop('checked')) audioStream.restart(); else audioStream.stop();
disableAndEnable($(this));
}
});
$('.video select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
});
$('.video input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#videoEnabled').prop('checked')) videoStream.restart(); else videoStream.stop();
disableAndEnable($(this));
}
});
$('.cache select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('select,input').change(function () {
saveSettings();
});
$('.section').click(function () {
$('.section').removeClass('selected');
$(this).addClass('selected');
updateTooltip($(this).attr('id'));
});
$(document).on('click', '.sound', function () {
$.post('request.json',JSON.stringify({'action':'play','name':$(this).attr('id')}));
});
$('#fullscreen').click(function () {
videoPlugin[0].video.toggleFullscreen();
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
videoPlugin[0].video.toggleFullscreen();
}
});
$('#hide-tooltip').click(function () {
$('body').width($('body').width() - $('#tooltip').width());
$('#tooltip').hide();
$('#need-help').show();
});
$('#tooltip').hide();
$('#need-help').show();
$('#need-help').click(function () {
$('body').width($('body').width() + $('#tooltip').width());
$('#tooltip').show();
$('#need-help').hide();
});
};
$(document).ready(function () {
$.post('request.json',"[{'action':'sounds'},{'action':'screen'},{'action':'get'},{'action':'battery'}]", function (data) {
// Verify that the screen is not turned off
testScreenState(data.screen);
// Fetch the list of sounds available on the phone
loadSoundsList(data.sounds);
// Retrieve the configuration of Spydroid on the phone
fetchSettings(data.get);
// Retrieve battery level
refreshBatteryLevel(data.battery);
});
// Translate the interface in the appropriate language
$('h1,h2,h3,span,p,a,em').translate();
// Bind DOM events to the js API
setupEvents();
});
}());
| JavaScript |
(function () {
var translations = {
en: {
1:"About",
2:"Return",
3:"Change quality settings",
4:"Flash/Vibrator",
5:"Click on the torch to enable or disable the flash",
6:"Play a prerecorded sound",
7:"Connect !!",
8:"Disconnect ?!",
9:"STATUS",
10:"NOT CONNECTED",
11:"ERROR :(",
12:"CONNECTION",
13:"UPDATING SETTINGS",
14:"CONNECTED",
15:"Show some tips",
16:"Hide those tips",
17:"Those buttons will trigger sounds on your phone...",
18:"Use them to surprise your victim.",
19:"Or you could use this to surprise your victim !",
20:"This will simply toggle the led in front of you're phone, so that even in the deepest darkness, you will not be blind...",
21:"If the stream is choppy, try reducing the bitrate or increasing the cache size.",
22:"Try it instead of H.263 if video streaming is not working at all !",
23:"The H.264 compression algorithm is more efficient but may not work on your phone...",
24:"You need to install VLC first !",
25:"During the installation make sure to check the firefox plugin !",
26:"Close",
27:"You must leave the screen of your smartphone on !",
28:"Front facing camera",
29:"Back facing camera",
30:"Switch between cameras",
31:"Streaming video but not audio",
32:"Streaming audio but not video",
33:"Streaming audio and video",
34:"Trying to connect...",
35:"Stream sound",
36:"Stream video",
37:"Fullscreen",
38:"Encoder",
39:"Resolution",
40:"Cache size",
41:"This generally happens when you are trying to use settings that are not supported by your phone.",
42:"Retrieving error message...",
43:"An error occurred",
44:"Click on the phone to make your phone buzz"
},
fr: {
1:"À propos",
2:"Retour",
3:"Changer la qualité du stream",
4:"Flash/Vibreur",
5:"Clique sur l'ampoule pour activer ou désactiver le flash",
6:"Jouer un son préenregistré",
7:"Connexion !!",
8:"Déconnecter ?!",
9:"STATUT",
10:"DÉCONNECTÉ",
11:"ERREUR :(",
12:"CONNEXION",
13:"M.A.J.",
14:"CONNECTÉ",
15:"Afficher l'aide",
16:"Masquer l'aide",
17:"Clique sur un de ces boutons pour lancer un son préenregistré sur ton smartphone !",
18:"Utilise les pour surprendre ta victime !!",
19:"Ça peut aussi servir à surprendre ta victime !",
20:"Clique sur l'ampoule pour allumer le flash de ton smartphone",
21:"Si le stream est saccadé essaye de réduire le bitrate ou d'augmenter la taille du cache.",
22:"Essaye le à la place du H.263 si le streaming de la vidéo ne marche pas du tout !",
23:"Le H.264 est un algo plus efficace pour compresser la vidéo mais il a moins de chance de marcher sur ton smartphone...",
24:"Tu dois d'abord installer VLC !!",
25:"Pendant l'installation laisse cochée l'option plugin mozilla !",
26:"Fermer",
27:"Tu dois laisser l'écran de ton smartphone allumé",
28:"Caméra face avant",
29:"Caméra face arrière",
30:"Choisir la caméra",
31:"Streaming de la vidéo",
32:"Streaming de l'audio",
33:"Streaming de l'audio et de la vidéo",
34:"Connexion en cours...",
35:"Streaming du son",
36:"Streaming de la vidéo",
37:"Plein écran",
38:"Encodeur",
39:"Résolution",
40:"Taille cache",
41:"En général, cette erreur se produit quand les paramètres sélectionnés ne sont pas compatibles avec le smartphone.",
42:"Attente du message d'erreur...",
43:"Une erreur s'est produite",
44:"Clique pour faire vibrer ton tel."
},
ru: {
1:"Спасибо",
2:"Вернуться",
3:"Изменить настройки качества",
4:"Переключатель вспышки",
5:"Нажмите здесь, чтобы включить или выключить вспышку",
6:"Проиграть звук на телефоне",
7:"Подключиться !!",
8:"Отключиться ?!",
9:"СОСТОЯНИЕ",
10:"НЕТ ПОДКЛЮЧЕНИЯ",
11:"ОШИБКА :(",
12:"ПОДКЛЮЧЕНИЕ",
13:"ОБНОВЛЕНИЕ НАСТРОЕК",
14:"ПОДКЛЮЧЕНО",
15:"Показать поясняющие советы",
16:"Спрятать эти советы",
17:"Эти кнопки будут проигрывать звуки на вашем телефоне...",
18:"Используйте их, чтобы удивить вашу жертву.",
19:"Или вы можете удивить свою жертву!",
20:"Это переключатель режима подсветки на передней части вашего телефона, так что даже в самой кромешной тьме, вы не будете слепы ...",
21:"Если поток прерывается, попробуйте уменьшить битрейт или увеличив размер кэша.",
22:"Если топоковое видео не работает совсем, попробуйте сжатие Н.263",
23:"Алгоритм сжатия H.264, является более эффективным, но может не работать на вашем телефоне ...",
24:"Вначале Вам необходимо установить VLC !",
25:"При установке убедитесь в наличии плагина для firefox !",
26:"Закрыть",
27:"Вам надо отойти от вашего смартфона.",
28:"Фронтальная камера",
29:"Камера с обратной стороны",
30:"Переключиться на другую камеру",
31:"Передача видео без звука",
32:"Передача звука без видео",
33:"Передача звука и видео",
34:"Пытаемся подключится",
35:"Аудио поток",
36:"Видео поток",
37:"На весь экран",
38:"Кодек",
39:"Разрешение",
40:"Размер кеша",
41:"Как правило, это происходит, когда вы пытаетесь использовать настройки, не поддерживаемые вашим телефоном.",
42:"Получение сообщения об ошибке ..."
},
de : {
1:"Apropos",
2:"Zurück",
3:"Qualität des Streams verändern",
4:"Fotolicht ein/aus",
5:"Klick die Glühbirne an, um das Fotolicht einzuschalten oder azufallen",
6:"Vereinbarten Ton spielen",
7:"Verbindung !!",
8:"Verbinden ?!",
9:"STATUS",
10:"NICHT VERBUNDEN",
11:"FEHLER :(",
12:"VERBINDUNG",
13:"UPDATE",
14:"VERBUNDEN",
15:"Hilfe anzeigen",
16:"Hilfe ausblenden",
17:"Klick diese Tasten an, um Töne auf deinem Smartphone spielen zu lassen !",
18:"Benutz sie, um deine Opfer zu überraschen !!",
19:"Das kann auch dein Opfer erschrecken !",
20:"Es wird die LED hinter deinem Handy anmachen, damit du nie blind bleibst, auch im tiefsten Dunkeln",
21:"Wenn das Stream ruckartig ist, versuch mal die Bitrate zu reduzieren oder die Größe vom Cache zu steigern.",
22:"Probier es ansatt H.263, wenn das Videostream überhaupt nicht funktionert !",
23:"Der H.264 Kompressionalgorithmus ist effizienter aber er wird auf deinem Handy vielleicht nicht funktionieren...",
24:"Du musst zuerst VLC installieren !!",
25:"Während der Installation, prüfe dass das Firefox plugin abgecheckt ist!",
26:"Zumachen",
27:"Du musst den Bildschirm deines Smartphones eingeschaltet lassen !",
28:"Frontkamera",
29:"Rückkamera",
30:"Kamera auswählen",
31:"Videostreaming",
32:"Audiostreaming",
33:"Video- und Audiostreaming",
34:"Ausstehende Verbindung...",
35:"Soundstreaming",
36:"Videostreaming",
37:"Ganzer Bildschirm",
38:"Encoder",
39:"Auflösung",
40:"Cachegröße",
41:"Dieser Fehler gescheht überhaupt, wenn die gewählten Einstellungen mit dem Smartphone nicht kompatibel sind.",
42:"Es wird auf die Fehlermeldung gewartet...",
43:"Ein Fehler ist geschehen..."
}
};
var lang = window.navigator.userLanguage || window.navigator.language;
//var lang = "ru";
var __ = function (text) {
var x,y=0,z;
if (lang.match(/en/i)!=null) return text;
for (x in translations) {
if (lang.match(new RegExp(x,"i"))!=null) {
for (z in translations.en) {
if (text==translations.en[z]) {
y = z;
break;
}
}
return translations[x][y]==undefined?text:translations[x][y];
}
}
return text;
};
$.fn.extend({
translate: function () {
return this.each(function () {
$(this).html(__($(this).html()));
});
}
});
window.__ = __;
}());
| JavaScript |
/*
tip_followscroll.js v. 1.1
The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de
Initial author: Walter Zorn
Last modified: 21.6.2007
Extension for the tooltip library wz_tooltip.js.
Lets a "sticky" tooltip keep its position inside the clientarea if the window
is scrolled.
*/
// Here we define new global configuration variable(s) (as members of the
// predefined "config." class).
// From each of these config variables, wz_tooltip.js will automatically derive
// a command which can be passed to Tip() or TagToTip() in order to customize
// tooltips individually. These command names are just the config variable
// name(s) translated to uppercase,
// e.g. from config. FollowScroll a command FOLLOWSCROLL will automatically be
// created.
//=================== GLOBAL TOOPTIP CONFIGURATION ======================//
config. FollowScroll = false // true or false - set to true if you want this to be the default behaviour
//======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============//
// Create a new tt_Extension object (make sure that the name of that object,
// here fscrl, is unique amongst the extensions available for
// wz_tooltips.js):
var fscrl = new tt_Extension();
// Implement extension eventhandlers on which our extension should react
fscrl.OnShow = function()
{
if(tt_aV[FOLLOWSCROLL])
{
// Permit FOLLOWSCROLL only if the tooltip is sticky
if(tt_aV[STICKY])
{
var x = tt_x - tt_GetScrollX(), y = tt_y - tt_GetScrollY();
if(tt_ie)
{
fscrl.MoveOnScrl.offX = x;
fscrl.MoveOnScrl.offY = y;
fscrl.AddRemEvtFncs(tt_AddEvtFnc);
}
else
{
tt_SetTipPos(x, y);
tt_aElt[0].style.position = "fixed";
}
return true;
}
tt_aV[FOLLOWSCROLL] = false;
}
return false;
};
fscrl.OnHide = function()
{
if(tt_aV[FOLLOWSCROLL])
{
if(tt_ie)
fscrl.AddRemEvtFncs(tt_RemEvtFnc);
else
tt_aElt[0].style.position = "absolute";
}
};
// Helper functions (encapsulate in the class to avoid conflicts with other
// extensions)
fscrl.MoveOnScrl = function()
{
tt_SetTipPos(fscrl.MoveOnScrl.offX + tt_GetScrollX(), fscrl.MoveOnScrl.offY + tt_GetScrollY());
};
fscrl.AddRemEvtFncs = function(PAddRem)
{
PAddRem(window, "resize", fscrl.MoveOnScrl);
PAddRem(window, "scroll", fscrl.MoveOnScrl);
};
| JavaScript |
/*
tip_centerwindow.js v. 1.2
The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de
Initial author: Walter Zorn
Last modified: 23.6.2007
Extension for the tooltip library wz_tooltip.js.
Centers a sticky tooltip in the window's visible clientarea,
optionally even if the window is being scrolled or resized.
*/
// Here we define new global configuration variable(s) (as members of the
// predefined "config." class).
// From each of these config variables, wz_tooltip.js will automatically derive
// a command which can be passed to Tip() or TagToTip() in order to customize
// tooltips individually. These command names are just the config variable
// name(s) translated to uppercase,
// e.g. from config. CenterWindow a command CENTERWINDOW will automatically be
// created.
//=================== GLOBAL TOOPTIP CONFIGURATION =========================//
config. CenterWindow = false // true or false - set to true if you want this to be the default behaviour
config. CenterAlways = false // true or false - recenter if window is resized or scrolled
//======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============//
// Create a new tt_Extension object (make sure that the name of that object,
// here ctrwnd, is unique amongst the extensions available for
// wz_tooltips.js):
var ctrwnd = new tt_Extension();
// Implement extension eventhandlers on which our extension should react
ctrwnd.OnLoadConfig = function()
{
if(tt_aV[CENTERWINDOW])
{
// Permit CENTERWINDOW only if the tooltip is sticky
if(tt_aV[STICKY])
{
if(tt_aV[CENTERALWAYS])
{
// IE doesn't support style.position "fixed"
if(tt_ie)
tt_AddEvtFnc(window, "scroll", Ctrwnd_DoCenter);
else
tt_aElt[0].style.position = "fixed";
tt_AddEvtFnc(window, "resize", Ctrwnd_DoCenter);
}
return true;
}
tt_aV[CENTERWINDOW] = false;
}
return false;
};
// We react on the first OnMouseMove event to center the tip on that occasion
ctrwnd.OnMoveBefore = Ctrwnd_DoCenter;
ctrwnd.OnKill = function()
{
if(tt_aV[CENTERWINDOW] && tt_aV[CENTERALWAYS])
{
tt_RemEvtFnc(window, "resize", Ctrwnd_DoCenter);
if(tt_ie)
tt_RemEvtFnc(window, "scroll", Ctrwnd_DoCenter);
else
tt_aElt[0].style.position = "absolute";
}
return false;
};
// Helper function
function Ctrwnd_DoCenter()
{
if(tt_aV[CENTERWINDOW])
{
var x, y, dx, dy;
// Here we use some functions and variables (tt_w, tt_h) which the
// extension API of wz_tooltip.js provides for us
if(tt_ie || !tt_aV[CENTERALWAYS])
{
dx = tt_GetScrollX();
dy = tt_GetScrollY();
}
else
{
dx = 0;
dy = 0;
}
// Position the tip, offset from the center by OFFSETX and OFFSETY
x = (tt_GetClientW() - tt_w) / 2 + dx + tt_aV[OFFSETX];
y = (tt_GetClientH() - tt_h) / 2 + dy + tt_aV[OFFSETY];
tt_SetTipPos(x, y);
return true;
}
return false;
}
| JavaScript |
/* This notice must be untouched at all times.
wz_tooltip.js v. 4.12
The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de
Copyright (c) 2002-2007 Walter Zorn. All rights reserved.
Created 1.12.2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 13.7.2007
Easy-to-use cross-browser tooltips.
Just include the script at the beginning of the <body> section, and invoke
Tip('Tooltip text') from within the desired HTML onmouseover eventhandlers.
No container DIV, no onmouseouts required.
By default, width of tooltips is automatically adapted to content.
Is even capable of dynamically converting arbitrary HTML elements to tooltips
by calling TagToTip('ID_of_HTML_element_to_be_converted') instead of Tip(),
which means you can put important, search-engine-relevant stuff into tooltips.
Appearance of tooltips can be individually configured
via commands passed to Tip() or TagToTip().
Tab Width: 4
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
var config = new Object();
//=================== GLOBAL TOOPTIP CONFIGURATION =========================//
var tt_Debug = true // false or true - recommended: false once you release your page to the public
var tt_Enabled = true // Allows to (temporarily) suppress tooltips, e.g. by providing the user with a button that sets this global variable to false
var TagsToTip = true // false or true - if true, the script is capable of converting HTML elements to tooltips
// For each of the following config variables there exists a command, which is
// just the variablename in uppercase, to be passed to Tip() or TagToTip() to
// configure tooltips individually. Individual commands override global
// configuration. Order of commands is arbitrary.
// Example: onmouseover="Tip('Tooltip text', LEFT, true, BGCOLOR, '#FF9900', FADEIN, 400)"
config. Above = false // false or true - tooltip above mousepointer?
config. BgColor = '#E4E7FF' // Background color
config. BgImg = '' // Path to background image, none if empty string ''
config. BorderColor = '#002299'
config. BorderStyle = 'solid' // Any permitted CSS value, but I recommend 'solid', 'dotted' or 'dashed'
config. BorderWidth = 1
config. CenterMouse = false // false or true - center the tip horizontally below (or above) the mousepointer
config. ClickClose = false // false or true - close tooltip if the user clicks somewhere
config. CloseBtn = false // false or true - closebutton in titlebar
config. CloseBtnColors = ['#990000', '#FFFFFF', '#DD3333', '#FFFFFF'] // [Background, text, hovered background, hovered text] - use empty strings '' to inherit title colors
config. CloseBtnText = ' X ' // Close button text (may also be an image tag)
config. CopyContent = true // When converting a HTML element to a tooltip, copy only the element's content, rather than converting the element by its own
config. Delay = 400 // Time span in ms until tooltip shows up
config. Duration = 0 // Time span in ms after which the tooltip disappears; 0 for infinite duration
config. FadeIn = 0 // Fade-in duration in ms, e.g. 400; 0 for no animation
config. FadeOut = 0
config. FadeInterval = 30 // Duration of each fade step in ms (recommended: 30) - shorter is smoother but causes more CPU-load
config. Fix = null // Fixated position - x- an y-oordinates in brackets, e.g. [210, 480], or null for no fixation
config. FollowMouse = true // false or true - tooltip follows the mouse
config. FontColor = '#000044'
config. FontFace = 'Verdana,Geneva,sans-serif'
config. FontSize = '8pt' // E.g. '9pt' or '12px' - unit is mandatory
config. FontWeight = 'normal' // 'normal' or 'bold';
config. Left = false // false or true - tooltip on the left of the mouse
config. OffsetX = 14 // Horizontal offset of left-top corner from mousepointer
config. OffsetY = 8 // Vertical offset
config. Opacity = 100 // Integer between 0 and 100 - opacity of tooltip in percent
config. Padding = 3 // Spacing between border and content
config. Shadow = false // false or true
config. ShadowColor = '#C0C0C0'
config. ShadowWidth = 5
config. Sticky = false // Do NOT hide tooltip on mouseout? false or true
config. TextAlign = 'left' // 'left', 'right' or 'justify'
config. Title = '' // Default title text applied to all tips (no default title: empty string '')
config. TitleAlign = 'left' // 'left' or 'right' - text alignment inside the title bar
config. TitleBgColor = '' // If empty string '', BorderColor will be used
config. TitleFontColor = '#ffffff' // Color of title text - if '', BgColor (of tooltip body) will be used
config. TitleFontFace = '' // If '' use FontFace (boldified)
config. TitleFontSize = '' // If '' use FontSize
config. Width = 0 // Tooltip width; 0 for automatic adaption to tooltip content
//======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============//
//====================== PUBLIC ============================================//
function Tip()
{
tt_Tip(arguments, null);
}
function TagToTip()
{
if(TagsToTip)
{
var t2t = tt_GetElt(arguments[0]);
if(t2t)
tt_Tip(arguments, t2t);
}
}
//================== PUBLIC EXTENSION API ==================================//
// Extension eventhandlers currently supported:
// OnLoadConfig, OnCreateContentString, OnSubDivsCreated, OnShow, OnMoveBefore,
// OnMoveAfter, OnHideInit, OnHide, OnKill
var tt_aElt = new Array(10), // Container DIV, outer title & body DIVs, inner title & body TDs, closebutton SPAN, shadow DIVs, and IFRAME to cover windowed elements in IE
tt_aV = new Array(), // Caches and enumerates config data for currently active tooltip
tt_sContent, // Inner tooltip text or HTML
tt_scrlX = 0, tt_scrlY = 0,
tt_musX, tt_musY,
tt_over,
tt_x, tt_y, tt_w, tt_h; // Position, width and height of currently displayed tooltip
function tt_Extension()
{
tt_ExtCmdEnum();
tt_aExt[tt_aExt.length] = this;
return this;
}
function tt_SetTipPos(x, y)
{
var css = tt_aElt[0].style;
tt_x = x;
tt_y = y;
css.left = x + "px";
css.top = y + "px";
if(tt_ie56)
{
var ifrm = tt_aElt[tt_aElt.length - 1];
if(ifrm)
{
ifrm.style.left = css.left;
ifrm.style.top = css.top;
}
}
}
function tt_Hide()
{
if(tt_db && tt_iState)
{
if(tt_iState & 0x2)
{
tt_aElt[0].style.visibility = "hidden";
tt_ExtCallFncs(0, "Hide");
}
tt_tShow.EndTimer();
tt_tHide.EndTimer();
tt_tDurt.EndTimer();
tt_tFade.EndTimer();
if(!tt_op && !tt_ie)
{
tt_tWaitMov.EndTimer();
tt_bWait = false;
}
if(tt_aV[CLICKCLOSE])
tt_RemEvtFnc(document, "mouseup", tt_HideInit);
tt_AddRemOutFnc(false);
tt_ExtCallFncs(0, "Kill");
// In case of a TagToTip tooltip, hide converted DOM node and
// re-insert it into document
if(tt_t2t && !tt_aV[COPYCONTENT])
{
tt_t2t.style.display = "none";
tt_MovDomNode(tt_t2t, tt_aElt[6], tt_t2tDad);
}
tt_iState = 0;
tt_over = null;
tt_ResetMainDiv();
if(tt_aElt[tt_aElt.length - 1])
tt_aElt[tt_aElt.length - 1].style.display = "none";
}
}
function tt_GetElt(id)
{
return(document.getElementById ? document.getElementById(id)
: document.all ? document.all[id]
: null);
}
function tt_GetDivW(el)
{
return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0);
}
function tt_GetDivH(el)
{
return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0);
}
function tt_GetScrollX()
{
return(window.pageXOffset || (tt_db ? (tt_db.scrollLeft || 0) : 0));
}
function tt_GetScrollY()
{
return(window.pageYOffset || (tt_db ? (tt_db.scrollTop || 0) : 0));
}
function tt_GetClientW()
{
return(document.body && (typeof(document.body.clientWidth) != tt_u) ? document.body.clientWidth
: (typeof(window.innerWidth) != tt_u) ? window.innerWidth
: tt_db ? (tt_db.clientWidth || 0)
: 0);
}
function tt_GetClientH()
{
// Exactly this order seems to yield correct values in all major browsers
return(document.body && (typeof(document.body.clientHeight) != tt_u) ? document.body.clientHeight
: (typeof(window.innerHeight) != tt_u) ? window.innerHeight
: tt_db ? (tt_db.clientHeight || 0)
: 0);
}
function tt_GetEvtX(e)
{
return (e ? ((typeof(e.pageX) != tt_u) ? e.pageX : (e.clientX + tt_scrlX)) : 0);
}
function tt_GetEvtY(e)
{
return (e ? ((typeof(e.pageY) != tt_u) ? e.pageY : (e.clientY + tt_scrlY)) : 0);
}
function tt_AddEvtFnc(el, sEvt, PFnc)
{
if(el)
{
if(el.addEventListener)
el.addEventListener(sEvt, PFnc, false);
else
el.attachEvent("on" + sEvt, PFnc);
}
}
function tt_RemEvtFnc(el, sEvt, PFnc)
{
if(el)
{
if(el.removeEventListener)
el.removeEventListener(sEvt, PFnc, false);
else
el.detachEvent("on" + sEvt, PFnc);
}
}
//====================== PRIVATE ===========================================//
var tt_aExt = new Array(), // Array of extension objects
tt_db, tt_op, tt_ie, tt_ie56, tt_bBoxOld, // Browser flags
tt_body,
tt_flagOpa, // Opacity support: 1=IE, 2=Khtml, 3=KHTML, 4=Moz, 5=W3C
tt_maxPosX, tt_maxPosY,
tt_iState = 0, // Tooltip active |= 1, shown |= 2, move with mouse |= 4
tt_opa, // Currently applied opacity
tt_bJmpVert, // Tip above mouse (or ABOVE tip below mouse)
tt_t2t, tt_t2tDad, // Tag converted to tip, and its parent element in the document
tt_elDeHref, // The tag from which Opera has removed the href attribute
// Timer
tt_tShow = new Number(0), tt_tHide = new Number(0), tt_tDurt = new Number(0),
tt_tFade = new Number(0), tt_tWaitMov = new Number(0),
tt_bWait = false,
tt_u = "undefined";
function tt_Init()
{
tt_MkCmdEnum();
// Send old browsers instantly to hell
if(!tt_Browser() || !tt_MkMainDiv())
return;
tt_IsW3cBox();
tt_OpaSupport();
tt_AddEvtFnc(document, "mousemove", tt_Move);
// In Debug mode we search for TagToTip() calls in order to notify
// the user if they've forgotten to set the TagsToTip config flag
if(TagsToTip || tt_Debug)
tt_SetOnloadFnc();
tt_AddEvtFnc(window, "scroll",
function()
{
tt_scrlX = tt_GetScrollX();
tt_scrlY = tt_GetScrollY();
if(tt_iState && !(tt_aV[STICKY] && (tt_iState & 2)))
tt_HideInit();
} );
// Ensure the tip be hidden when the page unloads
tt_AddEvtFnc(window, "unload", tt_Hide);
tt_Hide();
}
// Creates command names by translating config variable names to upper case
function tt_MkCmdEnum()
{
var n = 0;
for(var i in config)
eval("window." + i.toString().toUpperCase() + " = " + n++);
tt_aV.length = n;
}
function tt_Browser()
{
var n, nv, n6, w3c;
n = navigator.userAgent.toLowerCase(),
nv = navigator.appVersion;
tt_op = (document.defaultView && typeof(eval("w" + "indow" + "." + "o" + "p" + "er" + "a")) != tt_u);
tt_ie = n.indexOf("msie") != -1 && document.all && !tt_op;
if(tt_ie)
{
var ieOld = (!document.compatMode || document.compatMode == "BackCompat");
tt_db = !ieOld ? document.documentElement : (document.body || null);
if(tt_db)
tt_ie56 = parseFloat(nv.substring(nv.indexOf("MSIE") + 5)) >= 5.5
&& typeof document.body.style.maxHeight == tt_u;
}
else
{
tt_db = document.documentElement || document.body ||
(document.getElementsByTagName ? document.getElementsByTagName("body")[0]
: null);
if(!tt_op)
{
n6 = document.defaultView && typeof document.defaultView.getComputedStyle != tt_u;
w3c = !n6 && document.getElementById;
}
}
tt_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0]
: (document.body || null));
if(tt_ie || n6 || tt_op || w3c)
{
if(tt_body && tt_db)
{
if(document.attachEvent || document.addEventListener)
return true;
}
else
tt_Err("wz_tooltip.js must be included INSIDE the body section,"
+ " immediately after the opening <body> tag.");
}
tt_db = null;
return false;
}
function tt_MkMainDiv()
{
// Create the tooltip DIV
if(tt_body.insertAdjacentHTML)
tt_body.insertAdjacentHTML("afterBegin", tt_MkMainDivHtm());
else if(typeof tt_body.innerHTML != tt_u && document.createElement && tt_body.appendChild)
tt_body.appendChild(tt_MkMainDivDom());
// FireFox Alzheimer bug
if(window.tt_GetMainDivRefs && tt_GetMainDivRefs())
return true;
tt_db = null;
return false;
}
function tt_MkMainDivHtm()
{
return('<div id="WzTtDiV"></div>' +
(tt_ie56 ? ('<iframe id="WzTtIfRm" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>')
: ''));
}
function tt_MkMainDivDom()
{
var el = document.createElement("div");
if(el)
el.id = "WzTtDiV";
return el;
}
function tt_GetMainDivRefs()
{
tt_aElt[0] = tt_GetElt("WzTtDiV");
if(tt_ie56 && tt_aElt[0])
{
tt_aElt[tt_aElt.length - 1] = tt_GetElt("WzTtIfRm");
if(!tt_aElt[tt_aElt.length - 1])
tt_aElt[0] = null;
}
if(tt_aElt[0])
{
var css = tt_aElt[0].style;
css.visibility = "hidden";
css.position = "absolute";
css.overflow = "hidden";
return true;
}
return false;
}
function tt_ResetMainDiv()
{
var w = (window.screen && screen.width) ? screen.width : 10000;
tt_SetTipPos(-w, 0);
tt_aElt[0].innerHTML = "";
tt_aElt[0].style.width = (w - 1) + "px";
}
function tt_IsW3cBox()
{
var css = tt_aElt[0].style;
css.padding = "10px";
css.width = "40px";
tt_bBoxOld = (tt_GetDivW(tt_aElt[0]) == 40);
css.padding = "0px";
tt_ResetMainDiv();
}
function tt_OpaSupport()
{
var css = tt_body.style;
tt_flagOpa = (typeof(css.filter) != tt_u) ? 1
: (typeof(css.KhtmlOpacity) != tt_u) ? 2
: (typeof(css.KHTMLOpacity) != tt_u) ? 3
: (typeof(css.MozOpacity) != tt_u) ? 4
: (typeof(css.opacity) != tt_u) ? 5
: 0;
}
// Ported from http://dean.edwards.name/weblog/2006/06/again/
// (Dean Edwards et al.)
function tt_SetOnloadFnc()
{
tt_AddEvtFnc(document, "DOMContentLoaded", tt_HideSrcTags);
tt_AddEvtFnc(window, "load", tt_HideSrcTags);
if(tt_body.attachEvent)
tt_body.attachEvent("onreadystatechange",
function() {
if(tt_body.readyState == "complete")
tt_HideSrcTags();
} );
if(/WebKit|KHTML/i.test(navigator.userAgent))
{
var t = setInterval(function() {
if(/loaded|complete/.test(document.readyState))
{
clearInterval(t);
tt_HideSrcTags();
}
}, 10);
}
}
function tt_HideSrcTags()
{
if(!window.tt_HideSrcTags || window.tt_HideSrcTags.done)
return;
window.tt_HideSrcTags.done = true;
if(!tt_HideSrcTagsRecurs(tt_body))
tt_Err("To enable the capability to convert HTML elements to tooltips,"
+ " you must set TagsToTip in the global tooltip configuration"
+ " to true.");
}
function tt_HideSrcTagsRecurs(dad)
{
var a, ovr, asT2t;
// Walk the DOM tree for tags that have an onmouseover attribute
// containing a TagToTip('...') call.
// (.childNodes first since .children is bugous in Safari)
a = dad.childNodes || dad.children || null;
for(var i = a ? a.length : 0; i;)
{--i;
if(!tt_HideSrcTagsRecurs(a[i]))
return false;
ovr = a[i].getAttribute ? a[i].getAttribute("onmouseover")
: (typeof a[i].onmouseover == "function") ? a[i].onmouseover
: null;
if(ovr)
{
asT2t = ovr.toString().match(/TagToTip\s*\(\s*'[^'.]+'\s*[\),]/);
if(asT2t && asT2t.length)
{
if(!tt_HideSrcTag(asT2t[0]))
return false;
}
}
}
return true;
}
function tt_HideSrcTag(sT2t)
{
var id, el;
// The ID passed to the found TagToTip() call identifies an HTML element
// to be converted to a tooltip, so hide that element
id = sT2t.replace(/.+'([^'.]+)'.+/, "$1");
el = tt_GetElt(id);
if(el)
{
if(tt_Debug && !TagsToTip)
return false;
else
el.style.display = "none";
}
else
tt_Err("Invalid ID\n'" + id + "'\npassed to TagToTip()."
+ " There exists no HTML element with that ID.");
return true;
}
function tt_Tip(arg, t2t)
{
if(!tt_db)
return;
if(tt_iState)
tt_Hide();
if(!tt_Enabled)
return;
tt_t2t = t2t;
if(!tt_ReadCmds(arg))
return;
tt_iState = 0x1 | 0x4;
tt_AdaptConfig1();
tt_MkTipContent(arg);
tt_MkTipSubDivs();
tt_FormatTip();
tt_bJmpVert = false;
tt_maxPosX = tt_GetClientW() + tt_scrlX - tt_w - 1;
tt_maxPosY = tt_GetClientH() + tt_scrlY - tt_h - 1;
tt_AdaptConfig2();
// We must fake the first mousemove in order to ensure the tip
// be immediately shown and positioned
tt_Move();
tt_ShowInit();
}
function tt_ReadCmds(a)
{
var i;
// First load the global config values, to initialize also values
// for which no command has been passed
i = 0;
for(var j in config)
tt_aV[i++] = config[j];
// Then replace each cached config value for which a command has been
// passed (ensure the # of command args plus value args be even)
if(a.length & 1)
{
for(i = a.length - 1; i > 0; i -= 2)
tt_aV[a[i - 1]] = a[i];
return true;
}
tt_Err("Incorrect call of Tip() or TagToTip().\n"
+ "Each command must be followed by a value.");
return false;
}
function tt_AdaptConfig1()
{
tt_ExtCallFncs(0, "LoadConfig");
// Inherit unspecified title formattings from body
if(!tt_aV[TITLEBGCOLOR].length)
tt_aV[TITLEBGCOLOR] = tt_aV[BORDERCOLOR];
if(!tt_aV[TITLEFONTCOLOR].length)
tt_aV[TITLEFONTCOLOR] = tt_aV[BGCOLOR];
if(!tt_aV[TITLEFONTFACE].length)
tt_aV[TITLEFONTFACE] = tt_aV[FONTFACE];
if(!tt_aV[TITLEFONTSIZE].length)
tt_aV[TITLEFONTSIZE] = tt_aV[FONTSIZE];
if(tt_aV[CLOSEBTN])
{
// Use title colors for non-specified closebutton colors
if(!tt_aV[CLOSEBTNCOLORS])
tt_aV[CLOSEBTNCOLORS] = new Array("", "", "", "");
for(var i = 4; i;)
{--i;
if(!tt_aV[CLOSEBTNCOLORS][i].length)
tt_aV[CLOSEBTNCOLORS][i] = (i & 1) ? tt_aV[TITLEFONTCOLOR] : tt_aV[TITLEBGCOLOR];
}
// Enforce titlebar be shown
if(!tt_aV[TITLE].length)
tt_aV[TITLE] = " ";
}
// Circumvents broken display of images and fade-in flicker in Geckos < 1.8
if(tt_aV[OPACITY] == 100 && typeof tt_aElt[0].style.MozOpacity != tt_u && !Array.every)
tt_aV[OPACITY] = 99;
// Smartly shorten the delay for fade-in tooltips
if(tt_aV[FADEIN] && tt_flagOpa && tt_aV[DELAY] > 100)
tt_aV[DELAY] = Math.max(tt_aV[DELAY] - tt_aV[FADEIN], 100);
}
function tt_AdaptConfig2()
{
if(tt_aV[CENTERMOUSE])
tt_aV[OFFSETX] -= ((tt_w - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0)) >> 1);
}
// Expose content globally so extensions can modify it
function tt_MkTipContent(a)
{
if(tt_t2t)
{
if(tt_aV[COPYCONTENT])
tt_sContent = tt_t2t.innerHTML;
else
tt_sContent = "";
}
else
tt_sContent = a[0];
tt_ExtCallFncs(0, "CreateContentString");
}
function tt_MkTipSubDivs()
{
var sCss = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:auto;',
sTbTrTd = ' cellspacing=0 cellpadding=0 border=0 style="' + sCss + '"><tbody style="' + sCss + '"><tr><td ';
tt_aElt[0].innerHTML =
(''
+ (tt_aV[TITLE].length ?
('<div id="WzTiTl" style="position:relative;z-index:1;">'
+ '<table id="WzTiTlTb"' + sTbTrTd + 'id="WzTiTlI" style="' + sCss + '">'
+ tt_aV[TITLE]
+ '</td>'
+ (tt_aV[CLOSEBTN] ?
('<td align="right" style="' + sCss
+ 'text-align:right;">'
+ '<span id="WzClOsE" style="padding-left:2px;padding-right:2px;'
+ 'cursor:' + (tt_ie ? 'hand' : 'pointer')
+ ';" onmouseover="tt_OnCloseBtnOver(1)" onmouseout="tt_OnCloseBtnOver(0)" onclick="tt_HideInit()">'
+ tt_aV[CLOSEBTNTEXT]
+ '</span></td>')
: '')
+ '</tr></tbody></table></div>')
: '')
+ '<div id="WzBoDy" style="position:relative;z-index:0;">'
+ '<table' + sTbTrTd + 'id="WzBoDyI" style="' + sCss + '">'
+ tt_sContent
+ '</td></tr></tbody></table></div>'
+ (tt_aV[SHADOW]
? ('<div id="WzTtShDwR" style="position:absolute;overflow:hidden;"></div>'
+ '<div id="WzTtShDwB" style="position:relative;overflow:hidden;"></div>')
: '')
);
tt_GetSubDivRefs();
// Convert DOM node to tip
if(tt_t2t && !tt_aV[COPYCONTENT])
{
// Store the tag's parent element so we can restore that DOM branch
// once the tooltip is hidden
tt_t2tDad = tt_t2t.parentNode || tt_t2t.parentElement || tt_t2t.offsetParent || null;
if(tt_t2tDad)
{
tt_MovDomNode(tt_t2t, tt_t2tDad, tt_aElt[6]);
tt_t2t.style.display = "block";
}
}
tt_ExtCallFncs(0, "SubDivsCreated");
}
function tt_GetSubDivRefs()
{
var aId = new Array("WzTiTl", "WzTiTlTb", "WzTiTlI", "WzClOsE", "WzBoDy", "WzBoDyI", "WzTtShDwB", "WzTtShDwR");
for(var i = aId.length; i; --i)
tt_aElt[i] = tt_GetElt(aId[i - 1]);
}
function tt_FormatTip()
{
var css, w, iOffY, iOffSh;
//--------- Title DIV ----------
if(tt_aV[TITLE].length)
{
css = tt_aElt[1].style;
css.background = tt_aV[TITLEBGCOLOR];
css.paddingTop = (tt_aV[CLOSEBTN] ? 2 : 0) + "px";
css.paddingBottom = "1px";
css.paddingLeft = css.paddingRight = tt_aV[PADDING] + "px";
css = tt_aElt[3].style;
css.color = tt_aV[TITLEFONTCOLOR];
css.fontFamily = tt_aV[TITLEFONTFACE];
css.fontSize = tt_aV[TITLEFONTSIZE];
css.fontWeight = "bold";
css.textAlign = tt_aV[TITLEALIGN];
// Close button DIV
if(tt_aElt[4])
{
css.paddingRight = (tt_aV[PADDING] << 1) + "px";
css = tt_aElt[4].style;
css.background = tt_aV[CLOSEBTNCOLORS][0];
css.color = tt_aV[CLOSEBTNCOLORS][1];
css.fontFamily = tt_aV[TITLEFONTFACE];
css.fontSize = tt_aV[TITLEFONTSIZE];
css.fontWeight = "bold";
}
if(tt_aV[WIDTH] > 0)
tt_w = tt_aV[WIDTH] + ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1);
else
{
tt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]);
// Some spacing between title DIV and closebutton
if(tt_aElt[4])
tt_w += tt_aV[PADDING];
}
// Ensure the top border of the body DIV be covered by the title DIV
iOffY = -tt_aV[BORDERWIDTH];
}
else
{
tt_w = 0;
iOffY = 0;
}
//-------- Body DIV ------------
css = tt_aElt[5].style;
css.top = iOffY + "px";
if(tt_aV[BORDERWIDTH])
{
css.borderColor = tt_aV[BORDERCOLOR];
css.borderStyle = tt_aV[BORDERSTYLE];
css.borderWidth = tt_aV[BORDERWIDTH] + "px";
}
if(tt_aV[BGCOLOR].length)
css.background = tt_aV[BGCOLOR];
if(tt_aV[BGIMG].length)
css.backgroundImage = "url(" + tt_aV[BGIMG] + ")";
css.padding = tt_aV[PADDING] + "px";
css.textAlign = tt_aV[TEXTALIGN];
// TD inside body DIV
css = tt_aElt[6].style;
css.color = tt_aV[FONTCOLOR];
css.fontFamily = tt_aV[FONTFACE];
css.fontSize = tt_aV[FONTSIZE];
css.fontWeight = tt_aV[FONTWEIGHT];
css.background = "";
css.textAlign = tt_aV[TEXTALIGN];
if(tt_aV[WIDTH] > 0)
w = tt_aV[WIDTH] + ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1);
else
// We measure the width of the body's inner TD, because some browsers
// expand the width of the container and outer body DIV to 100%
w = tt_GetDivW(tt_aElt[6]) + ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1);
if(w > tt_w)
tt_w = w;
//--------- Shadow DIVs ------------
if(tt_aV[SHADOW])
{
tt_w += tt_aV[SHADOWWIDTH];
iOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3);
// Bottom shadow
css = tt_aElt[7].style;
css.top = iOffY + "px";
css.left = iOffSh + "px";
css.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + "px";
css.height = tt_aV[SHADOWWIDTH] + "px";
css.background = tt_aV[SHADOWCOLOR];
// Right shadow
css = tt_aElt[8].style;
css.top = iOffSh + "px";
css.left = (tt_w - tt_aV[SHADOWWIDTH]) + "px";
css.width = tt_aV[SHADOWWIDTH] + "px";
css.background = tt_aV[SHADOWCOLOR];
}
else
iOffSh = 0;
//-------- Container DIV -------
tt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]);
tt_FixSize(iOffY, iOffSh);
}
// Fixate the size so it can't dynamically change while the tooltip is moving.
function tt_FixSize(iOffY, iOffSh)
{
var wIn, wOut, i;
tt_aElt[0].style.width = tt_w + "px";
tt_aElt[0].style.pixelWidth = tt_w;
wOut = tt_w - ((tt_aV[SHADOW]) ? tt_aV[SHADOWWIDTH] : 0);
// Body
wIn = wOut;
if(!tt_bBoxOld)
wIn -= ((tt_aV[PADDING] + tt_aV[BORDERWIDTH]) << 1);
tt_aElt[5].style.width = wIn + "px";
// Title
if(tt_aElt[1])
{
wIn = wOut - (tt_aV[PADDING] << 1);
if(!tt_bBoxOld)
wOut = wIn;
tt_aElt[1].style.width = wOut + "px";
tt_aElt[2].style.width = wIn + "px";
}
tt_h = tt_GetDivH(tt_aElt[0]) + iOffY;
// Right shadow
if(tt_aElt[8])
tt_aElt[8].style.height = (tt_h - iOffSh) + "px";
i = tt_aElt.length - 1;
if(tt_aElt[i])
{
tt_aElt[i].style.width = tt_w + "px";
tt_aElt[i].style.height = tt_h + "px";
}
}
function tt_DeAlt(el)
{
var aKid;
if(el.alt)
el.alt = "";
if(el.title)
el.title = "";
aKid = el.childNodes || el.children || null;
if(aKid)
{
for(var i = aKid.length; i;)
tt_DeAlt(aKid[--i]);
}
}
// This hack removes the annoying native tooltips over links in Opera
function tt_OpDeHref(el)
{
if(!tt_op)
return;
if(tt_elDeHref)
tt_OpReHref();
while(el)
{
if(el.hasAttribute("href"))
{
el.t_href = el.getAttribute("href");
el.t_stats = window.status;
el.removeAttribute("href");
el.style.cursor = "hand";
tt_AddEvtFnc(el, "mousedown", tt_OpReHref);
window.status = el.t_href;
tt_elDeHref = el;
break;
}
el = el.parentElement;
}
}
function tt_ShowInit()
{
tt_tShow.Timer("tt_Show()", tt_aV[DELAY], true);
if(tt_aV[CLICKCLOSE])
tt_AddEvtFnc(document, "mouseup", tt_HideInit);
}
function tt_OverInit(e)
{
tt_over = e.target || e.srcElement;
tt_DeAlt(tt_over);
tt_OpDeHref(tt_over);
tt_AddRemOutFnc(true);
}
function tt_Show()
{
var css = tt_aElt[0].style;
// Override the z-index of the topmost wz_dragdrop.js D&D item
css.zIndex = Math.max((window.dd && dd.z) ? (dd.z + 2) : 0, 1010);
if(tt_aV[STICKY] || !tt_aV[FOLLOWMOUSE])
tt_iState &= ~0x4;
if(tt_aV[DURATION] > 0)
tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true);
tt_ExtCallFncs(0, "Show")
css.visibility = "visible";
tt_iState |= 0x2;
if(tt_aV[FADEIN])
tt_Fade(0, 0, tt_aV[OPACITY], Math.round(tt_aV[FADEIN] / tt_aV[FADEINTERVAL]));
tt_ShowIfrm();
}
function tt_ShowIfrm()
{
if(tt_ie56)
{
var ifrm = tt_aElt[tt_aElt.length - 1];
if(ifrm)
{
var css = ifrm.style;
css.zIndex = tt_aElt[0].style.zIndex - 1;
css.display = "block";
}
}
}
function tt_Move(e)
{
e = window.event || e;
if(e)
{
tt_musX = tt_GetEvtX(e);
tt_musY = tt_GetEvtY(e);
}
if(tt_iState)
{
if(!tt_over && e)
tt_OverInit(e);
if(tt_iState & 0x4)
{
// Protect some browsers against jam of mousemove events
if(!tt_op && !tt_ie)
{
if(tt_bWait)
return;
tt_bWait = true;
tt_tWaitMov.Timer("tt_bWait = false;", 1, true);
}
if(tt_aV[FIX])
{
tt_iState &= ~0x4;
tt_SetTipPos(tt_aV[FIX][0], tt_aV[FIX][1]);
}
else if(!tt_ExtCallFncs(e, "MoveBefore"))
tt_SetTipPos(tt_PosX(), tt_PosY());
tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter")
}
}
}
function tt_PosX()
{
var x;
x = tt_musX;
if(tt_aV[LEFT])
x -= tt_w + tt_aV[OFFSETX] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
else
x += tt_aV[OFFSETX];
// Prevent tip from extending past right/left clientarea boundary
if(x > tt_maxPosX)
x = tt_maxPosX;
return((x < tt_scrlX) ? tt_scrlX : x);
}
function tt_PosY()
{
var y;
// Apply some hysteresis after the tip has snapped to the other side of the
// mouse. In case of insufficient space above and below the mouse, we place
// the tip below.
if(tt_aV[ABOVE] && (!tt_bJmpVert || tt_CalcPosYAbove() >= tt_scrlY + 16))
y = tt_DoPosYAbove();
else if(!tt_aV[ABOVE] && tt_bJmpVert && tt_CalcPosYBelow() > tt_maxPosY - 16)
y = tt_DoPosYAbove();
else
y = tt_DoPosYBelow();
// Snap to other side of mouse if tip would extend past window boundary
if(y > tt_maxPosY)
y = tt_DoPosYAbove();
if(y < tt_scrlY)
y = tt_DoPosYBelow();
return y;
}
function tt_DoPosYBelow()
{
tt_bJmpVert = tt_aV[ABOVE];
return tt_CalcPosYBelow();
}
function tt_DoPosYAbove()
{
tt_bJmpVert = !tt_aV[ABOVE];
return tt_CalcPosYAbove();
}
function tt_CalcPosYBelow()
{
return(tt_musY + tt_aV[OFFSETY]);
}
function tt_CalcPosYAbove()
{
var dy = tt_aV[OFFSETY] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
if(tt_aV[OFFSETY] > 0 && dy <= 0)
dy = 1;
return(tt_musY - tt_h - dy);
}
function tt_OnOut()
{
tt_AddRemOutFnc(false);
if(!(tt_aV[STICKY] && (tt_iState & 0x2)))
tt_HideInit();
}
function tt_HideInit()
{
tt_ExtCallFncs(0, "HideInit");
tt_iState &= ~0x4;
if(tt_flagOpa && tt_aV[FADEOUT])
{
tt_tFade.EndTimer();
if(tt_opa)
{
var n = Math.round(tt_aV[FADEOUT] / (tt_aV[FADEINTERVAL] * (tt_aV[OPACITY] / tt_opa)));
tt_Fade(tt_opa, tt_opa, 0, n);
return;
}
}
tt_tHide.Timer("tt_Hide();", 1, false);
}
function tt_OpReHref()
{
if(tt_elDeHref)
{
tt_elDeHref.setAttribute("href", tt_elDeHref.t_href);
tt_RemEvtFnc(tt_elDeHref, "mousedown", tt_OpReHref);
window.status = tt_elDeHref.t_stats;
tt_elDeHref = null;
}
}
function tt_Fade(a, now, z, n)
{
if(n)
{
now += Math.round((z - now) / n);
if((z > a) ? (now >= z) : (now <= z))
now = z;
else
tt_tFade.Timer("tt_Fade("
+ a + "," + now + "," + z + "," + (n - 1)
+ ")",
tt_aV[FADEINTERVAL],
true);
}
now ? tt_SetTipOpa(now) : tt_Hide();
}
// To circumvent the opacity nesting flaws of IE, we set the opacity
// for each sub-DIV separately, rather than for the container DIV.
function tt_SetTipOpa(opa)
{
tt_SetOpa(tt_aElt[5].style, opa);
if(tt_aElt[1])
tt_SetOpa(tt_aElt[1].style, opa);
if(tt_aV[SHADOW])
{
opa = Math.round(opa * 0.8);
tt_SetOpa(tt_aElt[7].style, opa);
tt_SetOpa(tt_aElt[8].style, opa);
}
}
function tt_OnCloseBtnOver(iOver)
{
var css = tt_aElt[4].style;
iOver <<= 1;
css.background = tt_aV[CLOSEBTNCOLORS][iOver];
css.color = tt_aV[CLOSEBTNCOLORS][iOver + 1];
}
function tt_Int(x)
{
var y;
return(isNaN(y = parseInt(x)) ? 0 : y);
}
// Adds or removes the document.mousemove or HoveredElem.mouseout handler
// conveniently. Keeps track of those handlers to prevent them from being
// set or removed redundantly.
function tt_AddRemOutFnc(bAdd)
{
var PSet = bAdd ? tt_AddEvtFnc : tt_RemEvtFnc;
if(bAdd != tt_AddRemOutFnc.bOn)
{
PSet(tt_over, "mouseout", tt_OnOut);
tt_AddRemOutFnc.bOn = bAdd;
if(!bAdd)
tt_OpReHref();
}
}
tt_AddRemOutFnc.bOn = false;
Number.prototype.Timer = function(s, iT, bUrge)
{
if(!this.value || bUrge)
this.value = window.setTimeout(s, iT);
}
Number.prototype.EndTimer = function()
{
if(this.value)
{
window.clearTimeout(this.value);
this.value = 0;
}
}
function tt_SetOpa(css, opa)
{
tt_opa = opa;
if(tt_flagOpa == 1)
{
// Hack for bugs of IE:
// A DIV cannot be made visible in a single step if an opacity < 100
// has been applied while the DIV was hidden.
// Moreover, in IE6, applying an opacity < 100 has no effect if the
// concerned element has no layout (position, size, zoom, ...).
if(opa < 100)
{
var bVis = css.visibility != "hidden";
css.zoom = "100%";
if(!bVis)
css.visibility = "visible";
css.filter = "alpha(opacity=" + opa + ")";
if(!bVis)
css.visibility = "hidden";
}
else
css.filter = "";
}
else
{
opa /= 100.0;
switch(tt_flagOpa)
{
case 2:
css.KhtmlOpacity = opa; break;
case 3:
css.KHTMLOpacity = opa; break;
case 4:
css.MozOpacity = opa; break;
case 5:
css.opacity = opa; break;
}
}
}
function tt_MovDomNode(el, dadFrom, dadTo)
{
if(dadFrom)
dadFrom.removeChild(el);
if(dadTo)
dadTo.appendChild(el);
}
function tt_Err(sErr)
{
if(tt_Debug)
alert("Tooltip Script Error Message:\n\n" + sErr);
}
//=========== DEALING WITH EXTENSIONS ==============//
function tt_ExtCmdEnum()
{
var s;
// Add new command(s) to the commands enum
for(var i in config)
{
s = "window." + i.toString().toUpperCase();
if(eval("typeof(" + s + ") == tt_u"))
{
eval(s + " = " + tt_aV.length);
tt_aV[tt_aV.length] = null;
}
}
}
function tt_ExtCallFncs(arg, sFnc)
{
var b = false;
for(var i = tt_aExt.length; i;)
{--i;
var fnc = tt_aExt[i]["On" + sFnc];
// Call the method the extension has defined for this event
if(fnc && fnc(arg))
b = true;
}
return b;
}
tt_Init();
| JavaScript |
function webstartVersionCheck(versionString) {
if (!(navigator.mimeTypes && navigator.mimeTypes.length))return false;
// Mozilla may not recognize new plugins without this refresh
navigator.plugins.refresh(false);
// First, determine if Web Start is available
if (navigator.mimeTypes['application/x-java-jnlp-file']) {
// Next, check for appropriate version family
for (var i = 0; i < navigator.mimeTypes.length; ++i) {
pluginType = navigator.mimeTypes[i].type;
if(pluginType.indexOf("application/x-java-applet;version=")==0)
{
if (pluginType == "application/x-java-applet;version=" + versionString) {
return true;
}
}
}
}
return false;
}
if(typeof(javawsInstalled)=='undefined')javawsInstalled=false;
if(typeof(javaws150Installed)=='undefined')javaws150Installed=false;
if(typeof(javaws160Installed)=='undefined')javaws160Installed=false;
function DetectJWS() {
if (Prototype.Browser.IE && (javaws160Installed)) {
return true;
}
if (typeof(navigator.mimeTypes)!='undefined' && typeof(navigator.mimeTypes.length)!='undefined')
{
if (webstartVersionCheck("1.6")) {
return true;
}
return false;
}
if(Prototype.Browser.Gecko)
return true;
return false;
}
if(!javawsInstalled)
javawsInstalled = DetectJWS();
| JavaScript |
// =========================================================================
// getRealPopup v1.42
// by John Norton - http://www.amplifystudios.com
// Last Modified: 6/3/08
//
// Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
// - Free for use in both personal and commercial projects
// - Attribution requires leaving author name, author link, and the license info intact.
//
// How to use:
// To use the popup function make sure you import the apropreate libraries
// ( those found in this example ). No modifications have been made to any
// acompaning javascript libraries. Once you have imported the libraries
// call the showPop() function ( see TOC for proper formatting ). To set
// any default features please modify the variable below. To close a popup
// all the hidePopup() function ( see TOC for proper formatting ).
//
// ============================= EDIT THIS VARIABLE =============================
// PopupVariables = [float FadeDuration, float FadeValue, string MaskColor, bool UseAutoPopupPosition, int PopupWidth, int PopupHeight];
var PopupVariables = [0.5, 0.6, '#000000', true, 200, 200];
// ============================= EDIT THIS VARIABLE =============================
//
// Table of contents:
// ---------------------
// Variables
// - getPageSize()
// - hidePop( string PopupObject )
// - PopupVariables[]
// - showPop( string PopupObject, int Width(Optional), int Height(Optional) )
// - SetEventHandler( string EventName, function EventHandler )
// Classes
// - PopupClass
// PopupControl Class
// - PopupControl
// - PopupControl.FadeDuration : 0.0 -> ...
// - PopupControl.FadeVal : 0.0 -> 1.0
// - PopupControl.MaskColor : #000000 -> #FFFFFF OR red, blue, ect...
// - PopupControl.UseAutoPopupPos : true | false
// - PopupControl.PopupWidth : 1 -> ...
// - PopupControl.PopupHeight : 1 -> ...
// - PopupControl.CurrentPopup : Dont set this. The popup functions modify this when needed.
// - PopupControl.CurrentPopupW : Dont set this. The popup functions modify this when needed.
// - PopupControl.CurrentPopupH : Dont set this. The popup functions modify this when needed.
// - PopupControl.createMask()
// - PopupControl.togglePopup( string PopupObject, bool ShowPopup, int Width, int Height )
// - PopupControl.getPopPos( int Width, int Height )
// - PopupControl.autoPosFix()
// - PopupControl.togMask( bool ShowMask )
// - PopupControl.report()
//
// =========================================================================
// =========================================================================
// Popup Class
var PopupClass = Class.create({
initialize: function(PopupVariables) {
this.FadeDuration = PopupVariables[0];
this.FadeVal = PopupVariables[1];
this.MaskColor = PopupVariables[2];
this.UseAutoPopupPos = PopupVariables[3];
this.PopupWidth = PopupVariables[4];
this.PopupHeight = PopupVariables[5];
this.CurrentPopup = null; //I get overwriten alot. I wouldnt bother with me
this.CurrentPopupW = null; //I get overwriten alot. I wouldnt bother with me
this.CurrentPopupH = null; //I get overwriten alot. I wouldnt bother with me
this.createMask(PopupVariables[2]);
},
// PopupControl.createMask();
createMask: function(mc){
//create popup function
var bo = document.getElementsByTagName("body").item(0);
var objS = document.createElement("div");
objS.setAttribute('id','popFadeO');
objS.style.zIndex = 100;
objS.style.position = 'absolute';
objS.style.lineHeight = '0px';
objS.style.left = '0px';
objS.style.backgroundColor = mc;
objS.style.display = 'none';
objS.style.top = '0px';
bo.appendChild(objS);
$( 'popFadeO' ).style.width = getPageSize()[0] + "px";
$( 'popFadeO' ).style.height = getPageSize()[1] + "px";
//initialize page events
},
// PopupControl.togglePopup( string PopupObject, bool ShowPopup, int Width, int Height );
togglePopup: function( o, b, w, h ){
if( b )
{ //show popup
PopupControl.CurrentPopup = o;
PopupControl.CurrentPopupW = w;
PopupControl.CurrentPopupH = h;
$( o ).style.top = this.setPopPos( w, h )[0] + "px";
$( o ).style.left = this.setPopPos( w, h )[1] + "px";
this.togMask( true );
$( o ).style.zIndex = 101; //so we dont have to do it in the css
new Effect.Appear( o, { duration: PopupControl.FadeDuration, from: 0.0, to: 1.0 });
}
else
{ //hide popup
this.togMask( false );
this.CurrentPopup = null;
new Effect.Fade( o, { duration: PopupControl.FadeDuration, from: 1.0, to: 0.0 });
}
},
// PopupControl.getPopPos( int Width, int Height );
setPopPos: function( w, h )
{
var top = (((getPageSize()[3] - h) / 2) < 0) ? 0 : ((getPageSize()[3] - h) / 2);
top += getPageSize()[5];
var left = (((getPageSize()[2] - w) / 2) < 0) ? 0 : ((getPageSize()[2] - w) / 2);
left += getPageSize()[4];
return [top, left];
},
// PopupControl.autoPosFix();
autoPosFix: function()
{
if( PopupControl.CurrentPopup != null && PopupControl.UseAutoPopupPos )
{
$( PopupControl.CurrentPopup ).style.top = PopupControl.setPopPos( PopupControl.CurrentPopupW, PopupControl.CurrentPopupH )[0] + "px";
$( PopupControl.CurrentPopup ).style.left = PopupControl.setPopPos( PopupControl.CurrentPopupW, PopupControl.CurrentPopupH )[1] + "px";
}
$( 'popFadeO' ).style.width = getPageSize()[0] + "px";
$( 'popFadeO' ).style.height = getPageSize()[1] + "px";
},
// PopupControl.togMask( bool ShowMask );
togMask: function( b )
{ //Note: calling this function alone will result in an inacesable site.
// This displays NO close buttons. Just the mask.
if( b )
{
new Effect.Appear('popFadeO', { duration: PopupControl.FadeDuration, from: 0.0, to: PopupControl.FadeVal });
}
else
{
new Effect.Fade('popFadeO', { duration: PopupControl.FadeDuration, from: PopupControl.FadeVal, to: 0.0 });
}
},
// PopupControl.report();
report: function()
{
alert("Reporting popup class object variables:" +
"\nFadeDuration=" + PopupControl.FadeDuration +
"\nFadeVal=" + PopupControl.FadeVal +
"\nMaskColor=" + PopupControl.MaskColor +
"\nUseAutoPopupPos=" + PopupControl.UseAutoPopupPos +
"\nPopupWidth=" + PopupControl.PopupWidth +
"\nPopupHeight=" + PopupControl.PopupHeight);
}
});
// =========================================================================
// =========================================================================
// Popup Display Functions
var PopupControl = null;
// showPop( string PopupObject, int Width(Optional), int Height(Optional) );
function showPop( o, w, h )
{ //This is a simple go-between. you dont need it but it makes it easier to call popups.
//See togglePopup for actual popup calls.
if( PopupControl == null )
{ //create the popup object if it dosn't exist yet.
PopupControl = new PopupClass(PopupVariables);
SetEventHandler("resize", PopupControl.autoPosFix);
SetEventHandler("scroll", PopupControl.autoPosFix);
}
w = (w == null) ? PopupControl.PopupWidth : w;
h = (h == null) ? PopupControl.PopupHeight : h;
PopupControl.togglePopup( o, true, w, h );
}
// hidePop( string PopupObject );
function hidePop( o )
{ //This is a simple go-between. you dont need it but it makes it easier to call popups.
//See togPop for actual popup calls.
if( PopupControl == null )
{ //just incase we need to hide a popup before we use the show function.
PopupControl = new PopupClass( PopupVariables );
SetEventHandler("resize", PopupControl.autoPosFix);
SetEventHandler("scroll", PopupControl.autoPosFix);
}
PopupControl.togglePopup( o, false );
}
// =========================================================================
// Page Functions
// getPageSize();
function getPageSize()
{
var xScroll, yScroll;
var xScrollPos, yScrollPos;
if (window.innerHeight && window.scrollMaxY)
{
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
xScrollPos = window.pageXOffset;
yScrollPos = window.pageYOffset;
}
else if (document.body.scrollHeight > document.body.offsetHeight)
{ // all but Explorer Mac
xScroll = document.body.scrollWidth + 20;
yScroll = document.body.scrollHeight + 28;
xScrollPos = document.documentElement.scrollLeft;
yScrollPos = document.documentElement.scrollTop;
}
else
{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth + 20;
yScroll = document.body.offsetHeight + 28;
xScrollPos = document.documentElement.scrollLeft;
yScrollPos = document.documentElement.scrollTop;
}
var windowWidth, windowHeight;
if (self.innerHeight)
{ // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
}
else
{
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
{ // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
}
else if (document.body)
{ // other Explorers
windowWidth = document.body.clientWidth + 20;
windowHeight = document.body.clientHeight + 28;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight)
{
pageHeight = windowHeight;
}
else
{
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
return [pageWidth, pageHeight, windowWidth, windowHeight, xScrollPos, yScrollPos];
}
// SetEventHandler( string EventName, function EventHandler );
function SetEventHandler(eventname, handler)
{
if(window.addEventListener)
{
window.addEventListener(eventname, handler, false);
}
else if(window.attachEvent)
{
window.attachEvent("on" + eventname, handler);
}
}
// ========================================================================= | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var Scriptaculous = {
Version: '1.5.1',
require: function(libraryName) {
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
},
load: function() {
if((typeof Prototype=='undefined') ||
parseFloat(Prototype.Version.split(".")[0] + "." +
Prototype.Version.split(".")[1]) < 1.4)
throw("script.aculo.us requires the Prototype JavaScript framework >= 1.4.0");
$A(document.getElementsByTagName("script")).findAll( function(s) {
return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
}).each( function(s) {
var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
var includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
}
}
Scriptaculous.load(); | JavaScript |
if(typeof Class == "undefined")
{
Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
}
var JavaScriptExecuter = Class.create();
JavaScriptExecuter.prototype = {
initialize: function(url) {
this.url = url;
this.osrc = null;
},
run: function(url)
{
if(url!=null)
this.url=url;
if(this.url!=null)
{
if(this.osrc!=null)
{
document.body.removeChild(this.osrc);
this.osrc=null;
}
var scr=document.createElement('script');
scr.type = "text/javascript" ;
scr.setAttribute("src",this.url);
document.body.appendChild(scr);
this.osrc=scr;
}
}
}
| JavaScript |
/*
Date Format 1.1
(c) 2007 Steven Levithan <stevenlevithan.com>
MIT license
With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/
/*** dateFormat
Accepts a date, a mask, or a date and a mask.
Returns a formatted version of the given date.
The date defaults to the current date/time.
The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (value, length) {
value = String(value);
length = parseInt(length) || 2;
while (value.length < length)
value = "0" + value;
return value;
};
// Regexes and supporting functions are cached through closure
return function (date, mask) {
// Treat the first argument as a mask if it doesn't contain any numbers
if (
arguments.length == 1 &&
(typeof date == "string" || date instanceof String) &&
!/\d/.test(date)
) {
mask = date;
date = undefined;
}
date = date ? new Date(date) : new Date();
if (isNaN(date))
throw "invalid date";
var dF = dateFormat;
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
var d = date.getDate(),
D = date.getDay(),
m = date.getMonth(),
y = date.getFullYear(),
H = date.getHours(),
M = date.getMinutes(),
s = date.getSeconds(),
L = date.getMilliseconds(),
o = date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
};
return mask.replace(token, function ($0) {
return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm d yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask) {
return dateFormat(this, mask);
}
| JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
function ShowText(elementId, description){
var elem = document.getElementById(elementId);
if(elem){
elem.innerHTML = description;
}
}
| JavaScript |
if (typeof Prototype == 'undefined')
{
warning = "ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>).";
alert(warning);
}
if (Prototype.Version.substring(0, 8) == '1.5.0_rc')
{
warning = "ActiveScaffold Error: Prototype 1.5.0_rc is not supported. Please update prototype.js (rake rails:update:javascripts).";
alert(warning);
}
/*
* Simple utility methods
*/
var ActiveScaffold = {
records_for: function(tbody_id) {
var rows = [];
var child = $(tbody_id).down('.record');
while (child) {
rows.push(child);
child = child.next('.record');
}
return rows;
},
stripe: function(tbody_id) {
var even = false;
var rows = this.records_for(tbody_id);
for (var i = 0; i < rows.length; i++) {
var child = rows[i];
//Make sure to skip rows that are create or edit rows or messages
if (child.tagName != 'SCRIPT'
&& !child.hasClassName("create")
&& !child.hasClassName("update")
&& !child.hasClassName("inline-adapter")
&& !child.hasClassName("active-scaffold-calculations")) {
if (even) child.addClassName("even-record");
else child.removeClassName("even-record");
even = !even;
}
}
},
hide_empty_message: function(tbody, empty_message_id) {
if (this.records_for(tbody).length != 0) {
$(empty_message_id).hide();
}
},
reload_if_empty: function(tbody, url) {
var content_container_id = tbody.replace('tbody', 'content');
if (this.records_for(tbody).length == 0) {
new Ajax.Updater($(content_container_id), url, {
method: 'get',
asynchronous: true,
evalScripts: true
});
}
},
removeSortClasses: function(scaffold_id) {
$$('#' + scaffold_id + ' td.sorted').each(function(element) {
element.removeClassName("sorted");
});
$$('#' + scaffold_id + ' th.sorted').each(function(element) {
element.removeClassName("sorted");
element.removeClassName("asc");
element.removeClassName("desc");
});
},
decrement_record_count: function(scaffold_id) {
count = $$('#' + scaffold_id + ' span.active-scaffold-records').first();
count.innerHTML = parseInt(count.innerHTML) - 1;
},
increment_record_count: function(scaffold_id) {
count = $$('#' + scaffold_id + ' span.active-scaffold-records').first();
count.innerHTML = parseInt(count.innerHTML) + 1;
},
server_error_response: '',
report_500_response: function(active_scaffold_id) {
messages_container = $(active_scaffold_id).down('td.messages-container');
new Insertion.Top(messages_container, this.server_error_response);
}
}
/*
* DHTML history tie-in
*/
function addActiveScaffoldPageToHistory(url, active_scaffold_id) {
if (typeof dhtmlHistory == 'undefined') return; // it may not be loaded
var array = url.split('?');
var qs = new Querystring(array[1]);
var sort = qs.get('sort')
var dir = qs.get('sort_direction')
var page = qs.get('page')
if (sort || dir || page) dhtmlHistory.add(active_scaffold_id+":"+page+":"+sort+":"+dir, url);
}
/*
* Add-ons/Patches to Prototype
*/
/* patch to support replacing TR/TD/TBODY in Internet Explorer, courtesy of http://dev.rubyonrails.org/ticket/4273 */
Element.replace = function(element, html) {
element = $(element);
if (element.outerHTML) {
try {
element.outerHTML = html.stripScripts();
} catch (e) {
var tn = element.tagName;
if(tn=='TBODY' || tn=='TR' || tn=='TD')
{
var tempDiv = document.createElement("div");
tempDiv.innerHTML = '<table id="tempTable" style="display: none">' + html.stripScripts() + '</table>';
element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element);
}
else throw e;
}
} else {
var range = element.ownerDocument.createRange();
/* patch to fix <form> replaces in Firefox. see http://dev.rubyonrails.org/ticket/8010 */
range.selectNodeContents(element.parentNode);
element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element);
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
};
/*
* URL modification support. Incomplete functionality.
*/
Object.extend(String.prototype, {
append_params: function(params) {
url = this;
if (url.indexOf('?') == -1) url += '?';
else if (url.lastIndexOf('&') != url.length) url += '&';
url += $H(params).collect(function(item) {
return item.key + '=' + item.value;
}).join('&');
return url;
}
});
/*
* Prototype's implementation was throwing an error instead of false
*/
Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
var t = Element._attributeTranslations;
attribute = (t.names && t.names[attribute]) || attribute;
// Return false if we get an error here
try {
return $(element).getAttributeNode(attribute).specified;
} catch (e) {
return false;
}
}
};
/**
* A set of links. As a set, they can be controlled such that only one is "open" at a time, etc.
*/
ActiveScaffold.Actions = new Object();
ActiveScaffold.Actions.Abstract = function(){}
ActiveScaffold.Actions.Abstract.prototype = {
initialize: function(links, target, loading_indicator, options) {
this.target = $(target);
this.loading_indicator = $(loading_indicator);
this.options = options;
this.links = links.collect(function(link) {
return this.instantiate_link(link);
}.bind(this));
},
instantiate_link: function(link) {
throw 'unimplemented'
}
}
/**
* A DataStructures::ActionLink, represented in JavaScript.
* Concerned with AJAX-enabling a link and adapting the result for insertion into the table.
*/
ActiveScaffold.ActionLink = new Object();
ActiveScaffold.ActionLink.Abstract = function(){}
ActiveScaffold.ActionLink.Abstract.prototype = {
initialize: function(a, target, loading_indicator) {
this.tag = $(a);
this.url = this.tag.href;
this.target = target;
this.loading_indicator = loading_indicator;
this.hide_target = false;
this.position = this.tag.getAttribute('position');
this.page_link = this.tag.getAttribute('page_link');
this.onclick = this.tag.onclick;
this.tag.onclick = null;
this.tag.observe('click', function(event) {
this.open();
Event.stop(event);
}.bind(this));
this.tag.action_link = this;
},
open: function() {
if (this.is_disabled()) return;
if (this.tag.hasAttribute( "dhtml_confirm")) {
if (this.onclick) this.onclick();
return;
} else {
if (this.onclick && !this.onclick()) return;//e.g. confirmation messages
this.open_action();
}
},
open_action: function() {
if (this.position) this.disable();
if (this.page_link) {
window.location = this.url;
} else {
if (this.loading_indicator) this.loading_indicator.style.visibility = 'visible';
new Ajax.Request(this.url, {
asynchronous: true,
evalScripts: true,
onSuccess: function(request) {
if (this.position) {
this.insert(request.responseText);
if (this.hide_target) this.target.hide();
} else {
request.evalResponse();
}
}.bind(this),
onFailure: function(request) {
ActiveScaffold.report_500_response(this.scaffold_id());
if (this.position) this.enable()
}.bind(this),
onComplete: function(request) {
if (this.loading_indicator) this.loading_indicator.style.visibility = 'hidden';
}.bind(this)
});
}
},
insert: function(content) {
throw 'unimplemented'
},
close: function() {
this.enable();
this.adapter.remove();
if (this.hide_target) this.target.show();
},
register_cancel_hooks: function() {
// anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure
var self = this;
this.adapter.getElementsByClassName('cancel').each(function(elem) {
elem.observe('click', this.close_handler.bind(this));
elem.link = self;
}.bind(this))
},
reload: function() {
this.close();
this.open();
},
get_new_adapter_id: function() {
var id = 'adapter_';
var i = 0;
while ($(id + i)) i++;
return id + i;
},
enable: function() {
return this.tag.removeClassName('disabled');
},
disable: function() {
return this.tag.addClassName('disabled');
},
is_disabled: function() {
return this.tag.hasClassName('disabled');
},
scaffold_id: function() {
return this.tag.up('div.active-scaffold').id;
}
}
/**
* Concrete classes for record actions
*/
ActiveScaffold.Actions.Record = Class.create();
ActiveScaffold.Actions.Record.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
instantiate_link: function(link) {
var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator);
l.refresh_url = this.options.refresh_url;
if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
l.set = this;
return l;
}
});
ActiveScaffold.ActionLink.Record = Class.create();
ActiveScaffold.ActionLink.Record.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
insert: function(content) {
this.set.links.each(function(item) {
if (item.url != this.url && item.is_disabled() && item.adapter) item.close();
}.bind(this));
if (this.position == 'replace') {
this.position = 'after';
this.hide_target = true;
}
if (this.position == 'after') {
new Insertion.After(this.target, content);
this.adapter = this.target.next();
}
else if (this.position == 'before') {
new Insertion.Before(this.target, content);
this.adapter = this.target.previous();
}
else {
return false;
}
this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this));
this.register_cancel_hooks();
new Effect.Highlight(this.adapter.down('td'));
},
close_handler: function(event) {
this.close_with_refresh();
if (event) Event.stop(event);
},
/* it might simplify things to just override the close function. then the Record and Table links could share more code ... wouldn't need custom close_handler functions, for instance */
close_with_refresh: function() {
new Ajax.Request(this.refresh_url, {
asynchronous: true,
evalScripts: true,
onSuccess: function(request) {
Element.replace(this.target, request.responseText);
var new_target = $(this.target.id);
if (this.target.hasClassName('even-record')) new_target.addClassName('even-record');
this.target = new_target;
this.close();
}.bind(this),
onFailure: function(request) {
ActiveScaffold.report_500_response(this.scaffold_id());
}
});
},
enable: function() {
this.set.links.each(function(item) {
if (item.url != this.url) return;
item.tag.removeClassName('disabled');
}.bind(this));
},
disable: function() {
this.set.links.each(function(item) {
if (item.url != this.url) return;
item.tag.addClassName('disabled');
}.bind(this));
}
});
/**
* Concrete classes for table actions
*/
ActiveScaffold.Actions.Table = Class.create();
ActiveScaffold.Actions.Table.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), {
instantiate_link: function(link) {
var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator);
if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'});
return l;
}
});
ActiveScaffold.ActionLink.Table = Class.create();
ActiveScaffold.ActionLink.Table.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), {
insert: function(content) {
if (this.position == 'top') {
new Insertion.Top(this.target, content);
this.adapter = this.target.immediateDescendants().first();
}
else {
throw 'Unknown position "' + this.position + '"'
}
this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this));
this.register_cancel_hooks();
new Effect.Highlight(this.adapter.down('td'));
},
close_handler: function(event) {
this.close();
if (event) Event.stop(event);
}
}); | JavaScript |
function NukeBadChars(textElement)
{
var strTemp = textElement.value;
for (i=0; i < strTemp.length; i++)
{
if (
(strTemp.charAt(i) == "'") ||
(strTemp.charAt(i) == '"'))
{
strTemp = strTemp.substr(0,i) + strTemp.substr(i + 1);
i--;
}
}
textElement.value = strTemp
}
function NumberCleanUp(num)
{
var sVal='';
var nVal = num.length;
var sChar='';
// First
try
{
for(i = 0 ; i < nVal; i++)
{
sChar = num.charAt(i);
nChar = sChar.charCodeAt(0);
if (sChar =='.')
{
//alert('here');
sVal += num.charAt(i);
// i = nVal; // Done
}
else if ((nChar >=48) && (nChar <=57))
{
sVal += num.charAt(i);
}
}
}
catch (exception) { AlertError("Format Clean",e); }
return sVal;
}
function PercentageFormat(textElement)
{
var strTemp = textElement.value;
var szTemp = strTemp.split(".");
if (szTemp.length > 1)
{
textElement.value = NumberCleanUp(szTemp[0]) + "." + NumberCleanUp(szTemp[1]) + "%";
}
else
{
textElement.value = NumberCleanUp(szTemp[0]) + "%";
}
}
function UsaPhoneDashAdd(textElement)
{
var strTemp = textElement.value;
strTemp = NumberCleanUp(textElement.value);
if (strTemp)
{
textElement.value = strTemp.substr(0,3) + '-' + strTemp.substr(3,3) + '-' + strTemp.substr(6);
}
}
function UsaZipDashAdd(textElement)
{
var strTemp = textElement.value;
strTemp = NumberCleanUp(textElement.value);
if (strTemp.length > 5)
{
textElement.value = strTemp.substr(0,5) + '-' + strTemp.substr(5);
}
}
function UsaMoney(textElement)
{
var strAmount = NumberCleanUp(textElement.value);
if (strAmount.length == 0)
{
textElement.value = '';
}
else
{
strAmount = NumberDelimeterAdd(strAmount, ",");
if (strAmount.length == 0)
{
textElement.value = '';
}
else
{
textElement.value = "$" + strAmount;
}
}
}
function UsaNumberDelimeterAdd(textElement)
{
var strAmount = NumberCleanUp(textElement.value);
if (strAmount.length == 0)
{
textElement.value = '';
}
else
{
strAmount = NumberDelimeterAdd(strAmount, ",");
if (strAmount.length == 0)
{
textElement.value = '';
}
else
{
textElement.value = strAmount;
}
}
}
function NumberDelimeterAdd(amount, CommaDelimiter)
{
try
{
amount = parseFloat(amount);
var samount = new String(amount);
var decimal = '';
if (samount.indexOf(".") >= 0)
{
decimal = samount.substr(samount.length-3,3);
samount = samount.substr(0, samount.length-3);
//alert(samount + " : " + decimal);
}
for (var i = 0; i < Math.floor((samount.length-(1+i))/3); i++)
{
samount = samount.substring(0,samount.length-(4*i+3)) + CommaDelimiter + samount.substring(samount.length-(4*i+3));
}
samount += decimal;
}
catch (exception) { AlertError("Format Comma",e); }
return samount;
}
| JavaScript |
// TODO Change to dropping the name property off the input element when in example mode
TextFieldWithExample = Class.create();
TextFieldWithExample.prototype = {
initialize: function(inputElementId, defaultText, options) {
this.setOptions(options);
this.input = $(inputElementId);
this.name = this.input.name;
this.defaultText = defaultText;
this.createHiddenInput();
this.checkAndShowExample();
Event.observe(this.input, "blur", this.onBlur.bindAsEventListener(this));
Event.observe(this.input, "focus", this.onFocus.bindAsEventListener(this));
Event.observe(this.input, "select", this.onFocus.bindAsEventListener(this));
Event.observe(this.input, "keydown", this.onKeyPress.bindAsEventListener(this));
Event.observe(this.input, "click", this.onClick.bindAsEventListener(this));
},
createHiddenInput: function() {
this.hiddenInput = document.createElement("input");
this.hiddenInput.type = "hidden";
this.hiddenInput.value = "";
this.input.parentNode.appendChild(this.hiddenInput);
},
setOptions: function(options) {
this.options = { exampleClassName: 'example' };
Object.extend(this.options, options || {});
},
onKeyPress: function(event) {
if (!event) var event = window.event;
var code = (event.which) ? event.which : event.keyCode
if (this.isAlphanumeric(code)) {
this.removeExample();
}
},
onBlur: function(event) {
this.checkAndShowExample();
},
onFocus: function(event) {
if (this.exampleShown()) {
this.removeExample();
}
},
onClick: function(event) {
this.removeExample();
},
isAlphanumeric: function(keyCode) {
return keyCode >= 40 && keyCode <= 90;
},
checkAndShowExample: function() {
if (this.input.value == '') {
this.input.value = this.defaultText;
this.input.name = null;
this.hiddenInput.name = this.name;
Element.addClassName(this.input, this.options.exampleClassName);
}
},
removeExample: function() {
if (this.exampleShown()) {
this.input.value = '';
this.input.name = this.name;
this.hiddenInput.name = null;
Element.removeClassName(this.input, this.options.exampleClassName);
}
},
exampleShown: function() {
return Element.hasClassName(this.input, this.options.exampleClassName);
}
}
Form.disable = function(form) {
var elements = this.getElements(form);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
try { element.blur(); } catch (e) {}
element.disabled = 'disabled';
Element.addClassName(element, 'disabled');
}
}
Form.enable = function(form) {
var elements = this.getElements(form);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.disabled = '';
Element.removeClassName(element, 'disabled');
}
} | JavaScript |
/**
Copyright (c) 2005, Brad Neuberg, bkn3@columbia.edu
http://codinginparadise.org
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The JSON class near the end of this file is
Copyright 2005, JSON.org
*/
/** An object that provides DHTML history, history data, and bookmarking
for AJAX applications. */
window.dhtmlHistory = {
/** Initializes our DHTML history. You should
call this after the page is finished loading. */
/** public */ initialize: function() {
// only Internet Explorer needs to be explicitly initialized;
// other browsers don't have its particular behaviors.
// Basicly, IE doesn't autofill form data until the page
// is finished loading, which means historyStorage won't
// work until onload has been fired.
if (this.isInternetExplorer() == false) {
return;
}
// if this is the first time this page has loaded...
if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) {
this.fireOnNewListener = false;
this.firstLoad = true;
historyStorage.put("DhtmlHistory_pageLoaded", true);
}
// else if this is a fake onload event
else {
this.fireOnNewListener = true;
this.firstLoad = false;
}
},
/** Adds a history change listener. Note that
only one listener is supported at this
time. */
/** public */ addListener: function(callback) {
this.listener = callback;
// if the page was just loaded and we
// should not ignore it, fire an event
// to our new listener now
if (this.fireOnNewListener == true) {
this.fireHistoryEvent(this.currentLocation);
this.fireOnNewListener = false;
}
},
/** public */ add: function(newLocation, historyData) {
// most browsers require that we wait a certain amount of time before changing the
// location, such as 200 milliseconds; rather than forcing external callers to use
// window.setTimeout to account for this to prevent bugs, we internally handle this
// detail by using a 'currentWaitTime' variable and have requests wait in line
var self = this;
var addImpl = function() {
// indicate that the current wait time is now less
if (self.currentWaitTime > 0)
self.currentWaitTime = self.currentWaitTime - self.WAIT_TIME;
// remove any leading hash symbols on newLocation
newLocation = self.removeHash(newLocation);
// IE has a strange bug; if the newLocation
// is the same as _any_ preexisting id in the
// document, then the history action gets recorded
// twice; throw a programmer exception if there is
// an element with this ID
var idCheck = $(newLocation);
if (idCheck != undefined || idCheck != null) {
var message =
"Exception: History locations can not have "
+ "the same value as _any_ id's "
+ "that might be in the document, "
+ "due to a bug in Internet "
+ "Explorer; please ask the "
+ "developer to choose a history "
+ "location that does not match "
+ "any HTML id's in this "
+ "document. The following ID "
+ "is already taken and can not "
+ "be a location: "
+ newLocation;
throw message;
}
// store the history data into history storage
historyStorage.put(newLocation, historyData);
// indicate to the browser to ignore this upcomming
// location change
self.ignoreLocationChange = true;
// indicate to IE that this is an atomic location change
// block
this.ieAtomicLocationChange = true;
// save this as our current location
self.currentLocation = newLocation;
// change the browser location
window.location.hash = newLocation;
// change the hidden iframe's location if on IE
if (self.isInternetExplorer())
self.iframe.src = "/blank.html?" + newLocation;
// end of atomic location change block
// for IE
this.ieAtomicLocationChange = false;
};
// now execute this add request after waiting a certain amount of time, so as to
// queue up requests
window.setTimeout(addImpl, this.currentWaitTime);
// indicate that the next request will have to wait for awhile
this.currentWaitTime = this.currentWaitTime + this.WAIT_TIME;
},
/** public */ isFirstLoad: function() {
if (this.firstLoad == true) {
return true;
}
else {
return false;
}
},
/** public */ isInternational: function() {
return false;
},
/** public */ getVersion: function() {
return "0.05";
},
/** Gets the current hash value that is in the browser's
location bar, removing leading # symbols if they are present. */
/** public */ getCurrentLocation: function() {
var currentLocation = escape(this.removeHash(window.location.hash));
return currentLocation;
},
/** Our current hash location, without the "#" symbol. */
/** private */ currentLocation: null,
/** Our history change listener. */
/** private */ listener: null,
/** A hidden IFrame we use in Internet Explorer to detect history
changes. */
/** private */ iframe: null,
/** Indicates to the browser whether to ignore location changes. */
/** private */ ignoreLocationChange: null,
/** The amount of time in milliseconds that we should wait between add requests.
Firefox is okay with 200 ms, but Internet Explorer needs 400. */
/** private */ WAIT_TIME: 200,
/** The amount of time in milliseconds an add request has to wait in line before being
run on a window.setTimeout. */
/** private */ currentWaitTime: 0,
/** A flag that indicates that we should fire a history change event
when we are ready, i.e. after we are initialized and
we have a history change listener. This is needed due to
an edge case in browsers other than Internet Explorer; if
you leave a page entirely then return, we must fire this
as a history change event. Unfortunately, we have lost
all references to listeners from earlier, because JavaScript
clears out. */
/** private */ fireOnNewListener: null,
/** A variable that indicates whether this is the first time
this page has been loaded. If you go to a web page, leave
it for another one, and then return, the page's onload
listener fires again. We need a way to differentiate
between the first page load and subsequent ones.
This variable works hand in hand with the pageLoaded
variable we store into historyStorage.*/
/** private */ firstLoad: null,
/** A variable to handle an important edge case in Internet
Explorer. In IE, if a user manually types an address into
their browser's location bar, we must intercept this by
continiously checking the location bar with an timer
interval. However, if we manually change the location
bar ourselves programmatically, when using our hidden
iframe, we need to ignore these changes. Unfortunately,
these changes are not atomic, so we surround them with
the variable 'ieAtomicLocationChange', that if true,
means we are programmatically setting the location and
should ignore this atomic chunked change. */
/** private */ ieAtomicLocationChange: null,
/** Creates the DHTML history infrastructure. */
/** private */ create: function() {
// get our initial location
var initialHash = this.getCurrentLocation();
// save this as our current location
this.currentLocation = initialHash;
// write out a hidden iframe for IE and
// set the amount of time to wait between add() requests
if (this.isInternetExplorer()) {
document.write("<iframe style='border: 0px; width: 1px; "
+ "height: 1px; position: absolute; bottom: 0px; "
+ "right: 0px; visibility: visible;' "
+ "name='DhtmlHistoryFrame' id='DhtmlHistoryFrame' "
+ "src='/blank.html?" + initialHash + "'>"
+ "</iframe>");
// wait 400 milliseconds between history
// updates on IE, versus 200 on Firefox
this.WAIT_TIME = 400;
}
// add an unload listener for the page; this is
// needed for Firefox 1.5+ because this browser caches all
// dynamic updates to the page, which can break some of our
// logic related to testing whether this is the first instance
// a page has loaded or whether it is being pulled from the cache
var self = this;
window.onunload = function() {
self.firstLoad = null;
};
// determine if this is our first page load;
// for Internet Explorer, we do this in
// this.iframeLoaded(), which is fired on
// page load. We do it there because
// we have no historyStorage at this point
// in IE, which only exists after the page
// is finished loading for that browser
if (this.isInternetExplorer() == false) {
if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) {
this.ignoreLocationChange = true;
this.firstLoad = true;
historyStorage.put("DhtmlHistory_pageLoaded", true);
}
else {
// indicate that we want to pay attention
// to this location change
this.ignoreLocationChange = false;
// For browser's other than IE, fire
// a history change event; on IE,
// the event will be thrown automatically
// when it's hidden iframe reloads
// on page load.
// Unfortunately, we don't have any
// listeners yet; indicate that we want
// to fire an event when a listener
// is added.
this.fireOnNewListener = true;
}
}
else { // Internet Explorer
// the iframe will get loaded on page
// load, and we want to ignore this fact
this.ignoreLocationChange = true;
}
if (this.isInternetExplorer()) {
this.iframe = $("DhtmlHistoryFrame");
}
// other browsers can use a location handler that checks
// at regular intervals as their primary mechanism;
// we use it for Internet Explorer as well to handle
// an important edge case; see checkLocation() for
// details
var self = this;
var locationHandler = function() {
self.checkLocation();
};
setInterval(locationHandler, 100);
},
/** Notify the listener of new history changes. */
/** private */ fireHistoryEvent: function(newHash) {
// extract the value from our history storage for
// this hash
var historyData = historyStorage.get(newHash);
// call our listener
this.listener.call(null, newHash, historyData);
},
/** Sees if the browsers has changed location. This is the primary history mechanism
for Firefox. For Internet Explorer, we use this to handle an important edge case:
if a user manually types in a new hash value into their Internet Explorer location
bar and press enter, we want to intercept this and notify any history listener. */
/** private */ checkLocation: function() {
// ignore any location changes that we made ourselves
// for browsers other than Internet Explorer
if (this.isInternetExplorer() == false
&& this.ignoreLocationChange == true) {
this.ignoreLocationChange = false;
return;
}
// if we are dealing with Internet Explorer
// and we are in the middle of making a location
// change from an iframe, ignore it
if (this.isInternetExplorer() == false
&& this.ieAtomicLocationChange == true) {
return;
}
// get hash location
var hash = this.getCurrentLocation();
// see if there has been a change
if (hash == this.currentLocation)
return;
// on Internet Explorer, we need to intercept users manually
// entering locations into the browser; we do this by comparing
// the browsers location against the iframes location; if they
// differ, we are dealing with a manual event and need to
// place it inside our history, otherwise we can return
this.ieAtomicLocationChange = true;
if (this.isInternetExplorer()
&& this.getIFrameHash() != hash) {
this.iframe.src = "/blank.html?" + hash;
}
else if (this.isInternetExplorer()) {
// the iframe is unchanged
return;
}
// save this new location
this.currentLocation = hash;
this.ieAtomicLocationChange = false;
// notify listeners of the change
this.fireHistoryEvent(hash);
},
/** Gets the current location of the hidden IFrames
that is stored as history. For Internet Explorer. */
/** private */ getIFrameHash: function() {
// get the new location
var historyFrame = $("DhtmlHistoryFrame");
var doc = historyFrame.contentWindow.document;
var hash = new String(doc.location.search);
if (hash.length == 1 && hash.charAt(0) == "?")
hash = "";
else if (hash.length >= 2 && hash.charAt(0) == "?")
hash = hash.substring(1);
return hash;
},
/** Removes any leading hash that might be on a location. */
/** private */ removeHash: function(hashValue) {
if (hashValue == null || hashValue == undefined)
return null;
else if (hashValue == "")
return "";
else if (hashValue.length == 1 && hashValue.charAt(0) == "#")
return "";
else if (hashValue.length > 1 && hashValue.charAt(0) == "#")
return hashValue.substring(1);
else
return hashValue;
},
/** For IE, says when the hidden iframe has finished loading. */
/** private */ iframeLoaded: function(newLocation) {
// ignore any location changes that we made ourselves
if (this.ignoreLocationChange == true) {
this.ignoreLocationChange = false;
return;
}
// get the new location
var hash = new String(newLocation.search);
if (hash.length == 1 && hash.charAt(0) == "?")
hash = "";
else if (hash.length >= 2 && hash.charAt(0) == "?")
hash = hash.substring(1);
// move to this location in the browser location bar
// if we are not dealing with a page load event
if (this.pageLoadEvent != true) {
window.location.hash = hash;
}
// notify listeners of the change
this.fireHistoryEvent(hash);
},
/** Determines if this is Internet Explorer. */
/** private */ isInternetExplorer: function() {
var userAgent = navigator.userAgent.toLowerCase();
if (document.all && userAgent.indexOf('msie')!=-1) {
return true;
}
else {
return false;
}
}
};
/** An object that uses a hidden form to store history state
across page loads. The chief mechanism for doing so is using
the fact that browser's save the text in form data for the
life of the browser and cache, which means the text is still
there when the user navigates back to the page. See
http://codinginparadise.org/weblog/2005/08/ajax-tutorial-saving-session-across.html
for full details. */
window.historyStorage = {
/** If true, we are debugging and show the storage textfield. */
/** public */ debugging: false,
/** Our hash of key name/values. */
/** private */ storageHash: new Object(),
/** If true, we have loaded our hash table out of the storage form. */
/** private */ hashLoaded: false,
/** public */ put: function(key, value) {
this.assertValidKey(key);
// if we already have a value for this,
// remove the value before adding the
// new one
if (this.hasKey(key)) {
this.remove(key);
}
// store this new key
this.storageHash[key] = value;
// save and serialize the hashtable into the form
this.saveHashTable();
},
/** public */ get: function(key) {
this.assertValidKey(key);
// make sure the hash table has been loaded
// from the form
this.loadHashTable();
var value = this.storageHash[key];
if (value == undefined)
return null;
else
return value;
},
/** public */ remove: function(key) {
this.assertValidKey(key);
// make sure the hash table has been loaded
// from the form
this.loadHashTable();
// delete the value
delete this.storageHash[key];
// serialize and save the hash table into the
// form
this.saveHashTable();
},
/** Clears out all saved data. */
/** public */ reset: function() {
this.storageField.value = "";
this.storageHash = new Object();
},
/** public */ hasKey: function(key) {
this.assertValidKey(key);
// make sure the hash table has been loaded
// from the form
this.loadHashTable();
if (typeof this.storageHash[key] == "undefined")
return false;
else
return true;
},
/** public */ isValidKey: function(key) {
// allow all strings, since we don't use XML serialization
// format anymore
return (typeof key == "string");
},
/** A reference to our textarea field. */
/** private */ storageField: null,
/** private */ init: function() {
/** simplified newContent from <div><form><input/></form></div> to fix an IE display glitch */
var newContent = "<input type='text' id='historyStorageField' name='historyStorageField' style='display: none;'/>";
document.write(newContent);
this.storageField = $("historyStorageField");
},
/** Asserts that a key is valid, throwing
an exception if it is not. */
/** private */ assertValidKey: function(key) {
if (this.isValidKey(key) == false) {
throw "Please provide a valid key for "
+ "window.historyStorage, key= "
+ key;
}
},
/** Loads the hash table up from the form. */
/** private */ loadHashTable: function() {
if (this.hashLoaded == false) {
// get the hash table as a serialized
// string
var serializedHashTable = this.storageField.value;
if (serializedHashTable != "" &&
serializedHashTable != null) {
// destringify the content back into a
// real JavaScript object
this.storageHash = eval('(' + serializedHashTable + ')');
}
this.hashLoaded = true;
}
},
/** Saves the hash table into the form. */
/** private */ saveHashTable: function() {
this.loadHashTable();
// serialized the hash table
var serializedHashTable = JSON.stringify(this.storageHash);
// save this value
this.storageField.value = serializedHashTable;
}
};
/** The JSON class is copyright 2005 JSON.org. */
Array.prototype.______array = '______array';
var JSON = {
org: 'http://www.JSON.org',
copyright: '(c)2005 JSON.org',
license: 'http://www.crockford.com/JSON/license.html',
stringify: function (arg) {
var c, i, l, s = '', v;
switch (typeof arg) {
case 'object':
if (arg) {
if (arg.______array == '______array') {
for (i = 0; i < arg.length; ++i) {
v = this.stringify(arg[i]);
if (s) {
s += ',';
}
s += v;
}
return '[' + s + ']';
} else if (typeof arg.toString != 'undefined') {
for (i in arg) {
v = arg[i];
if (typeof v != 'undefined' && typeof v != 'function') {
v = this.stringify(v);
if (s) {
s += ',';
}
s += this.stringify(i) + ':' + v;
}
}
return '{' + s + '}';
}
}
return 'null';
case 'number':
return isFinite(arg) ? String(arg) : 'null';
case 'string':
l = arg.length;
s = '"';
for (i = 0; i < l; i += 1) {
c = arg.charAt(i);
if (c >= ' ') {
if (c == '\\' || c == '"') {
s += '\\';
}
s += c;
} else {
switch (c) {
case '\b':
s += '\\b';
break;
case '\f':
s += '\\f';
break;
case '\n':
s += '\\n';
break;
case '\r':
s += '\\r';
break;
case '\t':
s += '\\t';
break;
default:
c = c.charCodeAt();
s += '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}
}
}
return s + '"';
case 'boolean':
return String(arg);
default:
return 'null';
}
},
parse: function (text) {
var at = 0;
var ch = ' ';
function error(m) {
throw {
name: 'JSONError',
message: m,
at: at - 1,
text: text
};
}
function next() {
ch = text.charAt(at);
at += 1;
return ch;
}
function white() {
while (ch != '' && ch <= ' ') {
next();
}
}
function str() {
var i, s = '', t, u;
if (ch == '"') {
outer: while (next()) {
if (ch == '"') {
next();
return s;
} else if (ch == '\\') {
switch (next()) {
case 'b':
s += '\b';
break;
case 'f':
s += '\f';
break;
case 'n':
s += '\n';
break;
case 'r':
s += '\r';
break;
case 't':
s += '\t';
break;
case 'u':
u = 0;
for (i = 0; i < 4; i += 1) {
t = parseInt(next(), 16);
if (!isFinite(t)) {
break outer;
}
u = u * 16 + t;
}
s += String.fromCharCode(u);
break;
default:
s += ch;
}
} else {
s += ch;
}
}
}
error("Bad string");
}
function arr() {
var a = [];
if (ch == '[') {
next();
white();
if (ch == ']') {
next();
return a;
}
while (ch) {
a.push(val());
white();
if (ch == ']') {
next();
return a;
} else if (ch != ',') {
break;
}
next();
white();
}
}
error("Bad array");
}
function obj() {
var k, o = {};
if (ch == '{') {
next();
white();
if (ch == '}') {
next();
return o;
}
while (ch) {
k = str();
white();
if (ch != ':') {
break;
}
next();
o[k] = val();
white();
if (ch == '}') {
next();
return o;
} else if (ch != ',') {
break;
}
next();
white();
}
}
error("Bad object");
}
function num() {
var n = '', v;
if (ch == '-') {
n = '-';
next();
}
while (ch >= '0' && ch <= '9') {
n += ch;
next();
}
if (ch == '.') {
n += '.';
while (next() && ch >= '0' && ch <= '9') {
n += ch;
}
}
if (ch == 'e' || ch == 'E') {
n += 'e';
next();
if (ch == '-' || ch == '+') {
n += ch;
next();
}
while (ch >= '0' && ch <= '9') {
n += ch;
next();
}
}
v = +n;
if (!isFinite(v)) {
error("Bad number");
} else {
return v;
}
}
function word() {
switch (ch) {
case 't':
if (next() == 'r' && next() == 'u' && next() == 'e') {
next();
return true;
}
break;
case 'f':
if (next() == 'a' && next() == 'l' && next() == 's' &&
next() == 'e') {
next();
return false;
}
break;
case 'n':
if (next() == 'u' && next() == 'l' && next() == 'l') {
next();
return null;
}
break;
}
error("Syntax error");
}
function val() {
white();
switch (ch) {
case '{':
return obj();
case '[':
return arr();
case '"':
return str();
case '-':
return num();
default:
return ch >= '0' && ch <= '9' ? num() : word();
}
}
return val();
}
};
/** QueryString Object from http://adamv.com/dev/javascript/querystring */
/* Client-side access to querystring name=value pairs
Version 1.2.3
22 Jun 2005
Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
this.params = new Object()
this.get=Querystring_get
if (qs == null)
qs=location.search.substring(1,location.search.length)
if (qs.length == 0) return
// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
qs = qs.replace(/\+/g, ' ')
// added by Scott Rutherford, change all & to &
qs = qs.replace(/&/g, '&')
var args = qs.split('&') // parse out name/value pairs separated via &
// split out each name=value pair
for (var i=0;i<args.length;i++) {
var value;
var pair = args[i].split('=')
var name = unescape(pair[0])
if (pair.length == 2)
value = unescape(pair[1])
else
value = name
this.params[name] = value
}
}
function Querystring_get(key, default_) {
// This silly looking line changes UNDEFINED to NULL
if (default_ == null) default_ = null;
var value=this.params[key]
if (value==null) value=default_;
return value
}
/** ADDED BY SCOTT RUTHERFORD, COMINDED July 2006 scott@cominded */
/** Initialize all of our objects now. */
window.historyStorage.init();
window.dhtmlHistory.create();
/** Create init methods for ActiveScaffold */
function initialize() {
// initialize our DHTML history
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(handleHistoryChange);
}
/** Our callback to receive history
change events. */
function handleHistoryChange(pageId, pageData) {
if (!pageData) return;
var info = pageId.split(':');
var id = info[0];
pageData += '&_method=get';
new Ajax.Updater(id+'-content', pageData, {asynchronous:true, evalScripts:true, onLoading:function(request){Element.show(id+'-pagination-loading-indicator');}});
}
/** set onload handler */
Event.observe(window, 'load', initialize, false);
| JavaScript |
/**
*
* Copyright 2005 Sabre Airline Solutions
*
* 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.
**/
//-------------------- rico.js
var Rico = {
Version: '1.1.0',
prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1])
}
//-------------------- ricoColor.js
Rico.Color = Class.create();
Rico.Color.prototype = {
initialize: function(red, green, blue) {
this.rgb = { r: red, g : green, b : blue };
},
blend: function(other) {
this.rgb.r = Math.floor((this.rgb.r + other.rgb.r)/2);
this.rgb.g = Math.floor((this.rgb.g + other.rgb.g)/2);
this.rgb.b = Math.floor((this.rgb.b + other.rgb.b)/2);
},
asRGB: function() {
return "rgb(" + this.rgb.r + "," + this.rgb.g + "," + this.rgb.b + ")";
},
asHex: function() {
return "#" + this.rgb.r.toColorPart() + this.rgb.g.toColorPart() + this.rgb.b.toColorPart();
},
asHSB: function() {
return Rico.Color.RGBtoHSB(this.rgb.r, this.rgb.g, this.rgb.b);
},
toString: function() {
return this.asHex();
}
};
Rico.Color.createFromHex = function(hexCode) {
if(hexCode.length==4) {
var shortHexCode = hexCode;
var hexCode = '#';
for(var i=1;i<4;i++) hexCode += (shortHexCode.charAt(i) + shortHexCode.charAt(i));
}
if ( hexCode.indexOf('#') == 0 )
hexCode = hexCode.substring(1);
var red = hexCode.substring(0,2);
var green = hexCode.substring(2,4);
var blue = hexCode.substring(4,6);
return new Rico.Color( parseInt(red,16), parseInt(green,16), parseInt(blue,16) );
}
/**
* Factory method for creating a color from the background of
* an HTML element.
*/
Rico.Color.createColorFromBackground = function(elem) {
//var actualColor = RicoUtil.getElementsComputedStyle($(elem), "backgroundColor", "background-color"); // Changed to prototype style
var actualColor = $(elem).getStyle('backgroundColor');
if ( actualColor == "transparent" && elem.parentNode )
return Rico.Color.createColorFromBackground(elem.parentNode);
if ( actualColor == null )
return new Rico.Color(255,255,255);
if ( actualColor.indexOf("rgb(") == 0 ) {
var colors = actualColor.substring(4, actualColor.length - 1 );
var colorArray = colors.split(",");
return new Rico.Color( parseInt( colorArray[0] ),
parseInt( colorArray[1] ),
parseInt( colorArray[2] ) );
}
else if ( actualColor.indexOf("#") == 0 ) {
return Rico.Color.createFromHex(actualColor);
}
else
return new Rico.Color(255,255,255);
}
/* next two functions changed to mootools color.js functions */
Rico.Color.HSBtoRGB = function(hue, saturation, brightness) {
var br = Math.round(brightness / 100 * 255);
if (this[1] == 0){
return [br, br, br];
} else {
var hue = this[0] % 360;
var f = hue % 60;
var p = Math.round((brightness * (100 - saturation)) / 10000 * 255);
var q = Math.round((brightness * (6000 - saturation * f)) / 600000 * 255);
var t = Math.round((brightness * (6000 - saturation * (60 - f))) / 600000 * 255);
switch(Math.floor(hue / 60)){
case 0: return { r : br, g : t, b : p };
case 1: return { r : q, g : br, b : p };
case 2: return { r : p, g : br, b : t };
case 3: return { r : p, g : q, b : br };
case 4: return { r : t, g : p, b : br };
case 5: return { r : br, g : p, b : q };
}
}
return false;
}
Rico.Color.RGBtoHSB = function(red, green, blue) {
var hue, saturation, brightness;
var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
var delta = max - min;
brightness = max / 255;
saturation = (max != 0) ? delta / max : 0;
if (saturation == 0){
hue = 0;
} else {
var rr = (max - red) / delta;
var gr = (max - green) / delta;
var br = (max - blue) / delta;
if (red == max) hue = br - gr;
else if (green == max) hue = 2 + rr - br;
else hue = 4 + gr - rr;
hue /= 6;
if (hue < 0) hue++;
}
return { h : Math.round(hue * 360), s : Math.round(saturation * 100), b : Math.round(brightness * 100)};
}
//-------------------- ricoCorner.js
Rico.Corner = {
round: function(e, options) {
var e = $(e);
this._setOptions(options);
var color = this.options.color;
if ( this.options.color == "fromElement" )
color = this._background(e);
var bgColor = this.options.bgColor;
if ( this.options.bgColor == "fromParent" )
bgColor = this._background(e.offsetParent);
this._roundCornersImpl(e, color, bgColor);
},
_roundCornersImpl: function(e, color, bgColor) {
if(this.options.border)
this._renderBorder(e,bgColor);
if(this._isTopRounded())
this._roundTopCorners(e,color,bgColor);
if(this._isBottomRounded())
this._roundBottomCorners(e,color,bgColor);
},
_renderBorder: function(el,bgColor) {
var borderValue = "1px solid " + this._borderColor(bgColor);
var borderL = "border-left: " + borderValue;
var borderR = "border-right: " + borderValue;
var style = "style='" + borderL + ";" + borderR + "'";
el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>"
},
_roundTopCorners: function(el, color, bgColor) {
var corner = this._createCorner(bgColor);
for(var i=0 ; i < this.options.numSlices ; i++ )
corner.appendChild(this._createCornerSlice(color,bgColor,i,"top"));
el.style.paddingTop = 0;
el.insertBefore(corner,el.firstChild);
},
_roundBottomCorners: function(el, color, bgColor) {
var corner = this._createCorner(bgColor);
for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- )
corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom"));
el.style.paddingBottom = 0;
el.appendChild(corner);
},
_createCorner: function(bgColor) {
var corner = document.createElement("div");
corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor);
return corner;
},
_createCornerSlice: function(color,bgColor, n, position) {
var slice = document.createElement("span");
var inStyle = slice.style;
inStyle.backgroundColor = color;
inStyle.display = "block";
inStyle.height = "1px";
inStyle.overflow = "hidden";
inStyle.fontSize = "1px";
var borderColor = this._borderColor(color,bgColor);
if ( this.options.border && n == 0 ) {
inStyle.borderTopStyle = "solid";
inStyle.borderTopWidth = "1px";
inStyle.borderLeftWidth = "0px";
inStyle.borderRightWidth = "0px";
inStyle.borderBottomWidth = "0px";
inStyle.height = "0px"; // assumes css compliant box model
inStyle.borderColor = borderColor;
}
else if(borderColor) {
inStyle.borderColor = borderColor;
inStyle.borderStyle = "solid";
inStyle.borderWidth = "0px 1px";
}
if ( !this.options.compact && (n == (this.options.numSlices-1)) )
inStyle.height = "2px";
this._setMargin(slice, n, position);
this._setBorder(slice, n, position);
return slice;
},
_setOptions: function(options) {
this.options = {
corners : "all",
color : "fromElement",
bgColor : "fromParent",
blend : true,
border : false,
compact : false
}
Object.extend(this.options, options || {});
this.options.numSlices = this.options.compact ? 2 : 4;
if ( this._isTransparent() )
this.options.blend = false;
},
_whichSideTop: function() {
if ( this._hasString(this.options.corners, "all", "top") )
return "";
if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 )
return "";
if (this.options.corners.indexOf("tl") >= 0)
return "left";
else if (this.options.corners.indexOf("tr") >= 0)
return "right";
return "";
},
_whichSideBottom: function() {
if ( this._hasString(this.options.corners, "all", "bottom") )
return "";
if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 )
return "";
if(this.options.corners.indexOf("bl") >=0)
return "left";
else if(this.options.corners.indexOf("br")>=0)
return "right";
return "";
},
_borderColor : function(color,bgColor) {
if ( color == "transparent" )
return bgColor;
else if ( this.options.border )
return this.options.border;
else if ( this.options.blend )
return this._blend( bgColor, color );
else
return "";
},
_setMargin: function(el, n, corners) {
var marginSize = this._marginSize(n);
var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();
if ( whichSide == "left" ) {
el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px";
}
else if ( whichSide == "right" ) {
el.style.marginRight = marginSize + "px"; el.style.marginLeft = "0px";
}
else {
el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px";
}
},
_setBorder: function(el,n,corners) {
var borderSize = this._borderSize(n);
var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();
if ( whichSide == "left" ) {
el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px";
}
else if ( whichSide == "right" ) {
el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth = "0px";
}
else {
el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
}
if (this.options.border != false)
el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
},
_marginSize: function(n) {
if ( this._isTransparent() )
return 0;
var marginSizes = [ 5, 3, 2, 1 ];
var blendedMarginSizes = [ 3, 2, 1, 0 ];
var compactMarginSizes = [ 2, 1 ];
var smBlendedMarginSizes = [ 1, 0 ];
if ( this.options.compact && this.options.blend )
return smBlendedMarginSizes[n];
else if ( this.options.compact )
return compactMarginSizes[n];
else if ( this.options.blend )
return blendedMarginSizes[n];
else
return marginSizes[n];
},
_borderSize: function(n) {
var transparentBorderSizes = [ 5, 3, 2, 1 ];
var blendedBorderSizes = [ 2, 1, 1, 1 ];
var compactBorderSizes = [ 1, 0 ];
var actualBorderSizes = [ 0, 2, 0, 0 ];
if ( this.options.compact && (this.options.blend || this._isTransparent()) )
return 1;
else if ( this.options.compact )
return compactBorderSizes[n];
else if ( this.options.blend )
return blendedBorderSizes[n];
else if ( this.options.border )
return actualBorderSizes[n];
else if ( this._isTransparent() )
return transparentBorderSizes[n];
return 0;
},
_hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; },
_blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; },
_background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } },
_isTransparent: function() { return this.options.color == "transparent"; },
_isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); },
_isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); },
_hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; }
}
| JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Scriptaculous = {
Version: '1.8.1',
require: function(libraryName) {
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
},
REQUIRED_PROTOTYPE: '1.6.0',
load: function() {
function convertVersionString(versionString){
var r = versionString.split('.');
return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
}
if((typeof Prototype=='undefined') ||
(typeof Element == 'undefined') ||
(typeof Element.Methods=='undefined') ||
(convertVersionString(Prototype.Version) <
convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= " +
Scriptaculous.REQUIRED_PROTOTYPE);
$A(document.getElementsByTagName("script")).findAll( function(s) {
return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
}).each( function(s) {
var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
var includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
}
}
Scriptaculous.load(); | JavaScript |
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true,onloadCoords:null,maxWidth:0,maxHeight:0},_8||{});
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
this.fixedWidth=(this.options.maxWidth>0&&(this.options.minWidth>=this.options.maxWidth));
this.fixedHeight=(this.options.maxHeight>0&&(this.options.minHeight>=this.options.maxHeight));
if(typeof this.img=="undefined"){
return;
}
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
this.startDragBind=this.startDrag.bindAsEventListener(this);
Event.observe(this.dragArea,"mousedown",this.startDragBind);
this.onDragBind=this.onDrag.bindAsEventListener(this);
Event.observe(document,"mousemove",this.onDragBind);
this.endCropBind=this.endCrop.bindAsEventListener(this);
Event.observe(document,"mouseup",this.endCropBind);
this.resizeBind=this.startResize.bindAsEventListener(this);
this.handles=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
this.registerHandles(true);
if(this.options.captureKeys){
this.keysBind=this.handleKeys.bindAsEventListener(this);
Event.observe(document,"keypress",this.keysBind);
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},registerHandles:function(_13){
for(var i=0;i<this.handles.length;i++){
var _15=$(this.handles[i]);
if(_13){
var _16=false;
if(this.fixedWidth&&this.fixedHeight){
_16=true;
}else{
if(this.fixedWidth||this.fixedHeight){
var _17=_15.className.match(/([S|N][E|W])$/);
var _18=_15.className.match(/(E|W)$/);
var _19=_15.className.match(/(N|S)$/);
if(_17){
_16=true;
}else{
if(this.fixedWidth&&_18){
_16=true;
}else{
if(this.fixedHeight&&_19){
_16=true;
}
}
}
}
}
if(_16){
_15.hide();
}else{
Event.observe(_15,"mousedown",this.resizeBind);
}
}else{
_15.show();
Event.stopObserving(_15,"mousedown",this.resizeBind);
}
}
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
$(this.north).setStyle({height:0});
$(this.east).setStyle({width:0,height:0});
$(this.south).setStyle({height:0});
$(this.west).setStyle({width:0,height:0});
$(this.imgWrap).setStyle({"width":this.imgW+"px","height":this.imgH+"px"});
$(this.selArea).hide();
var _1a={x1:0,y1:0,x2:0,y2:0};
var _1b=false;
if(this.options.onloadCoords!=null){
_1a=this.cloneCoords(this.options.onloadCoords);
_1b=true;
}else{
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
_1a.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_1a.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_1a.x2=_1a.x1+this.options.ratioDim.x;
_1a.y2=_1a.y1+this.options.ratioDim.y;
_1b=true;
}
}
this.setAreaCoords(_1a,false,false,1);
if(this.options.displayOnInit&&_1b){
this.selArea.show();
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
if(this.attached){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDragBind);
Event.stopObserving(document,"mousemove",this.onDragBind);
Event.stopObserving(document,"mouseup",this.endCropBind);
this.registerHandles(false);
if(this.options.captureKeys){
Event.stopObserving(document,"keypress",this.keysBind);
}
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1e){
this.setAreaCoords({x1:_1e[0],y1:_1e[1],x2:_1e[0]+this.calcW(),y2:_1e[1]+this.calcH()},true,false);
this.drawArea();
},cloneCoords:function(_1f){
return {x1:_1f.x1,y1:_1f.y1,x2:_1f.x2,y2:_1f.y2};
},setAreaCoords:function(_20,_21,_22,_23,_24){
if(_21){
var _25=_20.x2-_20.x1;
var _26=_20.y2-_20.y1;
if(_20.x1<0){
_20.x1=0;
_20.x2=_25;
}
if(_20.y1<0){
_20.y1=0;
_20.y2=_26;
}
if(_20.x2>this.imgW){
_20.x2=this.imgW;
_20.x1=this.imgW-_25;
}
if(_20.y2>this.imgH){
_20.y2=this.imgH;
_20.y1=this.imgH-_26;
}
}else{
if(_20.x1<0){
_20.x1=0;
}
if(_20.y1<0){
_20.y1=0;
}
if(_20.x2>this.imgW){
_20.x2=this.imgW;
}
if(_20.y2>this.imgH){
_20.y2=this.imgH;
}
if(_23!=null){
if(this.ratioX>0){
this.applyRatio(_20,{x:this.ratioX,y:this.ratioY},_23,_24);
}else{
if(_22){
this.applyRatio(_20,{x:1,y:1},_23,_24);
}
}
var _27=[this.options.minWidth,this.options.minHeight];
var _28=[this.options.maxWidth,this.options.maxHeight];
if(_27[0]>0||_27[1]>0||_28[0]>0||_28[1]>0){
var _29={a1:_20.x1,a2:_20.x2};
var _2a={a1:_20.y1,a2:_20.y2};
var _2b={min:0,max:this.imgW};
var _2c={min:0,max:this.imgH};
if((_27[0]!=0||_27[1]!=0)&&_22){
if(_27[0]>0){
_27[1]=_27[0];
}else{
if(_27[1]>0){
_27[0]=_27[1];
}
}
}
if((_28[0]!=0||_28[0]!=0)&&_22){
if(_28[0]>0&&_28[0]<=_28[1]){
_28[1]=_28[0];
}else{
if(_28[1]>0&&_28[1]<=_28[0]){
_28[0]=_28[1];
}
}
}
if(_27[0]>0){
this.applyDimRestriction(_29,_27[0],_23.x,_2b,"min");
}
if(_27[1]>1){
this.applyDimRestriction(_2a,_27[1],_23.y,_2c,"min");
}
if(_28[0]>0){
this.applyDimRestriction(_29,_28[0],_23.x,_2b,"max");
}
if(_28[1]>1){
this.applyDimRestriction(_2a,_28[1],_23.y,_2c,"max");
}
_20={x1:_29.a1,y1:_2a.a1,x2:_29.a2,y2:_2a.a2};
}
}
}
this.areaCoords=_20;
},applyDimRestriction:function(_2d,val,_2f,_30,_31){
var _32;
if(_31=="min"){
_32=((_2d.a2-_2d.a1)<val);
}else{
_32=((_2d.a2-_2d.a1)>val);
}
if(_32){
if(_2f==1){
_2d.a2=_2d.a1+val;
}else{
_2d.a1=_2d.a2-val;
}
if(_2d.a1<_30.min){
_2d.a1=_30.min;
_2d.a2=val;
}else{
if(_2d.a2>_30.max){
_2d.a1=_30.max-val;
_2d.a2=_30.max;
}
}
}
},applyRatio:function(_33,_34,_35,_36){
var _37;
if(_36=="N"||_36=="S"){
_37=this.applyRatioToAxis({a1:_33.y1,b1:_33.x1,a2:_33.y2,b2:_33.x2},{a:_34.y,b:_34.x},{a:_35.y,b:_35.x},{min:0,max:this.imgW});
_33.x1=_37.b1;
_33.y1=_37.a1;
_33.x2=_37.b2;
_33.y2=_37.a2;
}else{
_37=this.applyRatioToAxis({a1:_33.x1,b1:_33.y1,a2:_33.x2,b2:_33.y2},{a:_34.x,b:_34.y},{a:_35.x,b:_35.y},{min:0,max:this.imgH});
_33.x1=_37.a1;
_33.y1=_37.b1;
_33.x2=_37.a2;
_33.y2=_37.b2;
}
},applyRatioToAxis:function(_38,_39,_3a,_3b){
var _3c=Object.extend(_38,{});
var _3d=_3c.a2-_3c.a1;
var _3e=Math.floor(_3d*_39.b/_39.a);
var _3f;
var _40;
var _41=null;
if(_3a.b==1){
_3f=_3c.b1+_3e;
if(_3f>_3b.max){
_3f=_3b.max;
_41=_3f-_3c.b1;
}
_3c.b2=_3f;
}else{
_3f=_3c.b2-_3e;
if(_3f<_3b.min){
_3f=_3b.min;
_41=_3f+_3c.b2;
}
_3c.b1=_3f;
}
if(_41!=null){
_40=Math.floor(_41*_39.a/_39.b);
if(_3a.a==1){
_3c.a2=_3c.a1+_40;
}else{
_3c.a1=_3c.a1=_3c.a2-_40;
}
}
return _3c;
},drawArea:function(){
var _42=this.calcW();
var _43=this.calcH();
var px="px";
var _45=[this.areaCoords.x1+px,this.areaCoords.y1+px,_42+px,_43+px,this.areaCoords.x2+px,this.areaCoords.y2+px,(this.img.width-this.areaCoords.x2)+px,(this.img.height-this.areaCoords.y2)+px];
var _46=this.selArea.style;
_46.left=_45[0];
_46.top=_45[1];
_46.width=_45[2];
_46.height=_45[3];
var _47=Math.ceil((_42-6)/2)+px;
var _48=Math.ceil((_43-6)/2)+px;
this.handleN.style.left=_47;
this.handleE.style.top=_48;
this.handleS.style.left=_47;
this.handleW.style.top=_48;
this.north.style.height=_45[1];
var _49=this.east.style;
_49.top=_45[1];
_49.height=_45[3];
_49.left=_45[4];
_49.width=_45[6];
var _4a=this.south.style;
_4a.top=_45[5];
_4a.height=_45[7];
var _4b=this.west.style;
_4b.top=_45[1];
_4b.height=_45[3];
_4b.width=_45[0];
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4e=["SE","S","SW"];
for(i=0;i<_4e.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4e[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Event.element(e).classNames().toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
this.selArea.show();
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y},false,false,null);
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
var el=this.imgWrap,wrapOffsets=Position.cumulativeOffset(el);
while(el.nodeName!="BODY"){
wrapOffsets[1]-=el.scrollTop||0;
wrapOffsets[0]-=el.scrollLeft||0;
el=el.parentNode;
}
return curPos={x:Event.pointerX(e)-wrapOffsets[0],y:Event.pointerY(e)-wrapOffsets[1]};
},onDrag:function(e){
if(this.dragging||this.resizing){
var _54=null;
var _55=this.getCurPos(e);
var _56=this.cloneCoords(this.areaCoords);
var _57={x:1,y:1};
if(this.dragging){
if(_55.x<this.clickCoords.x){
_57.x=-1;
}
if(_55.y<this.clickCoords.y){
_57.y=-1;
}
this.transformCoords(_55.x,this.clickCoords.x,_56,"x");
this.transformCoords(_55.y,this.clickCoords.y,_56,"y");
}else{
if(this.resizing){
_54=this.resizeHandle;
if(_54.match(/E/)){
this.transformCoords(_55.x,this.startCoords.x1,_56,"x");
if(_55.x<this.startCoords.x1){
_57.x=-1;
}
}else{
if(_54.match(/W/)){
this.transformCoords(_55.x,this.startCoords.x2,_56,"x");
if(_55.x<this.startCoords.x2){
_57.x=-1;
}
}
}
if(_54.match(/N/)){
this.transformCoords(_55.y,this.startCoords.y2,_56,"y");
if(_55.y<this.startCoords.y2){
_57.y=-1;
}
}else{
if(_54.match(/S/)){
this.transformCoords(_55.y,this.startCoords.y1,_56,"y");
if(_55.y<this.startCoords.y1){
_57.y=-1;
}
}
}
}
}
this.setAreaCoords(_56,false,e.shiftKey,_57,_54);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_58,_59,_5a,_5b){
var _5c=[_58,_59];
if(_58>_59){
_5c.reverse();
}
_5a[_5b+"1"]=_5c[0];
_5a[_5b+"2"]=_5c[1];
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.previewImg.id="imgCrop_"+this.previewImg.id;
this.options.displayOnInit=true;
this.hasPreviewImg=true;
this.previewWrap.addClassName("imgCrop_previewWrap");
this.previewWrap.setStyle({width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _5d=this.calcW();
var _5e=this.calcH();
var _5f={x:this.imgW/_5d,y:this.imgH/_5e};
var _60={x:_5d/this.options.minWidth,y:_5e/this.options.minHeight};
var _61={w:Math.ceil(this.options.minWidth*_5f.x)+"px",h:Math.ceil(this.options.minHeight*_5f.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_60.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_60.y)+"px"};
var _62=this.previewImg.style;
_62.width=_61.w;
_62.height=_61.h;
_62.left=_61.x;
_62.top=_61.y;
}
}});
| JavaScript |
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
* -----------------------------------------------------------
*
* The DHTML Calendar, version 1.0 "It is happening again"
*
* Details and latest version at:
* www.dynarch.com/projects/calendar
*
* This script is developed by Dynarch.com. Visit us at www.dynarch.com.
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*/
// $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $
/** The Calendar object constructor. */
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) );
// ADDED
Calendar.is_ie7 = ( Calendar.is_ie && /msie 7\.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";
}
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) {
if (Prototype) {
this.muliple.each(function(multiple) {
var cell = this.datesCells[multiple.key];
var d = multiple.value;
if (!d)
return;
if (cell)
cell.className += " selected";
})
} else {
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;
}
//ADDED IE 7 popup fix
if (Calendar.is_ie7) {
br.y += window.scrollY;
br.x += window.scrollX;
} else {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
}
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", "iframe", "select");
var el = this.element;
var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;
for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;
for (var i = ar.length; i > 0;) {
cc = ar[--i];
p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;
if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
/** 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;
};
if ( !Date.prototype.__msh_oldSetFullYear ) {
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;
| JavaScript |
// ** I18N
Calendar._DN = new Array
("Duminică",
"Luni",
"Marţi",
"Miercuri",
"Joi",
"Vineri",
"Sâmbătă",
"Duminică");
Calendar._SDN_len = 2;
Calendar._MN = new Array
("Ianuarie",
"Februarie",
"Martie",
"Aprilie",
"Mai",
"Iunie",
"Iulie",
"August",
"Septembrie",
"Octombrie",
"Noiembrie",
"Decembrie");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Despre calendar";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Pentru ultima versiune vizitaţi: http://www.dynarch.com/projects/calendar/\n" +
"Distribuit sub GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Selecţia datei:\n" +
"- Folosiţi butoanele \xab, \xbb pentru a selecta anul\n" +
"- Folosiţi butoanele " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pentru a selecta luna\n" +
"- Tineţi butonul mouse-ului apăsat pentru selecţie mai rapidă.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selecţia orei:\n" +
"- Click pe ora sau minut pentru a mări valoarea cu 1\n" +
"- Sau Shift-Click pentru a micşora valoarea cu 1\n" +
"- Sau Click şi drag pentru a selecta mai repede.";
Calendar._TT["PREV_YEAR"] = "Anul precedent (lung pt menu)";
Calendar._TT["PREV_MONTH"] = "Luna precedentă (lung pt menu)";
Calendar._TT["GO_TODAY"] = "Data de azi";
Calendar._TT["NEXT_MONTH"] = "Luna următoare (lung pt menu)";
Calendar._TT["NEXT_YEAR"] = "Anul următor (lung pt menu)";
Calendar._TT["SEL_DATE"] = "Selectează data";
Calendar._TT["DRAG_TO_MOVE"] = "Trage pentru a mişca";
Calendar._TT["PART_TODAY"] = " (astăzi)";
Calendar._TT["DAY_FIRST"] = "Afişează %s prima zi";
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "Închide";
Calendar._TT["TODAY"] = "Astăzi";
Calendar._TT["TIME_PART"] = "(Shift-)Click sau drag pentru a selecta";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %d %B";
Calendar._TT["WK"] = "spt";
Calendar._TT["TIME"] = "Ora:";
| JavaScript |
// ** I18N Afrikaans
Calendar._DN = new Array
("Sondag",
"Maandag",
"Dinsdag",
"Woensdag",
"Donderdag",
"Vrydag",
"Saterdag",
"Sondag");
Calendar._MN = new Array
("Januarie",
"Februarie",
"Maart",
"April",
"Mei",
"Junie",
"Julie",
"Augustus",
"September",
"Oktober",
"November",
"Desember");
// tooltips
Calendar._TT = {};
Calendar._TT["TOGGLE"] = "Verander eerste dag van die week";
Calendar._TT["PREV_YEAR"] = "Vorige jaar (hou vir keuselys)";
Calendar._TT["PREV_MONTH"] = "Vorige maand (hou vir keuselys)";
Calendar._TT["GO_TODAY"] = "Gaan na vandag";
Calendar._TT["NEXT_MONTH"] = "Volgende maand (hou vir keuselys)";
Calendar._TT["NEXT_YEAR"] = "Volgende jaar (hou vir keuselys)";
Calendar._TT["SEL_DATE"] = "Kies datum";
Calendar._TT["DRAG_TO_MOVE"] = "Sleep om te skuif";
Calendar._TT["PART_TODAY"] = " (vandag)";
Calendar._TT["MON_FIRST"] = "Vertoon Maandag eerste";
Calendar._TT["SUN_FIRST"] = "Display Sunday first";
Calendar._TT["CLOSE"] = "Close";
Calendar._TT["TODAY"] = "Today";
| JavaScript |
// ** I18N
Calendar._DN = new Array
("Zondag",
"Maandag",
"Dinsdag",
"Woensdag",
"Donderdag",
"Vrijdag",
"Zaterdag",
"Zondag");
Calendar._SDN_len = 2;
Calendar._MN = new Array
("Januari",
"Februari",
"Maart",
"April",
"Mei",
"Juni",
"Juli",
"Augustus",
"September",
"Oktober",
"November",
"December");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Info";
Calendar._TT["ABOUT"] =
"DHTML Datum/Tijd Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Ga voor de meest recente versie naar: http://www.dynarch.com/projects/calendar/\n" +
"Verspreid onder de GNU LGPL. Zie http://gnu.org/licenses/lgpl.html voor details." +
"\n\n" +
"Datum selectie:\n" +
"- Gebruik de \xab \xbb knoppen om een jaar te selecteren\n" +
"- Gebruik de " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " knoppen om een maand te selecteren\n" +
"- Houd de muis ingedrukt op de genoemde knoppen voor een snellere selectie.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Tijd selectie:\n" +
"- Klik op een willekeurig onderdeel van het tijd gedeelte om het te verhogen\n" +
"- of Shift-klik om het te verlagen\n" +
"- of klik en sleep voor een snellere selectie.";
//Calendar._TT["TOGGLE"] = "Selecteer de eerste week-dag";
Calendar._TT["PREV_YEAR"] = "Vorig jaar (ingedrukt voor menu)";
Calendar._TT["PREV_MONTH"] = "Vorige maand (ingedrukt voor menu)";
Calendar._TT["GO_TODAY"] = "Ga naar Vandaag";
Calendar._TT["NEXT_MONTH"] = "Volgende maand (ingedrukt voor menu)";
Calendar._TT["NEXT_YEAR"] = "Volgend jaar (ingedrukt voor menu)";
Calendar._TT["SEL_DATE"] = "Selecteer datum";
Calendar._TT["DRAG_TO_MOVE"] = "Klik en sleep om te verplaatsen";
Calendar._TT["PART_TODAY"] = " (vandaag)";
//Calendar._TT["MON_FIRST"] = "Toon Maandag eerst";
//Calendar._TT["SUN_FIRST"] = "Toon Zondag eerst";
Calendar._TT["DAY_FIRST"] = "Toon %s eerst";
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "Sluiten";
Calendar._TT["TODAY"] = "(vandaag)";
Calendar._TT["TIME_PART"] = "(Shift-)Klik of sleep om de waarde te veranderen";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e %b %Y";
Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Tijd:"; | JavaScript |
// ** I18N
// Calendar pt_BR language
// Author: Adalberto Machado, <betosm@terra.com.br>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Domingo",
"Segunda",
"Terca",
"Quarta",
"Quinta",
"Sexta",
"Sabado",
"Domingo");
// 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
("Dom",
"Seg",
"Ter",
"Qua",
"Qui",
"Sex",
"Sab",
"Dom");
// full month names
Calendar._MN = new Array
("Janeiro",
"Fevereiro",
"Marco",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro");
// short month names
Calendar._SMN = new Array
("Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Sobre o calendario";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Ultima versao visite: http://www.dynarch.com/projects/calendar/\n" +
"Distribuido sobre GNU LGPL. Veja http://gnu.org/licenses/lgpl.html para detalhes." +
"\n\n" +
"Selecao de data:\n" +
"- Use os botoes \xab, \xbb para selecionar o ano\n" +
"- Use os botoes " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " para selecionar o mes\n" +
"- Segure o botao do mouse em qualquer um desses botoes para selecao rapida.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selecao de hora:\n" +
"- Clique em qualquer parte da hora para incrementar\n" +
"- ou Shift-click para decrementar\n" +
"- ou clique e segure para selecao rapida.";
Calendar._TT["PREV_YEAR"] = "Ant. ano (segure para menu)";
Calendar._TT["PREV_MONTH"] = "Ant. mes (segure para menu)";
Calendar._TT["GO_TODAY"] = "Hoje";
Calendar._TT["NEXT_MONTH"] = "Prox. mes (segure para menu)";
Calendar._TT["NEXT_YEAR"] = "Prox. ano (segure para menu)";
Calendar._TT["SEL_DATE"] = "Selecione a data";
Calendar._TT["DRAG_TO_MOVE"] = "Arraste para mover";
Calendar._TT["PART_TODAY"] = " (hoje)";
// 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"] = "Mostre %s primeiro";
// 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"] = "Fechar";
Calendar._TT["TODAY"] = "Hoje";
Calendar._TT["TIME_PART"] = "(Shift-)Click ou arraste para mudar valor";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d/%m/%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e %b";
Calendar._TT["WK"] = "sm";
Calendar._TT["TIME"] = "Hora:";
| JavaScript |
// ** I18N
// Calendar KO (Korean) language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Translation: Yourim Yi <yyi@yourim.net>
// Encoding: ASCII with \uXXXX unicode escapes
// lang : ko
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("\uc77c\uc694\uc77c",
"\uc6d4\uc694\uc77c",
"\ud654\uc694\uc77c",
"\uc218\uc694\uc77c",
"\ubaa9\uc694\uc77c",
"\uae08\uc694\uc77c",
"\ud1a0\uc694\uc77c",
"\uc77c\uc694\uc77c");
// 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
("\uc77c",
"\uc6d4",
"\ud654",
"\uc218",
"\ubaa9",
"\uae08",
"\ud1a0",
"\uc77c");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("1\uc6d4",
"2\uc6d4",
"3\uc6d4",
"4\uc6d4",
"5\uc6d4",
"6\uc6d4",
"7\uc6d4",
"8\uc6d4",
"9\uc6d4",
"10\uc6d4",
"11\uc6d4",
"12\uc6d4");
// short month names
Calendar._SMN = new Array
("1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "calendar \uc5d0 \ub300\ud574\uc11c";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"\n"+
"\ucd5c\uc2e0 \ubc84\uc804\uc744 \ubc1b\uc73c\uc2dc\ub824\uba74 http://www.dynarch.com/projects/calendar/ \uc5d0 \ubc29\ubb38\ud558\uc138\uc694\n" +
"\n"+
"GNU LGPL \ub77c\uc774\uc13c\uc2a4\ub85c \ubc30\ud3ec\ub429\ub2c8\ub2e4. \n"+
"\ub77c\uc774\uc13c\uc2a4\uc5d0 \ub300\ud55c \uc790\uc138\ud55c \ub0b4\uc6a9\uc740 http://gnu.org/licenses/lgpl.html \uc744 \uc77d\uc73c\uc138\uc694." +
"\n\n" +
"\ub0a0\uc9dc \uc120\ud0dd:\n" +
"- \uc5f0\ub3c4\ub97c \uc120\ud0dd\ud558\ub824\uba74 \u00ab, \u00bb \ubc84\ud2bc\uc744 \uc0ac\uc6a9\ud569\ub2c8\ub2e4\n" +
"- \ub2ec\uc744 \uc120\ud0dd\ud558\ub824\uba74 \u2039, \u203a \ubc84\ud2bc\uc744 \ub204\ub974\uc138\uc694\n" +
"- \uacc4\uc18d \ub204\ub974\uace0 \uc788\uc73c\uba74 \uc704 \uac12\ub4e4\uc744 \ube60\ub974\uac8c \uc120\ud0dd\ud558\uc2e4 \uc218 \uc788\uc2b5\ub2c8\ub2e4.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"\uc2dc\uac04 \uc120\ud0dd:\n" +
"- \ub9c8\uc6b0\uc2a4\ub85c \ub204\ub974\uba74 \uc2dc\uac04\uc774 \uc99d\uac00\ud569\ub2c8\ub2e4\n" +
"- Shift \ud0a4\uc640 \ud568\uaed8 \ub204\ub974\uba74 \uac10\uc18c\ud569\ub2c8\ub2e4\n" +
"- \ub204\ub978 \uc0c1\ud0dc\uc5d0\uc11c \ub9c8\uc6b0\uc2a4\ub97c \uc6c0\uc9c1\uc774\uba74 \uc880 \ub354 \ube60\ub974\uac8c \uac12\uc774 \ubcc0\ud569\ub2c8\ub2e4.\n";
Calendar._TT["PREV_YEAR"] = "\uc9c0\ub09c \ud574 (\uae38\uac8c \ub204\ub974\uba74 \ubaa9\ub85d)";
Calendar._TT["PREV_MONTH"] = "\uc9c0\ub09c \ub2ec (\uae38\uac8c \ub204\ub974\uba74 \ubaa9\ub85d)";
Calendar._TT["GO_TODAY"] = "\uc624\ub298 \ub0a0\uc9dc\ub85c";
Calendar._TT["NEXT_MONTH"] = "\ub2e4\uc74c \ub2ec (\uae38\uac8c \ub204\ub974\uba74 \ubaa9\ub85d)";
Calendar._TT["NEXT_YEAR"] = "\ub2e4\uc74c \ud574 (\uae38\uac8c \ub204\ub974\uba74 \ubaa9\ub85d)";
Calendar._TT["SEL_DATE"] = "\ub0a0\uc9dc\ub97c \uc120\ud0dd\ud558\uc138\uc694";
Calendar._TT["DRAG_TO_MOVE"] = "\ub9c8\uc6b0\uc2a4 \ub4dc\ub798\uadf8\ub85c \uc774\ub3d9 \ud558\uc138\uc694";
Calendar._TT["PART_TODAY"] = " (\uc624\ub298)";
Calendar._TT["MON_FIRST"] = "\uc6d4\uc694\uc77c\uc744 \ud55c \uc8fc\uc758 \uc2dc\uc791 \uc694\uc77c\ub85c";
Calendar._TT["SUN_FIRST"] = "\uc77c\uc694\uc77c\uc744 \ud55c \uc8fc\uc758 \uc2dc\uc791 \uc694\uc77c\ub85c";
Calendar._TT["CLOSE"] = "\ub2eb\uae30";
Calendar._TT["TODAY"] = "\uc624\ub298";
Calendar._TT["TIME_PART"] = "(Shift-)\ud074\ub9ad \ub610\ub294 \ub4dc\ub798\uadf8 \ud558\uc138\uc694";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%b/%e [%a]";
Calendar._TT["WK"] = "\uc8fc";
// Added by Dan Lipofsky just to get it working, but it still needs translation
Calendar._TT["DAY_FIRST"] = "Display %s first";
Calendar._TT["TIME"] = "Time:";
Calendar._TT["WEEKEND"] = "0,6";
| JavaScript |
// ** I18N
// Calendar NO language
// Author: Daniel Holmen, <daniel.holmen@ciber.no>
// Encoding: UTF-8
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Søndag",
"Mandag",
"Tirsdag",
"Onsdag",
"Torsdag",
"Fredag",
"Lørdag",
"Søndag");
// 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
("Søn",
"Man",
"Tir",
"Ons",
"Tor",
"Fre",
"Lør",
"Søn");
// full month names
Calendar._MN = new Array
("Januar",
"Februar",
"Mars",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Desember");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Des");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Om kalenderen";
Calendar._TT["ABOUT"] =
"DHTML Dato-/Tidsvelger\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For nyeste versjon, gå til: http://www.dynarch.com/projects/calendar/\n" +
"Distribuert under GNU LGPL. Se http://gnu.org/licenses/lgpl.html for detaljer." +
"\n\n" +
"Datovalg:\n" +
"- Bruk knappene \xab og \xbb for å velge år\n" +
"- Bruk knappene " + String.fromCharCode(0x2039) + " og " + String.fromCharCode(0x203a) + " for å velge måned\n" +
"- Hold inne musknappen eller knappene over for raskere valg.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Tidsvalg:\n" +
"- Klikk på en av tidsdelene for å øke den\n" +
"- eller Shift-klikk for å senke verdien\n" +
"- eller klikk-og-dra for raskere valg..";
Calendar._TT["PREV_YEAR"] = "Forrige. år (hold for meny)";
Calendar._TT["PREV_MONTH"] = "Forrige. måned (hold for meny)";
Calendar._TT["GO_TODAY"] = "Gå til idag";
Calendar._TT["NEXT_MONTH"] = "Neste måned (hold for meny)";
Calendar._TT["NEXT_YEAR"] = "Neste år (hold for meny)";
Calendar._TT["SEL_DATE"] = "Velg dato";
Calendar._TT["DRAG_TO_MOVE"] = "Dra for å flytte";
Calendar._TT["PART_TODAY"] = " (idag)";
Calendar._TT["MON_FIRST"] = "Vis mandag først";
Calendar._TT["SUN_FIRST"] = "Vis søndag først";
Calendar._TT["CLOSE"] = "Lukk";
Calendar._TT["TODAY"] = "Idag";
Calendar._TT["TIME_PART"] = "(Shift-)Klikk eller dra for å endre verdi";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d.%m.%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "uke"; | JavaScript |
/*
calendar-cs-win.js
language: Czech
encoding: windows-1250
author: Lubos Jerabek (xnet@seznam.cz)
Jan Uhlir (espinosa@centrum.cz)
*/
// ** I18N
Calendar._DN = new Array('Neděle','Pondělí','Úterý','Středa','Čtvrtek','Pátek','Sobota','Neděle');
Calendar._SDN = new Array('Ne','Po','Út','St','Čt','Pá','So','Ne');
Calendar._MN = new Array('Leden','Únor','Březen','Duben','Květen','Červen','Červenec','Srpen','Září','Říjen','Listopad','Prosinec');
Calendar._SMN = new Array('Led','Úno','Bře','Dub','Kvě','Črv','Čvc','Srp','Zář','Říj','Lis','Pro');
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O komponentě kalendář";
Calendar._TT["TOGGLE"] = "Změna prvního dne v týdnu";
Calendar._TT["PREV_YEAR"] = "Předchozí rok (přidrž pro menu)";
Calendar._TT["PREV_MONTH"] = "Předchozí měsíc (přidrž pro menu)";
Calendar._TT["GO_TODAY"] = "Dnešní datum";
Calendar._TT["NEXT_MONTH"] = "Další měsíc (přidrž pro menu)";
Calendar._TT["NEXT_YEAR"] = "Další rok (přidrž pro menu)";
Calendar._TT["SEL_DATE"] = "Vyber datum";
Calendar._TT["DRAG_TO_MOVE"] = "Chyť a táhni, pro přesun";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "Ukaž jako první Pondělí";
//Calendar._TT["SUN_FIRST"] = "Ukaž jako první Neděli";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Výběr datumu:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Použijte tlačítka " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " k výběru měsíce\n" +
"- Podržte tlačítko myši na jakémkoliv z těch tlačítek pro rychlejší výběr.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Výběr času:\n" +
"- Klikněte na jakoukoliv z částí výběru času pro zvýšení.\n" +
"- nebo Shift-click pro snížení\n" +
"- nebo klikněte a táhněte pro rychlejší výběr.";
// 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"] = "Zobraz %s první";
// 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"] = "Zavřít";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)Klikni nebo táhni pro změnu hodnoty";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "d.m.yy";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Čas:";
| JavaScript |
// ** I18N
// Calendar PL language
// Author: Dariusz Pietrzak, <eyck@ghost.anime.pl>
// Author: Janusz Piwowarski, <jpiw@go2.pl>
// Encoding: utf-8
// Distributed under the same terms as the calendar itself.
Calendar._DN = new Array
("Niedziela",
"Poniedziałek",
"Wtorek",
"Środa",
"Czwartek",
"Piątek",
"Sobota",
"Niedziela");
Calendar._SDN = new Array
("Nie",
"Pn",
"Wt",
"Śr",
"Cz",
"Pt",
"So",
"Nie");
Calendar._MN = new Array
("Styczeń",
"Luty",
"Marzec",
"Kwiecień",
"Maj",
"Czerwiec",
"Lipiec",
"Sierpień",
"Wrzesień",
"Październik",
"Listopad",
"Grudzień");
Calendar._SMN = new Array
("Sty",
"Lut",
"Mar",
"Kwi",
"Maj",
"Cze",
"Lip",
"Sie",
"Wrz",
"Paź",
"Lis",
"Gru");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendarzu";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Aby pobrać najnowszą wersję, odwiedź: http://www.dynarch.com/projects/calendar/\n" +
"Dostępny na licencji GNU LGPL. Zobacz szczegóły na http://gnu.org/licenses/lgpl.html." +
"\n\n" +
"Wybór daty:\n" +
"- Użyj przycisków \xab, \xbb by wybrać rok\n" +
"- Użyj przycisków " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " by wybrać miesiąc\n" +
"- Przytrzymaj klawisz myszy nad jednym z powyższych przycisków dla szybszego wyboru.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Wybór czasu:\n" +
"- Kliknij na jednym z pól czasu by zwiększyć jego wartość\n" +
"- lub kliknij trzymając Shift by zmiejszyć jego wartość\n" +
"- lub kliknij i przeciągnij dla szybszego wyboru.";
//Calendar._TT["TOGGLE"] = "Zmień pierwszy dzień tygodnia";
Calendar._TT["PREV_YEAR"] = "Poprzedni rok (przytrzymaj dla menu)";
Calendar._TT["PREV_MONTH"] = "Poprzedni miesiąc (przytrzymaj dla menu)";
Calendar._TT["GO_TODAY"] = "Idź do dzisiaj";
Calendar._TT["NEXT_MONTH"] = "Następny miesiąc (przytrzymaj dla menu)";
Calendar._TT["NEXT_YEAR"] = "Następny rok (przytrzymaj dla menu)";
Calendar._TT["SEL_DATE"] = "Wybierz datę";
Calendar._TT["DRAG_TO_MOVE"] = "Przeciągnij by przesunąć";
Calendar._TT["PART_TODAY"] = " (dzisiaj)";
Calendar._TT["MON_FIRST"] = "Wyświetl poniedziałek jako pierwszy";
Calendar._TT["SUN_FIRST"] = "Wyświetl niedzielę jako pierwszą";
Calendar._TT["CLOSE"] = "Zamknij";
Calendar._TT["TODAY"] = "Dzisiaj";
Calendar._TT["TIME_PART"] = "(Shift-)Kliknij lub przeciągnij by zmienić wartość";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%e %B, %A";
Calendar._TT["WK"] = "ty";
| JavaScript |
// ** I18N
// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Translation: Yourim Yi <yyi@yourim.net>
// Encoding: UTF-8
// lang : ko
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("일요일",
"월요일",
"화요일",
"수요일",
"목요일",
"금요일",
"토요일",
"일요일");
// 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
("일",
"월",
"화",
"수",
"목",
"금",
"토",
"일");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("1월",
"2월",
"3월",
"4월",
"5월",
"6월",
"7월",
"8월",
"9월",
"10월",
"11월",
"12월");
// short month names
Calendar._SMN = new Array
("1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "calendar 에 대해서";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"\n"+
"최신 버전을 받으시려면 http://www.dynarch.com/projects/calendar/ 에 방문하세요\n" +
"\n"+
"GNU LGPL 라이센스로 배포됩니다. \n"+
"라이센스에 대한 자세한 내용은 http://gnu.org/licenses/lgpl.html 을 읽으세요." +
"\n\n" +
"날짜 선택:\n" +
"- 연도를 선택하려면 \u00ab, \u00bb 버튼을 사용합니다\n" +
"- 달을 선택하려면 \u2039, \u203a 버튼을 누르세요\n" +
"- 계속 누르고 있으면 위 값들을 빠르게 선택하실 수 있습니다.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"시간 선택:\n" +
"- 마우스로 누르면 시간이 증가합니다\n" +
"- Shift 키와 함께 누르면 감소합니다\n" +
"- 누른 상태에서 마우스를 움직이면 좀 더 빠르게 값이 변합니다.\n";
Calendar._TT["PREV_YEAR"] = "지난 해 (길게 누르면 목록)";
Calendar._TT["PREV_MONTH"] = "지난 달 (길게 누르면 목록)";
Calendar._TT["GO_TODAY"] = "오늘 날짜로";
Calendar._TT["NEXT_MONTH"] = "다음 달 (길게 누르면 목록)";
Calendar._TT["NEXT_YEAR"] = "다음 해 (길게 누르면 목록)";
Calendar._TT["SEL_DATE"] = "날짜를 선택하세요";
Calendar._TT["DRAG_TO_MOVE"] = "마우스 드래그로 이동 하세요";
Calendar._TT["PART_TODAY"] = " (오늘)";
Calendar._TT["MON_FIRST"] = "월요일을 한 주의 시작 요일로";
Calendar._TT["SUN_FIRST"] = "일요일을 한 주의 시작 요일로";
Calendar._TT["CLOSE"] = "닫기";
Calendar._TT["TODAY"] = "오늘";
Calendar._TT["TIME_PART"] = "(Shift-)클릭 또는 드래그 하세요";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%b/%e [%a]";
Calendar._TT["WK"] = "주";
// Added by Dan Lipofsky just to get it working, but it still needs translation
Calendar._TT["DAY_FIRST"] = "Display %s first";
Calendar._TT["TIME"] = "Time:";
Calendar._TT["WEEKEND"] = "0,6";
| JavaScript |
// ** I18N
// Calendar FR language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Encoding: ASCII with \uXXXX unicode escapes
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// Translator: David Duret, <pilgrim@mala-template.net> from previous french version
// full day names
Calendar._DN = new Array
("Dimanche",
"Lundi",
"Mardi",
"Mercredi",
"Jeudi",
"Vendredi",
"Samedi",
"Dimanche");
// 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
("Dim",
"Lun",
"Mar",
"Mer",
"Jeu",
"Ven",
"Sam",
"Dim");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("Janvier",
"F\u00e9vrier",
"Mars",
"Avril",
"Mai",
"Juin",
"Juillet",
"Ao\u00fbt",
"Septembre",
"Octobre",
"Novembre",
"D\u00e9cembre");
// short month names
Calendar._SMN = new Array
("Jan",
"F\u00e9v",
"Mar",
"Avr",
"Mai",
"Juin",
"Juil",
"Ao\u00fbt",
"Sep",
"Oct",
"Nov",
"D\u00e9c");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "\u00c0 propos du calendrier";
Calendar._TT["ABOUT"] =
"DHTML Date/Heure Selecteur\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Pour la derniere version visitez : http://www.dynarch.com/projects/calendar/\n" +
"Distribu\u00e9 par GNU LGPL. Voir http://gnu.org/licenses/lgpl.html pour les details." +
"\n\n" +
"Selection de la date :\n" +
"- Utiliser les bouttons \u00ab, \u00bb pour selectionner l\'annee\n" +
"- Utiliser les bouttons \u2039, \u203a pour selectionner les mois\n" +
"- Garder la souris sur n'importe quels boutons pour une selection plus rapide";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selection de l\'heure :\n" +
"- Cliquer sur heures ou minutes pour incrementer\n" +
"- ou Maj-clic pour decrementer\n" +
"- ou clic et glisser-deplacer pour une selection plus rapide";
Calendar._TT["PREV_YEAR"] = "Ann\u00e9e pr\u00e9c. (maintenir pour menu)";
Calendar._TT["PREV_MONTH"] = "Mois pr\u00e9c. (maintenir pour menu)";
Calendar._TT["GO_TODAY"] = "Atteindre la date du jour";
Calendar._TT["NEXT_MONTH"] = "Mois suiv. (maintenir pour menu)";
Calendar._TT["NEXT_YEAR"] = "Ann\u00e9e suiv. (maintenir pour menu)";
Calendar._TT["SEL_DATE"] = "S\u00e9lectionner une date";
Calendar._TT["DRAG_TO_MOVE"] = "D\u00e9placer";
Calendar._TT["PART_TODAY"] = " (Aujourd'hui)";
// 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"] = "Afficher %s en premier";
// 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"] = "Fermer";
Calendar._TT["TODAY"] = "Aujourd'hui";
Calendar._TT["TIME_PART"] = "(Maj-)Clic ou glisser<BR>pour modifier la valeur";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d/%m/%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "Sem.";
Calendar._TT["TIME"] = "Heure :";
| JavaScript |
// ** I18N
// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Translator: Fabio Di Bernardini, <altraqua@email.it>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Domenica",
"Luned\u00ec",
"Marted\u00ec",
"Mercoled\u00ec",
"Gioved\u00ec",
"Venerd\u00ec",
"Sabato",
"Domenica");
// 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
("Dom",
"Lun",
"Mar",
"Mer",
"Gio",
"Ven",
"Sab",
"Dom");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("Gennaio",
"Febbraio",
"Marzo",
"Aprile",
"Maggio",
"Giugno",
"Luglio",
"Augosto",
"Settembre",
"Ottobre",
"Novembre",
"Dicembre");
// short month names
Calendar._SMN = new Array
("Gen",
"Feb",
"Mar",
"Apr",
"Mag",
"Giu",
"Lug",
"Ago",
"Set",
"Ott",
"Nov",
"Dic");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Informazioni sul calendario";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Per gli aggiornamenti: http://www.dynarch.com/projects/calendar/\n" +
"Distribuito sotto licenza GNU LGPL. Vedi http://gnu.org/licenses/lgpl.html per i dettagli." +
"\n\n" +
"Selezione data:\n" +
"- Usa \u00ab, \u00bb per selezionare l'anno\n" +
"- Usa \u2039, \u203a per i mesi\n" +
"- Tieni premuto a lungo il mouse per accedere alle funzioni di selezione veloce.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selezione orario:\n" +
"- Clicca sul numero per incrementarlo\n" +
"- o Shift+click per decrementarlo\n" +
"- o click e sinistra o destra per variarlo.";
Calendar._TT["PREV_YEAR"] = "Anno prec.(clicca a lungo per il men\u00f9)";
Calendar._TT["PREV_MONTH"] = "Mese prec. (clicca a lungo per il men\u00f9)";
Calendar._TT["GO_TODAY"] = "Oggi";
Calendar._TT["NEXT_MONTH"] = "Pross. mese (clicca a lungo per il men\u00f9)";
Calendar._TT["NEXT_YEAR"] = "Pross. anno (clicca a lungo per il men\u00f9)";
Calendar._TT["SEL_DATE"] = "Seleziona data";
Calendar._TT["DRAG_TO_MOVE"] = "Trascina per spostarlo";
Calendar._TT["PART_TODAY"] = " (oggi)";
// 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"] = "Mostra prima %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"] = "Chiudi";
Calendar._TT["TODAY"] = "Oggi";
Calendar._TT["TIME_PART"] = "(Shift-)Click o trascina per cambiare il valore";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a:%b:%e";
Calendar._TT["WK"] = "set";
Calendar._TT["TIME"] = "Ora:";
| JavaScript |
// ** I18N
// Calendar EN language
// Author: Mihai Bazon, <mishoo@infoiasi.ro>
// Encoding: any
// Translator : Niko <nikoused@gmail.com>
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("\u5468\u65e5",//\u5468\u65e5
"\u5468\u4e00",//\u5468\u4e00
"\u5468\u4e8c",//\u5468\u4e8c
"\u5468\u4e09",//\u5468\u4e09
"\u5468\u56db",//\u5468\u56db
"\u5468\u4e94",//\u5468\u4e94
"\u5468\u516d",//\u5468\u516d
"\u5468\u65e5");//\u5468\u65e5
// 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
("\u5468\u65e5",
"\u5468\u4e00",
"\u5468\u4e8c",
"\u5468\u4e09",
"\u5468\u56db",
"\u5468\u4e94",
"\u5468\u516d",
"\u5468\u65e5");
// full month names
Calendar._MN = new Array
("\u4e00\u6708",
"\u4e8c\u6708",
"\u4e09\u6708",
"\u56db\u6708",
"\u4e94\u6708",
"\u516d\u6708",
"\u4e03\u6708",
"\u516b\u6708",
"\u4e5d\u6708",
"\u5341\u6708",
"\u5341\u4e00\u6708",
"\u5341\u4e8c\u6708");
// short month names
Calendar._SMN = new Array
("\u4e00\u6708",
"\u4e8c\u6708",
"\u4e09\u6708",
"\u56db\u6708",
"\u4e94\u6708",
"\u516d\u6708",
"\u4e03\u6708",
"\u516b\u6708",
"\u4e5d\u6708",
"\u5341\u6708",
"\u5341\u4e00\u6708",
"\u5341\u4e8c\u6708");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "\u5173\u4e8e";
Calendar._TT["ABOUT"] =
" DHTML \u65e5\u8d77/\u65f6\u95f4\u9009\u62e9\u63a7\u4ef6\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: \u6700\u65b0\u7248\u672c\u8bf7\u767b\u9646http://www.dynarch.com/projects/calendar/\u5bdf\u770b\n" +
"\u9075\u5faaGNU LGPL. \u7ec6\u8282\u53c2\u9605 http://gnu.org/licenses/lgpl.html" +
"\n\n" +
"\u65e5\u671f\u9009\u62e9:\n" +
"- \u70b9\u51fb\xab(\xbb)\u6309\u94ae\u9009\u62e9\u4e0a(\u4e0b)\u4e00\u5e74\u5ea6.\n" +
"- \u70b9\u51fb" + String.fromCharCode(0x2039) + "(" + String.fromCharCode(0x203a) + ")\u6309\u94ae\u9009\u62e9\u4e0a(\u4e0b)\u4e2a\u6708\u4efd.\n" +
"- \u957f\u65f6\u95f4\u6309\u7740\u6309\u94ae\u5c06\u51fa\u73b0\u66f4\u591a\u9009\u62e9\u9879.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"\u65f6\u95f4\u9009\u62e9:\n" +
"-\u5728\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)\u4e0a\u5355\u51fb\u9f20\u6807\u5de6\u952e\u6765\u589e\u52a0\u5f53\u524d\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)\n" +
"-\u5728\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2)\u4e0a\u6309\u4f4fShift\u952e\u540e\u5355\u51fb\u9f20\u6807\u5de6\u952e\u6765\u51cf\u5c11\u5f53\u524d\u65f6\u95f4\u90e8\u5206(\u5206\u6216\u8005\u79d2).";
Calendar._TT["PREV_YEAR"] = "\u4e0a\u4e00\u5e74";
Calendar._TT["PREV_MONTH"] = "\u4e0a\u4e2a\u6708";
Calendar._TT["GO_TODAY"] = "\u5230\u4eca\u5929";
Calendar._TT["NEXT_MONTH"] = "\u4e0b\u4e2a\u6708";
Calendar._TT["NEXT_YEAR"] = "\u4e0b\u4e00\u5e74";
Calendar._TT["SEL_DATE"] = "\u9009\u62e9\u65e5\u671f";
Calendar._TT["DRAG_TO_MOVE"] = "\u62d6\u52a8";
Calendar._TT["PART_TODAY"] = " (\u4eca\u5929)";
// 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"] = "%s\u4e3a\u8fd9\u5468\u7684\u7b2c\u4e00\u5929";
// 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"] = "\u5173\u95ed";
Calendar._TT["TODAY"] = "\u4eca\u5929";
Calendar._TT["TIME_PART"] = "(\u6309\u7740Shift\u952e)\u5355\u51fb\u6216\u62d6\u52a8\u6539\u53d8\u503c";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e\u65e5";
Calendar._TT["WK"] = "\u5468";
Calendar._TT["TIME"] = "\u65f6\u95f4:";
| JavaScript |
/* Slovenian language file for the DHTML Calendar version 0.9.2
* Author David Milost <mercy@volja.net>, January 2004.
* Feel free to use this script under the terms of the GNU Lesser General
* Public License, as long as you do not remove or alter this notice.
*/
// full day names
Calendar._DN = new Array
("Nedelja",
"Ponedeljek",
"Torek",
"Sreda",
"Četrtek",
"Petek",
"Sobota",
"Nedelja");
// short day names
Calendar._SDN = new Array
("Ned",
"Pon",
"Tor",
"Sre",
"Čet",
"Pet",
"Sob",
"Ned");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Maj",
"Jun",
"Jul",
"Avg",
"Sep",
"Okt",
"Nov",
"Dec");
// full month names
Calendar._MN = new Array
("Januar",
"Februar",
"Marec",
"April",
"Maj",
"Junij",
"Julij",
"Avgust",
"September",
"Oktober",
"November",
"December");
// tooltips
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O koledarju";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Za zadnjo verzijo pojdine na naslov: http://www.dynarch.com/projects/calendar/\n" +
"Distribuirano pod GNU LGPL. Poglejte http://gnu.org/licenses/lgpl.html za podrobnosti." +
"\n\n" +
"Izbor datuma:\n" +
"- Uporabite \xab, \xbb gumbe za izbor leta\n" +
"- Uporabite " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " gumbe za izbor meseca\n" +
"- Zadržite klik na kateremkoli od zgornjih gumbov za hiter izbor.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Izbor ćasa:\n" +
"- Kliknite na katerikoli del ćasa za poveć. le-tega\n" +
"- ali Shift-click za zmanj. le-tega\n" +
"- ali kliknite in povlecite za hiter izbor.";
Calendar._TT["TOGGLE"] = "Spremeni dan s katerim se prićne teden";
Calendar._TT["PREV_YEAR"] = "Predhodnje leto (dolg klik za meni)";
Calendar._TT["PREV_MONTH"] = "Predhodnji mesec (dolg klik za meni)";
Calendar._TT["GO_TODAY"] = "Pojdi na tekoći dan";
Calendar._TT["NEXT_MONTH"] = "Naslednji mesec (dolg klik za meni)";
Calendar._TT["NEXT_YEAR"] = "Naslednje leto (dolg klik za meni)";
Calendar._TT["SEL_DATE"] = "Izberite datum";
Calendar._TT["DRAG_TO_MOVE"] = "Pritisni in povleci za spremembo pozicije";
Calendar._TT["PART_TODAY"] = " (danes)";
Calendar._TT["MON_FIRST"] = "Prikaži ponedeljek kot prvi dan";
Calendar._TT["SUN_FIRST"] = "Prikaži nedeljo kot prvi dan";
Calendar._TT["CLOSE"] = "Zapri";
Calendar._TT["TODAY"] = "Danes";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "Ted"; | JavaScript |
// ** I18N
// Calendar EN language
// Author: Idan Sofer, <idan@idanso.dyndns.org>
// Encoding: UTF-8
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("ראשון",
"שני",
"שלישי",
"רביעי",
"חמישי",
"שישי",
"שבת",
"ראשון");
// 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
("א",
"ב",
"ג",
"ד",
"ה",
"ו",
"ש",
"א");
// full month names
Calendar._MN = new Array
("ינואר",
"פברואר",
"מרץ",
"אפריל",
"מאי",
"יוני",
"יולי",
"אוגוסט",
"ספטמבר",
"אוקטובר",
"נובמבר",
"דצמבר");
// short month names
Calendar._SMN = new Array
("ינא",
"פבר",
"מרץ",
"אפר",
"מאי",
"יונ",
"יול",
"אוג",
"ספט",
"אוק",
"נוב",
"דצמ");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "אודות השנתון";
Calendar._TT["ABOUT"] =
"בחרן תאריך/שעה DHTML\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"הגירסא האחרונה זמינה ב: http://www.dynarch.com/projects/calendar/\n" +
"מופץ תחת זיכיון ה GNU LGPL. עיין ב http://gnu.org/licenses/lgpl.html לפרטים נוספים." +
"\n\n" +
בחירת תאריך:\n" +
"- השתמש בכפתורים \xab, \xbb לבחירת שנה\n" +
"- השתמש בכפתורים " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " לבחירת חודש\n" +
"- החזק העכבר לחוץ מעל הכפתורים המוזכרים לעיל לבחירה מהירה יותר.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"בחירת זמן:\n" +
"- לחץ על כל אחד מחלקי הזמן כדי להוסיף\n" +
"- או shift בשילוב עם לחיצה כדי להחסיר\n" +
"- או לחץ וגרור לפעולה מהירה יותר.";
Calendar._TT["PREV_YEAR"] = "שנה קודמת - החזק לקבלת תפריט";
Calendar._TT["PREV_MONTH"] = "חודש קודם - החזק לקבלת תפריט";
Calendar._TT["GO_TODAY"] = "עבור להיום";
Calendar._TT["NEXT_MONTH"] = "חודש הבא - החזק לתפריט";
Calendar._TT["NEXT_YEAR"] = "שנה הבאה - החזק לתפריט";
Calendar._TT["SEL_DATE"] = "בחר תאריך";
Calendar._TT["DRAG_TO_MOVE"] = "גרור להזזה";
Calendar._TT["PART_TODAY"] = " )היום(";
// 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"] = "הצג %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"] = "6";
Calendar._TT["CLOSE"] = "סגור";
Calendar._TT["TODAY"] = "היום";
Calendar._TT["TIME_PART"] = "(שיפט-)לחץ וגרור כדי לשנות ערך";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "שעה::";
| JavaScript |
/* Croatian language file for the DHTML Calendar version 0.9.2
* Author Krunoslav Zubrinic <krunoslav.zubrinic@vip.hr>, June 2003.
* Feel free to use this script under the terms of the GNU Lesser General
* Public License, as long as you do not remove or alter this notice.
*/
Calendar._DN = new Array
("Nedjelja",
"Ponedjeljak",
"Utorak",
"Srijeda",
"Četvrtak",
"Petak",
"Subota",
"Nedjelja");
Calendar._MN = new Array
("Siječanj",
"Veljača",
"Ožujak",
"Travanj",
"Svibanj",
"Lipanj",
"Srpanj",
"Kolovoz",
"Rujan",
"Listopad",
"Studeni",
"Prosinac");
// tooltips
Calendar._TT = {};
Calendar._TT["TOGGLE"] = "Promjeni dan s kojim počinje tjedan";
Calendar._TT["PREV_YEAR"] = "Prethodna godina (dugi pritisak za meni)";
Calendar._TT["PREV_MONTH"] = "Prethodni mjesec (dugi pritisak za meni)";
Calendar._TT["GO_TODAY"] = "Idi na tekući dan";
Calendar._TT["NEXT_MONTH"] = "Slijedeći mjesec (dugi pritisak za meni)";
Calendar._TT["NEXT_YEAR"] = "Slijedeća godina (dugi pritisak za meni)";
Calendar._TT["SEL_DATE"] = "Izaberite datum";
Calendar._TT["DRAG_TO_MOVE"] = "Pritisni i povuci za promjenu pozicije";
Calendar._TT["PART_TODAY"] = " (today)";
Calendar._TT["MON_FIRST"] = "Prikaži ponedjeljak kao prvi dan";
Calendar._TT["SUN_FIRST"] = "Prikaži nedjelju kao prvi dan";
Calendar._TT["CLOSE"] = "Zatvori";
Calendar._TT["TODAY"] = "Danas";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "dd-mm-y";
Calendar._TT["TT_DATE_FORMAT"] = "DD, dd.mm.y";
Calendar._TT["WK"] = "Tje"; | JavaScript |
// ** I18N
// Calendar pt-BR language
// Author: Fernando Dourado, <fernando.dourado@ig.com.br>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Domingo",
"Segunda",
"Terça",
"Quarta",
"Quinta",
"Sexta",
"Sabádo",
"Domingo");
// 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
// [No changes using default values]
// full month names
Calendar._MN = new Array
("Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro");
// short month names
// [No changes using default values]
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Sobre o calendário";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Translate to portuguese Brazil (pt-BR) by Fernando Dourado (fernando.dourado@ig.com.br)\n" +
"Tradução para o português Brasil (pt-BR) por Fernando Dourado (fernando.dourado@ig.com.br)" +
"\n\n" +
"Selecionar data:\n" +
"- Use as teclas \xab, \xbb para selecionar o ano\n" +
"- Use as teclas " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " para selecionar o mês\n" +
"- Clique e segure com o mouse em qualquer botão para selecionar rapidamente.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selecionar hora:\n" +
"- Clique em qualquer uma das partes da hora para aumentar\n" +
"- ou Shift-clique para diminuir\n" +
"- ou clique e arraste para selecionar rapidamente.";
Calendar._TT["PREV_YEAR"] = "Ano anterior (clique e segure para menu)";
Calendar._TT["PREV_MONTH"] = "Mês anterior (clique e segure para menu)";
Calendar._TT["GO_TODAY"] = "Ir para a data atual";
Calendar._TT["NEXT_MONTH"] = "Próximo mês (clique e segure para menu)";
Calendar._TT["NEXT_YEAR"] = "Próximo ano (clique e segure para menu)";
Calendar._TT["SEL_DATE"] = "Selecione uma data";
Calendar._TT["DRAG_TO_MOVE"] = "Clique e segure para mover";
Calendar._TT["PART_TODAY"] = " (hoje)";
// 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"] = "Exibir %s primeiro";
// 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"] = "Fechar";
Calendar._TT["TODAY"] = "Hoje";
Calendar._TT["TIME_PART"] = "(Shift-)Clique ou arraste para mudar o valor";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d/%m/%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%d de %B de %Y";
Calendar._TT["WK"] = "sem";
Calendar._TT["TIME"] = "Hora:";
| JavaScript |
// ** I18N
// Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// Distributed under the same terms as the calendar itself.
// full day names
Calendar._DN = new Array
("NedeÄľa",
"Pondelok",
"Utorok",
"Streda",
"Ĺ tvrtok",
"Piatok",
"Sobota",
"NedeÄľa");
// short day names
Calendar._SDN = new Array
("Ned",
"Pon",
"Uto",
"Str",
"Ĺ tv",
"Pia",
"Sob",
"Ned");
// full month names
Calendar._MN = new Array
("Január",
"Február",
"Marec",
"AprĂl",
"Máj",
"JĂşn",
"JĂşl",
"August",
"September",
"OktĂłber",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Máj",
"JĂşn",
"JĂşl",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendári";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Poslednú verziu nájdete na: http://www.dynarch.com/projects/calendar/\n" +
"Distribuované pod GNU LGPL. Viď http://gnu.org/licenses/lgpl.html pre detaily." +
"\n\n" +
"Výber dátumu:\n" +
"- Použite tlačidlá \xab, \xbb pre výber roku\n" +
"- Použite tlačidlá " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " pre výber mesiaca\n" +
"- Ak ktorĂ©koÄľvek z tĂ˝chto tlaÄŤidiel podrĹľĂte dlhšie, zobrazĂ sa rĂ˝chly vĂ˝ber.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Výber času:\n" +
"- Kliknutie na niektorú položku času ju zvýši\n" +
"- Shift-klik ju znĂĹľi\n" +
"- Ak podrĹľĂte tlaÄŤĂtko stlaÄŤenĂ©, posĂşvanĂm menĂte hodnotu.";
Calendar._TT["PREV_YEAR"] = "Predošlý rok (podržte pre menu)";
Calendar._TT["PREV_MONTH"] = "Predošlý mesiac (podržte pre menu)";
Calendar._TT["GO_TODAY"] = "Prejsť na dnešok";
Calendar._TT["NEXT_MONTH"] = "Nasl. mesiac (podrĹľte pre menu)";
Calendar._TT["NEXT_YEAR"] = "Nasl. rok (podrĹľte pre menu)";
Calendar._TT["SEL_DATE"] = "Zvoľte dátum";
Calendar._TT["DRAG_TO_MOVE"] = "PodrĹľanĂm tlaÄŤĂtka zmenĂte polohu";
Calendar._TT["PART_TODAY"] = " (dnes)";
Calendar._TT["MON_FIRST"] = "ZobraziĹĄ pondelok ako prvĂ˝";
Calendar._TT["SUN_FIRST"] = "ZobraziĹĄ nedeÄľu ako prvĂş";
Calendar._TT["CLOSE"] = "ZavrieĹĄ";
Calendar._TT["TODAY"] = "Dnes";
Calendar._TT["TIME_PART"] = "(Shift-)klik/ĹĄahanie zmenĂ hodnotu";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "$d. %m. %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e. %b";
Calendar._TT["WK"] = "týž";
| JavaScript |
// ** I18N
// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// 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");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";
Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Calendar._TT["GO_TODAY"] = "Go Today";
Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Calendar._TT["SEL_DATE"] = "Select date";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = " (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"] = "Display %s first";
// 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"] = "Close";
Calendar._TT["TODAY"] = "Today";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Time:";
| JavaScript |
// ** I18N
Calendar._DN = new Array
("Κυριακή",
"Δευτέρα",
"Τρίτη",
"Τετάρτη",
"Πέμπτη",
"Παρασκευή",
"Σάββατο",
"Κυριακή");
Calendar._SDN = new Array
("Κυ",
"Δε",
"Tρ",
"Τε",
"Πε",
"Πα",
"Σα",
"Κυ");
Calendar._MN = new Array
("Ιανουάριος",
"Φεβρουάριος",
"Μάρτιος",
"Απρίλιος",
"Μάϊος",
"Ιούνιος",
"Ιούλιος",
"Αύγουστος",
"Σεπτέμβριος",
"Οκτώβριος",
"Νοέμβριος",
"Δεκέμβριος");
Calendar._SMN = new Array
("Ιαν",
"Φεβ",
"Μαρ",
"Απρ",
"Μαι",
"Ιουν",
"Ιουλ",
"Αυγ",
"Σεπ",
"Οκτ",
"Νοε",
"Δεκ");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Για το ημερολόγιο";
Calendar._TT["ABOUT"] =
"Επιλογέας ημερομηνίας/ώρας σε DHTML\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Για τελευταία έκδοση: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Επιλογή ημερομηνίας:\n" +
"- Χρησιμοποιείστε τα κουμπιά \xab, \xbb για επιλογή έτους\n" +
"- Χρησιμοποιείστε τα κουμπιά " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " για επιλογή μήνα\n" +
"- Κρατήστε κουμπί ποντικού πατημένο στα παραπάνω κουμπιά για πιο γρήγορη επιλογή.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Επιλογή ώρας:\n" +
"- Κάντε κλικ σε ένα από τα μέρη της ώρας για αύξηση\n" +
"- ή Shift-κλικ για μείωση\n" +
"- ή κλικ και μετακίνηση για πιο γρήγορη επιλογή.";
Calendar._TT["TOGGLE"] = "Μπάρα πρώτης ημέρας της εβδομάδας";
Calendar._TT["PREV_YEAR"] = "Προηγ. έτος (κρατήστε για το μενού)";
Calendar._TT["PREV_MONTH"] = "Προηγ. μήνας (κρατήστε για το μενού)";
Calendar._TT["GO_TODAY"] = "Σήμερα";
Calendar._TT["NEXT_MONTH"] = "Επόμενος μήνας (κρατήστε για το μενού)";
Calendar._TT["NEXT_YEAR"] = "Επόμενο έτος (κρατήστε για το μενού)";
Calendar._TT["SEL_DATE"] = "Επιλέξτε ημερομηνία";
Calendar._TT["DRAG_TO_MOVE"] = "Σύρτε για να μετακινήσετε";
Calendar._TT["PART_TODAY"] = " (σήμερα)";
Calendar._TT["MON_FIRST"] = "Εμφάνιση Δευτέρας πρώτα";
Calendar._TT["SUN_FIRST"] = "Εμφάνιση Κυριακής πρώτα";
Calendar._TT["CLOSE"] = "Κλείσιμο";
Calendar._TT["TODAY"] = "Σήμερα";
Calendar._TT["TIME_PART"] = "(Shift-)κλικ ή μετακίνηση για αλλαγή";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "dd-mm-y";
Calendar._TT["TT_DATE_FORMAT"] = "D, d M";
Calendar._TT["WK"] = "εβδ";
| JavaScript |
// Calendar ALBANIAN language
//author Rigels Gordani rige@hotmail.com
// ditet
Calendar._DN = new Array
("E Diele",
"E Hene",
"E Marte",
"E Merkure",
"E Enjte",
"E Premte",
"E Shtune",
"E Diele");
//ditet shkurt
Calendar._SDN = new Array
("Die",
"Hen",
"Mar",
"Mer",
"Enj",
"Pre",
"Sht",
"Die");
// muajt
Calendar._MN = new Array
("Janar",
"Shkurt",
"Mars",
"Prill",
"Maj",
"Qeshor",
"Korrik",
"Gusht",
"Shtator",
"Tetor",
"Nentor",
"Dhjetor");
// muajte shkurt
Calendar._SMN = new Array
("Jan",
"Shk",
"Mar",
"Pri",
"Maj",
"Qes",
"Kor",
"Gus",
"Sht",
"Tet",
"Nen",
"Dhj");
// ndihmesa
Calendar._TT = {};
Calendar._TT["INFO"] = "Per kalendarin";
Calendar._TT["ABOUT"] =
"Zgjedhes i ores/dates ne DHTML \n" +
"\n\n" +"Zgjedhja e Dates:\n" +
"- Perdor butonat \xab, \xbb per te zgjedhur vitin\n" +
"- Perdor butonat" + String.fromCharCode(0x2039) + ", " +
String.fromCharCode(0x203a) +
" per te zgjedhur muajin\n" +
"- Mbani shtypur butonin e mousit per nje zgjedje me te shpejte.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Zgjedhja e kohes:\n" +
"- Kliko tek ndonje nga pjeset e ores per ta rritur ate\n" +
"- ose kliko me Shift per ta zvogeluar ate\n" +
"- ose cliko dhe terhiq per zgjedhje me te shpejte.";
Calendar._TT["PREV_YEAR"] = "Viti i shkuar (prit per menune)";
Calendar._TT["PREV_MONTH"] = "Muaji i shkuar (prit per menune)";
Calendar._TT["GO_TODAY"] = "Sot";
Calendar._TT["NEXT_MONTH"] = "Muaji i ardhshem (prit per menune)";
Calendar._TT["NEXT_YEAR"] = "Viti i ardhshem (prit per menune)";
Calendar._TT["SEL_DATE"] = "Zgjidh daten";
Calendar._TT["DRAG_TO_MOVE"] = "Terhiqe per te levizur";
Calendar._TT["PART_TODAY"] = " (sot)";
// "%s" eshte dita e pare e javes
// %s do te zevendesohet me emrin e dite
Calendar._TT["DAY_FIRST"] = "Trego te %s te paren";
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "Mbyll";
Calendar._TT["TODAY"] = "Sot";
Calendar._TT["TIME_PART"] = "Kliko me (Shift-)ose terhiqe per te ndryshuar
vleren";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "Java";
Calendar._TT["TIME"] = "Koha:";
| JavaScript |
// ** I18N
// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Encoding: ASCII with \uXXXX unicode escapes
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// 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");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \u00ab, \u00bb buttons to select the year\n" +
"- Use the \u2039, \u203a buttons to select the month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";
Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Calendar._TT["GO_TODAY"] = "Go To Today";
Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Calendar._TT["SEL_DATE"] = "Select date";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = " (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"] = "Display %s first";
// 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"] = "Close";
Calendar._TT["TODAY"] = "Today";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Time:";
| JavaScript |
// ** I18N
// Calendar PL language
// Author: Artur Filipiak, <imagen@poczta.fm>
// January, 2004
// Encoding: UTF-8
Calendar._DN = new Array
("Niedziela", "Poniedzia\u0142ek", "Wtorek", "\u015aroda", "Czwartek", "Pi\u0105tek", "Sobota", "Niedziela");
Calendar._SDN = new Array
("N", "Pn", "Wt", "\u015ar", "Cz", "Pt", "So", "N");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
Calendar._MN = new Array
("Stycze\u0144", "Luty", "Marzec", "Kwiecie\u0144", "Maj", "Czerwiec", "Lipiec", "Sierpie\u0144", "Wrzesie\u0144", "Pa\u017adziernik", "Listopad", "Grudzie\u0144");
Calendar._SMN = new Array
("Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Pa\u017a", "Lis", "Gru");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendarzu";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Wyb\u00f3r daty:\n" +
"- aby wybra\u0107 rok u\u017cyj przycisk\u00f3w \u00ab, \u00bb\n" +
"- aby wybra\u0107 miesi\u0105c u\u017cyj przycisk\u00f3w \u2039, \u203a\n" +
"- aby przyspieszy\u0107 wyb\u00f3r przytrzymaj wci\u015bni\u0119ty przycisk myszy nad ww. przyciskami.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Wyb\u00f3r czasu:\n" +
"- aby zwi\u0119kszy\u0107 warto\u015b\u0107 kliknij na dowolnym elemencie selekcji czasu\n" +
"- aby zmniejszy\u0107 warto\u015b\u0107 u\u017cyj dodatkowo klawisza Shift\n" +
"- mo\u017cesz r\u00f3wnie\u017c porusza\u0107 myszk\u0119 w lewo i prawo wraz z wci\u015bni\u0119tym lewym klawiszem.";
Calendar._TT["PREV_YEAR"] = "Poprz. rok (przytrzymaj dla menu)";
Calendar._TT["PREV_MONTH"] = "Poprz. miesi\u0105c (przytrzymaj dla menu)";
Calendar._TT["GO_TODAY"] = "Poka\u017c dzi\u015b";
Calendar._TT["NEXT_MONTH"] = "Nast. miesi\u0105c (przytrzymaj dla menu)";
Calendar._TT["NEXT_YEAR"] = "Nast. rok (przytrzymaj dla menu)";
Calendar._TT["SEL_DATE"] = "Wybierz dat\u0119";
Calendar._TT["DRAG_TO_MOVE"] = "Przesu\u0144 okienko";
Calendar._TT["PART_TODAY"] = " (dzi\u015b)";
Calendar._TT["MON_FIRST"] = "Poka\u017c Poniedzia\u0142ek jako pierwszy";
Calendar._TT["SUN_FIRST"] = "Poka\u017c Niedziel\u0119 jako pierwsz\u0105";
Calendar._TT["CLOSE"] = "Zamknij";
Calendar._TT["TODAY"] = "Dzi\u015b";
Calendar._TT["TIME_PART"] = "(Shift-)klik | drag, aby zmieni\u0107 warto\u015b\u0107";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y.%m.%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
// This still need to be translated.
// Copied from English to make eveything work
Calendar._TT["DAY_FIRST"] = "Display %s first";
Calendar._TT["TIME"] = "Time:";
// 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";
| JavaScript |
// ** I18N
// Calendar ES (spanish) language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Updater: Servilio Afre Puentes <servilios@yahoo.com>
// Updated: 2004-06-03
// Encoding: ISO-Latin-1
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Domingo",
"Lunes",
"Martes",
"Mi\u00e9rcoles",
"Jueves",
"Viernes",
"S\u00e1bado",
"Domingo");
// 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
("Dom",
"Lun",
"Mar",
"Mi\u00e9",
"Jue",
"Vie",
"S\u00e1b",
"Dom");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;
// full month names
Calendar._MN = new Array
("Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre");
// short month names
Calendar._SMN = new Array
("Ene",
"Feb",
"Mar",
"Abr",
"May",
"Jun",
"Jul",
"Ago",
"Sep",
"Oct",
"Nov",
"Dic");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Acerca del calendario";
Calendar._TT["ABOUT"] =
"Selector DHTML de Fecha/Hora\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Para conseguir la \u00faltima versi\u00f3n visite: http://www.dynarch.com/projects/calendar/\n" +
"Distribuido bajo licencia GNU LGPL. Visite http://gnu.org/licenses/lgpl.html para m\u00e1s detalles." +
"\n\n" +
"Selecci\u00f3n de fecha:\n" +
"- Use los botones \u00ab, \u00bb para seleccionar el a\u00f1o\n" +
"- Use los botones \u2039, \u203a para seleccionar el mes\n" +
"- Mantenga pulsado el rat\u00f3n en cualquiera de estos botones para una selecci\u00f3n r\u00e1pida.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selecci\u00f3n de hora:\n" +
"- Pulse en cualquiera de las partes de la hora para incrementarla\n" +
"- o pulse las may\u00fasculas mientras hace clic para decrementarla\n" +
"- o haga clic y arrastre el rat\u00f3n para una selecci\u00f3n m\u00e1s r\u00e1pida.";
Calendar._TT["PREV_YEAR"] = "A\u00f1o anterior (mantener para men\u00fa)";
Calendar._TT["PREV_MONTH"] = "Mes anterior (mantener para men\u00fa)";
Calendar._TT["GO_TODAY"] = "Ir a hoy";
Calendar._TT["NEXT_MONTH"] = "Mes siguiente (mantener para men\u00fa)";
Calendar._TT["NEXT_YEAR"] = "A\u00f1o siguiente (mantener para men\u00fa)";
Calendar._TT["SEL_DATE"] = "Seleccionar fecha";
Calendar._TT["DRAG_TO_MOVE"] = "Arrastrar para mover";
Calendar._TT["PART_TODAY"] = " (hoy)";
// 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"] = "Hacer %s primer d\u00eda de la semana";
// 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"] = "Cerrar";
Calendar._TT["TODAY"] = "Hoy";
Calendar._TT["TIME_PART"] = "(May\u00fascula-)Clic o arrastre<BR>para cambiar valor";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d/%m/%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %e de %B de %Y";
Calendar._TT["WK"] = "sem";
Calendar._TT["TIME"] = "Hora:";
| JavaScript |
// ** I18N
// Calendar RU language
// Translation: Sly Golovanov, http://golovanov.net, <sly@golovanov.net>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("воскресенье",
"понедельник",
"вторник",
"среда",
"четверг",
"пятница",
"суббота",
"воскресенье");
// 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
("вск",
"пон",
"втр",
"срд",
"чет",
"пят",
"суб",
"вск");
// full month names
Calendar._MN = new Array
("январь",
"февраль",
"март",
"апрель",
"май",
"июнь",
"июль",
"август",
"сентябрь",
"октябрь",
"ноябрь",
"декабрь");
// short month names
Calendar._SMN = new Array
("янв",
"фев",
"мар",
"апр",
"май",
"июн",
"июл",
"авг",
"сен",
"окт",
"ноя",
"дек");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "О календаре...";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Как выбрать дату:\n" +
"- При помощи кнопок \xab, \xbb можно выбрать год\n" +
"- При помощи кнопок " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " можно выбрать месяц\n" +
"- Подержите эти кнопки нажатыми, чтобы появилось меню быстрого выбора.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Как выбрать время:\n" +
"- При клике на часах или минутах они увеличиваются\n" +
"- при клике с нажатой клавишей Shift они уменьшаются\n" +
"- если нажать и двигать мышкой влево/вправо, они будут меняться быстрее.";
Calendar._TT["PREV_YEAR"] = "На год назад (удерживать для меню)";
Calendar._TT["PREV_MONTH"] = "На месяц назад (удерживать для меню)";
Calendar._TT["GO_TODAY"] = "Сегодня";
Calendar._TT["NEXT_MONTH"] = "На месяц вперед (удерживать для меню)";
Calendar._TT["NEXT_YEAR"] = "На год вперед (удерживать для меню)";
Calendar._TT["SEL_DATE"] = "Выберите дату";
Calendar._TT["DRAG_TO_MOVE"] = "Перетаскивайте мышкой";
Calendar._TT["PART_TODAY"] = " (сегодня)";
// 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"] = "Первый день недели будет %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._TT["TODAY"] = "Сегодня";
Calendar._TT["TIME_PART"] = "(Shift-)клик или нажать и двигать";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%e %b, %a";
Calendar._TT["WK"] = "нед";
Calendar._TT["TIME"] = "Время:";
| JavaScript |
// ** I18N
// Calendar DE language
// Author: Jack (tR), <jack@jtr.de>
// Encoding: ASCII with \uXXXX unicode escapes
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
"Sonntag");
// 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
("So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa",
"So");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"M\u00e4r",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "\u00DCber dieses Kalendarmodul";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Datum ausw\u00e4hlen:\n" +
"- Benutzen Sie die \u00ab, \u00bb Buttons um das Jahr zu w\u00e4hlen\n" +
"- Benutzen Sie die \u2039, \u203a Buttons um den Monat zu w\u00e4hlen\n" +
"- F\u00fcr eine Schnellauswahl halten Sie die Maustaste \u00fcber diesen Buttons fest.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Zeit ausw\u00e4hlen:\n" +
"- Klicken Sie auf die Teile der Uhrzeit, um diese zu erh\u00F6hen\n" +
"- oder klicken Sie mit festgehaltener Shift-Taste um diese zu verringern\n" +
"- oder klicken und festhalten f\u00fcr Schnellauswahl.";
Calendar._TT["TOGGLE"] = "Ersten Tag der Woche w\u00e4hlen";
Calendar._TT["PREV_YEAR"] = "Voriges Jahr<br>(Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["PREV_MONTH"] = "Voriger Monat<br>(Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["GO_TODAY"] = "Heute ausw\u00e4hlen";
Calendar._TT["NEXT_MONTH"] = "N\u00e4chst. Monat<br>(Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["NEXT_YEAR"] = "N\u00e4chst. Jahr<br>(Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["SEL_DATE"] = "Datum ausw\u00e4hlen";
Calendar._TT["DRAG_TO_MOVE"] = "Zum Bewegen festhalten";
Calendar._TT["PART_TODAY"] = " (Heute)";
// 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"] = "Woche beginnt mit %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"] = "Schlie\u00dfen";
Calendar._TT["TODAY"] = "Heute";
Calendar._TT["TIME_PART"] = "(Shift-)Klick oder Festhalten und<BR>Ziehen um den Wert zu \u00e4ndern";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d.%m.%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Zeit:";
| JavaScript |
// ** I18N
// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Translator: Fabio Di Bernardini, <altraqua@email.it>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Domenica",
"Lunedì",
"Martedì",
"Mercoledì",
"Giovedì",
"Venerdì",
"Sabato",
"Domenica");
// 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
("Dom",
"Lun",
"Mar",
"Mer",
"Gio",
"Ven",
"Sab",
"Dom");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
// full month names
Calendar._MN = new Array
("Gennaio",
"Febbraio",
"Marzo",
"Aprile",
"Maggio",
"Giugno",
"Luglio",
"Augosto",
"Settembre",
"Ottobre",
"Novembre",
"Dicembre");
// short month names
Calendar._SMN = new Array
("Gen",
"Feb",
"Mar",
"Apr",
"Mag",
"Giu",
"Lug",
"Ago",
"Set",
"Ott",
"Nov",
"Dic");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Informazioni sul calendario";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Per gli aggiornamenti: http://www.dynarch.com/projects/calendar/\n" +
"Distribuito sotto licenza GNU LGPL. Vedi http://gnu.org/licenses/lgpl.html per i dettagli." +
"\n\n" +
"Selezione data:\n" +
"- Usa \u00ab, \u00bb per selezionare l'anno\n" +
"- Usa \u2039, \u203a per i mesi\n" +
"- Tieni premuto a lungo il mouse per accedere alle funzioni di selezione veloce.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selezione orario:\n" +
"- Clicca sul numero per incrementarlo\n" +
"- o Shift+click per decrementarlo\n" +
"- o click e sinistra o destra per variarlo.";
Calendar._TT["PREV_YEAR"] = "Anno prec.(clicca a lungo per il menù)";
Calendar._TT["PREV_MONTH"] = "Mese prec. (clicca a lungo per il menù)";
Calendar._TT["GO_TODAY"] = "Oggi";
Calendar._TT["NEXT_MONTH"] = "Pross. mese (clicca a lungo per il menù)";
Calendar._TT["NEXT_YEAR"] = "Pross. anno (clicca a lungo per il menù)";
Calendar._TT["SEL_DATE"] = "Seleziona data";
Calendar._TT["DRAG_TO_MOVE"] = "Trascina per spostarlo";
Calendar._TT["PART_TODAY"] = " (oggi)";
// 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"] = "Mostra prima %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"] = "Chiudi";
Calendar._TT["TODAY"] = "Oggi";
Calendar._TT["TIME_PART"] = "(Shift-)Click o trascina per cambiare il valore";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a:%b:%e";
Calendar._TT["WK"] = "set";
Calendar._TT["TIME"] = "Ora:";
| JavaScript |
// ** I18N
// Calendar LT language
// Author: Martynas Majeris, <martynas@solmetra.lt>
// Encoding: UTF-8
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Sekmadienis",
"Pirmadienis",
"Antradienis",
"Trečiadienis",
"Ketvirtadienis",
"Pentadienis",
"Šeštadienis",
"Sekmadienis");
// 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
("Sek",
"Pir",
"Ant",
"Tre",
"Ket",
"Pen",
"Šeš",
"Sek");
// full month names
Calendar._MN = new Array
("Sausis",
"Vasaris",
"Kovas",
"Balandis",
"Gegužė",
"Birželis",
"Liepa",
"Rugpjūtis",
"Rugsėjis",
"Spalis",
"Lapkritis",
"Gruodis");
// short month names
Calendar._SMN = new Array
("Sau",
"Vas",
"Kov",
"Bal",
"Geg",
"Bir",
"Lie",
"Rgp",
"Rgs",
"Spa",
"Lap",
"Gru");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Apie kalendorių";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Naujausią versiją rasite: http://www.dynarch.com/projects/calendar/\n" +
"Platinamas pagal GNU LGPL licenciją. Aplankykite http://gnu.org/licenses/lgpl.html" +
"\n\n" +
"Datos pasirinkimas:\n" +
"- Metų pasirinkimas: \xab, \xbb\n" +
"- Mėnesio pasirinkimas: " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + "\n" +
"- Nuspauskite ir laikykite pelės klavišą greitesniam pasirinkimui.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Laiko pasirinkimas:\n" +
"- Spustelkite ant valandų arba minučių - skaičius padidės vienetu.\n" +
"- Jei spausite kartu su Shift, skaičius sumažės.\n" +
"- Greitam pasirinkimui spustelkite ir pajudinkite pelę.";
Calendar._TT["PREV_YEAR"] = "Ankstesni metai (laikykite, jei norite meniu)";
Calendar._TT["PREV_MONTH"] = "Ankstesnis mėnuo (laikykite, jei norite meniu)";
Calendar._TT["GO_TODAY"] = "Pasirinkti šiandieną";
Calendar._TT["NEXT_MONTH"] = "Kitas mėnuo (laikykite, jei norite meniu)";
Calendar._TT["NEXT_YEAR"] = "Kiti metai (laikykite, jei norite meniu)";
Calendar._TT["SEL_DATE"] = "Pasirinkite datą";
Calendar._TT["DRAG_TO_MOVE"] = "Tempkite";
Calendar._TT["PART_TODAY"] = " (šiandien)";
Calendar._TT["MON_FIRST"] = "Pirma savaitės diena - pirmadienis";
Calendar._TT["SUN_FIRST"] = "Pirma savaitės diena - sekmadienis";
Calendar._TT["CLOSE"] = "Uždaryti";
Calendar._TT["TODAY"] = "Šiandien";
Calendar._TT["TIME_PART"] = "Spustelkite arba tempkite jei norite pakeisti";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %Y-%m-%d";
Calendar._TT["WK"] = "sav";
| JavaScript |
// ** I18N
// Calendar PL language
// Author: Artur Filipiak, <imagen@poczta.fm>
// January, 2004
// Encoding: UTF-8
Calendar._DN = new Array
("Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela");
Calendar._SDN = new Array
("N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;
Calendar._MN = new Array
("Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień");
Calendar._SMN = new Array
("Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendarzu";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Wybór daty:\n" +
"- aby wybrać rok użyj przycisków \u00ab, \u00bb\n" +
"- aby wybrać miesiąc użyj przycisków \u2039, \u203a\n" +
"- aby przyspieszyć wybór przytrzymaj wciśnięty przycisk myszy nad ww. przyciskami.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Wybór czasu:\n" +
"- aby zwiększyć wartość kliknij na dowolnym elemencie selekcji czasu\n" +
"- aby zmniejszyć wartość użyj dodatkowo klawisza Shift\n" +
"- możesz również poruszać myszkę w lewo i prawo wraz z wciśniętym lewym klawiszem.";
Calendar._TT["PREV_YEAR"] = "Poprz. rok (przytrzymaj dla menu)";
Calendar._TT["PREV_MONTH"] = "Poprz. miesiąc (przytrzymaj dla menu)";
Calendar._TT["GO_TODAY"] = "Pokaż dziś";
Calendar._TT["NEXT_MONTH"] = "Nast. miesiąc (przytrzymaj dla menu)";
Calendar._TT["NEXT_YEAR"] = "Nast. rok (przytrzymaj dla menu)";
Calendar._TT["SEL_DATE"] = "Wybierz datę";
Calendar._TT["DRAG_TO_MOVE"] = "Przesuń okienko";
Calendar._TT["PART_TODAY"] = " (dziś)";
Calendar._TT["MON_FIRST"] = "Pokaż Poniedziałek jako pierwszy";
Calendar._TT["SUN_FIRST"] = "Pokaż Niedzielę jako pierwszą";
Calendar._TT["CLOSE"] = "Zamknij";
Calendar._TT["TODAY"] = "Dziś";
Calendar._TT["TIME_PART"] = "(Shift-)klik | drag, aby zmienić wartość";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y.%m.%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "wk";
// This still need to be translated.
// Copied from English to make eveything work
Calendar._TT["DAY_FIRST"] = "Display %s first";
Calendar._TT["TIME"] = "Time:";
// 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";
| JavaScript |
// ** I18N
// Calendar FI language (Finnish, Suomi)
// Author: Jarno Käyhkö, <gambler@phnet.fi>
// Encoding: UTF-8
// Distributed under the same terms as the calendar itself.
// full day names
Calendar._DN = new Array
("Sunnuntai",
"Maanantai",
"Tiistai",
"Keskiviikko",
"Torstai",
"Perjantai",
"Lauantai",
"Sunnuntai");
// short day names
Calendar._SDN = new Array
("Su",
"Ma",
"Ti",
"Ke",
"To",
"Pe",
"La",
"Su");
// full month names
Calendar._MN = new Array
("Tammikuu",
"Helmikuu",
"Maaliskuu",
"Huhtikuu",
"Toukokuu",
"Kesäkuu",
"Heinäkuu",
"Elokuu",
"Syyskuu",
"Lokakuu",
"Marraskuu",
"Joulukuu");
// short month names
Calendar._SMN = new Array
("Tam",
"Hel",
"Maa",
"Huh",
"Tou",
"Kes",
"Hei",
"Elo",
"Syy",
"Lok",
"Mar",
"Jou");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Tietoja kalenterista";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Uusin versio osoitteessa: http://www.dynarch.com/projects/calendar/\n" +
"Julkaistu GNU LGPL lisenssin alaisuudessa. Lisätietoja osoitteessa http://gnu.org/licenses/lgpl.html" +
"\n\n" +
"Päivämäärä valinta:\n" +
"- Käytä \xab, \xbb painikkeita valitaksesi vuosi\n" +
"- Käytä " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " painikkeita valitaksesi kuukausi\n" +
"- Pitämällä hiiren painiketta minkä tahansa yllä olevan painikkeen kohdalla, saat näkyviin valikon nopeampaan siirtymiseen.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Ajan valinta:\n" +
"- Klikkaa kellonajan numeroita lisätäksesi aikaa\n" +
"- tai pitämällä Shift-näppäintä pohjassa saat aikaa taaksepäin\n" +
"- tai klikkaa ja pidä hiiren painike pohjassa sekä liikuta hiirtä muuttaaksesi aikaa nopeasti eteen- ja taaksepäin.";
Calendar._TT["PREV_YEAR"] = "Edell. vuosi (paina hetki, näet valikon)";
Calendar._TT["PREV_MONTH"] = "Edell. kuukausi (paina hetki, näet valikon)";
Calendar._TT["GO_TODAY"] = "Siirry tähän päivään";
Calendar._TT["NEXT_MONTH"] = "Seur. kuukausi (paina hetki, näet valikon)";
Calendar._TT["NEXT_YEAR"] = "Seur. vuosi (paina hetki, näet valikon)";
Calendar._TT["SEL_DATE"] = "Valitse päivämäärä";
Calendar._TT["DRAG_TO_MOVE"] = "Siirrä kalenterin paikkaa";
Calendar._TT["PART_TODAY"] = " (tänään)";
Calendar._TT["MON_FIRST"] = "Näytä maanantai ensimmäisenä";
Calendar._TT["SUN_FIRST"] = "Näytä sunnuntai ensimmäisenä";
Calendar._TT["CLOSE"] = "Sulje";
Calendar._TT["TODAY"] = "Tänään";
Calendar._TT["TIME_PART"] = "(Shift-) Klikkaa tai liikuta muuttaaksesi aikaa";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d.%m.%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%d.%m.%Y";
Calendar._TT["WK"] = "Vko";
| JavaScript |
// ** I18N
Calendar._DN = new Array
("Zondag",
"Maandag",
"Dinsdag",
"Woensdag",
"Donderdag",
"Vrijdag",
"Zaterdag",
"Zondag");
Calendar._MN = new Array
("Januari",
"Februari",
"Maart",
"April",
"Mei",
"Juni",
"Juli",
"Augustus",
"September",
"Oktober",
"November",
"December");
// tooltips
Calendar._TT = {};
Calendar._TT["TOGGLE"] = "Toggle startdag van de week";
Calendar._TT["PREV_YEAR"] = "Vorig jaar (indrukken voor menu)";
Calendar._TT["PREV_MONTH"] = "Vorige month (indrukken voor menu)";
Calendar._TT["GO_TODAY"] = "Naar Vandaag";
Calendar._TT["NEXT_MONTH"] = "Volgende Maand (indrukken voor menu)";
Calendar._TT["NEXT_YEAR"] = "Volgend jaar (indrukken voor menu)";
Calendar._TT["SEL_DATE"] = "Selecteer datum";
Calendar._TT["DRAG_TO_MOVE"] = "Sleep om te verplaatsen";
Calendar._TT["PART_TODAY"] = " (vandaag)";
Calendar._TT["MON_FIRST"] = "Toon Maandag eerst";
Calendar._TT["SUN_FIRST"] = "Toon Zondag eerst";
Calendar._TT["CLOSE"] = "Sluiten";
Calendar._TT["TODAY"] = "Vandaag";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "y-mm-dd";
Calendar._TT["TT_DATE_FORMAT"] = "D, M d";
Calendar._TT["WK"] = "wk";
| JavaScript |
// ** I18N
// Calendar DA language
// Author: Michael Thingmand Henriksen, <michael (a) thingmand dot dk>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Søndag",
"Mandag",
"Tirsdag",
"Onsdag",
"Torsdag",
"Fredag",
"Lørdag",
"Søndag");
// 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
("Søn",
"Man",
"Tir",
"Ons",
"Tor",
"Fre",
"Lør",
"Søn");
// full month names
Calendar._MN = new Array
("Januar",
"Februar",
"Marts",
"April",
"Maj",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"December");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"Mar",
"Apr",
"Maj",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Om Kalenderen";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For den seneste version besøg: http://www.dynarch.com/projects/calendar/\n"; +
"Distribueret under GNU LGPL. Se http://gnu.org/licenses/lgpl.html for detajler." +
"\n\n" +
"Valg af dato:\n" +
"- Brug \xab, \xbb knapperne for at vælge år\n" +
"- Brug " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " knapperne for at vælge måned\n" +
"- Hold knappen på musen nede på knapperne ovenfor for hurtigere valg.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Valg af tid:\n" +
"- Klik på en vilkårlig del for større værdi\n" +
"- eller Shift-klik for for mindre værdi\n" +
"- eller klik og træk for hurtigere valg.";
Calendar._TT["PREV_YEAR"] = "Ét år tilbage (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Én måned tilbage (hold for menu)";
Calendar._TT["GO_TODAY"] = "Gå til i dag";
Calendar._TT["NEXT_MONTH"] = "Én måned frem (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Ét år frem (hold for menu)";
Calendar._TT["SEL_DATE"] = "Vælg dag";
Calendar._TT["DRAG_TO_MOVE"] = "Træk vinduet";
Calendar._TT["PART_TODAY"] = " (i dag)";
// 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"] = "Vis %s først";
// 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"] = "Luk";
Calendar._TT["TODAY"] = "I dag";
Calendar._TT["TIME_PART"] = "(Shift-)klik eller træk for at ændre værdi";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "Uge";
Calendar._TT["TIME"] = "Tid:";
| JavaScript |
// ** I18N
// Calendar big5-utf8 language
// Author: Gary Fu, <gary@garyfu.idv.tw>
// Encoding: utf8
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
"星期日");
// 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
("日",
"一",
"二",
"三",
"四",
"五",
"六",
"日");
// full month names
Calendar._MN = new Array
("一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月");
// short month names
Calendar._SMN = new Array
("一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "關於";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"日期選擇方法:\n" +
"- 使用 \xab, \xbb 按鈕可選擇年份\n" +
"- 使用 " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " 按鈕可選擇月份\n" +
"- 按住上面的按鈕可以加快選取";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"時間選擇方法:\n" +
"- 點擊任何的時間部份可增加其值\n" +
"- 同時按Shift鍵再點擊可減少其值\n" +
"- 點擊並拖曳可加快改變的值";
Calendar._TT["PREV_YEAR"] = "上一年 (按住選單)";
Calendar._TT["PREV_MONTH"] = "下一年 (按住選單)";
Calendar._TT["GO_TODAY"] = "到今日";
Calendar._TT["NEXT_MONTH"] = "上一月 (按住選單)";
Calendar._TT["NEXT_YEAR"] = "下一月 (按住選單)";
Calendar._TT["SEL_DATE"] = "選擇日期";
Calendar._TT["DRAG_TO_MOVE"] = "拖曳";
Calendar._TT["PART_TODAY"] = " (今日)";
// 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"] = "將 %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._TT["TODAY"] = "今日";
Calendar._TT["TIME_PART"] = "點擊or拖曳可改變時間(同時按Shift為減)";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "週";
Calendar._TT["TIME"] = "Time:";
| JavaScript |
/////////////////////////////////////////////////////////////////////////////////////
// Then Modified by:
// Ed Moss
//
// Modified and enhanced by:
// Nathaniel Brown - http://nshb.net
// Email: nshb@inimit.com
//
// Created by:
// Simon Willison - http://simon.incutio.com
//
// License:
// GNU Lesser General Public License version 2.1 or above.
// http://www.gnu.org/licenses/lgpl.html
//
// Bugs:
// Please submit bug reports to http://dev.toolbocks.com
//
/////////////////////////////////////////////////////////////////////////////////////
// Dates such as 2/29/2005 to rollover to 3/1/2005
var configAutoRollOver = true;
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Functions
function dateBocksKeyListener(event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13 || keyCode == 10) {
return false;
}
}
function windowProperties(param_properties){
var oRegex = new RegExp('');
oRegex.compile( "(?:^|,)([^=]+)=(\\d+|yes|no|auto)", 'gim' );
var oProperties = new Object();
var oPropertiesMatch;
while( ( oPropertiesMatch = oRegex.exec( param_properties ) ) != null ) {
var sValue = oPropertiesMatch[2];
if ( sValue == ( 'yes' || '1' ) ) {
oProperties[ oPropertiesMatch[1] ] = true;
} else if ( (! isNaN( sValue ) && sValue != 0) || ('auto' == sValue ) ) {
oProperties[ oPropertiesMatch[1] ] = sValue;
}
}
return oProperties;
}
function windowOpenCenter(window_url, window_name, window_properties){
try {
var oProperties = windowProperties(window_properties);
//if( !oProperties['autocenter'] || oProperties['fullscreen'] ) {
// return window.open(window_url, window_name, window_properties);
//}
w = parseInt(oProperties['width']);
h = parseInt(oProperties['height']);
w = w > 0 ? w : 640;
h = h > 0 ? h : 480;
if (screen) {
t = (screen.height - h) / 2;
l = (screen.width - w) / 2;
} else {
t = 250;
l = 250;
}
window_properties = (w>0?",width="+w:"") + (h>0?",height="+h:"") + (t>0?",top="+t:"") + (l>0?",left="+l:"") + "," + window_properties.replace(/,(width=\s*\d+\s*|height=\s*\d+\s*|top=\s*\d+\s*||left=\s*\d+\s*)/gi, "");
return window.open(window_url, window_name, window_properties);
} catch( e ) {};
}
// add indexOf function to Array type
// finds the index of the first occurence of item in the array, or -1 if not found
Array.prototype.indexOf = function(item) {
for (var i = 0; i < this.length; i++) {
if (this[i] == item) {
return i;
}
}
return -1;
};
// add filter function to Array type
// returns an array of items judged true by the passed in test function
Array.prototype.filter = function(test) {
var matches = [];
for (var i = 0; i < this.length; i++) {
if (test(this[i])) {
matches[matches.length] = this[i];
}
}
return matches;
};
// add right function to String type
// returns the rightmost x characters
String.prototype.right = function( intLength ) {
if (intLength >= this.length)
return this;
else
return this.substr( this.length - intLength, intLength );
};
// add trim function to String type
// trims leading and trailing whitespace
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
// arrays for month and weekday names
var monthNames = "January February March April May June July August September October November December".split(" ");
var weekdayNames = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");
/* Takes a string, returns the index of the month matching that string, throws
an error if 0 or more than 1 matches
*/
function parseMonth(month) {
var matches = monthNames.filter(function(item) {
return new RegExp("^" + month, "i").test(item);
});
if (matches.length == 0) {
throw new Error("Invalid month string");
}
if (matches.length < 1) {
throw new Error("Ambiguous month");
}
return monthNames.indexOf(matches[0]);
}
/* Same as parseMonth but for days of the week */
function parseWeekday(weekday) {
var matches = weekdayNames.filter(function(item) {
return new RegExp("^" + weekday, "i").test(item);
});
if (matches.length == 0) {
throw new Error("Invalid day string");
}
if (matches.length < 1) {
throw new Error("Ambiguous weekday");
}
return weekdayNames.indexOf(matches[0]);
}
function DateInRange( yyyy, mm, dd )
{
// if month out of range
if ( mm < 0 || mm > 11 )
throw new Error('Invalid month value. Valid months values are 1 to 12');
if (!configAutoRollOver) {
// get last day in month
var d = (11 == mm) ? new Date(yyyy + 1, 0, 0) : new Date(yyyy, mm + 1, 0);
// if date out of range
if ( dd < 1 || dd > d.getDate() )
throw new Error('Invalid date value. Valid date values for ' + monthNames[mm] + ' are 1 to ' + d.getDate().toString());
}
return true;
}
function getDateObj(yyyy, mm, dd, hh, min, ss) {
var obj = new Date();
if (!hh) hh = 0;
if (!min) min = 0;
if (!ss) ss = 0;
obj.setDate(1);
obj.setYear(yyyy);
obj.setMonth(mm);
obj.setDate(dd);
obj.setHours(hh);
obj.setMinutes(min);
obj.setSeconds(ss);
return obj;
}
/* Array of objects, each has 're', a regular expression and 'handler', a
function for creating a date from something that matches the regular
expression. Handlers may throw errors if string is unparseable.
*/
var dateParsePatterns = [
// Today
{ re: /^tod|now/i,
handler: function() {
return new Date();
}
},
// Tomorrow
{ re: /^tom/i,
handler: function() {
var d = new Date();
d.setDate(d.getDate() + 1);
return d;
}
},
// Yesterday
{ re: /^yes/i,
handler: function() {
var d = new Date();
d.setDate(d.getDate() - 1);
return d;
}
},
// 4th
{ re: /^(\d{1,2})(st|nd|rd|th)?$/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear();
var dd = parseInt(bits[1], 10);
var mm = d.getMonth();
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// 4th Jan
{ re: /^(\d{1,2})(?:st|nd|rd|th)? (?:of\s)?(\w+)$/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear();
var dd = parseInt(bits[1], 10);
var mm = parseMonth(bits[2]);
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// 4th Jan 2003
{ re: /^(\d{1,2})(?:st|nd|rd|th)? (?:of )?(\w+),? (\d{4})$/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
d.setDate(parseInt(bits[1], 10));
d.setMonth(parseMonth(bits[2]));
d.setYear(bits[3]);
return d;
}
},
// Jan 4th
{ re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear();
var dd = parseInt(bits[2], 10);
var mm = parseMonth(bits[1]);
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// Jan 4th 2003
{ re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i,
handler: function(bits, calendarIfFormat) {
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[2], 10);
var mm = parseMonth(bits[1]);
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// Next Week, Last Week, Next Month, Last Month, Next Year, Last Year
{ re: /((next|last)\s(week|month|year))/i,
handler: function(bits, calendarIfFormat) {
var objDate = new Date();
var dd = objDate.getDate();
var mm = objDate.getMonth();
var yyyy = objDate.getFullYear();
switch (bits[3]) {
case 'week':
var newDay = (bits[2] == 'next') ? (dd + 7) : (dd - 7);
objDate.setDate(newDay);
break;
case 'month':
var newMonth = (bits[2] == 'next') ? (mm + 1) : (mm - 1);
objDate.setMonth(newMonth);
break;
case 'year':
var newYear = (bits[2] == 'next') ? (yyyy + 1) : (yyyy - 1);
objDate.setYear(newYear);
break;
}
return objDate;
}
},
// next Tuesday - this is suspect due to weird meaning of "next"
{ re: /^next (\w+)$/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var day = d.getDay();
var newDay = parseWeekday(bits[1]);
var addDays = newDay - day;
if (newDay <= day) {
addDays += 7;
}
d.setDate(d.getDate() + addDays);
return d;
}
},
// last Tuesday
{ re: /^last (\w+)$/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var wd = d.getDay();
var nwd = parseWeekday(bits[1]);
// determine the number of days to subtract to get last weekday
var addDays = (-1 * (wd + 7 - nwd)) % 7;
// above calculate 0 if weekdays are the same so we have to change this to 7
if (0 == addDays)
addDays = -7;
// adjust date and return
d.setDate(d.getDate() + addDays);
return d;
}
},
// mm/dd/yyyy or dd/mm/yyyy
{ re: /(\d{1,2})\/(\d{1,2})\/(\d{4})/,
handler: function(bits, calendarIfFormat) {
// if config date type is set to another format, use that instead
if (calendarIfFormat[1] == 'd') {
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[1], 10);
var mm = parseInt(bits[2], 10) - 1;
} else {
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[2], 10);
var mm = parseInt(bits[1], 10) - 1;
}
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// mm/dd/yy (American style) short year
{ re: /(\d{1,2})\/(\d{1,2})\/(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear() - (d.getFullYear() % 100) + parseInt(bits[3], 10);
var dd = parseInt(bits[2], 10);
var mm = parseInt(bits[1], 10) - 1;
if ( DateInRange(yyyy, mm, dd) )
return getDateObj(yyyy, mm, dd);
}
},
// mm/dd (American style) omitted year
{ re: /(\d{1,2})\/(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear();
var dd = parseInt(bits[2], 10);
var mm = parseInt(bits[1], 10) - 1;
if ( DateInRange(yyyy, mm, dd) )
return getDateObj(yyyy, mm, dd);
}
},
// mm-dd-yyyy :HH:MM:SS or dd-mm-yyyy :HH:MM:SS
{ re: /(\d{1,2})-(\d{1,2})-(\d{4}) (\d{1,2}):(\d{1,2}):(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
if (calendarIfFormat[1] == 'd') {
// if the config is set to use a different schema, then use that instead
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[1], 10);
var mm = parseInt(bits[2], 10) - 1;
} else {
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[2], 10);
var mm = parseInt(bits[1], 10) - 1;
}
var hh = parseInt(bits[4], 10);
var min = parseInt(bits[5], 10);
var ss = parseInt(bits[6], 10);
if ( DateInRange( yyyy, mm, dd ) ) {
return getDateObj(yyyy, mm, dd, hh, min, ss);
}
}
},
// mm-dd-yyyy or dd-mm-yyyy
{ re: /(\d{1,2})-(\d{1,2})-(\d{4})/,
handler: function(bits, calendarIfFormat) {
if (calendarIfFormat[1] == 'd') {
// if the config is set to use a different schema, then use that instead
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[1], 10);
var mm = parseInt(bits[2], 10) - 1;
} else {
var yyyy = parseInt(bits[3], 10);
var dd = parseInt(bits[2], 10);
var mm = parseInt(bits[1], 10) - 1;
}
if ( DateInRange( yyyy, mm, dd ) ) {
return getDateObj(yyyy, mm, dd);
}
}
},
// dd.mm.yyyy :HH:MM:SS
{ re: /(\d{1,2})\.(\d{1,2})\.(\d{4}) (\d{1,2}):(\d{1,2}):(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var dd = parseInt(bits[1], 10);
var mm = parseInt(bits[2], 10) - 1;
var yyyy = parseInt(bits[3], 10);
var hh = parseInt(bits[4], 10);
var min = parseInt(bits[5], 10);
var ss = parseInt(bits[6], 10);
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd, hh, min, ss);
}
},
// dd.mm.yyyy
{ re: /(\d{1,2})\.(\d{1,2})\.(\d{4})/,
handler: function(bits, calendarIfFormat) {
var dd = parseInt(bits[1], 10);
var mm = parseInt(bits[2], 10) - 1;
var yyyy = parseInt(bits[3], 10);
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// yyyy-mm-dd HH:MM:SS (ISO style)
{ re: /(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var yyyy = parseInt(bits[1], 10);
var dd = parseInt(bits[3], 10);
var mm = parseInt(bits[2], 10) - 1;
var hh = parseInt(bits[4], 10);
var min = parseInt(bits[5], 10);
var ss = parseInt(bits[6], 10);
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd, hh, min, ss);
}
},
// yyyy-mm-dd HH:MM:SS (ISO style)
{ re: /(\d{4})-(\d{1,2})-(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var yyyy = parseInt(bits[1], 10);
var dd = parseInt(bits[3], 10);
var mm = parseInt(bits[2], 10) - 1;
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// yy-mm-dd (ISO style) short year
{ re: /(\d{1,2})-(\d{1,2})-(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear() - (d.getFullYear() % 100) + parseInt(bits[1], 10);
var dd = parseInt(bits[3], 10);
var mm = parseInt(bits[2], 10) - 1;
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// mm-dd (ISO style) omitted year
{ re: /(\d{1,2})-(\d{1,2})/,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var yyyy = d.getFullYear();
var dd = parseInt(bits[2], 10);
var mm = parseInt(bits[1], 10) - 1;
if ( DateInRange( yyyy, mm, dd ) )
return getDateObj(yyyy, mm, dd);
}
},
// mon, tue, wed, thr, fri, sat, sun
{ re: /(^mon.*|^tue.*|^wed.*|^thu.*|^fri.*|^sat.*|^sun.*)/i,
handler: function(bits, calendarIfFormat) {
var d = new Date();
var day = d.getDay();
var newDay = parseWeekday(bits[1]);
var addDays = newDay - day;
if (newDay <= day) {
addDays += 7;
}
d.setDate(d.getDate() + addDays);
return d;
}
},
];
function parseDateString(s, calendarIfFormat) {
for (var i = 0; i < dateParsePatterns.length; i++) {
var re = dateParsePatterns[i].re;
var handler = dateParsePatterns[i].handler;
var bits = re.exec(s, calendarIfFormat);
if (bits) {
return handler(bits, calendarIfFormat);
}
}
throw new Error("Invalid date string");
}
function magicDateOnlyOnSubmit(id, calendarIfFormat, event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13 || keyCode == 10) {
magicDate(id, calendarIfFormat);
}
}
function magicDate(id, calendarIfFormat) {
var input = document.getElementById(id);
var messagespan = input.id + 'Msg';
try {
var d = parseDateString(input.value, calendarIfFormat);
var year = d.getFullYear();
var day = (d.getDate() <= 9) ? '0' + d.getDate().toString() : d.getDate();
var month = ((d.getMonth() + 1) <= 9) ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
var hours = (d.getHours() <= 9) ? '0' + d.getHours().toString() : d.getHours();
var minutes = (d.getMinutes() <= 9) ? '0' + d.getMinutes().toString() : d.getMinutes();
var seconds = (d.getSeconds() <= 9) ? '0' + d.getSeconds().toString() : d.getSeconds();
if (calendarIfFormat) {
date_value = calendarIfFormat.replace("%Y", year).replace("%m", month).replace("%d", day).replace("%H", hours).replace("%M", minutes).replace("%S", seconds);
}
else {
date_value = year + '-' + month + '-' + day;
}
input.value = date_value;
// Human readable date
if (document.getElementById(messagespan)) document.getElementById(messagespan).innerHTML = d.toDateString();
if (document.getElementById(messagespan)) document.getElementById(messagespan).className = 'normal';
}
catch (e) {
input.className = 'fieldWithErrors';
var message = e.message;
// Fix for IE6 bug
if (message.indexOf('is null or not an object') > -1) {
message = 'Invalid date string';
}
if (document.getElementById(messagespan)) document.getElementById(messagespan).innerHTML = message;
if (document.getElementById(messagespan)) document.getElementById(messagespan).className = 'error';
}
}
/*
Compact Forms (for Prototype)
http://www.alistapart.com/articles/makingcompactformsmoreaccessible/
*/
// OverLabel = Class.create();
// OverLabel.prototype = {
// label: null,
// target: null,
//
// initialize: function(label) {
// this.label = $(label);
// this.target = $(this.label.htmlFor || this.label.getAttribute('for'));
// this.label.addClassName('overlabel-apply');
// this.hide_or_show(); // initialize the state
// this.target.observe('focus', this.hide.bind(this));
// this.target.observe('blur', this.hide_or_show.bind(this));
//
// this.label.observe('click', function() {
// this.target.focus();
// }.bind(this));
// },
//
// hide_or_show: function() {
// if (this.target.value) this.hide();
// else this.show();
// },
//
// hide: function() {
// this.label.style.textIndent = '-2000px';
// },
// show: function() {
// this.label.style.textIndent = '0px';
// }
// }
// OverLabel.initialize_all = function() {
// $$('label.overlabel').each(function(label) {
// if (label.htmlFor || label.getAttribute('for')) new OverLabel(label);
// });
// }
//
// Event.observe(window, 'load', function() {
// setTimeout(OverLabel.initialize_all, 50)
// }); | JavaScript |
/* Copyright Mihai Bazon, 2002, 2003 | http://dynarch.com/mishoo/
* ---------------------------------------------------------------------------
*
* The DHTML Calendar
*
* Details and latest version at:
* http://dynarch.com/mishoo/calendar.epl
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*
* This file defines helper functions for setting up the calendar. They are
* intended to help non-programmers get a working calendar on their site
* quickly. This script should not be seen as part of the calendar. It just
* shows you what one can do with the calendar, while in the same time
* providing a quick and simple method for setting it up. If you need
* exhaustive customization of the calendar creation process feel free to
* modify this code to suit your needs (this is recommended and much better
* than modifying calendar.js itself).
*/
// $Id: calendar-setup.js,v 1.25 2005/03/07 09:51:33 mishoo Exp $
/**
* This function "patches" an input field (or other element) to use a calendar
* widget for date selection.
*
* The "params" is a single object that can have the following properties:
*
* prop. name | description
* -------------------------------------------------------------------------------------------------
* inputField | the ID of an input field to store the date
* displayArea | the ID of a DIV or other element to show the date
* button | ID of a button or other element that will trigger the calendar
* eventName | event that will trigger the calendar, without the "on" prefix (default: "click")
* ifFormat | date format that will be stored in the input field
* daFormat | the date format that will be used to display the date in displayArea
* singleClick | (true/false) wether the calendar is in single click mode or not (default: true)
* firstDay | numeric: 0 to 6. "0" means display Sunday first, "1" means display Monday first, etc.
* align | alignment (default: "Br"); if you don't know what's this see the calendar documentation
* range | array with 2 elements. Default: [1900, 2999] -- the range of years available
* weekNumbers | (true/false) if it's true (default) the calendar will display week numbers
* flat | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID
* flatCallback | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar)
* disableFunc | function that receives a JS Date object and should return true if that date has to be disabled in the calendar
* onSelect | function that gets called when a date is selected. You don't _have_ to supply this (the default is generally okay)
* onClose | function that gets called when the calendar is closed. [default]
* onUpdate | function that gets called after the date is updated in the input field. Receives a reference to the calendar.
* date | the date that the calendar will be initially displayed to
* showsTime | default: false; if true the calendar will include a time selector
* timeFormat | the time format; can be "12" or "24", default is "12"
* electric | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close
* step | configures the step of the years in drop-down boxes; default: 2
* position | configures the calendar absolute position; default: null
* cache | if "true" (but default: "false") it will reuse the same calendar object, where possible
* showOthers | if "true" (but default: "false") it will show days from other months too
*
* None of them is required, they all have default values. However, if you
* pass none of "inputField", "displayArea" or "button" you'll get a warning
* saying "nothing to setup".
*/
Calendar.setup = function (params) {
function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };
param_default("formName", null);
param_default("inputFieldYear", null);
param_default("inputFieldMonth", null);
param_default("inputFieldDay", null);
param_default("inputFieldHour", null);
param_default("inputFieldMinute", null);
param_default("inputField", null);
param_default("displayArea", null);
param_default("button", null);
param_default("help", null);
param_default("eventName", "click");
param_default("ifFormat", "%Y/%m/%d");
param_default("daFormat", "%Y/%m/%d");
param_default("singleClick", true);
param_default("disableFunc", null);
param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
param_default("dateText", null);
param_default("firstDay", null);
param_default("align", "Br");
param_default("range", [1900, 2999]);
param_default("weekNumbers", true);
param_default("flat", null);
param_default("flatCallback", null);
param_default("onSelect", null);
param_default("onClose", null);
param_default("onUpdate", null);
param_default("date", null);
param_default("showsTime", false);
param_default("timeFormat", "24");
param_default("electric", true);
param_default("step", 2);
param_default("position", null);
param_default("cache", false);
param_default("showOthers", false);
param_default("multiple", null);
var tmp = ["inputField", "displayArea", "button", "help", "inputFieldDay", "inputFieldMonth", "inputFieldYear", "inputFieldHour", "inputFieldMinute"];
for (var i in tmp) {
if (typeof params[tmp[i]] == "string") {
if (params['formName'])
params[tmp[i]] = document.forms[params['formName']][params[tmp[i]]];
else
params[tmp[i]] = document.getElementById(params[tmp[i]]);
}
}
if (!(params.flat || params.multiple || params.inputField || params.inputFieldDay || params.inputFieldMonth || params.inputFieldYear || params.inputFieldHour || params.inputFieldMinute || params.displayArea || params.button)) {
alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code");
return false;
}
function onSelect(cal) {
var p = cal.params;
var update = (cal.dateClicked || p.electric);
if (update && p.inputField) {
p.inputField.value = cal.date.print(p.ifFormat);
if (typeof p.inputField.onchange == "function")
p.inputField.onchange();
}
if (update && p.inputFieldHour) {
p.inputFieldHour.value = cal.date.getHours();
if (typeof p.inputFieldHour.onchange == "function")
p.inputFieldHour.onchange();
}
if (update && p.inputFieldMinute) {
p.inputFieldMinute.value = cal.date.getMinutes();
if (typeof p.inputFieldMinute.onchange == "function")
p.inputFieldMinute.onchange();
}
if (update && p.inputFieldDay) {
p.inputFieldDay.value = cal.date.getDate();
if (typeof p.inputFieldDay.onchange == "function")
p.inputFieldDay.onchange();
}
if (update && p.inputFieldMonth) {
p.inputFieldMonth.value = cal.date.getMonth() + 1;
if (typeof p.inputFieldMonth.onchange == "function")
p.inputFieldMonth.onchange();
}
if (update && p.inputFieldYear) {
p.inputFieldYear.value = cal.date.getFullYear();
if (typeof p.inputFieldYear.onchange == "function")
p.inputFieldYear.onchange();
}
if (update && p.displayArea)
p.displayArea.innerHTML = cal.date.print(p.daFormat);
if (update && typeof p.onUpdate == "function")
p.onUpdate(cal);
if (update && p.flat) {
if (typeof p.flatCallback == "function")
p.flatCallback(cal);
}
if (update && p.singleClick && cal.dateClicked)
cal.callCloseHandler();
};
if (params.flat != null) {
if (typeof params.flat == "string")
params.flat = document.getElementById(params.flat);
if (!params.flat) {
alert("Calendar.setup:\n Flat specified but can't find parent.");
return false;
}
var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
cal.showsOtherMonths = params.showOthers;
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.params = params;
cal.weekNumbers = params.weekNumbers;
cal.setRange(params.range[0], params.range[1]);
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
if (params.ifFormat) {
cal.setDateFormat(params.ifFormat);
}
if (params.inputField && typeof params.inputField.value == "string") {
cal.parseDate(params.inputField.value);
}
cal.create(params.flat);
cal.show();
return false;
}
/* var triggerElHelp = params.help; */
/* triggerElHelp["on" + params.eventName] = function() { */
/* DateBocks.windowOpenCenter('/datebocks/help', 'dateBocksHelp', 'width=500,height=430,autocenter=true'); */
/* } */
var triggerEl = params.button || params.displayArea || params.inputField;
triggerEl["on" + params.eventName] = function() {
var dateEl = params.inputField || params.displayArea;
var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
var mustCreate = false;
var cal = window.calendar;
if (dateEl)
params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
if (!(cal && params.cache)) {
window.calendar = cal = new Calendar(params.firstDay,
params.date,
params.onSelect || onSelect,
params.onClose || function(cal) { cal.hide(); });
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.weekNumbers = params.weekNumbers;
mustCreate = true;
} else {
if (params.date)
cal.setDate(params.date);
cal.hide();
}
if (params.multiple) {
cal.multiple = {};
for (var i = params.multiple.length; --i >= 0;) {
var d = params.multiple[i];
var ds = d.print("%Y%m%d");
cal.multiple[ds] = d;
}
}
cal.showsOtherMonths = params.showOthers;
cal.yearStep = params.step;
cal.setRange(params.range[0], params.range[1]);
cal.params = params;
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
cal.setDateFormat(dateFmt);
if (mustCreate)
cal.create();
cal.refresh();
if (!params.position) {
cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
} else {
cal.showAt(params.position[0], params.position[1]);
}
return false;
};
return cal;
};
| JavaScript |
// script.aculo.us builder.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array) ||
arguments[1].tagName) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return element;
},
_text: function(text) {
return document.createTextNode(text);
},
ATTR_MAP: {
'className': 'class',
'htmlFor': 'for'
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(children.tagName) {
element.appendChild(children);
return;
}
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e)
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
build: function(html) {
var element = this.node('div');
$(element).update(html.strip());
return element.down();
},
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each( function(tag){
scope[tag] = function() {
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
}
});
}
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/Focus.js
function WebForm_FindFirstFocusableChild(control) {
if (!control || !(control.tagName)) {
return null;
}
var tagName = control.tagName.toLowerCase();
if (tagName == "undefined") {
return null;
}
var children = control.childNodes;
if (children) {
for (var i = 0; i < children.length; i++) {
try {
if (WebForm_CanFocus(children[i])) {
return children[i];
}
else {
var focused = WebForm_FindFirstFocusableChild(children[i]);
if (WebForm_CanFocus(focused)) {
return focused;
}
}
} catch (e) {
}
}
}
return null;
}
function WebForm_AutoFocus(focusId) {
var targetControl;
if (__nonMSDOMBrowser) {
targetControl = document.getElementById(focusId);
}
else {
targetControl = document.all[focusId];
}
var focused = targetControl;
if (targetControl && (!WebForm_CanFocus(targetControl)) ) {
focused = WebForm_FindFirstFocusableChild(targetControl);
}
if (focused) {
try {
focused.focus();
if (__nonMSDOMBrowser) {
focused.scrollIntoView(false);
}
if (window.__smartNav) {
window.__smartNav.ae = focused.id;
}
}
catch (e) {
}
}
}
function WebForm_CanFocus(element) {
if (!element || !(element.tagName)) return false;
var tagName = element.tagName.toLowerCase();
return (!(element.disabled) &&
(!(element.type) || element.type.toLowerCase() != "hidden") &&
WebForm_IsFocusableTag(tagName) &&
WebForm_IsInVisibleContainer(element)
);
}
function WebForm_IsFocusableTag(tagName) {
return (tagName == "input" ||
tagName == "textarea" ||
tagName == "select" ||
tagName == "button" ||
tagName == "a");
}
function WebForm_IsInVisibleContainer(ctrl) {
var current = ctrl;
while((typeof(current) != "undefined") && (current != null)) {
if (current.disabled ||
( typeof(current.style) != "undefined" &&
( ( typeof(current.style.display) != "undefined" &&
current.style.display == "none") ||
( typeof(current.style.visibility) != "undefined" &&
current.style.visibility == "hidden") ) ) ) {
return false;
}
if (typeof(current.parentNode) != "undefined" &&
current.parentNode != null &&
current.parentNode != current &&
current.parentNode.tagName.toLowerCase() != "body") {
current = current.parentNode;
}
else {
return true;
}
}
return true;
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/WebForms.js
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
if (typeof(Page_ClientValidate) == 'function') {
validationResult = Page_ClientValidate(options.validationGroup);
}
}
if (validationResult) {
if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
theForm.action = options.actionUrl;
}
if (options.trackFocus) {
var lastFocus = theForm.elements["__LASTFOCUS"];
if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
if (typeof(document.activeElement) == "undefined") {
lastFocus.value = options.eventTarget;
}
else {
var active = document.activeElement;
if ((typeof(active) != "undefined") && (active != null)) {
if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
lastFocus.value = active.id;
}
else if (typeof(active.name) != "undefined") {
lastFocus.value = active.name;
}
}
}
}
}
}
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
}
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}
var xmlRequest,e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
}
catch(e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// e.g. http:
var action = theForm.action || document.location.pathname, fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
action = action.substr(0, fragmentIndex);
}
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
}
else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame = document.createElement("IFRAME");
xmlRequestFrame.width = "1";
xmlRequestFrame.height = "1";
xmlRequestFrame.frameBorder = "0";
xmlRequestFrame.id = callbackFrameID;
xmlRequestFrame.name = callbackFrameID;
xmlRequestFrame.style.position = "absolute";
xmlRequestFrame.style.top = "-100px"
xmlRequestFrame.style.left = "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src = callBackFrameUrl;
}
}
catch(e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame = document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write("");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element = __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type = "hidden";
fieldElement.name = element.name;
fieldElement.value = element.value;
xmlRequestFrame.document.forms[0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type = "hidden";
callbackIdFieldElement.name = "__CALLBACKID";
callbackIdFieldElement.value = eventTarget;
xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type = "hidden";
callbackParamFieldElement.name = "__CALLBACKPARAM";
callbackParamFieldElement.value = eventArgument;
xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type = "hidden";
callbackValidationFieldElement.name = "__EVENTVALIDATION";
callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type = "hidden";
callbackIndexFieldElement.name = "__CALLBACKINDEX";
callbackIndexFieldElement.value = callbackIndex;
xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[0].submit();
}
}, 10);
}
function WebForm_CallbackComplete() {
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(1), callbackObject.context);
}
}
else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(1), callbackObject.context);
}
}
else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement = document.createElement("INPUT");
validationFieldElement.type = "hidden";
validationFieldElement.name = "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value = validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context);
}
}
}
}
}
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i] = element;
return i;
}
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
var __theFormPostData = "";
var __theFormPostCollection = new Array();
var __callbackTextTypes = /^(text|password|hidden|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function WebForm_InitCallback() {
var formElements = theForm.elements,
count = formElements.length,
element;
for (var i = 0; i < count; i++) {
element = formElements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((__callbackTextTypes.test(type) || ((type == "checkbox" || type == "radio") && element.checked))
&& (element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
function WebForm_EncodeCallback(parameter) {
if (encodeURIComponent) {
return encodeURIComponent(parameter);
}
else {
return escape(parameter);
}
}
var __disabledControlArray = new Array();
function WebForm_ReEnableControls() {
if (typeof(__enabledControlArray) == 'undefined') {
return false;
}
var disabledIndex = 0;
for (var i = 0; i < __enabledControlArray.length; i++) {
var c;
if (__nonMSDOMBrowser) {
c = document.getElementById(__enabledControlArray[i]);
}
else {
c = document.all[__enabledControlArray[i]];
}
if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
c.disabled = false;
__disabledControlArray[disabledIndex++] = c;
}
}
setTimeout("WebForm_ReDisableControls()", 0);
return true;
}
function WebForm_ReDisableControls() {
for (var i = 0; i < __disabledControlArray.length; i++) {
__disabledControlArray[i].disabled = true;
}
}
function WebForm_SimulateClick(element, event) {
var clickEvent;
if (element) {
if (element.click) {
element.click();
} else {
clickEvent = document.createEvent("MouseEvents");
clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
if (!element.dispatchEvent(clickEvent)) {
return true;
}
}
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
return true;
}
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (src &&
((src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) ||
((src.tagName.toLowerCase() == "a") &&
(src.href != null) && (src.href != "")) ||
(src.tagName.toLowerCase() == "textarea")) {
return true;
}
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton) {
return WebForm_SimulateClick(defaultButton, event);
}
}
return true;
}
function WebForm_GetScrollX() {
if (__nonMSDOMBrowser) {
return window.pageXOffset;
}
else {
if (document.documentElement && document.documentElement.scrollLeft) {
return document.documentElement.scrollLeft;
}
else if (document.body) {
return document.body.scrollLeft;
}
}
return 0;
}
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
}
else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
}
else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
}
else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
function WebForm_SaveScrollPositionOnSubmit() {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
return this.oldOnSubmit();
}
return true;
}
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
}
else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
function WebForm_TextBoxKeyHandler(event) {
if (event.keyCode == 13) {
var target;
if (__nonMSDOMBrowser) {
target = event.target;
}
else {
target = event.srcElement;
}
if ((typeof(target) != "undefined") && (target != null)) {
if (typeof(target.onchange) != "undefined") {
target.onchange();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
function WebForm_TrimString(value) {
return value.replace(/^\s+|\s+$/g, '')
}
function WebForm_AppendToClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index === -1) {
element.className = (element.className === '') ? className : element.className + ' ' + className;
}
}
function WebForm_RemoveClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index >= 0) {
element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
currentClassName.substring(index + className.length + 1, currentClassName.length));
}
}
function WebForm_GetElementById(elementId) {
if (document.getElementById) {
return document.getElementById(elementId);
}
else if (document.all) {
return document.all[elementId];
}
else return null;
}
function WebForm_GetElementByTagName(element, tagName) {
var elements = WebForm_GetElementsByTagName(element, tagName);
if (elements && elements.length > 0) {
return elements[0];
}
else return null;
}
function WebForm_GetElementsByTagName(element, tagName) {
if (element && tagName) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(tagName);
}
if (element.all && element.all.tags) {
return element.all.tags(tagName);
}
}
return null;
}
function WebForm_GetElementDir(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return WebForm_GetElementDir(element.parentNode);
}
return "ltr";
}
function WebForm_GetElementPosition(element) {
var result = new Object();
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
}
else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
}
else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
}
else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}
function WebForm_GetParentByTagName(element, tagName) {
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function WebForm_SetElementHeight(element, height) {
if (element && element.style) {
element.style.height = height + "px";
}
}
function WebForm_SetElementWidth(element, width) {
if (element && element.style) {
element.style.width = width + "px";
}
}
function WebForm_SetElementX(element, x) {
if (element && element.style) {
element.style.left = x + "px";
}
}
function WebForm_SetElementY(element, y) {
if (element && element.style) {
element.style.top = y + "px";
}
} | JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/WebUIValidation.js
var Page_ValidationVer = "125";
var Page_IsValid = true;
var Page_BlockSubmit = false;
var Page_InvalidControlToBeFocused = null;
var Page_TextTypes = /^(text|password|file|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function ValidatorUpdateDisplay(val) {
if (typeof(val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
function ValidatorUpdateIsValid() {
Page_IsValid = AllValidatorsValid(Page_Validators);
}
function AllValidatorsValid(validators) {
if ((typeof(validators) != "undefined") && (validators != null)) {
var i;
for (i = 0; i < validators.length; i++) {
if (!validators[i].isvalid) {
return false;
}
}
}
return true;
}
function ValidatorHookupControlID(controlID, val) {
if (typeof(controlID) != "string") {
return;
}
var ctrl = document.getElementById(controlID);
if ((typeof(ctrl) != "undefined") && (ctrl != null)) {
ValidatorHookupControl(ctrl, val);
}
else {
val.isvalid = true;
val.enabled = false;
}
}
function ValidatorHookupControl(control, val) {
if (typeof(control.tagName) != "string") {
return;
}
if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" && control.tagName != "SELECT") {
var i;
for (i = 0; i < control.childNodes.length; i++) {
ValidatorHookupControl(control.childNodes[i], val);
}
return;
}
else {
if (typeof(control.Validators) == "undefined") {
control.Validators = new Array;
var eventType;
if (control.type == "radio") {
eventType = "onclick";
} else {
eventType = "onchange";
if (typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorHookupEvent(control, "onblur", "ValidatedControlOnBlur(event); ");
}
}
ValidatorHookupEvent(control, eventType, "ValidatorOnChange(event); ");
if (Page_TextTypes.test(control.type)) {
ValidatorHookupEvent(control, "onkeypress",
"event = event || window.event; if (!ValidatedTextBoxOnKeyPress(event)) { event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } ");
}
}
control.Validators[control.Validators.length] = val;
}
}
function ValidatorHookupEvent(control, eventType, functionPrefix) {
var ev = control[eventType];
if (typeof(ev) == "function") {
ev = ev.toString();
ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
}
else {
ev = "";
}
control[eventType] = new Function("event", functionPrefix + " " + ev);
}
function ValidatorGetValue(id) {
var control;
control = document.getElementById(id);
if (typeof(control.value) == "string") {
return control.value;
}
return ValidatorGetValueRecursive(control);
}
function ValidatorGetValueRecursive(control)
{
if (typeof(control.value) == "string" && (control.type != "radio" || control.checked == true)) {
return control.value;
}
var i, val;
for (i = 0; i<control.childNodes.length; i++) {
val = ValidatorGetValueRecursive(control.childNodes[i]);
if (val != "") return val;
}
return "";
}
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
function ValidatorCommonOnSubmit() {
Page_InvalidControlToBeFocused = null;
var result = !Page_BlockSubmit;
if ((typeof(window.event) != "undefined") && (window.event != null)) {
window.event.returnValue = result;
}
Page_BlockSubmit = false;
return result;
}
function ValidatorEnable(val, enable) {
val.enabled = (enable != false);
ValidatorValidate(val);
ValidatorUpdateIsValid();
}
function ValidatorOnChange(event) {
event = event || window.event;
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof(targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
if (vals) {
for (var i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
function ValidatedTextBoxOnKeyPress(event) {
event = event || window.event;
if (event.keyCode == 13) {
ValidatorOnChange(event);
var vals;
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
vals = event.srcElement.Validators;
}
else {
vals = event.target.Validators;
}
return AllValidatorsValid(vals);
}
return true;
}
function ValidatedControlOnBlur(event) {
event = event || window.event;
var control;
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
control = event.srcElement;
}
else {
control = event.target;
}
if ((typeof(control) != "undefined") && (control != null) && (Page_InvalidControlToBeFocused == control)) {
control.focus();
Page_InvalidControlToBeFocused = null;
}
}
function ValidatorValidate(val, validationGroup, event) {
val.isvalid = true;
if ((typeof(val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, validationGroup)) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorSetFocus(val, event);
}
}
}
ValidatorUpdateDisplay(val);
}
function ValidatorSetFocus(val, event) {
var ctrl;
if (typeof(val.controlhookup) == "string") {
var eventCtrl;
if ((typeof(event) != "undefined") && (event != null)) {
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
eventCtrl = event.srcElement;
}
else {
eventCtrl = event.target;
}
}
if ((typeof(eventCtrl) != "undefined") && (eventCtrl != null) &&
(typeof(eventCtrl.id) == "string") &&
(eventCtrl.id == val.controlhookup)) {
ctrl = eventCtrl;
}
}
if ((typeof(ctrl) == "undefined") || (ctrl == null)) {
ctrl = document.getElementById(val.controltovalidate);
}
if ((typeof(ctrl) != "undefined") && (ctrl != null) &&
(ctrl.tagName.toLowerCase() != "table" || (typeof(event) == "undefined") || (event == null)) &&
((ctrl.tagName.toLowerCase() != "input") || (ctrl.type.toLowerCase() != "hidden")) &&
(typeof(ctrl.disabled) == "undefined" || ctrl.disabled == null || ctrl.disabled == false) &&
(typeof(ctrl.visible) == "undefined" || ctrl.visible == null || ctrl.visible != false) &&
(IsInVisibleContainer(ctrl))) {
if ((ctrl.tagName.toLowerCase() == "table" && (typeof(__nonMSDOMBrowser) == "undefined" || __nonMSDOMBrowser)) ||
(ctrl.tagName.toLowerCase() == "span")) {
var inputElements = ctrl.getElementsByTagName("input");
var lastInputElement = inputElements[inputElements.length -1];
if (lastInputElement != null) {
ctrl = lastInputElement;
}
}
if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
}
}
}
function IsInVisibleContainer(ctrl) {
if (typeof(ctrl.style) != "undefined" &&
( ( typeof(ctrl.style.display) != "undefined" &&
ctrl.style.display == "none") ||
( typeof(ctrl.style.visibility) != "undefined" &&
ctrl.style.visibility == "hidden") ) ) {
return false;
}
else if (typeof(ctrl.parentNode) != "undefined" &&
ctrl.parentNode != null &&
ctrl.parentNode != ctrl) {
return IsInVisibleContainer(ctrl.parentNode);
}
return true;
}
function IsValidationGroupMatch(control, validationGroup) {
if ((typeof(validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
if (typeof(control.validationGroup) == "string") {
controlGroup = control.validationGroup;
}
return (controlGroup == validationGroup);
}
function ValidatorOnLoad() {
if (typeof(Page_Validators) == "undefined")
return;
var i, val;
for (i = 0; i < Page_Validators.length; i++) {
val = Page_Validators[i];
if (typeof(val.evaluationfunction) == "string") {
eval("val.evaluationfunction = " + val.evaluationfunction + ";");
}
if (typeof(val.isvalid) == "string") {
if (val.isvalid == "False") {
val.isvalid = false;
Page_IsValid = false;
}
else {
val.isvalid = true;
}
} else {
val.isvalid = true;
}
if (typeof(val.enabled) == "string") {
val.enabled = (val.enabled != "False");
}
if (typeof(val.controltovalidate) == "string") {
ValidatorHookupControlID(val.controltovalidate, val);
}
if (typeof(val.controlhookup) == "string") {
ValidatorHookupControlID(val.controlhookup, val);
}
}
Page_ValidationActive = true;
}
function ValidatorConvert(op, dataType, val) {
function GetFullYear(year) {
var twoDigitCutoffYear = val.cutoffyear % 100;
var cutoffYearCentury = val.cutoffyear - twoDigitCutoffYear;
return ((year > twoDigitCutoffYear) ? (cutoffYearCentury - 100 + year) : (cutoffYearCentury + year));
}
var num, cleanInput, m, exp;
if (dataType == "Integer") {
exp = /^\s*[-\+]?\d+\s*$/;
if (op.match(exp) == null)
return null;
num = parseInt(op, 10);
return (isNaN(num) ? null : num);
}
else if(dataType == "Double") {
exp = new RegExp("^\\s*([-\\+])?(\\d*)\\" + val.decimalchar + "?(\\d*)\\s*$");
m = op.match(exp);
if (m == null)
return null;
if (m[2].length == 0 && m[3].length == 0)
return null;
cleanInput = (m[1] != null ? m[1] : "") + (m[2].length>0 ? m[2] : "0") + (m[3].length>0 ? "." + m[3] : "");
num = parseFloat(cleanInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Currency") {
var hasDigits = (val.digits > 0);
var beginGroupSize, subsequentGroupSize;
var groupSizeNum = parseInt(val.groupsize, 10);
if (!isNaN(groupSizeNum) && groupSizeNum > 0) {
beginGroupSize = "{1," + groupSizeNum + "}";
subsequentGroupSize = "{" + groupSizeNum + "}";
}
else {
beginGroupSize = subsequentGroupSize = "+";
}
exp = new RegExp("^\\s*([-\\+])?((\\d" + beginGroupSize + "(\\" + val.groupchar + "\\d" + subsequentGroupSize + ")+)|\\d*)"
+ (hasDigits ? "\\" + val.decimalchar + "?(\\d{0," + val.digits + "})" : "")
+ "\\s*$");
m = op.match(exp);
if (m == null)
return null;
if (m[2].length == 0 && hasDigits && m[5].length == 0)
return null;
cleanInput = (m[1] != null ? m[1] : "") + m[2].replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((hasDigits && m[5].length > 0) ? "." + m[5] : "");
num = parseFloat(cleanInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Date") {
var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\.?\\s*$");
m = op.match(yearFirstExp);
var day, month, year;
if (m != null && (((typeof(m[2]) != "undefined") && (m[2].length == 4)) || val.dateorder == "ymd")) {
day = m[6];
month = m[5];
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
}
else {
if (val.dateorder == "ymd"){
return null;
}
var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})(?:\\s|\\2)((\\d{4})|(\\d{2}))(?:\\s\u0433\\.|\\.)?\\s*$");
m = op.match(yearLastExp);
if (m == null) {
return null;
}
if (val.dateorder == "mdy") {
day = m[3];
month = m[1];
}
else {
day = m[1];
month = m[3];
}
year = ((typeof(m[5]) != "undefined") && (m[5].length == 4)) ? m[5] : GetFullYear(parseInt(m[6], 10));
}
month -= 1;
var date = new Date(year, month, day);
if (year < 100) {
date.setFullYear(year);
}
return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
}
else {
return op.toString();
}
}
function ValidatorCompare(operand1, operand2, operator, val) {
var dataType = val.type;
var op1, op2;
if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
return false;
if (operator == "DataTypeCheck")
return true;
if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
return true;
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
}
}
function CompareValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var compareTo = "";
if ((typeof(val.controltocompare) != "string") ||
(typeof(document.getElementById(val.controltocompare)) == "undefined") ||
(null == document.getElementById(val.controltocompare))) {
if (typeof(val.valuetocompare) == "string") {
compareTo = val.valuetocompare;
}
}
else {
compareTo = ValidatorGetValue(val.controltocompare);
}
var operator = "Equal";
if (typeof(val.operator) == "string") {
operator = val.operator;
}
return ValidatorCompare(value, compareTo, operator, val);
}
function CustomValidatorEvaluateIsValid(val) {
var value = "";
if (typeof(val.controltovalidate) == "string") {
value = ValidatorGetValue(val.controltovalidate);
if ((ValidatorTrim(value).length == 0) &&
((typeof(val.validateemptytext) != "string") || (val.validateemptytext != "true"))) {
return true;
}
}
var args = { Value:value, IsValid:true };
if (typeof(val.clientvalidationfunction) == "string") {
eval(val.clientvalidationfunction + "(val, args) ;");
}
return args.IsValid;
}
function RegularExpressionValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var rx = new RegExp(val.validationexpression);
var matches = rx.exec(value);
return (matches != null && value == matches[0]);
}
function ValidatorTrim(s) {
var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
return (m == null) ? "" : m[1];
}
function RequiredFieldValidatorEvaluateIsValid(val) {
return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != ValidatorTrim(val.initialvalue))
}
function RangeValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
return (ValidatorCompare(value, val.minimumvalue, "GreaterThanEqual", val) &&
ValidatorCompare(value, val.maximumvalue, "LessThanEqual", val));
}
function ValidationSummaryOnSubmit(validationGroup) {
if (typeof(Page_ValidationSummaries) == "undefined")
return;
var summary, sums, s;
var headerSep, first, pre, post, end;
for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
summary = Page_ValidationSummaries[sums];
if (!summary) continue;
summary.style.display = "none";
if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
var i;
if (summary.showsummary != "False") {
summary.style.display = "";
if (typeof(summary.displaymode) != "string") {
summary.displaymode = "BulletList";
}
switch (summary.displaymode) {
case "List":
headerSep = "<br>";
first = "";
pre = "";
post = "<br>";
end = "";
break;
case "BulletList":
default:
headerSep = "";
first = "<ul>";
pre = "<li>";
post = "</li>";
end = "</ul>";
break;
case "SingleParagraph":
headerSep = " ";
first = "";
pre = "";
post = " ";
end = "<br>";
break;
}
s = "";
if (typeof(summary.headertext) == "string") {
s += summary.headertext + headerSep;
}
s += first;
for (i=0; i<Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
s += pre + Page_Validators[i].errormessage + post;
}
}
s += end;
summary.innerHTML = s;
window.scrollTo(0,0);
}
if (summary.showmessagebox == "True") {
s = "";
if (typeof(summary.headertext) == "string") {
s += summary.headertext + "\r\n";
}
var lastValIndex = Page_Validators.length - 1;
for (i=0; i<=lastValIndex; i++) {
if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
switch (summary.displaymode) {
case "List":
s += Page_Validators[i].errormessage;
if (i < lastValIndex) {
s += "\r\n";
}
break;
case "BulletList":
default:
s += "- " + Page_Validators[i].errormessage;
if (i < lastValIndex) {
s += "\r\n";
}
break;
case "SingleParagraph":
s += Page_Validators[i].errormessage + " ";
break;
}
}
}
alert(s);
}
}
}
}
if (window.jQuery) {
(function ($) {
var dataValidationAttribute = "data-val",
dataValidationSummaryAttribute = "data-valsummary",
normalizedAttributes = { validationgroup: "validationGroup", focusonerror: "focusOnError" };
function getAttributesWithPrefix(element, prefix) {
var i,
attribute,
list = {},
attributes = element.attributes,
length = attributes.length,
prefixLength = prefix.length;
prefix = prefix.toLowerCase();
for (i = 0; i < length; i++) {
attribute = attributes[i];
if (attribute.specified && attribute.name.substr(0, prefixLength).toLowerCase() === prefix) {
list[attribute.name.substr(prefixLength)] = attribute.value;
}
}
return list;
}
function normalizeKey(key) {
key = key.toLowerCase();
return normalizedAttributes[key] === undefined ? key : normalizedAttributes[key];
}
function addValidationExpando(element) {
var attributes = getAttributesWithPrefix(element, dataValidationAttribute + "-");
$.each(attributes, function (key, value) {
element[normalizeKey(key)] = value;
});
}
function dispose(element) {
var index = $.inArray(element, Page_Validators);
if (index >= 0) {
Page_Validators.splice(index, 1);
}
}
function addNormalizedAttribute(name, normalizedName) {
normalizedAttributes[name.toLowerCase()] = normalizedName;
}
function parseSpecificAttribute(selector, attribute, validatorsArray) {
return $(selector).find("[" + attribute + "='true']").each(function (index, element) {
addValidationExpando(element);
element.dispose = function () { dispose(element); element.dispose = null; };
if ($.inArray(element, validatorsArray) === -1) {
validatorsArray.push(element);
}
}).length;
}
function parse(selector) {
var length = parseSpecificAttribute(selector, dataValidationAttribute, Page_Validators);
length += parseSpecificAttribute(selector, dataValidationSummaryAttribute, Page_ValidationSummaries);
return length;
}
function loadValidators() {
if (typeof (ValidatorOnLoad) === "function") {
ValidatorOnLoad();
}
if (typeof (ValidatorOnSubmit) === "undefined") {
window.ValidatorOnSubmit = function () {
return Page_ValidationActive ? ValidatorCommonOnSubmit() : true;
};
}
}
function registerUpdatePanel() {
if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
var prm = Sys.WebForms.PageRequestManager.getInstance(),
postBackElement, endRequestHandler;
if (prm.get_isInAsyncPostBack()) {
endRequestHandler = function (sender, args) {
if (parse(document)) {
loadValidators();
}
prm.remove_endRequest(endRequestHandler);
endRequestHandler = null;
};
prm.add_endRequest(endRequestHandler);
}
prm.add_beginRequest(function (sender, args) {
postBackElement = args.get_postBackElement();
});
prm.add_pageLoaded(function (sender, args) {
var i, panels, valFound = 0;
if (typeof (postBackElement) === "undefined") {
return;
}
panels = args.get_panelsUpdated();
for (i = 0; i < panels.length; i++) {
valFound += parse(panels[i]);
}
panels = args.get_panelsCreated();
for (i = 0; i < panels.length; i++) {
valFound += parse(panels[i]);
}
if (valFound) {
loadValidators();
}
});
}
}
$(function () {
if (typeof (Page_Validators) === "undefined") {
window.Page_Validators = [];
}
if (typeof (Page_ValidationSummaries) === "undefined") {
window.Page_ValidationSummaries = [];
}
if (typeof (Page_ValidationActive) === "undefined") {
window.Page_ValidationActive = false;
}
$.WebFormValidator = {
addNormalizedAttribute: addNormalizedAttribute,
parse: parse
};
if (parse(document)) {
loadValidators();
}
registerUpdatePanel();
});
} (jQuery));
} | JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/SmartNav.js
var snSrc;
if ((typeof(window.__smartNav) == "undefined") || (window.__smartNav == null))
{
window.__smartNav = new Object();
window.__smartNav.update = function()
{
var sn = window.__smartNav;
var fd;
document.detachEvent("onstop", sn.stopHif);
sn.inPost = false;
try { fd = frames["__hifSmartNav"].document; } catch (e) {return;}
var fdr = fd.getElementsByTagName("asp_smartnav_rdir");
if (fdr.length > 0)
{
if ((typeof(sn.sHif) == "undefined") || (sn.sHif == null))
{
sn.sHif = document.createElement("IFRAME");
sn.sHif.name = "__hifSmartNav";
sn.sHif.style.display = "none";
sn.sHif.src = snSrc;
}
try {window.location = fdr[0].url;} catch (e) {};
return;
}
var fdurl = fd.location.href;
var index = fdurl.indexOf(snSrc);
if ((index != -1 && index == fdurl.length-snSrc.length)
|| fdurl == "about:blank")
return;
var fdurlb = fdurl.split("?")[0];
if (document.location.href.indexOf(fdurlb) < 0)
{
document.location.href=fdurl;
return;
}
sn._savedOnLoad = window.onload;
window.onload = null;
window.__smartNav.updateHelper();
}
window.__smartNav.updateHelper = function()
{
if (document.readyState != "complete")
{
window.setTimeout(window.__smartNav.updateHelper, 25);
return;
}
window.__smartNav.loadNewContent();
}
window.__smartNav.loadNewContent = function()
{
var sn = window.__smartNav;
var fd;
try { fd = frames["__hifSmartNav"].document; } catch (e) {return;}
if ((typeof(sn.sHif) != "undefined") && (sn.sHif != null))
{
sn.sHif.removeNode(true);
sn.sHif = null;
}
var hdm = document.getElementsByTagName("head")[0];
var hk = hdm.childNodes;
var tt = null;
var i;
for (i = hk.length - 1; i>= 0; i--)
{
if (hk[i].tagName == "TITLE")
{
tt = hk[i].outerHTML;
continue;
}
if (hk[i].tagName != "BASEFONT" || hk[i].innerHTML.length == 0)
hdm.removeChild(hdm.childNodes[i]);
}
var kids = fd.getElementsByTagName("head")[0].childNodes;
for (i = 0; i < kids.length; i++)
{
var tn = kids[i].tagName;
var k = document.createElement(tn);
k.id = kids[i].id;
k.mergeAttributes(kids[i]);
switch(tn)
{
case "TITLE":
if (tt == kids[i].outerHTML)
continue;
k.innerText = kids[i].text;
hdm.insertAdjacentElement("afterbegin", k);
continue;
case "BASEFONT" :
if (kids[i].innerHTML.length > 0)
continue;
break;
default:
var o = document.createElement("BODY");
o.innerHTML = "<BODY>" + kids[i].outerHTML + "</BODY>";
k = o.firstChild;
break;
}
if((typeof(k) != "undefined") && (k != null))
hdm.appendChild(k);
}
document.body.clearAttributes();
document.body.id = fd.body.id;
document.body.mergeAttributes(fd.body);
var newBodyLoad = fd.body.onload;
if ((typeof(newBodyLoad) != "undefined") && (newBodyLoad != null))
document.body.onload = newBodyLoad;
else
document.body.onload = sn._savedOnLoad;
var s = "<BODY>" + fd.body.innerHTML + "</BODY>";
if ((typeof(sn.hif) != "undefined") && (sn.hif != null))
{
var hifP = sn.hif.parentElement;
if ((typeof(hifP) != "undefined") && (hifP != null))
sn.sHif=hifP.removeChild(sn.hif);
}
document.body.innerHTML = s;
var sc = document.scripts;
for (i = 0; i < sc.length; i++)
{
sc[i].text = sc[i].text;
}
sn.hif = document.all("__hifSmartNav");
if ((typeof(sn.hif) != "undefined") && (sn.hif != null))
{
var hif = sn.hif;
sn.hifName = "__hifSmartNav" + (new Date()).getTime();
frames["__hifSmartNav"].name = sn.hifName;
sn.hifDoc = hif.contentWindow.document;
if (sn.ie5)
hif.parentElement.removeChild(hif);
window.setTimeout(sn.restoreFocus,0);
}
if (typeof(window.onload) == "string")
{
try { eval(window.onload) } catch (e) {};
}
else if ((typeof(window.onload) != "undefined") && (window.onload != null))
{
try { window.onload() } catch (e) {};
}
sn._savedOnLoad = null;
sn.attachForm();
};
window.__smartNav.restoreFocus = function()
{
if (window.__smartNav.inPost == true) return;
var curAe = document.activeElement;
var sAeId = window.__smartNav.ae;
if (((typeof(sAeId) == "undefined") || (sAeId == null)) ||
(typeof(curAe) != "undefined") && (curAe != null) && (curAe.id == sAeId || curAe.name == sAeId))
return;
var ae = document.all(sAeId);
if ((typeof(ae) == "undefined") || (ae == null)) return;
try { ae.focus(); } catch(e){};
}
window.__smartNav.saveHistory = function()
{
if ((typeof(window.__smartNav.hif) != "undefined") && (window.__smartNav.hif != null))
window.__smartNav.hif.removeNode();
if ((typeof(window.__smartNav.sHif) != "undefined") && (window.__smartNav.sHif != null)
&& (typeof(document.all[window.__smartNav.siHif]) != "undefined")
&& (document.all[window.__smartNav.siHif] != null)) {
document.all[window.__smartNav.siHif].insertAdjacentElement(
"BeforeBegin", window.__smartNav.sHif);
}
}
window.__smartNav.stopHif = function()
{
document.detachEvent("onstop", window.__smartNav.stopHif);
var sn = window.__smartNav;
if (((typeof(sn.hifDoc) == "undefined") || (sn.hifDoc == null)) &&
(typeof(sn.hif) != "undefined") && (sn.hif != null))
{
try {sn.hifDoc = sn.hif.contentWindow.document;}
catch(e){sn.hifDoc=null}
}
if (sn.hifDoc != null)
{
try {sn.hifDoc.execCommand("stop");} catch (e){}
}
}
window.__smartNav.init = function()
{
var sn = window.__smartNav;
window.__smartNav.form.__smartNavPostBack.value = 'true';
document.detachEvent("onstop", sn.stopHif);
document.attachEvent("onstop", sn.stopHif);
try { if (window.event.returnValue == false) return; } catch(e) {}
sn.inPost = true;
if ((typeof(document.activeElement) != "undefined") && (document.activeElement != null))
{
var ae = document.activeElement.id;
if (ae.length == 0)
ae = document.activeElement.name;
sn.ae = ae;
}
else
sn.ae = null;
try {document.selection.empty();} catch (e) {}
if ((typeof(sn.hif) == "undefined") || (sn.hif == null))
{
sn.hif = document.all("__hifSmartNav");
sn.hifDoc = sn.hif.contentWindow.document;
}
if ((typeof(sn.hifDoc) != "undefined") && (sn.hifDoc != null))
try {sn.hifDoc.designMode = "On";} catch(e){};
if ((typeof(sn.hif.parentElement) == "undefined") || (sn.hif.parentElement == null))
document.body.appendChild(sn.hif);
var hif = sn.hif;
hif.detachEvent("onload", sn.update);
hif.attachEvent("onload", sn.update);
window.__smartNav.fInit = true;
};
window.__smartNav.submit = function()
{
window.__smartNav.fInit = false;
try { window.__smartNav.init(); } catch(e) {}
if (window.__smartNav.fInit) {
window.__smartNav.form._submit();
}
};
window.__smartNav.attachForm = function()
{
var cf = document.forms;
for (var i=0; i<cf.length; i++)
{
if ((typeof(cf[i].__smartNavEnabled) != "undefined") && (cf[i].__smartNavEnabled != null))
{
window.__smartNav.form = cf[i];
window.__smartNav.form.insertAdjacentHTML("beforeEnd", "<input type='hidden' name='__smartNavPostBack' value='false' />");
break;
}
}
var snfm = window.__smartNav.form;
if ((typeof(snfm) == "undefined") || (snfm == null)) return false;
var sft = snfm.target;
if (sft.length != 0 && sft.indexOf("__hifSmartNav") != 0) return false;
var sfc = snfm.action.split("?")[0];
var url = window.location.href.split("?")[0];
if (url.charAt(url.length-1) != '/' && url.lastIndexOf(sfc) + sfc.length != url.length) return false;
if (snfm.__formAttached == true) return true;
snfm.__formAttached = true;
snfm.attachEvent("onsubmit", window.__smartNav.init);
snfm._submit = snfm.submit;
snfm.submit = window.__smartNav.submit;
snfm.target = window.__smartNav.hifName;
return true;
};
window.__smartNav.hifName = "__hifSmartNav" + (new Date()).getTime();
window.__smartNav.ie5 = navigator.appVersion.indexOf("MSIE 5") > 0;
var rc = window.__smartNav.attachForm();
var hif = document.all("__hifSmartNav");
if ((typeof(snSrc) == "undefined") || (snSrc == null)) {
if (typeof(window.dialogHeight) != "undefined") {
snSrc = "IEsmartnav1";
hif.src = snSrc;
} else {
snSrc = hif.src;
}
}
if (rc)
{
var fsn = frames["__hifSmartNav"];
fsn.name = window.__smartNav.hifName;
window.__smartNav.siHif = hif.sourceIndex;
try {
if (fsn.document.location != snSrc)
{
fsn.document.designMode = "On";
hif.attachEvent("onload",window.__smartNav.update);
window.__smartNav.hif = hif;
}
}
catch (e) { window.__smartNav.hif = hif; }
window.attachEvent("onbeforeunload", window.__smartNav.saveHistory);
}
else
window.__smartNav = null;
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/Menu.js
var __rootMenuItem;
var __menuInterval;
var __scrollPanel;
var __disappearAfter = 500;
function Menu_ClearInterval() {
if (__menuInterval) {
window.clearInterval(__menuInterval);
}
}
function Menu_Collapse(item) {
Menu_SetRoot(item);
if (__rootMenuItem) {
Menu_ClearInterval();
if (__disappearAfter >= 0) {
__menuInterval = window.setInterval("Menu_HideItems()", __disappearAfter);
}
}
}
function Menu_Expand(item, horizontalOffset, verticalOffset, hideScrollers) {
Menu_ClearInterval();
var tr = item.parentNode.parentNode.parentNode.parentNode.parentNode;
var horizontal = true;
if (!tr.id) {
horizontal = false;
tr = tr.parentNode;
}
var child = Menu_FindSubMenu(item);
if (child) {
var data = Menu_GetData(item);
if (!data) {
return null;
}
child.rel = tr.id;
child.x = horizontalOffset;
child.y = verticalOffset;
if (horizontal) child.pos = "bottom";
PopOut_Show(child.id, hideScrollers, data);
}
Menu_SetRoot(item);
if (child) {
if (!document.body.__oldOnClick && document.body.onclick) {
document.body.__oldOnClick = document.body.onclick;
}
if (__rootMenuItem) {
document.body.onclick = Menu_HideItems;
}
}
Menu_ResetSiblings(tr);
return child;
}
function Menu_FindMenu(item) {
if (item && item.menu) return item.menu;
var tr = item.parentNode.parentNode.parentNode.parentNode.parentNode;
if (!tr.id) {
tr = tr.parentNode;
}
for (var i = tr.id.length - 1; i >= 0; i--) {
if (tr.id.charAt(i) < '0' || tr.id.charAt(i) > '9') {
var menu = WebForm_GetElementById(tr.id.substr(0, i));
if (menu) {
item.menu = menu;
return menu;
}
}
}
return null;
}
function Menu_FindNext(item) {
var a = WebForm_GetElementByTagName(item, "A");
var parent = Menu_FindParentContainer(item);
var first = null;
if (parent) {
var links = WebForm_GetElementsByTagName(parent, "A");
var match = false;
for (var i = 0; i < links.length; i++) {
var link = links[i];
if (Menu_IsSelectable(link)) {
if (Menu_FindParentContainer(link) == parent) {
if (match) {
return link;
}
else if (!first) {
first = link;
}
}
if (!match && link == a) {
match = true;
}
}
}
}
return first;
}
function Menu_FindParentContainer(item) {
if (item.menu_ParentContainerCache) return item.menu_ParentContainerCache;
var a = (item.tagName.toLowerCase() == "a") ? item : WebForm_GetElementByTagName(item, "A");
var menu = Menu_FindMenu(a);
if (menu) {
var parent = item;
while (parent && parent.tagName &&
parent.id != menu.id &&
parent.tagName.toLowerCase() != "div") {
parent = parent.parentNode;
}
item.menu_ParentContainerCache = parent;
return parent;
}
}
function Menu_FindParentItem(item) {
var parentContainer = Menu_FindParentContainer(item);
var parentContainerID = parentContainer.id;
var len = parentContainerID.length;
if (parentContainerID && parentContainerID.substr(len - 5) == "Items") {
var parentItemID = parentContainerID.substr(0, len - 5);
return WebForm_GetElementById(parentItemID);
}
return null;
}
function Menu_FindPrevious(item) {
var a = WebForm_GetElementByTagName(item, "A");
var parent = Menu_FindParentContainer(item);
var last = null;
if (parent) {
var links = WebForm_GetElementsByTagName(parent, "A");
for (var i = 0; i < links.length; i++) {
var link = links[i];
if (Menu_IsSelectable(link)) {
if (link == a && last) {
return last;
}
if (Menu_FindParentContainer(link) == parent) {
last = link;
}
}
}
}
return last;
}
function Menu_FindSubMenu(item) {
var tr = item.parentNode.parentNode.parentNode.parentNode.parentNode;
if (!tr.id) {
tr=tr.parentNode;
}
return WebForm_GetElementById(tr.id + "Items");
}
function Menu_Focus(item) {
if (item && item.focus) {
var pos = WebForm_GetElementPosition(item);
var parentContainer = Menu_FindParentContainer(item);
if (!parentContainer.offset) {
parentContainer.offset = 0;
}
var posParent = WebForm_GetElementPosition(parentContainer);
var delta;
if (pos.y + pos.height > posParent.y + parentContainer.offset + parentContainer.clippedHeight) {
delta = pos.y + pos.height - posParent.y - parentContainer.offset - parentContainer.clippedHeight;
PopOut_Scroll(parentContainer, delta);
}
else if (pos.y < posParent.y + parentContainer.offset) {
delta = posParent.y + parentContainer.offset - pos.y;
PopOut_Scroll(parentContainer, -delta);
}
PopOut_HideScrollers(parentContainer);
item.focus();
}
}
function Menu_GetData(item) {
if (!item.data) {
var a = (item.tagName.toLowerCase() == "a" ? item : WebForm_GetElementByTagName(item, "a"));
var menu = Menu_FindMenu(a);
try {
item.data = eval(menu.id + "_Data");
}
catch(e) {}
}
return item.data;
}
function Menu_HideItems(items) {
if (document.body.__oldOnClick) {
document.body.onclick = document.body.__oldOnClick;
document.body.__oldOnClick = null;
}
Menu_ClearInterval();
if (!items || ((typeof(items.tagName) == "undefined") && (items instanceof Event))) {
items = __rootMenuItem;
}
var table = items;
if ((typeof(table) == "undefined") || (table == null) || !table.tagName || (table.tagName.toLowerCase() != "table")) {
table = WebForm_GetElementByTagName(table, "TABLE");
}
if ((typeof(table) == "undefined") || (table == null) || !table.tagName || (table.tagName.toLowerCase() != "table")) {
return;
}
var rows = table.rows ? table.rows : table.firstChild.rows;
var isVertical = false;
for (var r = 0; r < rows.length; r++) {
if (rows[r].id) {
isVertical = true;
break;
}
}
var i, child, nextLevel;
if (isVertical) {
for(i = 0; i < rows.length; i++) {
if (rows[i].id) {
child = WebForm_GetElementById(rows[i].id + "Items");
if (child) {
Menu_HideItems(child);
}
}
else if (rows[i].cells[0]) {
nextLevel = WebForm_GetElementByTagName(rows[i].cells[0], "TABLE");
if (nextLevel) {
Menu_HideItems(nextLevel);
}
}
}
}
else if (rows[0]) {
for(i = 0; i < rows[0].cells.length; i++) {
if (rows[0].cells[i].id) {
child = WebForm_GetElementById(rows[0].cells[i].id + "Items");
if (child) {
Menu_HideItems(child);
}
}
else {
nextLevel = WebForm_GetElementByTagName(rows[0].cells[i], "TABLE");
if (nextLevel) {
Menu_HideItems(rows[0].cells[i].firstChild);
}
}
}
}
if (items && items.id) {
PopOut_Hide(items.id);
}
}
function Menu_HoverDisabled(item) {
var node = (item.tagName.toLowerCase() == "td") ?
item:
item.cells[0];
var data = Menu_GetData(item);
if (!data) return;
node = WebForm_GetElementByTagName(node, "table").rows[0].cells[0].childNodes[0];
if (data.disappearAfter >= 200) {
__disappearAfter = data.disappearAfter;
}
Menu_Expand(node, data.horizontalOffset, data.verticalOffset);
}
function Menu_HoverDynamic(item) {
var node = (item.tagName.toLowerCase() == "td") ?
item:
item.cells[0];
var data = Menu_GetData(item);
if (!data) return;
var nodeTable = WebForm_GetElementByTagName(node, "table");
if (data.hoverClass) {
nodeTable.hoverClass = data.hoverClass;
WebForm_AppendToClassName(nodeTable, data.hoverClass);
}
node = nodeTable.rows[0].cells[0].childNodes[0];
if (data.hoverHyperLinkClass) {
node.hoverHyperLinkClass = data.hoverHyperLinkClass;
WebForm_AppendToClassName(node, data.hoverHyperLinkClass);
}
if (data.disappearAfter >= 200) {
__disappearAfter = data.disappearAfter;
}
Menu_Expand(node, data.horizontalOffset, data.verticalOffset);
}
function Menu_HoverRoot(item) {
var node = (item.tagName.toLowerCase() == "td") ?
item:
item.cells[0];
var data = Menu_GetData(item);
if (!data) {
return null;
}
var nodeTable = WebForm_GetElementByTagName(node, "table");
if (data.staticHoverClass) {
nodeTable.hoverClass = data.staticHoverClass;
WebForm_AppendToClassName(nodeTable, data.staticHoverClass);
}
node = nodeTable.rows[0].cells[0].childNodes[0];
if (data.staticHoverHyperLinkClass) {
node.hoverHyperLinkClass = data.staticHoverHyperLinkClass;
WebForm_AppendToClassName(node, data.staticHoverHyperLinkClass);
}
return node;
}
function Menu_HoverStatic(item) {
var node = Menu_HoverRoot(item);
var data = Menu_GetData(item);
if (!data) return;
__disappearAfter = data.disappearAfter;
Menu_Expand(node, data.horizontalOffset, data.verticalOffset);
}
function Menu_IsHorizontal(item) {
if (item) {
var a = ((item.tagName && (item.tagName.toLowerCase == "a")) ? item : WebForm_GetElementByTagName(item, "A"));
if (!a) {
return false;
}
var td = a.parentNode.parentNode.parentNode.parentNode.parentNode;
if (td.id) {
return true;
}
}
return false;
}
function Menu_IsSelectable(link) {
return (link && link.href)
}
function Menu_Key(item) {
var event;
if (window.event) {
event = window.event;
}
else {
event = item;
item = event.currentTarget;
}
var key = (event ? event.keyCode : -1);
var data = Menu_GetData(item);
if (!data) return;
var horizontal = Menu_IsHorizontal(item);
var a = WebForm_GetElementByTagName(item, "A");
var nextItem, parentItem, previousItem;
if ((!horizontal && key == 38) || (horizontal && key == 37)) {
previousItem = Menu_FindPrevious(item);
while (previousItem && previousItem.disabled) {
previousItem = Menu_FindPrevious(previousItem);
}
if (previousItem) {
Menu_Focus(previousItem);
Menu_Expand(previousItem, data.horizontalOffset, data.verticalOffset, true);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
if ((!horizontal && key == 40) || (horizontal && key == 39)) {
if (horizontal) {
var subMenu = Menu_FindSubMenu(a);
if (subMenu && subMenu.style && subMenu.style.visibility &&
subMenu.style.visibility.toLowerCase() == "hidden") {
Menu_Expand(a, data.horizontalOffset, data.verticalOffset, true);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
nextItem = Menu_FindNext(item);
while (nextItem && nextItem.disabled) {
nextItem = Menu_FindNext(nextItem);
}
if (nextItem) {
Menu_Focus(nextItem);
Menu_Expand(nextItem, data.horizontalOffset, data.verticalOffset, true);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
if ((!horizontal && key == 39) || (horizontal && key == 40)) {
var children = Menu_Expand(a, data.horizontalOffset, data.verticalOffset, true);
if (children) {
var firstChild;
children = WebForm_GetElementsByTagName(children, "A");
for (var i = 0; i < children.length; i++) {
if (!children[i].disabled && Menu_IsSelectable(children[i])) {
firstChild = children[i];
break;
}
}
if (firstChild) {
Menu_Focus(firstChild);
Menu_Expand(firstChild, data.horizontalOffset, data.verticalOffset, true);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
else {
parentItem = Menu_FindParentItem(item);
while (parentItem && !Menu_IsHorizontal(parentItem)) {
parentItem = Menu_FindParentItem(parentItem);
}
if (parentItem) {
nextItem = Menu_FindNext(parentItem);
while (nextItem && nextItem.disabled) {
nextItem = Menu_FindNext(nextItem);
}
if (nextItem) {
Menu_Focus(nextItem);
Menu_Expand(nextItem, data.horizontalOffset, data.verticalOffset, true);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
}
}
if ((!horizontal && key == 37) || (horizontal && key == 38)) {
parentItem = Menu_FindParentItem(item);
if (parentItem) {
if (Menu_IsHorizontal(parentItem)) {
previousItem = Menu_FindPrevious(parentItem);
while (previousItem && previousItem.disabled) {
previousItem = Menu_FindPrevious(previousItem);
}
if (previousItem) {
Menu_Focus(previousItem);
Menu_Expand(previousItem, data.horizontalOffset, data.verticalOffset, true);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
var parentA = WebForm_GetElementByTagName(parentItem, "A");
if (parentA) {
Menu_Focus(parentA);
}
Menu_ResetSiblings(parentItem);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
if (key == 27) {
Menu_HideItems();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return;
}
}
function Menu_ResetSiblings(item) {
var table = (item.tagName.toLowerCase() == "td") ?
item.parentNode.parentNode.parentNode :
item.parentNode.parentNode;
var isVertical = false;
for (var r = 0; r < table.rows.length; r++) {
if (table.rows[r].id) {
isVertical = true;
break;
}
}
var i, child, childNode;
if (isVertical) {
for(i = 0; i < table.rows.length; i++) {
childNode = table.rows[i];
if (childNode != item) {
child = WebForm_GetElementById(childNode.id + "Items");
if (child) {
Menu_HideItems(child);
}
}
}
}
else {
for(i = 0; i < table.rows[0].cells.length; i++) {
childNode = table.rows[0].cells[i];
if (childNode != item) {
child = WebForm_GetElementById(childNode.id + "Items");
if (child) {
Menu_HideItems(child);
}
}
}
}
Menu_ResetTopMenus(table, table, 0, true);
}
function Menu_ResetTopMenus(table, doNotReset, level, up) {
var i, child, childNode;
if (up && table.id == "") {
var parentTable = table.parentNode.parentNode.parentNode.parentNode;
if (parentTable.tagName.toLowerCase() == "table") {
Menu_ResetTopMenus(parentTable, doNotReset, level + 1, true);
}
}
else {
if (level == 0 && table != doNotReset) {
if (table.rows[0].id) {
for(i = 0; i < table.rows.length; i++) {
childNode = table.rows[i];
child = WebForm_GetElementById(childNode.id + "Items");
if (child) {
Menu_HideItems(child);
}
}
}
else {
for(i = 0; i < table.rows[0].cells.length; i++) {
childNode = table.rows[0].cells[i];
child = WebForm_GetElementById(childNode.id + "Items");
if (child) {
Menu_HideItems(child);
}
}
}
}
else if (level > 0) {
for (i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
var subTable = table.rows[i].cells[j].firstChild;
if (subTable && subTable.tagName.toLowerCase() == "table") {
Menu_ResetTopMenus(subTable, doNotReset, level - 1, false);
}
}
}
}
}
}
function Menu_RestoreInterval() {
if (__menuInterval && __rootMenuItem) {
Menu_ClearInterval();
__menuInterval = window.setInterval("Menu_HideItems()", __disappearAfter);
}
}
function Menu_SetRoot(item) {
var newRoot = Menu_FindMenu(item);
if (newRoot) {
if (__rootMenuItem && __rootMenuItem != newRoot) {
Menu_HideItems();
}
__rootMenuItem = newRoot;
}
}
function Menu_Unhover(item) {
var node = (item.tagName.toLowerCase() == "td") ?
item:
item.cells[0];
var nodeTable = WebForm_GetElementByTagName(node, "table");
if (nodeTable.hoverClass) {
WebForm_RemoveClassName(nodeTable, nodeTable.hoverClass);
}
node = nodeTable.rows[0].cells[0].childNodes[0];
if (node.hoverHyperLinkClass) {
WebForm_RemoveClassName(node, node.hoverHyperLinkClass);
}
Menu_Collapse(node);
}
function PopOut_Clip(element, y, height) {
if (element && element.style) {
element.style.clip = "rect(" + y + "px auto " + (y + height) + "px auto)";
element.style.overflow = "hidden";
}
}
function PopOut_Down(scroller) {
Menu_ClearInterval();
var panel;
if (scroller) {
panel = scroller.parentNode
}
else {
panel = __scrollPanel;
}
if (panel && ((panel.offset + panel.clippedHeight) < panel.physicalHeight)) {
PopOut_Scroll(panel, 2)
__scrollPanel = panel;
PopOut_ShowScrollers(panel);
PopOut_Stop();
__scrollPanel.interval = window.setInterval("PopOut_Down()", 8);
}
else {
PopOut_ShowScrollers(panel);
}
}
function PopOut_Hide(panelId) {
var panel = WebForm_GetElementById(panelId);
if (panel && panel.tagName.toLowerCase() == "div") {
panel.style.visibility = "hidden";
panel.style.display = "none";
panel.offset = 0;
panel.scrollTop = 0;
var table = WebForm_GetElementByTagName(panel, "TABLE");
if (table) {
WebForm_SetElementY(table, 0);
}
if (window.navigator && window.navigator.appName == "Microsoft Internet Explorer" &&
!window.opera) {
var childFrameId = panel.id + "_MenuIFrame";
var childFrame = WebForm_GetElementById(childFrameId);
if (childFrame) {
childFrame.style.display = "none";
}
}
}
}
function PopOut_HideScrollers(panel) {
if (panel && panel.style) {
var up = WebForm_GetElementById(panel.id + "Up");
var dn = WebForm_GetElementById(panel.id + "Dn");
if (up) {
up.style.visibility = "hidden";
up.style.display = "none";
}
if (dn) {
dn.style.visibility = "hidden";
dn.style.display = "none";
}
}
}
function PopOut_Position(panel, hideScrollers) {
if (window.opera) {
panel.parentNode.removeChild(panel);
document.forms[0].appendChild(panel);
}
var rel = WebForm_GetElementById(panel.rel);
var relTable = WebForm_GetElementByTagName(rel, "TABLE");
var relCoordinates = WebForm_GetElementPosition(relTable ? relTable : rel);
var panelCoordinates = WebForm_GetElementPosition(panel);
var panelHeight = ((typeof(panel.physicalHeight) != "undefined") && (panel.physicalHeight != null)) ?
panel.physicalHeight :
panelCoordinates.height;
panel.physicalHeight = panelHeight;
var panelParentCoordinates;
if (panel.offsetParent) {
panelParentCoordinates = WebForm_GetElementPosition(panel.offsetParent);
}
else {
panelParentCoordinates = new Object();
panelParentCoordinates.x = 0;
panelParentCoordinates.y = 0;
}
var overflowElement = WebForm_GetElementById("__overFlowElement");
if (!overflowElement) {
overflowElement = document.createElement("img");
overflowElement.id="__overFlowElement";
WebForm_SetElementWidth(overflowElement, 1);
document.body.appendChild(overflowElement);
}
WebForm_SetElementHeight(overflowElement, panelHeight + relCoordinates.y + parseInt(panel.y ? panel.y : 0));
overflowElement.style.visibility = "visible";
overflowElement.style.display = "inline";
var clientHeight = 0;
var clientWidth = 0;
if (window.innerHeight) {
clientHeight = window.innerHeight;
clientWidth = window.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight) {
clientHeight = document.documentElement.clientHeight;
clientWidth = document.documentElement.clientWidth;
}
else if (document.body && document.body.clientHeight) {
clientHeight = document.body.clientHeight;
clientWidth = document.body.clientWidth;
}
var scrollTop = 0;
var scrollLeft = 0;
if (typeof(window.pageYOffset) != "undefined") {
scrollTop = window.pageYOffset;
scrollLeft = window.pageXOffset;
}
else if (document.documentElement && (typeof(document.documentElement.scrollTop) != "undefined")) {
scrollTop = document.documentElement.scrollTop;
scrollLeft = document.documentElement.scrollLeft;
}
else if (document.body && (typeof(document.body.scrollTop) != "undefined")) {
scrollTop = document.body.scrollTop;
scrollLeft = document.body.scrollLeft;
}
overflowElement.style.visibility = "hidden";
overflowElement.style.display = "none";
var bottomWindowBorder = clientHeight + scrollTop;
var rightWindowBorder = clientWidth + scrollLeft;
var position = panel.pos;
if ((typeof(position) == "undefined") || (position == null) || (position == "")) {
position = (WebForm_GetElementDir(rel) == "rtl" ? "middleleft" : "middleright");
}
position = position.toLowerCase();
var y = relCoordinates.y + parseInt(panel.y ? panel.y : 0) - panelParentCoordinates.y;
var borderParent = (rel && rel.parentNode && rel.parentNode.parentNode && rel.parentNode.parentNode.parentNode
&& rel.parentNode.parentNode.parentNode.tagName.toLowerCase() == "div") ?
rel.parentNode.parentNode.parentNode : null;
WebForm_SetElementY(panel, y);
PopOut_SetPanelHeight(panel, panelHeight, true);
var clip = false;
var overflow;
if (position.indexOf("top") != -1) {
y -= panelHeight;
WebForm_SetElementY(panel, y);
if (y < -panelParentCoordinates.y) {
y = -panelParentCoordinates.y;
WebForm_SetElementY(panel, y);
if (panelHeight > clientHeight - 2) {
clip = true;
PopOut_SetPanelHeight(panel, clientHeight - 2);
}
}
}
else {
if (position.indexOf("bottom") != -1) {
y += relCoordinates.height;
WebForm_SetElementY(panel, y);
}
overflow = y + panelParentCoordinates.y + panelHeight - bottomWindowBorder;
if (overflow > 0) {
y -= overflow;
WebForm_SetElementY(panel, y);
if (y < -panelParentCoordinates.y) {
y = 2 - panelParentCoordinates.y + scrollTop;
WebForm_SetElementY(panel, y);
clip = true;
PopOut_SetPanelHeight(panel, clientHeight - 2);
}
}
}
if (!clip) {
PopOut_SetPanelHeight(panel, panel.clippedHeight, true);
}
var panelParentOffsetY = 0;
if (panel.offsetParent) {
panelParentOffsetY = WebForm_GetElementPosition(panel.offsetParent).y;
}
var panelY = ((typeof(panel.originY) != "undefined") && (panel.originY != null)) ?
panel.originY :
y - panelParentOffsetY;
panel.originY = panelY;
if (!hideScrollers) {
PopOut_ShowScrollers(panel);
}
else {
PopOut_HideScrollers(panel);
}
var x = relCoordinates.x + parseInt(panel.x ? panel.x : 0) - panelParentCoordinates.x;
if (borderParent && borderParent.clientLeft) {
x += 2 * borderParent.clientLeft;
}
WebForm_SetElementX(panel, x);
if (position.indexOf("left") != -1) {
x -= panelCoordinates.width;
WebForm_SetElementX(panel, x);
if (x < -panelParentCoordinates.x) {
WebForm_SetElementX(panel, -panelParentCoordinates.x);
}
}
else {
if (position.indexOf("right") != -1) {
x += relCoordinates.width;
WebForm_SetElementX(panel, x);
}
overflow = x + panelParentCoordinates.x + panelCoordinates.width - rightWindowBorder;
if (overflow > 0) {
if (position.indexOf("bottom") == -1 && relCoordinates.x > panelCoordinates.width) {
x -= relCoordinates.width + panelCoordinates.width;
}
else {
x -= overflow;
}
WebForm_SetElementX(panel, x);
if (x < -panelParentCoordinates.x) {
WebForm_SetElementX(panel, -panelParentCoordinates.x);
}
}
}
}
function PopOut_Scroll(panel, offsetDelta) {
var table = WebForm_GetElementByTagName(panel, "TABLE");
if (!table) return;
table.style.position = "relative";
var tableY = (table.style.top ? parseInt(table.style.top) : 0);
panel.offset += offsetDelta;
WebForm_SetElementY(table, tableY - offsetDelta);
}
function PopOut_SetPanelHeight(element, height, doNotClip) {
if (element && element.style) {
var size = WebForm_GetElementPosition(element);
element.physicalWidth = size.width;
element.clippedHeight = height;
WebForm_SetElementHeight(element, height - (element.clientTop ? (2 * element.clientTop) : 0));
if (doNotClip && element.style) {
element.style.clip = "rect(auto auto auto auto)";
}
else {
PopOut_Clip(element, 0, height);
}
}
}
function PopOut_Show(panelId, hideScrollers, data) {
var panel = WebForm_GetElementById(panelId);
if (panel && panel.tagName.toLowerCase() == "div") {
panel.style.visibility = "visible";
panel.style.display = "inline";
if (!panel.offset || hideScrollers) {
panel.scrollTop = 0;
panel.offset = 0;
var table = WebForm_GetElementByTagName(panel, "TABLE");
if (table) {
WebForm_SetElementY(table, 0);
}
}
PopOut_Position(panel, hideScrollers);
var z = 1;
var isIE = window.navigator && window.navigator.appName == "Microsoft Internet Explorer" && !window.opera;
if (isIE && data) {
var childFrameId = panel.id + "_MenuIFrame";
var childFrame = WebForm_GetElementById(childFrameId);
var parent = panel.offsetParent;
if (!childFrame) {
childFrame = document.createElement("iframe");
childFrame.id = childFrameId;
childFrame.src = (data.iframeUrl ? data.iframeUrl : "about:blank");
childFrame.style.position = "absolute";
childFrame.style.display = "none";
childFrame.scrolling = "no";
childFrame.frameBorder = "0";
if (parent.tagName.toLowerCase() == "html") {
document.body.appendChild(childFrame);
}
else {
parent.appendChild(childFrame);
}
}
var pos = WebForm_GetElementPosition(panel);
var parentPos = WebForm_GetElementPosition(parent);
WebForm_SetElementX(childFrame, pos.x - parentPos.x);
WebForm_SetElementY(childFrame, pos.y - parentPos.y);
WebForm_SetElementWidth(childFrame, pos.width);
WebForm_SetElementHeight(childFrame, pos.height);
childFrame.style.display = "block";
if (panel.currentStyle && panel.currentStyle.zIndex && panel.currentStyle.zIndex != "auto") {
z = panel.currentStyle.zIndex;
}
else if (panel.style.zIndex) {
z = panel.style.zIndex;
}
}
panel.style.zIndex = z;
}
}
function PopOut_ShowScrollers(panel) {
if (panel && panel.style) {
var up = WebForm_GetElementById(panel.id + "Up");
var dn = WebForm_GetElementById(panel.id + "Dn");
var cnt = 0;
if (up && dn) {
if (panel.offset && panel.offset > 0) {
up.style.visibility = "visible";
up.style.display = "inline";
cnt++;
if (panel.clientWidth) {
WebForm_SetElementWidth(up, panel.clientWidth
- (up.clientLeft ? (2 * up.clientLeft) : 0));
}
WebForm_SetElementY(up, 0);
}
else {
up.style.visibility = "hidden";
up.style.display = "none";
}
if (panel.offset + panel.clippedHeight + 2 <= panel.physicalHeight) {
dn.style.visibility = "visible";
dn.style.display = "inline";
cnt++;
if (panel.clientWidth) {
WebForm_SetElementWidth(dn, panel.clientWidth
- (dn.clientLeft ? (2 * dn.clientLeft) : 0));
}
WebForm_SetElementY(dn, panel.clippedHeight - WebForm_GetElementPosition(dn).height
- (panel.clientTop ? (2 * panel.clientTop) : 0));
}
else {
dn.style.visibility = "hidden";
dn.style.display = "none";
}
if (cnt == 0) {
panel.style.clip = "rect(auto auto auto auto)";
}
}
}
}
function PopOut_Stop() {
if (__scrollPanel && __scrollPanel.interval) {
window.clearInterval(__scrollPanel.interval);
}
Menu_RestoreInterval();
}
function PopOut_Up(scroller) {
Menu_ClearInterval();
var panel;
if (scroller) {
panel = scroller.parentNode
}
else {
panel = __scrollPanel;
}
if (panel && panel.offset && panel.offset > 0) {
PopOut_Scroll(panel, -2);
__scrollPanel = panel;
PopOut_ShowScrollers(panel);
PopOut_Stop();
__scrollPanel.interval = window.setInterval("PopOut_Up()", 8);
}
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/WebParts.js
var __wpm = null;
function Point(x, y) {
this.x = x;
this.y = y;
}
function __wpTranslateOffset(x, y, offsetElement, relativeToElement, includeScroll) {
while ((typeof(offsetElement) != "undefined") && (offsetElement != null) && (offsetElement != relativeToElement)) {
x += offsetElement.offsetLeft;
y += offsetElement.offsetTop;
var tagName = offsetElement.tagName;
if ((tagName != "TABLE") && (tagName != "BODY")) {
x += offsetElement.clientLeft;
y += offsetElement.clientTop;
}
if (includeScroll && (tagName != "BODY")) {
x -= offsetElement.scrollLeft;
y -= offsetElement.scrollTop;
}
offsetElement = offsetElement.offsetParent;
}
return new Point(x, y);
}
function __wpGetPageEventLocation(event, includeScroll) {
if ((typeof(event) == "undefined") || (event == null)) {
event = window.event;
}
return __wpTranslateOffset(event.offsetX, event.offsetY, event.srcElement, null, includeScroll);
}
function __wpClearSelection() {
document.selection.empty();
}
function WebPart(webPartElement, webPartTitleElement, zone, zoneIndex, allowZoneChange) {
this.webPartElement = webPartElement;
this.allowZoneChange = allowZoneChange;
this.zone = zone;
this.zoneIndex = zoneIndex;
this.title = ((typeof(webPartTitleElement) != "undefined") && (webPartTitleElement != null)) ?
webPartTitleElement.innerText : "";
webPartElement.__webPart = this;
if ((typeof(webPartTitleElement) != "undefined") && (webPartTitleElement != null)) {
webPartTitleElement.style.cursor = "move";
webPartTitleElement.attachEvent("onmousedown", WebPart_OnMouseDown);
webPartElement.attachEvent("ondragstart", WebPart_OnDragStart);
webPartElement.attachEvent("ondrag", WebPart_OnDrag);
webPartElement.attachEvent("ondragend", WebPart_OnDragEnd);
}
this.UpdatePosition = WebPart_UpdatePosition;
this.Dispose = WebPart_Dispose;
}
function WebPart_Dispose() {
this.webPartElement.__webPart = null
}
function WebPart_OnMouseDown() {
var currentEvent = window.event;
var draggedWebPart = WebPart_GetParentWebPartElement(currentEvent.srcElement);
if ((typeof(draggedWebPart) == "undefined") || (draggedWebPart == null)) {
return;
}
document.selection.empty();
try {
__wpm.draggedWebPart = draggedWebPart;
__wpm.DragDrop();
}
catch (e) {
__wpm.draggedWebPart = draggedWebPart;
window.setTimeout("__wpm.DragDrop()", 0);
}
currentEvent.returnValue = false;
currentEvent.cancelBubble = true;
}
function WebPart_OnDragStart() {
var currentEvent = window.event;
var webPartElement = currentEvent.srcElement;
if ((typeof(webPartElement.__webPart) == "undefined") || (webPartElement.__webPart == null)) {
currentEvent.returnValue = false;
currentEvent.cancelBubble = true;
return;
}
var dataObject = currentEvent.dataTransfer;
dataObject.effectAllowed = __wpm.InitiateWebPartDragDrop(webPartElement);
}
function WebPart_OnDrag() {
__wpm.ContinueWebPartDragDrop();
}
function WebPart_OnDragEnd() {
__wpm.CompleteWebPartDragDrop();
}
function WebPart_GetParentWebPartElement(containedElement) {
var elem = containedElement;
while ((typeof(elem.__webPart) == "undefined") || (elem.__webPart == null)) {
elem = elem.parentElement;
if ((typeof(elem) == "undefined") || (elem == null)) {
break;
}
}
return elem;
}
function WebPart_UpdatePosition() {
var location = __wpTranslateOffset(0, 0, this.webPartElement, null, false);
this.middleX = location.x + this.webPartElement.offsetWidth / 2;
this.middleY = location.y + this.webPartElement.offsetHeight / 2;
}
function Zone(zoneElement, zoneIndex, uniqueID, isVertical, allowLayoutChange, highlightColor) {
var webPartTable = null;
if (zoneElement.rows.length == 1) {
webPartTableContainer = zoneElement.rows[0].cells[0];
}
else {
webPartTableContainer = zoneElement.rows[1].cells[0];
}
var i;
for (i = 0; i < webPartTableContainer.childNodes.length; i++) {
var node = webPartTableContainer.childNodes[i];
if (node.tagName == "TABLE") {
webPartTable = node;
break;
}
}
this.zoneElement = zoneElement;
this.zoneIndex = zoneIndex;
this.webParts = new Array();
this.uniqueID = uniqueID;
this.isVertical = isVertical;
this.allowLayoutChange = allowLayoutChange;
this.allowDrop = false;
this.webPartTable = webPartTable;
this.highlightColor = highlightColor;
this.savedBorderColor = (webPartTable != null) ? webPartTable.style.borderColor : null;
this.dropCueElements = new Array();
if (webPartTable != null) {
if (isVertical) {
for (i = 0; i < webPartTable.rows.length; i += 2) {
this.dropCueElements[i / 2] = webPartTable.rows[i].cells[0].childNodes[0];
}
}
else {
for (i = 0; i < webPartTable.rows[0].cells.length; i += 2) {
this.dropCueElements[i / 2] = webPartTable.rows[0].cells[i].childNodes[0];
}
}
}
this.AddWebPart = Zone_AddWebPart;
this.GetWebPartIndex = Zone_GetWebPartIndex;
this.ToggleDropCues = Zone_ToggleDropCues;
this.UpdatePosition = Zone_UpdatePosition;
this.Dispose = Zone_Dispose;
webPartTable.__zone = this;
webPartTable.attachEvent("ondragenter", Zone_OnDragEnter);
webPartTable.attachEvent("ondrop", Zone_OnDrop);
}
function Zone_Dispose() {
for (var i = 0; i < this.webParts.length; i++) {
this.webParts[i].Dispose();
}
this.webPartTable.__zone = null;
}
function Zone_OnDragEnter() {
var handled = __wpm.ProcessWebPartDragEnter();
var currentEvent = window.event;
if (handled) {
currentEvent.returnValue = false;
currentEvent.cancelBubble = true;
}
}
function Zone_OnDragOver() {
var handled = __wpm.ProcessWebPartDragOver();
var currentEvent = window.event;
if (handled) {
currentEvent.returnValue = false;
currentEvent.cancelBubble = true;
}
}
function Zone_OnDrop() {
var handled = __wpm.ProcessWebPartDrop();
var currentEvent = window.event;
if (handled) {
currentEvent.returnValue = false;
currentEvent.cancelBubble = true;
}
}
function Zone_GetParentZoneElement(containedElement) {
var elem = containedElement;
while ((typeof(elem.__zone) == "undefined") || (elem.__zone == null)) {
elem = elem.parentElement;
if ((typeof(elem) == "undefined") || (elem == null)) {
break;
}
}
return elem;
}
function Zone_AddWebPart(webPartElement, webPartTitleElement, allowZoneChange) {
var webPart = null;
var zoneIndex = this.webParts.length;
if (this.allowLayoutChange && __wpm.IsDragDropEnabled()) {
webPart = new WebPart(webPartElement, webPartTitleElement, this, zoneIndex, allowZoneChange);
}
else {
webPart = new WebPart(webPartElement, null, this, zoneIndex, allowZoneChange);
}
this.webParts[zoneIndex] = webPart;
return webPart;
}
function Zone_ToggleDropCues(show, index, ignoreOutline) {
if (ignoreOutline == false) {
this.webPartTable.style.borderColor = (show ? this.highlightColor : this.savedBorderColor);
}
if (index == -1) {
return;
}
var dropCue = this.dropCueElements[index];
if (dropCue && dropCue.style) {
if (dropCue.style.height == "100%" && !dropCue.webPartZoneHorizontalCueResized) {
var oldParentHeight = dropCue.parentElement.clientHeight;
var realHeight = oldParentHeight - 10;
dropCue.style.height = realHeight + "px";
var dropCueVerticalBar = dropCue.getElementsByTagName("DIV")[0];
if (dropCueVerticalBar && dropCueVerticalBar.style) {
dropCueVerticalBar.style.height = dropCue.style.height;
var heightDiff = (dropCue.parentElement.clientHeight - oldParentHeight);
if (heightDiff) {
dropCue.style.height = (realHeight - heightDiff) + "px";
dropCueVerticalBar.style.height = dropCue.style.height;
}
}
dropCue.webPartZoneHorizontalCueResized = true;
}
dropCue.style.visibility = (show ? "visible" : "hidden");
}
}
function Zone_GetWebPartIndex(location) {
var x = location.x;
var y = location.y;
if ((x < this.webPartTableLeft) || (x > this.webPartTableRight) ||
(y < this.webPartTableTop) || (y > this.webPartTableBottom)) {
return -1;
}
var vertical = this.isVertical;
var webParts = this.webParts;
var webPartsCount = webParts.length;
for (var i = 0; i < webPartsCount; i++) {
var webPart = webParts[i];
if (vertical) {
if (y < webPart.middleY) {
return i;
}
}
else {
if (x < webPart.middleX) {
return i;
}
}
}
return webPartsCount;
}
function Zone_UpdatePosition() {
var topLeft = __wpTranslateOffset(0, 0, this.webPartTable, null, false);
this.webPartTableLeft = topLeft.x;
this.webPartTableTop = topLeft.y;
this.webPartTableRight = (this.webPartTable != null) ? topLeft.x + this.webPartTable.offsetWidth : topLeft.x;
this.webPartTableBottom = (this.webPartTable != null) ? topLeft.y + this.webPartTable.offsetHeight : topLeft.y;
for (var i = 0; i < this.webParts.length; i++) {
this.webParts[i].UpdatePosition();
}
}
function WebPartDragState(webPartElement, effect) {
this.webPartElement = webPartElement;
this.dropZoneElement = null;
this.dropIndex = -1;
this.effect = effect;
this.dropped = false;
}
function WebPartMenu(menuLabelElement, menuDropDownElement, menuElement) {
this.menuLabelElement = menuLabelElement;
this.menuDropDownElement = menuDropDownElement;
this.menuElement = menuElement;
this.menuLabelElement.__menu = this;
this.menuLabelElement.attachEvent('onclick', WebPartMenu_OnClick);
this.menuLabelElement.attachEvent('onkeypress', WebPartMenu_OnKeyPress);
this.menuLabelElement.attachEvent('onmouseenter', WebPartMenu_OnMouseEnter);
this.menuLabelElement.attachEvent('onmouseleave', WebPartMenu_OnMouseLeave);
if ((typeof(this.menuDropDownElement) != "undefined") && (this.menuDropDownElement != null)) {
this.menuDropDownElement.__menu = this;
}
this.menuItemStyle = "";
this.menuItemHoverStyle = "";
this.popup = null;
this.hoverClassName = "";
this.hoverColor = "";
this.oldColor = this.menuLabelElement.style.color;
this.oldTextDecoration = this.menuLabelElement.style.textDecoration;
this.oldClassName = this.menuLabelElement.className;
this.Show = WebPartMenu_Show;
this.Hide = WebPartMenu_Hide;
this.Hover = WebPartMenu_Hover;
this.Unhover = WebPartMenu_Unhover;
this.Dispose = WebPartMenu_Dispose;
var menu = this;
this.disposeDelegate = function() { menu.Dispose(); };
window.attachEvent('onunload', this.disposeDelegate);
}
function WebPartMenu_Dispose() {
this.menuLabelElement.__menu = null;
this.menuDropDownElement.__menu = null;
window.detachEvent('onunload', this.disposeDelegate);
}
function WebPartMenu_Show() {
if ((typeof(__wpm.menu) != "undefined") && (__wpm.menu != null)) {
__wpm.menu.Hide();
}
var menuHTML =
"<html><head><style>" +
"a.menuItem, a.menuItem:Link { display: block; padding: 1px; text-decoration: none; " + this.itemStyle + " }" +
"a.menuItem:Hover { " + this.itemHoverStyle + " }" +
"</style><body scroll=\"no\" style=\"border: none; margin: 0; padding: 0;\" ondragstart=\"window.event.returnValue=false;\" onclick=\"popup.hide()\">" +
this.menuElement.innerHTML +
"</body></html>";
var width = 16;
var height = 16;
this.popup = window.createPopup();
__wpm.menu = this;
var popupDocument = this.popup.document;
popupDocument.write(menuHTML);
this.popup.show(0, 0, width, height);
var popupBody = popupDocument.body;
width = popupBody.scrollWidth;
height = popupBody.scrollHeight;
if (width < this.menuLabelElement.offsetWidth) {
width = this.menuLabelElement.offsetWidth + 16;
}
if (this.menuElement.innerHTML.indexOf("progid:DXImageTransform.Microsoft.Shadow") != -1) {
popupBody.style.paddingRight = "4px";
}
popupBody.__wpm = __wpm;
popupBody.__wpmDeleteWarning = __wpmDeleteWarning;
popupBody.__wpmCloseProviderWarning = __wpmCloseProviderWarning;
popupBody.popup = this.popup;
this.popup.hide();
this.popup.show(0, this.menuLabelElement.offsetHeight, width, height, this.menuLabelElement);
}
function WebPartMenu_Hide() {
if (__wpm.menu == this) {
__wpm.menu = null;
if ((typeof(this.popup) != "undefined") && (this.popup != null)) {
this.popup.hide();
this.popup = null;
}
}
}
function WebPartMenu_Hover() {
if (this.labelHoverClassName != "") {
this.menuLabelElement.className = this.menuLabelElement.className + " " + this.labelHoverClassName;
}
if (this.labelHoverColor != "") {
this.menuLabelElement.style.color = this.labelHoverColor;
}
}
function WebPartMenu_Unhover() {
if (this.labelHoverClassName != "") {
this.menuLabelElement.style.textDecoration = this.oldTextDecoration;
this.menuLabelElement.className = this.oldClassName;
}
if (this.labelHoverColor != "") {
this.menuLabelElement.style.color = this.oldColor;
}
}
function WebPartMenu_OnClick() {
var menu = window.event.srcElement.__menu;
if ((typeof(menu) != "undefined") && (menu != null)) {
window.event.returnValue = false;
window.event.cancelBubble = true;
menu.Show();
}
}
function WebPartMenu_OnKeyPress() {
if (window.event.keyCode == 13) {
var menu = window.event.srcElement.__menu;
if ((typeof(menu) != "undefined") && (menu != null)) {
window.event.returnValue = false;
window.event.cancelBubble = true;
menu.Show();
}
}
}
function WebPartMenu_OnMouseEnter() {
var menu = window.event.srcElement.__menu;
if ((typeof(menu) != "undefined") && (menu != null)) {
menu.Hover();
}
}
function WebPartMenu_OnMouseLeave() {
var menu = window.event.srcElement.__menu;
if ((typeof(menu) != "undefined") && (menu != null)) {
menu.Unhover();
}
}
function WebPartManager() {
this.overlayContainerElement = null;
this.zones = new Array();
this.dragState = null;
this.menu = null;
this.draggedWebPart = null;
this.AddZone = WebPartManager_AddZone;
this.IsDragDropEnabled = WebPartManager_IsDragDropEnabled;
this.DragDrop = WebPartManager_DragDrop;
this.InitiateWebPartDragDrop = WebPartManager_InitiateWebPartDragDrop;
this.CompleteWebPartDragDrop = WebPartManager_CompleteWebPartDragDrop;
this.ContinueWebPartDragDrop = WebPartManager_ContinueWebPartDragDrop;
this.ProcessWebPartDragEnter = WebPartManager_ProcessWebPartDragEnter;
this.ProcessWebPartDragOver = WebPartManager_ProcessWebPartDragOver;
this.ProcessWebPartDrop = WebPartManager_ProcessWebPartDrop;
this.ShowHelp = WebPartManager_ShowHelp;
this.ExportWebPart = WebPartManager_ExportWebPart;
this.Execute = WebPartManager_Execute;
this.SubmitPage = WebPartManager_SubmitPage;
this.UpdatePositions = WebPartManager_UpdatePositions;
window.attachEvent("onunload", WebPartManager_Dispose);
}
function WebPartManager_Dispose() {
for (var i = 0; i < __wpm.zones.length; i++) {
__wpm.zones[i].Dispose();
}
window.detachEvent("onunload", WebPartManager_Dispose);
}
function WebPartManager_AddZone(zoneElement, uniqueID, isVertical, allowLayoutChange, highlightColor) {
var zoneIndex = this.zones.length;
var zone = new Zone(zoneElement, zoneIndex, uniqueID, isVertical, allowLayoutChange, highlightColor);
this.zones[zoneIndex] = zone;
return zone;
}
function WebPartManager_IsDragDropEnabled() {
return ((typeof(this.overlayContainerElement) != "undefined") && (this.overlayContainerElement != null));
}
function WebPartManager_DragDrop() {
if ((typeof(this.draggedWebPart) != "undefined") && (this.draggedWebPart != null)) {
var tempWebPart = this.draggedWebPart;
this.draggedWebPart = null;
tempWebPart.dragDrop();
window.setTimeout("__wpClearSelection()", 0);
}
}
function WebPartManager_InitiateWebPartDragDrop(webPartElement) {
var webPart = webPartElement.__webPart;
this.UpdatePositions();
this.dragState = new WebPartDragState(webPartElement, "move");
var location = __wpGetPageEventLocation(window.event, true);
var overlayContainerElement = this.overlayContainerElement;
overlayContainerElement.style.left = location.x - webPartElement.offsetWidth / 2;
overlayContainerElement.style.top = location.y + 4 + (webPartElement.clientTop ? webPartElement.clientTop : 0);
overlayContainerElement.style.display = "block";
overlayContainerElement.style.width = webPartElement.offsetWidth;
overlayContainerElement.style.height = webPartElement.offsetHeight;
overlayContainerElement.appendChild(webPartElement.cloneNode(true));
if (webPart.allowZoneChange == false) {
webPart.zone.allowDrop = true;
}
else {
for (var i = 0; i < __wpm.zones.length; i++) {
var zone = __wpm.zones[i];
if (zone.allowLayoutChange) {
zone.allowDrop = true;
}
}
}
document.body.attachEvent("ondragover", Zone_OnDragOver);
return "move";
}
function WebPartManager_CompleteWebPartDragDrop() {
var dragState = this.dragState;
this.dragState = null;
if ((typeof(dragState.dropZoneElement) != "undefined") && (dragState.dropZoneElement != null)) {
dragState.dropZoneElement.__zone.ToggleDropCues(false, dragState.dropIndex, false);
}
document.body.detachEvent("ondragover", Zone_OnDragOver);
for (var i = 0; i < __wpm.zones.length; i++) {
__wpm.zones[i].allowDrop = false;
}
this.overlayContainerElement.removeChild(this.overlayContainerElement.firstChild);
this.overlayContainerElement.style.display = "none";
if ((typeof(dragState) != "undefined") && (dragState != null) && (dragState.dropped == true)) {
var currentZone = dragState.webPartElement.__webPart.zone;
var currentZoneIndex = dragState.webPartElement.__webPart.zoneIndex;
if ((currentZone != dragState.dropZoneElement.__zone) ||
((currentZoneIndex != dragState.dropIndex) &&
(currentZoneIndex != (dragState.dropIndex - 1)))) {
var eventTarget = dragState.dropZoneElement.__zone.uniqueID;
var eventArgument = "Drag:" + dragState.webPartElement.id + ":" + dragState.dropIndex;
this.SubmitPage(eventTarget, eventArgument);
}
}
}
function WebPartManager_ContinueWebPartDragDrop() {
var dragState = this.dragState;
if ((typeof(dragState) != "undefined") && (dragState != null)) {
var style = this.overlayContainerElement.style;
var location = __wpGetPageEventLocation(window.event, true);
style.left = location.x - dragState.webPartElement.offsetWidth / 2;
style.top = location.y + 4 + (dragState.webPartElement.clientTop ? dragState.webPartElement.clientTop : 0);
}
}
function WebPartManager_Execute(script) {
if (this.menu) {
this.menu.Hide();
}
var scriptReference = new Function(script);
return (scriptReference() != false);
}
function WebPartManager_ProcessWebPartDragEnter() {
var dragState = __wpm.dragState;
if ((typeof(dragState) != "undefined") && (dragState != null)) {
var currentEvent = window.event;
var newDropZoneElement = Zone_GetParentZoneElement(currentEvent.srcElement);
if ((typeof(newDropZoneElement.__zone) == "undefined") || (newDropZoneElement.__zone == null) ||
(newDropZoneElement.__zone.allowDrop == false)) {
newDropZoneElement = null;
}
var newDropIndex = -1;
if ((typeof(newDropZoneElement) != "undefined") && (newDropZoneElement != null)) {
newDropIndex = newDropZoneElement.__zone.GetWebPartIndex(__wpGetPageEventLocation(currentEvent, false));
if (newDropIndex == -1) {
newDropZoneElement = null;
}
}
if (dragState.dropZoneElement != newDropZoneElement) {
if ((typeof(dragState.dropZoneElement) != "undefined") && (dragState.dropZoneElement != null)) {
dragState.dropZoneElement.__zone.ToggleDropCues(false, dragState.dropIndex, false);
}
dragState.dropZoneElement = newDropZoneElement;
dragState.dropIndex = newDropIndex;
if ((typeof(newDropZoneElement) != "undefined") && (newDropZoneElement != null)) {
newDropZoneElement.__zone.ToggleDropCues(true, newDropIndex, false);
}
}
else if (dragState.dropIndex != newDropIndex) {
if (dragState.dropIndex != -1) {
dragState.dropZoneElement.__zone.ToggleDropCues(false, dragState.dropIndex, false);
}
dragState.dropIndex = newDropIndex;
if ((typeof(newDropZoneElement) != "undefined") && (newDropZoneElement != null)) {
newDropZoneElement.__zone.ToggleDropCues(true, newDropIndex, false);
}
}
if ((typeof(dragState.dropZoneElement) != "undefined") && (dragState.dropZoneElement != null)) {
currentEvent.dataTransfer.effectAllowed = dragState.effect;
}
return true;
}
return false;
}
function WebPartManager_ProcessWebPartDragOver() {
var dragState = __wpm.dragState;
var currentEvent = window.event;
var handled = false;
if ((typeof(dragState) != "undefined") && (dragState != null) &&
(typeof(dragState.dropZoneElement) != "undefined") && (dragState.dropZoneElement != null)) {
var dropZoneElement = Zone_GetParentZoneElement(currentEvent.srcElement);
if ((typeof(dropZoneElement) != "undefined") && (dropZoneElement != null) && (dropZoneElement.__zone.allowDrop == false)) {
dropZoneElement = null;
}
if (((typeof(dropZoneElement) == "undefined") || (dropZoneElement == null)) &&
(typeof(dragState.dropZoneElement) != "undefined") && (dragState.dropZoneElement != null)) {
dragState.dropZoneElement.__zone.ToggleDropCues(false, __wpm.dragState.dropIndex, false);
dragState.dropZoneElement = null;
dragState.dropIndex = -1;
}
else if ((typeof(dropZoneElement) != "undefined") && (dropZoneElement != null)) {
var location = __wpGetPageEventLocation(currentEvent, false);
var newDropIndex = dropZoneElement.__zone.GetWebPartIndex(location);
if (newDropIndex == -1) {
dropZoneElement = null;
}
if (dragState.dropZoneElement != dropZoneElement) {
if ((dragState.dropIndex != -1) || (typeof(dropZoneElement) == "undefined") || (dropZoneElement == null)) {
dragState.dropZoneElement.__zone.ToggleDropCues(false, __wpm.dragState.dropIndex, false);
}
dragState.dropZoneElement = dropZoneElement;
}
else {
dragState.dropZoneElement.__zone.ToggleDropCues(false, dragState.dropIndex, true);
}
dragState.dropIndex = newDropIndex;
if ((typeof(dropZoneElement) != "undefined") && (dropZoneElement != null)) {
dropZoneElement.__zone.ToggleDropCues(true, newDropIndex, false);
}
}
handled = true;
}
if ((typeof(dragState) == "undefined") || (dragState == null) ||
(typeof(dragState.dropZoneElement) == "undefined") || (dragState.dropZoneElement == null)) {
currentEvent.dataTransfer.effectAllowed = "none";
}
return handled;
}
function WebPartManager_ProcessWebPartDrop() {
var dragState = this.dragState;
if ((typeof(dragState) != "undefined") && (dragState != null)) {
var currentEvent = window.event;
var dropZoneElement = Zone_GetParentZoneElement(currentEvent.srcElement);
if ((typeof(dropZoneElement) != "undefined") && (dropZoneElement != null) && (dropZoneElement.__zone.allowDrop == false)) {
dropZoneElement = null;
}
if ((typeof(dropZoneElement) != "undefined") && (dropZoneElement != null) && (dragState.dropZoneElement == dropZoneElement)) {
dragState.dropped = true;
}
return true;
}
return false;
}
function WebPartManager_ShowHelp(helpUrl, helpMode) {
if ((typeof(this.menu) != "undefined") && (this.menu != null)) {
this.menu.Hide();
}
if (helpMode == 0 || helpMode == 1) {
if (helpMode == 0) {
var dialogInfo = "edge: Sunken; center: yes; help: no; resizable: yes; status: no";
window.showModalDialog(helpUrl, null, dialogInfo);
}
else {
window.open(helpUrl, null, "scrollbars=yes,resizable=yes,status=no,toolbar=no,menubar=no,location=no");
}
}
else if (helpMode == 2) {
window.location = helpUrl;
}
}
function WebPartManager_ExportWebPart(exportUrl, warn, confirmOnly) {
if (warn == true && __wpmExportWarning.length > 0 && this.personalizationScopeShared != true) {
if (confirm(__wpmExportWarning) == false) {
return false;
}
}
if (confirmOnly == false) {
window.location = exportUrl;
}
return true;
}
function WebPartManager_UpdatePositions() {
for (var i = 0; i < this.zones.length; i++) {
this.zones[i].UpdatePosition();
}
}
function WebPartManager_SubmitPage(eventTarget, eventArgument) {
if ((typeof(this.menu) != "undefined") && (this.menu != null)) {
this.menu.Hide();
}
__doPostBack(eventTarget, eventArgument);
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/MenuStandards.js
if (!window.Sys) { window.Sys = {}; }
if (!Sys.WebForms) { Sys.WebForms = {}; }
Sys.WebForms.Menu = function(options) {
this.items = [];
this.depth = options.depth || 1;
this.parentMenuItem = options.parentMenuItem;
this.element = Sys.WebForms.Menu._domHelper.getElement(options.element);
if (this.element.tagName === 'DIV') {
var containerElement = this.element;
this.element = Sys.WebForms.Menu._domHelper.firstChild(containerElement);
this.element.tabIndex = options.tabIndex || 0;
options.element = containerElement;
options.menu = this;
this.container = new Sys.WebForms._MenuContainer(options);
Sys.WebForms.Menu._domHelper.setFloat(this.element, this.container.rightToLeft ? "right" : "left");
}
else {
this.container = options.container;
this.keyMap = options.keyMap;
}
Sys.WebForms.Menu._elementObjectMapper.map(this.element, this);
if (this.parentMenuItem && this.parentMenuItem.parentMenu) {
this.parentMenu = this.parentMenuItem.parentMenu;
this.rootMenu = this.parentMenu.rootMenu;
if (!this.element.id) {
this.element.id = (this.container.element.id || 'menu') + ':submenu:' + Sys.WebForms.Menu._elementObjectMapper._computedId;
}
if (this.depth > this.container.staticDisplayLevels) {
this.displayMode = "dynamic";
this.element.style.display = "none";
this.element.style.position = "absolute";
if (this.rootMenu && this.container.orientation === 'horizontal' && this.parentMenu.isStatic()) {
this.element.style.top = "100%";
if (this.container.rightToLeft) {
this.element.style.right = "0px";
}
else {
this.element.style.left = "0px";
}
}
else {
this.element.style.top = "0px";
if (this.container.rightToLeft) {
this.element.style.right = "100%";
}
else {
this.element.style.left = "100%";
}
}
if (this.container.rightToLeft) {
this.keyMap = Sys.WebForms.Menu._keyboardMapping.verticalRtl;
}
else {
this.keyMap = Sys.WebForms.Menu._keyboardMapping.vertical;
}
}
else {
this.displayMode = "static";
this.element.style.display = "block";
if (this.container.orientation === 'horizontal') {
Sys.WebForms.Menu._domHelper.setFloat(this.element, this.container.rightToLeft ? "right" : "left");
}
}
}
Sys.WebForms.Menu._domHelper.appendCssClass(this.element, this.displayMode);
var children = this.element.childNodes;
var count = children.length;
for (var i = 0; i < count; i++) {
var node = children[i];
if (node.nodeType !== 1) {
continue;
}
var topLevelMenuItem = null;
if (this.parentMenuItem) {
topLevelMenuItem = this.parentMenuItem.topLevelMenuItem;
}
var menuItem = new Sys.WebForms.MenuItem(this, node, topLevelMenuItem);
var previousMenuItem = this.items[this.items.length - 1];
if (previousMenuItem) {
menuItem.previousSibling = previousMenuItem;
previousMenuItem.nextSibling = menuItem;
}
this.items[this.items.length] = menuItem;
}
};
Sys.WebForms.Menu.prototype = {
blur: function() { if (this.container) this.container.blur(); },
collapse: function() {
this.each(function(menuItem) {
menuItem.hover(false);
menuItem.blur();
var childMenu = menuItem.childMenu;
if (childMenu) {
childMenu.collapse();
}
});
this.hide();
},
doDispose: function() { this.each(function(item) { item.doDispose(); }); },
each: function(fn) {
var count = this.items.length;
for (var i = 0; i < count; i++) {
fn(this.items[i]);
}
},
firstChild: function() { return this.items[0]; },
focus: function() { if (this.container) this.container.focus(); },
get_displayed: function() { return this.element.style.display !== 'none'; },
get_focused: function() {
if (this.container) {
return this.container.focused;
}
return false;
},
handleKeyPress: function(keyCode) {
if (this.keyMap.contains(keyCode)) {
if (this.container.focusedMenuItem) {
this.container.focusedMenuItem.navigate(keyCode);
return;
}
var firstChild = this.firstChild();
if (firstChild) {
this.container.navigateTo(firstChild);
}
}
},
hide: function() {
if (!this.get_displayed()) {
return;
}
this.each(function(item) {
if (item.childMenu) {
item.childMenu.hide();
}
});
if (!this.isRoot()) {
if (this.get_focused()) {
this.container.navigateTo(this.parentMenuItem);
}
this.element.style.display = 'none';
}
},
isRoot: function() { return this.rootMenu === this; },
isStatic: function() { return this.displayMode === 'static'; },
lastChild: function() { return this.items[this.items.length - 1]; },
show: function() { this.element.style.display = 'block'; }
};
if (Sys.WebForms.Menu.registerClass) {
Sys.WebForms.Menu.registerClass('Sys.WebForms.Menu');
}
Sys.WebForms.MenuItem = function(parentMenu, listElement, topLevelMenuItem) {
this.keyMap = parentMenu.keyMap;
this.parentMenu = parentMenu;
this.container = parentMenu.container;
this.element = listElement;
this.topLevelMenuItem = topLevelMenuItem || this;
this._anchor = Sys.WebForms.Menu._domHelper.firstChild(listElement);
while (this._anchor && this._anchor.tagName !== 'A') {
this._anchor = Sys.WebForms.Menu._domHelper.nextSibling(this._anchor);
}
if (this._anchor) {
this._anchor.tabIndex = -1;
var subMenu = this._anchor;
while (subMenu && subMenu.tagName !== 'UL') {
subMenu = Sys.WebForms.Menu._domHelper.nextSibling(subMenu);
}
if (subMenu) {
this.childMenu = new Sys.WebForms.Menu({ element: subMenu, parentMenuItem: this, depth: parentMenu.depth + 1, container: this.container, keyMap: this.keyMap });
if (!this.childMenu.isStatic()) {
Sys.WebForms.Menu._domHelper.appendCssClass(this.element, 'has-popup');
Sys.WebForms.Menu._domHelper.appendAttributeValue(this.element, 'aria-haspopup', this.childMenu.element.id);
}
}
}
Sys.WebForms.Menu._elementObjectMapper.map(listElement, this);
Sys.WebForms.Menu._domHelper.appendAttributeValue(listElement, 'role', 'menuitem');
Sys.WebForms.Menu._domHelper.appendCssClass(listElement, parentMenu.displayMode);
if (this._anchor) {
Sys.WebForms.Menu._domHelper.appendCssClass(this._anchor, parentMenu.displayMode);
}
this.element.style.position = "relative";
if (this.parentMenu.depth == 1 && this.container.orientation == 'horizontal') {
Sys.WebForms.Menu._domHelper.setFloat(this.element, this.container.rightToLeft ? "right" : "left");
}
if (!this.container.disabled) {
Sys.WebForms.Menu._domHelper.addEvent(this.element, 'mouseover', Sys.WebForms.MenuItem._onmouseover);
Sys.WebForms.Menu._domHelper.addEvent(this.element, 'mouseout', Sys.WebForms.MenuItem._onmouseout);
}
};
Sys.WebForms.MenuItem.prototype = {
applyUp: function(fn, condition) {
condition = condition || function(menuItem) { return menuItem; };
var menuItem = this;
var lastMenuItem = null;
while (condition(menuItem)) {
fn(menuItem);
lastMenuItem = menuItem;
menuItem = menuItem.parentMenu.parentMenuItem;
}
return lastMenuItem;
},
blur: function() { this.setTabIndex(-1); },
doDispose: function() {
Sys.WebForms.Menu._domHelper.removeEvent(this.element, 'mouseover', Sys.WebForms.MenuItem._onmouseover);
Sys.WebForms.Menu._domHelper.removeEvent(this.element, 'mouseout', Sys.WebForms.MenuItem._onmouseout);
if (this.childMenu) {
this.childMenu.doDispose();
}
},
focus: function() {
if (!this.parentMenu.get_displayed()) {
this.parentMenu.show();
}
this.setTabIndex(0);
this.container.focused = true;
this._anchor.focus();
},
get_highlighted: function() { return /(^|\s)highlighted(\s|$)/.test(this._anchor.className); },
getTabIndex: function() { return this._anchor.tabIndex; },
highlight: function(highlighting) {
if (highlighting) {
this.applyUp(function(menuItem) {
menuItem.parentMenu.parentMenuItem.highlight(true);
},
function(menuItem) {
return !menuItem.parentMenu.isStatic() && menuItem.parentMenu.parentMenuItem;
}
);
Sys.WebForms.Menu._domHelper.appendCssClass(this._anchor, 'highlighted');
}
else {
Sys.WebForms.Menu._domHelper.removeCssClass(this._anchor, 'highlighted');
this.setTabIndex(-1);
}
},
hover: function(hovering) {
if (hovering) {
var currentHoveredItem = this.container.hoveredMenuItem;
if (currentHoveredItem) {
currentHoveredItem.hover(false);
}
var currentFocusedItem = this.container.focusedMenuItem;
if (currentFocusedItem && currentFocusedItem !== this) {
currentFocusedItem.hover(false);
}
this.applyUp(function(menuItem) {
if (menuItem.childMenu && !menuItem.childMenu.get_displayed()) {
menuItem.childMenu.show();
}
});
this.container.hoveredMenuItem = this;
this.highlight(true);
}
else {
var menuItem = this;
while (menuItem) {
menuItem.highlight(false);
if (menuItem.childMenu) {
if (!menuItem.childMenu.isStatic()) {
menuItem.childMenu.hide();
}
}
menuItem = menuItem.parentMenu.parentMenuItem;
}
}
},
isSiblingOf: function(menuItem) { return menuItem.parentMenu === this.parentMenu; },
mouseout: function() {
var menuItem = this,
id = this.container.pendingMouseoutId,
disappearAfter = this.container.disappearAfter;
if (id) {
window.clearTimeout(id);
}
if (disappearAfter > -1) {
this.container.pendingMouseoutId =
window.setTimeout(function() { menuItem.hover(false); }, disappearAfter);
}
},
mouseover: function() {
var id = this.container.pendingMouseoutId;
if (id) {
window.clearTimeout(id);
this.container.pendingMouseoutId = null;
}
this.hover(true);
if (this.container.menu.get_focused()) {
this.container.navigateTo(this);
}
},
navigate: function(keyCode) {
switch (this.keyMap[keyCode]) {
case this.keyMap.next:
this.navigateNext();
break;
case this.keyMap.previous:
this.navigatePrevious();
break;
case this.keyMap.child:
this.navigateChild();
break;
case this.keyMap.parent:
this.navigateParent();
break;
case this.keyMap.tab:
this.navigateOut();
break;
}
},
navigateChild: function() {
var subMenu = this.childMenu;
if (subMenu) {
var firstChild = subMenu.firstChild();
if (firstChild) {
this.container.navigateTo(firstChild);
}
}
else {
if (this.container.orientation === 'horizontal') {
var nextItem = this.topLevelMenuItem.nextSibling || this.topLevelMenuItem.parentMenu.firstChild();
if (nextItem == this.topLevelMenuItem) {
return;
}
this.topLevelMenuItem.childMenu.hide();
this.container.navigateTo(nextItem);
if (nextItem.childMenu) {
this.container.navigateTo(nextItem.childMenu.firstChild());
}
}
}
},
navigateNext: function() {
if (this.childMenu) {
this.childMenu.hide();
}
var nextMenuItem = this.nextSibling;
if (!nextMenuItem && this.parentMenu.isRoot()) {
nextMenuItem = this.parentMenu.parentMenuItem;
if (nextMenuItem) {
nextMenuItem = nextMenuItem.nextSibling;
}
}
if (!nextMenuItem) {
nextMenuItem = this.parentMenu.firstChild();
}
if (nextMenuItem) {
this.container.navigateTo(nextMenuItem);
}
},
navigateOut: function() {
this.parentMenu.blur();
},
navigateParent: function() {
var parentMenu = this.parentMenu,
horizontal = this.container.orientation === 'horizontal';
if (!parentMenu) return;
if (horizontal && this.childMenu && parentMenu.isRoot()) {
this.navigateChild();
return;
}
if (parentMenu.parentMenuItem && !parentMenu.isRoot()) {
if (horizontal && this.parentMenu.depth === 2) {
var previousItem = this.parentMenu.parentMenuItem.previousSibling;
if (!previousItem) {
previousItem = this.parentMenu.rootMenu.lastChild();
}
this.topLevelMenuItem.childMenu.hide();
this.container.navigateTo(previousItem);
if (previousItem.childMenu) {
this.container.navigateTo(previousItem.childMenu.firstChild());
}
}
else {
this.parentMenu.hide();
}
}
},
navigatePrevious: function() {
if (this.childMenu) {
this.childMenu.hide();
}
var previousMenuItem = this.previousSibling;
if (previousMenuItem) {
var childMenu = previousMenuItem.childMenu;
if (childMenu && childMenu.isRoot()) {
previousMenuItem = childMenu.lastChild();
}
}
if (!previousMenuItem && this.parentMenu.isRoot()) {
previousMenuItem = this.parentMenu.parentMenuItem;
}
if (!previousMenuItem) {
previousMenuItem = this.parentMenu.lastChild();
}
if (previousMenuItem) {
this.container.navigateTo(previousMenuItem);
}
},
setTabIndex: function(index) { if (this._anchor) this._anchor.tabIndex = index; }
};
Sys.WebForms.MenuItem._onmouseout = function(e) {
var menuItem = Sys.WebForms.Menu._elementObjectMapper.getMappedObject(this);
if (!menuItem) {
return;
}
menuItem.mouseout();
Sys.WebForms.Menu._domHelper.cancelEvent(e);
};
Sys.WebForms.MenuItem._onmouseover = function(e) {
var menuItem = Sys.WebForms.Menu._elementObjectMapper.getMappedObject(this);
if (!menuItem) {
return;
}
menuItem.mouseover();
Sys.WebForms.Menu._domHelper.cancelEvent(e);
};
Sys.WebForms.Menu._domHelper = {
addEvent: function(element, eventName, fn, useCapture) {
if (element.addEventListener) {
element.addEventListener(eventName, fn, !!useCapture);
}
else {
element['on' + eventName] = fn;
}
},
appendAttributeValue: function(element, name, value) {
this.updateAttributeValue('append', element, name, value);
},
appendCssClass: function(element, value) {
this.updateClassName('append', element, name, value);
},
appendString: function(getString, setString, value) {
var currentValue = getString();
if (!currentValue) {
setString(value);
return;
}
var regex = this._regexes.getRegex('(^| )' + value + '($| )');
if (regex.test(currentValue)) {
return;
}
setString(currentValue + ' ' + value);
},
cancelEvent: function(e) {
var event = e || window.event;
if (event) {
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
}
},
contains: function(ancestor, descendant) {
for (; descendant && (descendant !== ancestor); descendant = descendant.parentNode) { }
return !!descendant;
},
firstChild: function(element) {
var child = element.firstChild;
if (child && child.nodeType !== 1) {
child = this.nextSibling(child);
}
return child;
},
getElement: function(elementOrId) { return typeof elementOrId === 'string' ? document.getElementById(elementOrId) : elementOrId; },
getElementDirection: function(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return this.getElementDirection(element.parentNode);
}
return "ltr";
},
getKeyCode: function(event) { return event.keyCode || event.charCode || 0; },
insertAfter: function(element, elementToInsert) {
var next = element.nextSibling;
if (next) {
element.parentNode.insertBefore(elementToInsert, next);
}
else if (element.parentNode) {
element.parentNode.appendChild(elementToInsert);
}
},
nextSibling: function(element) {
var sibling = element.nextSibling;
while (sibling) {
if (sibling.nodeType === 1) {
return sibling;
}
sibling = sibling.nextSibling;
}
},
removeAttributeValue: function(element, name, value) {
this.updateAttributeValue('remove', element, name, value);
},
removeCssClass: function(element, value) {
this.updateClassName('remove', element, name, value);
},
removeEvent: function(element, eventName, fn, useCapture) {
if (element.removeEventListener) {
element.removeEventListener(eventName, fn, !!useCapture);
}
else if (element.detachEvent) {
element.detachEvent('on' + eventName, fn)
}
element['on' + eventName] = null;
},
removeString: function(getString, setString, valueToRemove) {
var currentValue = getString();
if (currentValue) {
var regex = this._regexes.getRegex('(\\s|\\b)' + valueToRemove + '$|\\b' + valueToRemove + '\\s+');
setString(currentValue.replace(regex, ''));
}
},
setFloat: function(element, direction) {
element.style.styleFloat = direction;
element.style.cssFloat = direction;
},
updateAttributeValue: function(operation, element, name, value) {
this[operation + 'String'](
function() {
return element.getAttribute(name);
},
function(newValue) {
element.setAttribute(name, newValue);
},
value
);
},
updateClassName: function(operation, element, name, value) {
this[operation + 'String'](
function() {
return element.className;
},
function(newValue) {
element.className = newValue;
},
value
);
},
_regexes: {
getRegex: function(pattern) {
var regex = this[pattern];
if (!regex) {
this[pattern] = regex = new RegExp(pattern);
}
return regex;
}
}
};
Sys.WebForms.Menu._elementObjectMapper = {
_computedId: 0,
_mappings: {},
_mappingIdName: 'Sys.WebForms.Menu.Mapping',
getMappedObject: function(element) {
var id = element[this._mappingIdName];
if (id) {
return this._mappings[this._mappingIdName + ':' + id];
}
},
map: function(element, theObject) {
var mappedObject = element[this._mappingIdName];
if (mappedObject === theObject) {
return;
}
var objectId = element[this._mappingIdName] || element.id || '%' + (++this._computedId);
element[this._mappingIdName] = objectId;
this._mappings[this._mappingIdName + ':' + objectId] = theObject;
theObject.mappingId = objectId;
}
};
Sys.WebForms.Menu._keyboardMapping = new (function() {
var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;
var TAB = 9;
var ESCAPE = 27;
this.vertical = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 };
this.vertical[DOWN_ARROW] = this.vertical.next;
this.vertical[UP_ARROW] = this.vertical.previous;
this.vertical[RIGHT_ARROW] = this.vertical.child;
this.vertical[LEFT_ARROW] = this.vertical.parent;
this.vertical[TAB] = this.vertical[ESCAPE] = this.vertical.tab;
this.verticalRtl = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 };
this.verticalRtl[DOWN_ARROW] = this.verticalRtl.next;
this.verticalRtl[UP_ARROW] = this.verticalRtl.previous;
this.verticalRtl[LEFT_ARROW] = this.verticalRtl.child;
this.verticalRtl[RIGHT_ARROW] = this.verticalRtl.parent;
this.verticalRtl[TAB] = this.verticalRtl[ESCAPE] = this.verticalRtl.tab;
this.horizontal = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 };
this.horizontal[RIGHT_ARROW] = this.horizontal.next;
this.horizontal[LEFT_ARROW] = this.horizontal.previous;
this.horizontal[DOWN_ARROW] = this.horizontal.child;
this.horizontal[UP_ARROW] = this.horizontal.parent;
this.horizontal[TAB] = this.horizontal[ESCAPE] = this.horizontal.tab;
this.horizontalRtl = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 };
this.horizontalRtl[RIGHT_ARROW] = this.horizontalRtl.previous;
this.horizontalRtl[LEFT_ARROW] = this.horizontalRtl.next;
this.horizontalRtl[DOWN_ARROW] = this.horizontalRtl.child;
this.horizontalRtl[UP_ARROW] = this.horizontalRtl.parent;
this.horizontalRtl[TAB] = this.horizontalRtl[ESCAPE] = this.horizontalRtl.tab;
this.horizontal.contains = this.horizontalRtl.contains = this.vertical.contains = this.verticalRtl.contains = function(keycode) {
return this[keycode] != null;
};
})();
Sys.WebForms._MenuContainer = function(options) {
this.focused = false;
this.disabled = options.disabled;
this.staticDisplayLevels = options.staticDisplayLevels || 1;
this.element = options.element;
this.orientation = options.orientation || 'vertical';
this.disappearAfter = options.disappearAfter;
this.rightToLeft = Sys.WebForms.Menu._domHelper.getElementDirection(this.element) === 'rtl';
Sys.WebForms.Menu._elementObjectMapper.map(this.element, this);
this.menu = options.menu;
this.menu.rootMenu = this.menu;
this.menu.displayMode = 'static';
this.menu.element.style.position = 'relative';
this.menu.element.style.width = 'auto';
if (this.orientation === 'vertical') {
Sys.WebForms.Menu._domHelper.appendAttributeValue(this.menu.element, 'role', 'menu');
if (this.rightToLeft) {
this.menu.keyMap = Sys.WebForms.Menu._keyboardMapping.verticalRtl;
}
else {
this.menu.keyMap = Sys.WebForms.Menu._keyboardMapping.vertical;
}
}
else {
Sys.WebForms.Menu._domHelper.appendAttributeValue(this.menu.element, 'role', 'menubar');
if (this.rightToLeft) {
this.menu.keyMap = Sys.WebForms.Menu._keyboardMapping.horizontalRtl;
}
else {
this.menu.keyMap = Sys.WebForms.Menu._keyboardMapping.horizontal;
}
}
var floatBreak = document.createElement('div');
floatBreak.style.clear = this.rightToLeft ? "right" : "left";
this.element.appendChild(floatBreak);
Sys.WebForms.Menu._domHelper.setFloat(this.element, this.rightToLeft ? "right" : "left");
Sys.WebForms.Menu._domHelper.insertAfter(this.element, floatBreak);
if (!this.disabled) {
Sys.WebForms.Menu._domHelper.addEvent(this.menu.element, 'focus', this._onfocus, true);
Sys.WebForms.Menu._domHelper.addEvent(this.menu.element, 'keydown', this._onkeydown);
var menuContainer = this;
this.element.dispose = function() {
if (menuContainer.element.dispose) {
menuContainer.element.dispose = null;
Sys.WebForms.Menu._domHelper.removeEvent(menuContainer.menu.element, 'focus', menuContainer._onfocus, true);
Sys.WebForms.Menu._domHelper.removeEvent(menuContainer.menu.element, 'keydown', menuContainer._onkeydown);
menuContainer.menu.doDispose();
}
};
Sys.WebForms.Menu._domHelper.addEvent(window, 'unload', function() {
if (menuContainer.element.dispose) {
menuContainer.element.dispose();
}
});
}
};
Sys.WebForms._MenuContainer.prototype = {
blur: function() {
this.focused = false;
this.isBlurring = false;
this.menu.collapse();
this.focusedMenuItem = null;
},
focus: function(e) { this.focused = true; },
navigateTo: function(menuItem) {
if (this.focusedMenuItem && this.focusedMenuItem !== this) {
this.focusedMenuItem.highlight(false);
}
menuItem.highlight(true);
menuItem.focus();
this.focusedMenuItem = menuItem;
},
_onfocus: function(e) {
var event = e || window.event;
if (event.srcElement && this) {
if (Sys.WebForms.Menu._domHelper.contains(this.element, event.srcElement)) {
if (!this.focused) {
this.focus();
}
}
}
},
_onkeydown: function(e) {
var thisMenu = Sys.WebForms.Menu._elementObjectMapper.getMappedObject(this);
var keyCode = Sys.WebForms.Menu._domHelper.getKeyCode(e || window.event);
if (thisMenu) {
thisMenu.handleKeyPress(keyCode);
}
}
};
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/GridView.js
function GridView() {
this.pageIndex = null;
this.sortExpression = null;
this.sortDirection = null;
this.dataKeys = null;
this.createPropertyString = GridView_createPropertyString;
this.setStateField = GridView_setStateValue;
this.getHiddenFieldContents = GridView_getHiddenFieldContents;
this.stateField = null;
this.panelElement = null;
this.callback = null;
}
function GridView_createPropertyString() {
return createPropertyStringFromValues_GridView(this.pageIndex, this.sortDirection, this.sortExpression, this.dataKeys);
}
function GridView_setStateValue() {
this.stateField.value = this.createPropertyString();
}
function GridView_OnCallback (result, context) {
var value = new String(result);
var valsArray = value.split("|");
var innerHtml = valsArray[4];
for (var i = 5; i < valsArray.length; i++) {
innerHtml += "|" + valsArray[i];
}
context.panelElement.innerHTML = innerHtml;
context.stateField.value = createPropertyStringFromValues_GridView(valsArray[0], valsArray[1], valsArray[2], valsArray[3]);
}
function GridView_getHiddenFieldContents(arg) {
return arg + "|" + this.stateField.value;
}
function createPropertyStringFromValues_GridView(pageIndex, sortDirection, sortExpression, dataKeys) {
var value = new Array(pageIndex, sortDirection, sortExpression, dataKeys);
return value.join("|");
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/TreeView.js
function TreeView_HoverNode(data, node) {
if (!data) {
return;
}
node.hoverClass = data.hoverClass;
WebForm_AppendToClassName(node, data.hoverClass);
if (__nonMSDOMBrowser) {
node = node.childNodes[node.childNodes.length - 1];
}
else {
node = node.children[node.children.length - 1];
}
node.hoverHyperLinkClass = data.hoverHyperLinkClass;
WebForm_AppendToClassName(node, data.hoverHyperLinkClass);
}
function TreeView_GetNodeText(node) {
var trNode = WebForm_GetParentByTagName(node, "TR");
var outerNodes;
if (trNode.childNodes[trNode.childNodes.length - 1].getElementsByTagName) {
outerNodes = trNode.childNodes[trNode.childNodes.length - 1].getElementsByTagName("A");
if (!outerNodes || outerNodes.length == 0) {
outerNodes = trNode.childNodes[trNode.childNodes.length - 1].getElementsByTagName("SPAN");
}
}
var textNode = (outerNodes && outerNodes.length > 0) ?
outerNodes[0].childNodes[0] :
trNode.childNodes[trNode.childNodes.length - 1].childNodes[0];
return (textNode && textNode.nodeValue) ? textNode.nodeValue : "";
}
function TreeView_PopulateNode(data, index, node, selectNode, selectImageNode, lineType, text, path, databound, datapath, parentIsLast) {
if (!data) {
return;
}
var context = new Object();
context.data = data;
context.node = node;
context.selectNode = selectNode;
context.selectImageNode = selectImageNode;
context.lineType = lineType;
context.index = index;
context.isChecked = "f";
var tr = WebForm_GetParentByTagName(node, "TR");
if (tr) {
var checkbox = tr.getElementsByTagName("INPUT");
if (checkbox && (checkbox.length > 0)) {
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].type.toLowerCase() == "checkbox") {
if (checkbox[i].checked) {
context.isChecked = "t";
}
break;
}
}
}
}
var param = index + "|" + data.lastIndex + "|" + databound + context.isChecked + parentIsLast + "|" +
text.length + "|" + text + datapath.length + "|" + datapath + path;
TreeView_PopulateNodeDoCallBack(context, param);
}
function TreeView_ProcessNodeData(result, context) {
var treeNode = context.node;
if (result.length > 0) {
var ci = result.indexOf("|", 0);
context.data.lastIndex = result.substring(0, ci);
ci = result.indexOf("|", ci + 1);
var newExpandState = result.substring(context.data.lastIndex.length + 1, ci);
context.data.expandState.value += newExpandState;
var chunk = result.substr(ci + 1);
var newChildren, table;
if (__nonMSDOMBrowser) {
var newDiv = document.createElement("div");
newDiv.innerHTML = chunk;
table = WebForm_GetParentByTagName(treeNode, "TABLE");
newChildren = null;
if ((typeof(table.nextSibling) == "undefined") || (table.nextSibling == null)) {
table.parentNode.insertBefore(newDiv.firstChild, table.nextSibling);
newChildren = table.previousSibling;
}
else {
table = table.nextSibling;
table.parentNode.insertBefore(newDiv.firstChild, table);
newChildren = table.previousSibling;
}
newChildren = document.getElementById(treeNode.id + "Nodes");
}
else {
table = WebForm_GetParentByTagName(treeNode, "TABLE");
table.insertAdjacentHTML("afterEnd", chunk);
newChildren = document.all[treeNode.id + "Nodes"];
}
if ((typeof(newChildren) != "undefined") && (newChildren != null)) {
TreeView_ToggleNode(context.data, context.index, treeNode, context.lineType, newChildren);
treeNode.href = document.getElementById ?
"javascript:TreeView_ToggleNode(" + context.data.name + "," + context.index + ",document.getElementById('" + treeNode.id + "'),'" + context.lineType + "',document.getElementById('" + newChildren.id + "'))" :
"javascript:TreeView_ToggleNode(" + context.data.name + "," + context.index + "," + treeNode.id + ",'" + context.lineType + "'," + newChildren.id + ")";
if ((typeof(context.selectNode) != "undefined") && (context.selectNode != null) && context.selectNode.href &&
(context.selectNode.href.indexOf("javascript:TreeView_PopulateNode", 0) == 0)) {
context.selectNode.href = treeNode.href;
}
if ((typeof(context.selectImageNode) != "undefined") && (context.selectImageNode != null) && context.selectNode.href &&
(context.selectImageNode.href.indexOf("javascript:TreeView_PopulateNode", 0) == 0)) {
context.selectImageNode.href = treeNode.href;
}
}
context.data.populateLog.value += context.index + ",";
}
else {
var img = treeNode.childNodes ? treeNode.childNodes[0] : treeNode.children[0];
if ((typeof(img) != "undefined") && (img != null)) {
var lineType = context.lineType;
if (lineType == "l") {
img.src = context.data.images[13];
}
else if (lineType == "t") {
img.src = context.data.images[10];
}
else if (lineType == "-") {
img.src = context.data.images[16];
}
else {
img.src = context.data.images[3];
}
var pe;
if (__nonMSDOMBrowser) {
pe = treeNode.parentNode;
pe.insertBefore(img, treeNode);
pe.removeChild(treeNode);
}
else {
pe = treeNode.parentElement;
treeNode.style.visibility="hidden";
treeNode.style.display="none";
pe.insertAdjacentElement("afterBegin", img);
}
}
}
}
function TreeView_SelectNode(data, node, nodeId) {
if (!data) {
return;
}
if ((typeof(data.selectedClass) != "undefined") && (data.selectedClass != null)) {
var id = data.selectedNodeID.value;
if (id.length > 0) {
var selectedNode = document.getElementById(id);
if ((typeof(selectedNode) != "undefined") && (selectedNode != null)) {
WebForm_RemoveClassName(selectedNode, data.selectedHyperLinkClass);
selectedNode = WebForm_GetParentByTagName(selectedNode, "TD");
WebForm_RemoveClassName(selectedNode, data.selectedClass);
}
}
WebForm_AppendToClassName(node, data.selectedHyperLinkClass);
node = WebForm_GetParentByTagName(node, "TD");
WebForm_AppendToClassName(node, data.selectedClass)
}
data.selectedNodeID.value = nodeId;
}
function TreeView_ToggleNode(data, index, node, lineType, children) {
if (!data) {
return;
}
var img = node.childNodes[0];
var newExpandState;
try {
if (children.style.display == "none") {
children.style.display = "block";
newExpandState = "e";
if ((typeof(img) != "undefined") && (img != null)) {
if (lineType == "l") {
img.src = data.images[15];
}
else if (lineType == "t") {
img.src = data.images[12];
}
else if (lineType == "-") {
img.src = data.images[18];
}
else {
img.src = data.images[5];
}
img.alt = data.collapseToolTip.replace(/\{0\}/, TreeView_GetNodeText(node));
}
}
else {
children.style.display = "none";
newExpandState = "c";
if ((typeof(img) != "undefined") && (img != null)) {
if (lineType == "l") {
img.src = data.images[14];
}
else if (lineType == "t") {
img.src = data.images[11];
}
else if (lineType == "-") {
img.src = data.images[17];
}
else {
img.src = data.images[4];
}
img.alt = data.expandToolTip.replace(/\{0\}/, TreeView_GetNodeText(node));
}
}
}
catch(e) {}
data.expandState.value = data.expandState.value.substring(0, index) + newExpandState + data.expandState.value.slice(index + 1);
}
function TreeView_UnhoverNode(node) {
if (!node.hoverClass) {
return;
}
WebForm_RemoveClassName(node, node.hoverClass);
if (__nonMSDOMBrowser) {
node = node.childNodes[node.childNodes.length - 1];
}
else {
node = node.children[node.children.length - 1];
}
WebForm_RemoveClassName(node, node.hoverHyperLinkClass);
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/DetailsView.js
function DetailsView() {
this.pageIndex = null;
this.dataKeys = null;
this.createPropertyString = DetailsView_createPropertyString;
this.setStateField = DetailsView_setStateValue;
this.getHiddenFieldContents = DetailsView_getHiddenFieldContents;
this.stateField = null;
this.panelElement = null;
this.callback = null;
}
function DetailsView_createPropertyString() {
return createPropertyStringFromValues_DetailsView(this.pageIndex, this.dataKeys);
}
function DetailsView_setStateValue() {
this.stateField.value = this.createPropertyString();
}
function DetailsView_OnCallback (result, context) {
var value = new String(result);
var valsArray = value.split("|");
var innerHtml = valsArray[2];
for (var i = 3; i < valsArray.length; i++) {
innerHtml += "|" + valsArray[i];
}
context.panelElement.innerHTML = innerHtml;
context.stateField.value = createPropertyStringFromValues_DetailsView(valsArray[0], valsArray[1]);
}
function DetailsView_getHiddenFieldContents(arg) {
return arg + "|" + this.stateField.value;
}
function createPropertyStringFromValues_DetailsView(pageIndex, dataKeys) {
var value = new Array(pageIndex, dataKeys);
return value.join("|");
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/Focus.js
function WebForm_FindFirstFocusableChild(control) {
if (!control || !(control.tagName)) {
return null;
}
var tagName = control.tagName.toLowerCase();
if (tagName == "undefined") {
return null;
}
var children = control.childNodes;
if (children) {
for (var i = 0; i < children.length; i++) {
try {
if (WebForm_CanFocus(children[i])) {
return children[i];
}
else {
var focused = WebForm_FindFirstFocusableChild(children[i]);
if (WebForm_CanFocus(focused)) {
return focused;
}
}
} catch (e) {
}
}
}
return null;
}
function WebForm_AutoFocus(focusId) {
var targetControl;
if (__nonMSDOMBrowser) {
targetControl = document.getElementById(focusId);
}
else {
targetControl = document.all[focusId];
}
var focused = targetControl;
if (targetControl && (!WebForm_CanFocus(targetControl)) ) {
focused = WebForm_FindFirstFocusableChild(targetControl);
}
if (focused) {
try {
focused.focus();
if (__nonMSDOMBrowser) {
focused.scrollIntoView(false);
}
if (window.__smartNav) {
window.__smartNav.ae = focused.id;
}
}
catch (e) {
}
}
}
function WebForm_CanFocus(element) {
if (!element || !(element.tagName)) return false;
var tagName = element.tagName.toLowerCase();
return (!(element.disabled) &&
(!(element.type) || element.type.toLowerCase() != "hidden") &&
WebForm_IsFocusableTag(tagName) &&
WebForm_IsInVisibleContainer(element)
);
}
function WebForm_IsFocusableTag(tagName) {
return (tagName == "input" ||
tagName == "textarea" ||
tagName == "select" ||
tagName == "button" ||
tagName == "a");
}
function WebForm_IsInVisibleContainer(ctrl) {
var current = ctrl;
while((typeof(current) != "undefined") && (current != null)) {
if (current.disabled ||
( typeof(current.style) != "undefined" &&
( ( typeof(current.style.display) != "undefined" &&
current.style.display == "none") ||
( typeof(current.style.visibility) != "undefined" &&
current.style.visibility == "hidden") ) ) ) {
return false;
}
if (typeof(current.parentNode) != "undefined" &&
current.parentNode != null &&
current.parentNode != current &&
current.parentNode.tagName.toLowerCase() != "body") {
current = current.parentNode;
}
else {
return true;
}
}
return true;
}
| JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/WebForms.js
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
if (typeof(Page_ClientValidate) == 'function') {
validationResult = Page_ClientValidate(options.validationGroup);
}
}
if (validationResult) {
if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
theForm.action = options.actionUrl;
}
if (options.trackFocus) {
var lastFocus = theForm.elements["__LASTFOCUS"];
if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
if (typeof(document.activeElement) == "undefined") {
lastFocus.value = options.eventTarget;
}
else {
var active = document.activeElement;
if ((typeof(active) != "undefined") && (active != null)) {
if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
lastFocus.value = active.id;
}
else if (typeof(active.name) != "undefined") {
lastFocus.value = active.name;
}
}
}
}
}
}
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
}
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}
var xmlRequest,e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
}
catch(e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// e.g. http:
var action = theForm.action || document.location.pathname, fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
action = action.substr(0, fragmentIndex);
}
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
}
else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame = document.createElement("IFRAME");
xmlRequestFrame.width = "1";
xmlRequestFrame.height = "1";
xmlRequestFrame.frameBorder = "0";
xmlRequestFrame.id = callbackFrameID;
xmlRequestFrame.name = callbackFrameID;
xmlRequestFrame.style.position = "absolute";
xmlRequestFrame.style.top = "-100px"
xmlRequestFrame.style.left = "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src = callBackFrameUrl;
}
}
catch(e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame = document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write("");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element = __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type = "hidden";
fieldElement.name = element.name;
fieldElement.value = element.value;
xmlRequestFrame.document.forms[0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type = "hidden";
callbackIdFieldElement.name = "__CALLBACKID";
callbackIdFieldElement.value = eventTarget;
xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type = "hidden";
callbackParamFieldElement.name = "__CALLBACKPARAM";
callbackParamFieldElement.value = eventArgument;
xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type = "hidden";
callbackValidationFieldElement.name = "__EVENTVALIDATION";
callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type = "hidden";
callbackIndexFieldElement.name = "__CALLBACKINDEX";
callbackIndexFieldElement.value = callbackIndex;
xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[0].submit();
}
}, 10);
}
function WebForm_CallbackComplete() {
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(1), callbackObject.context);
}
}
else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(1), callbackObject.context);
}
}
else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement = document.createElement("INPUT");
validationFieldElement.type = "hidden";
validationFieldElement.name = "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value = validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context);
}
}
}
}
}
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i] = element;
return i;
}
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
var __theFormPostData = "";
var __theFormPostCollection = new Array();
var __callbackTextTypes = /^(text|password|hidden|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function WebForm_InitCallback() {
var formElements = theForm.elements,
count = formElements.length,
element;
for (var i = 0; i < count; i++) {
element = formElements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((__callbackTextTypes.test(type) || ((type == "checkbox" || type == "radio") && element.checked))
&& (element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
function WebForm_EncodeCallback(parameter) {
if (encodeURIComponent) {
return encodeURIComponent(parameter);
}
else {
return escape(parameter);
}
}
var __disabledControlArray = new Array();
function WebForm_ReEnableControls() {
if (typeof(__enabledControlArray) == 'undefined') {
return false;
}
var disabledIndex = 0;
for (var i = 0; i < __enabledControlArray.length; i++) {
var c;
if (__nonMSDOMBrowser) {
c = document.getElementById(__enabledControlArray[i]);
}
else {
c = document.all[__enabledControlArray[i]];
}
if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
c.disabled = false;
__disabledControlArray[disabledIndex++] = c;
}
}
setTimeout("WebForm_ReDisableControls()", 0);
return true;
}
function WebForm_ReDisableControls() {
for (var i = 0; i < __disabledControlArray.length; i++) {
__disabledControlArray[i].disabled = true;
}
}
function WebForm_SimulateClick(element, event) {
var clickEvent;
if (element) {
if (element.click) {
element.click();
} else {
clickEvent = document.createEvent("MouseEvents");
clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
if (!element.dispatchEvent(clickEvent)) {
return true;
}
}
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
return true;
}
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (src &&
((src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) ||
((src.tagName.toLowerCase() == "a") &&
(src.href != null) && (src.href != "")) ||
(src.tagName.toLowerCase() == "textarea")) {
return true;
}
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton) {
return WebForm_SimulateClick(defaultButton, event);
}
}
return true;
}
function WebForm_GetScrollX() {
if (__nonMSDOMBrowser) {
return window.pageXOffset;
}
else {
if (document.documentElement && document.documentElement.scrollLeft) {
return document.documentElement.scrollLeft;
}
else if (document.body) {
return document.body.scrollLeft;
}
}
return 0;
}
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
}
else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
}
else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
}
else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
function WebForm_SaveScrollPositionOnSubmit() {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
return this.oldOnSubmit();
}
return true;
}
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
}
else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
function WebForm_TextBoxKeyHandler(event) {
if (event.keyCode == 13) {
var target;
if (__nonMSDOMBrowser) {
target = event.target;
}
else {
target = event.srcElement;
}
if ((typeof(target) != "undefined") && (target != null)) {
if (typeof(target.onchange) != "undefined") {
target.onchange();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
function WebForm_TrimString(value) {
return value.replace(/^\s+|\s+$/g, '')
}
function WebForm_AppendToClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index === -1) {
element.className = (element.className === '') ? className : element.className + ' ' + className;
}
}
function WebForm_RemoveClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index >= 0) {
element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
currentClassName.substring(index + className.length + 1, currentClassName.length));
}
}
function WebForm_GetElementById(elementId) {
if (document.getElementById) {
return document.getElementById(elementId);
}
else if (document.all) {
return document.all[elementId];
}
else return null;
}
function WebForm_GetElementByTagName(element, tagName) {
var elements = WebForm_GetElementsByTagName(element, tagName);
if (elements && elements.length > 0) {
return elements[0];
}
else return null;
}
function WebForm_GetElementsByTagName(element, tagName) {
if (element && tagName) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(tagName);
}
if (element.all && element.all.tags) {
return element.all.tags(tagName);
}
}
return null;
}
function WebForm_GetElementDir(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return WebForm_GetElementDir(element.parentNode);
}
return "ltr";
}
function WebForm_GetElementPosition(element) {
var result = new Object();
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
}
else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
}
else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
}
else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}
function WebForm_GetParentByTagName(element, tagName) {
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function WebForm_SetElementHeight(element, height) {
if (element && element.style) {
element.style.height = height + "px";
}
}
function WebForm_SetElementWidth(element, width) {
if (element && element.style) {
element.style.width = width + "px";
}
}
function WebForm_SetElementX(element, x) {
if (element && element.style) {
element.style.left = x + "px";
}
}
function WebForm_SetElementY(element, y) {
if (element && element.style) {
element.style.top = y + "px";
}
} | JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/WebUIValidation.js
var Page_ValidationVer = "125";
var Page_IsValid = true;
var Page_BlockSubmit = false;
var Page_InvalidControlToBeFocused = null;
var Page_TextTypes = /^(text|password|file|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function ValidatorUpdateDisplay(val) {
if (typeof(val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
function ValidatorUpdateIsValid() {
Page_IsValid = AllValidatorsValid(Page_Validators);
}
function AllValidatorsValid(validators) {
if ((typeof(validators) != "undefined") && (validators != null)) {
var i;
for (i = 0; i < validators.length; i++) {
if (!validators[i].isvalid) {
return false;
}
}
}
return true;
}
function ValidatorHookupControlID(controlID, val) {
if (typeof(controlID) != "string") {
return;
}
var ctrl = document.getElementById(controlID);
if ((typeof(ctrl) != "undefined") && (ctrl != null)) {
ValidatorHookupControl(ctrl, val);
}
else {
val.isvalid = true;
val.enabled = false;
}
}
function ValidatorHookupControl(control, val) {
if (typeof(control.tagName) != "string") {
return;
}
if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" && control.tagName != "SELECT") {
var i;
for (i = 0; i < control.childNodes.length; i++) {
ValidatorHookupControl(control.childNodes[i], val);
}
return;
}
else {
if (typeof(control.Validators) == "undefined") {
control.Validators = new Array;
var eventType;
if (control.type == "radio") {
eventType = "onclick";
} else {
eventType = "onchange";
if (typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorHookupEvent(control, "onblur", "ValidatedControlOnBlur(event); ");
}
}
ValidatorHookupEvent(control, eventType, "ValidatorOnChange(event); ");
if (Page_TextTypes.test(control.type)) {
ValidatorHookupEvent(control, "onkeypress",
"event = event || window.event; if (!ValidatedTextBoxOnKeyPress(event)) { event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } ");
}
}
control.Validators[control.Validators.length] = val;
}
}
function ValidatorHookupEvent(control, eventType, functionPrefix) {
var ev = control[eventType];
if (typeof(ev) == "function") {
ev = ev.toString();
ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
}
else {
ev = "";
}
control[eventType] = new Function("event", functionPrefix + " " + ev);
}
function ValidatorGetValue(id) {
var control;
control = document.getElementById(id);
if (typeof(control.value) == "string") {
return control.value;
}
return ValidatorGetValueRecursive(control);
}
function ValidatorGetValueRecursive(control)
{
if (typeof(control.value) == "string" && (control.type != "radio" || control.checked == true)) {
return control.value;
}
var i, val;
for (i = 0; i<control.childNodes.length; i++) {
val = ValidatorGetValueRecursive(control.childNodes[i]);
if (val != "") return val;
}
return "";
}
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
function ValidatorCommonOnSubmit() {
Page_InvalidControlToBeFocused = null;
var result = !Page_BlockSubmit;
if ((typeof(window.event) != "undefined") && (window.event != null)) {
window.event.returnValue = result;
}
Page_BlockSubmit = false;
return result;
}
function ValidatorEnable(val, enable) {
val.enabled = (enable != false);
ValidatorValidate(val);
ValidatorUpdateIsValid();
}
function ValidatorOnChange(event) {
event = event || window.event;
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof(targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
if (vals) {
for (var i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
function ValidatedTextBoxOnKeyPress(event) {
event = event || window.event;
if (event.keyCode == 13) {
ValidatorOnChange(event);
var vals;
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
vals = event.srcElement.Validators;
}
else {
vals = event.target.Validators;
}
return AllValidatorsValid(vals);
}
return true;
}
function ValidatedControlOnBlur(event) {
event = event || window.event;
var control;
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
control = event.srcElement;
}
else {
control = event.target;
}
if ((typeof(control) != "undefined") && (control != null) && (Page_InvalidControlToBeFocused == control)) {
control.focus();
Page_InvalidControlToBeFocused = null;
}
}
function ValidatorValidate(val, validationGroup, event) {
val.isvalid = true;
if ((typeof(val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, validationGroup)) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorSetFocus(val, event);
}
}
}
ValidatorUpdateDisplay(val);
}
function ValidatorSetFocus(val, event) {
var ctrl;
if (typeof(val.controlhookup) == "string") {
var eventCtrl;
if ((typeof(event) != "undefined") && (event != null)) {
if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
eventCtrl = event.srcElement;
}
else {
eventCtrl = event.target;
}
}
if ((typeof(eventCtrl) != "undefined") && (eventCtrl != null) &&
(typeof(eventCtrl.id) == "string") &&
(eventCtrl.id == val.controlhookup)) {
ctrl = eventCtrl;
}
}
if ((typeof(ctrl) == "undefined") || (ctrl == null)) {
ctrl = document.getElementById(val.controltovalidate);
}
if ((typeof(ctrl) != "undefined") && (ctrl != null) &&
(ctrl.tagName.toLowerCase() != "table" || (typeof(event) == "undefined") || (event == null)) &&
((ctrl.tagName.toLowerCase() != "input") || (ctrl.type.toLowerCase() != "hidden")) &&
(typeof(ctrl.disabled) == "undefined" || ctrl.disabled == null || ctrl.disabled == false) &&
(typeof(ctrl.visible) == "undefined" || ctrl.visible == null || ctrl.visible != false) &&
(IsInVisibleContainer(ctrl))) {
if ((ctrl.tagName.toLowerCase() == "table" && (typeof(__nonMSDOMBrowser) == "undefined" || __nonMSDOMBrowser)) ||
(ctrl.tagName.toLowerCase() == "span")) {
var inputElements = ctrl.getElementsByTagName("input");
var lastInputElement = inputElements[inputElements.length -1];
if (lastInputElement != null) {
ctrl = lastInputElement;
}
}
if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
}
}
}
function IsInVisibleContainer(ctrl) {
if (typeof(ctrl.style) != "undefined" &&
( ( typeof(ctrl.style.display) != "undefined" &&
ctrl.style.display == "none") ||
( typeof(ctrl.style.visibility) != "undefined" &&
ctrl.style.visibility == "hidden") ) ) {
return false;
}
else if (typeof(ctrl.parentNode) != "undefined" &&
ctrl.parentNode != null &&
ctrl.parentNode != ctrl) {
return IsInVisibleContainer(ctrl.parentNode);
}
return true;
}
function IsValidationGroupMatch(control, validationGroup) {
if ((typeof(validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
if (typeof(control.validationGroup) == "string") {
controlGroup = control.validationGroup;
}
return (controlGroup == validationGroup);
}
function ValidatorOnLoad() {
if (typeof(Page_Validators) == "undefined")
return;
var i, val;
for (i = 0; i < Page_Validators.length; i++) {
val = Page_Validators[i];
if (typeof(val.evaluationfunction) == "string") {
eval("val.evaluationfunction = " + val.evaluationfunction + ";");
}
if (typeof(val.isvalid) == "string") {
if (val.isvalid == "False") {
val.isvalid = false;
Page_IsValid = false;
}
else {
val.isvalid = true;
}
} else {
val.isvalid = true;
}
if (typeof(val.enabled) == "string") {
val.enabled = (val.enabled != "False");
}
if (typeof(val.controltovalidate) == "string") {
ValidatorHookupControlID(val.controltovalidate, val);
}
if (typeof(val.controlhookup) == "string") {
ValidatorHookupControlID(val.controlhookup, val);
}
}
Page_ValidationActive = true;
}
function ValidatorConvert(op, dataType, val) {
function GetFullYear(year) {
var twoDigitCutoffYear = val.cutoffyear % 100;
var cutoffYearCentury = val.cutoffyear - twoDigitCutoffYear;
return ((year > twoDigitCutoffYear) ? (cutoffYearCentury - 100 + year) : (cutoffYearCentury + year));
}
var num, cleanInput, m, exp;
if (dataType == "Integer") {
exp = /^\s*[-\+]?\d+\s*$/;
if (op.match(exp) == null)
return null;
num = parseInt(op, 10);
return (isNaN(num) ? null : num);
}
else if(dataType == "Double") {
exp = new RegExp("^\\s*([-\\+])?(\\d*)\\" + val.decimalchar + "?(\\d*)\\s*$");
m = op.match(exp);
if (m == null)
return null;
if (m[2].length == 0 && m[3].length == 0)
return null;
cleanInput = (m[1] != null ? m[1] : "") + (m[2].length>0 ? m[2] : "0") + (m[3].length>0 ? "." + m[3] : "");
num = parseFloat(cleanInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Currency") {
var hasDigits = (val.digits > 0);
var beginGroupSize, subsequentGroupSize;
var groupSizeNum = parseInt(val.groupsize, 10);
if (!isNaN(groupSizeNum) && groupSizeNum > 0) {
beginGroupSize = "{1," + groupSizeNum + "}";
subsequentGroupSize = "{" + groupSizeNum + "}";
}
else {
beginGroupSize = subsequentGroupSize = "+";
}
exp = new RegExp("^\\s*([-\\+])?((\\d" + beginGroupSize + "(\\" + val.groupchar + "\\d" + subsequentGroupSize + ")+)|\\d*)"
+ (hasDigits ? "\\" + val.decimalchar + "?(\\d{0," + val.digits + "})" : "")
+ "\\s*$");
m = op.match(exp);
if (m == null)
return null;
if (m[2].length == 0 && hasDigits && m[5].length == 0)
return null;
cleanInput = (m[1] != null ? m[1] : "") + m[2].replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((hasDigits && m[5].length > 0) ? "." + m[5] : "");
num = parseFloat(cleanInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Date") {
var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\.?\\s*$");
m = op.match(yearFirstExp);
var day, month, year;
if (m != null && (((typeof(m[2]) != "undefined") && (m[2].length == 4)) || val.dateorder == "ymd")) {
day = m[6];
month = m[5];
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
}
else {
if (val.dateorder == "ymd"){
return null;
}
var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})(?:\\s|\\2)((\\d{4})|(\\d{2}))(?:\\s\u0433\\.|\\.)?\\s*$");
m = op.match(yearLastExp);
if (m == null) {
return null;
}
if (val.dateorder == "mdy") {
day = m[3];
month = m[1];
}
else {
day = m[1];
month = m[3];
}
year = ((typeof(m[5]) != "undefined") && (m[5].length == 4)) ? m[5] : GetFullYear(parseInt(m[6], 10));
}
month -= 1;
var date = new Date(year, month, day);
if (year < 100) {
date.setFullYear(year);
}
return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
}
else {
return op.toString();
}
}
function ValidatorCompare(operand1, operand2, operator, val) {
var dataType = val.type;
var op1, op2;
if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
return false;
if (operator == "DataTypeCheck")
return true;
if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
return true;
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
}
}
function CompareValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var compareTo = "";
if ((typeof(val.controltocompare) != "string") ||
(typeof(document.getElementById(val.controltocompare)) == "undefined") ||
(null == document.getElementById(val.controltocompare))) {
if (typeof(val.valuetocompare) == "string") {
compareTo = val.valuetocompare;
}
}
else {
compareTo = ValidatorGetValue(val.controltocompare);
}
var operator = "Equal";
if (typeof(val.operator) == "string") {
operator = val.operator;
}
return ValidatorCompare(value, compareTo, operator, val);
}
function CustomValidatorEvaluateIsValid(val) {
var value = "";
if (typeof(val.controltovalidate) == "string") {
value = ValidatorGetValue(val.controltovalidate);
if ((ValidatorTrim(value).length == 0) &&
((typeof(val.validateemptytext) != "string") || (val.validateemptytext != "true"))) {
return true;
}
}
var args = { Value:value, IsValid:true };
if (typeof(val.clientvalidationfunction) == "string") {
eval(val.clientvalidationfunction + "(val, args) ;");
}
return args.IsValid;
}
function RegularExpressionValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var rx = new RegExp(val.validationexpression);
var matches = rx.exec(value);
return (matches != null && value == matches[0]);
}
function ValidatorTrim(s) {
var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
return (m == null) ? "" : m[1];
}
function RequiredFieldValidatorEvaluateIsValid(val) {
return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != ValidatorTrim(val.initialvalue))
}
function RangeValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
return (ValidatorCompare(value, val.minimumvalue, "GreaterThanEqual", val) &&
ValidatorCompare(value, val.maximumvalue, "LessThanEqual", val));
}
function ValidationSummaryOnSubmit(validationGroup) {
if (typeof(Page_ValidationSummaries) == "undefined")
return;
var summary, sums, s;
var headerSep, first, pre, post, end;
for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
summary = Page_ValidationSummaries[sums];
if (!summary) continue;
summary.style.display = "none";
if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
var i;
if (summary.showsummary != "False") {
summary.style.display = "";
if (typeof(summary.displaymode) != "string") {
summary.displaymode = "BulletList";
}
switch (summary.displaymode) {
case "List":
headerSep = "<br>";
first = "";
pre = "";
post = "<br>";
end = "";
break;
case "BulletList":
default:
headerSep = "";
first = "<ul>";
pre = "<li>";
post = "</li>";
end = "</ul>";
break;
case "SingleParagraph":
headerSep = " ";
first = "";
pre = "";
post = " ";
end = "<br>";
break;
}
s = "";
if (typeof(summary.headertext) == "string") {
s += summary.headertext + headerSep;
}
s += first;
for (i=0; i<Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
s += pre + Page_Validators[i].errormessage + post;
}
}
s += end;
summary.innerHTML = s;
window.scrollTo(0,0);
}
if (summary.showmessagebox == "True") {
s = "";
if (typeof(summary.headertext) == "string") {
s += summary.headertext + "\r\n";
}
var lastValIndex = Page_Validators.length - 1;
for (i=0; i<=lastValIndex; i++) {
if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
switch (summary.displaymode) {
case "List":
s += Page_Validators[i].errormessage;
if (i < lastValIndex) {
s += "\r\n";
}
break;
case "BulletList":
default:
s += "- " + Page_Validators[i].errormessage;
if (i < lastValIndex) {
s += "\r\n";
}
break;
case "SingleParagraph":
s += Page_Validators[i].errormessage + " ";
break;
}
}
}
alert(s);
}
}
}
}
if (window.jQuery) {
(function ($) {
var dataValidationAttribute = "data-val",
dataValidationSummaryAttribute = "data-valsummary",
normalizedAttributes = { validationgroup: "validationGroup", focusonerror: "focusOnError" };
function getAttributesWithPrefix(element, prefix) {
var i,
attribute,
list = {},
attributes = element.attributes,
length = attributes.length,
prefixLength = prefix.length;
prefix = prefix.toLowerCase();
for (i = 0; i < length; i++) {
attribute = attributes[i];
if (attribute.specified && attribute.name.substr(0, prefixLength).toLowerCase() === prefix) {
list[attribute.name.substr(prefixLength)] = attribute.value;
}
}
return list;
}
function normalizeKey(key) {
key = key.toLowerCase();
return normalizedAttributes[key] === undefined ? key : normalizedAttributes[key];
}
function addValidationExpando(element) {
var attributes = getAttributesWithPrefix(element, dataValidationAttribute + "-");
$.each(attributes, function (key, value) {
element[normalizeKey(key)] = value;
});
}
function dispose(element) {
var index = $.inArray(element, Page_Validators);
if (index >= 0) {
Page_Validators.splice(index, 1);
}
}
function addNormalizedAttribute(name, normalizedName) {
normalizedAttributes[name.toLowerCase()] = normalizedName;
}
function parseSpecificAttribute(selector, attribute, validatorsArray) {
return $(selector).find("[" + attribute + "='true']").each(function (index, element) {
addValidationExpando(element);
element.dispose = function () { dispose(element); element.dispose = null; };
if ($.inArray(element, validatorsArray) === -1) {
validatorsArray.push(element);
}
}).length;
}
function parse(selector) {
var length = parseSpecificAttribute(selector, dataValidationAttribute, Page_Validators);
length += parseSpecificAttribute(selector, dataValidationSummaryAttribute, Page_ValidationSummaries);
return length;
}
function loadValidators() {
if (typeof (ValidatorOnLoad) === "function") {
ValidatorOnLoad();
}
if (typeof (ValidatorOnSubmit) === "undefined") {
window.ValidatorOnSubmit = function () {
return Page_ValidationActive ? ValidatorCommonOnSubmit() : true;
};
}
}
function registerUpdatePanel() {
if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
var prm = Sys.WebForms.PageRequestManager.getInstance(),
postBackElement, endRequestHandler;
if (prm.get_isInAsyncPostBack()) {
endRequestHandler = function (sender, args) {
if (parse(document)) {
loadValidators();
}
prm.remove_endRequest(endRequestHandler);
endRequestHandler = null;
};
prm.add_endRequest(endRequestHandler);
}
prm.add_beginRequest(function (sender, args) {
postBackElement = args.get_postBackElement();
});
prm.add_pageLoaded(function (sender, args) {
var i, panels, valFound = 0;
if (typeof (postBackElement) === "undefined") {
return;
}
panels = args.get_panelsUpdated();
for (i = 0; i < panels.length; i++) {
valFound += parse(panels[i]);
}
panels = args.get_panelsCreated();
for (i = 0; i < panels.length; i++) {
valFound += parse(panels[i]);
}
if (valFound) {
loadValidators();
}
});
}
}
$(function () {
if (typeof (Page_Validators) === "undefined") {
window.Page_Validators = [];
}
if (typeof (Page_ValidationSummaries) === "undefined") {
window.Page_ValidationSummaries = [];
}
if (typeof (Page_ValidationActive) === "undefined") {
window.Page_ValidationActive = false;
}
$.WebFormValidator = {
addNormalizedAttribute: addNormalizedAttribute,
parse: parse
};
if (parse(document)) {
loadValidators();
}
registerUpdatePanel();
});
} (jQuery));
} | JavaScript |
//CdnPath=http://ajax.aspnetcdn.com/ajax/4.5/6/SmartNav.js
var snSrc;
if ((typeof(window.__smartNav) == "undefined") || (window.__smartNav == null))
{
window.__smartNav = new Object();
window.__smartNav.update = function()
{
var sn = window.__smartNav;
var fd;
document.detachEvent("onstop", sn.stopHif);
sn.inPost = false;
try { fd = frames["__hifSmartNav"].document; } catch (e) {return;}
var fdr = fd.getElementsByTagName("asp_smartnav_rdir");
if (fdr.length > 0)
{
if ((typeof(sn.sHif) == "undefined") || (sn.sHif == null))
{
sn.sHif = document.createElement("IFRAME");
sn.sHif.name = "__hifSmartNav";
sn.sHif.style.display = "none";
sn.sHif.src = snSrc;
}
try {window.location = fdr[0].url;} catch (e) {};
return;
}
var fdurl = fd.location.href;
var index = fdurl.indexOf(snSrc);
if ((index != -1 && index == fdurl.length-snSrc.length)
|| fdurl == "about:blank")
return;
var fdurlb = fdurl.split("?")[0];
if (document.location.href.indexOf(fdurlb) < 0)
{
document.location.href=fdurl;
return;
}
sn._savedOnLoad = window.onload;
window.onload = null;
window.__smartNav.updateHelper();
}
window.__smartNav.updateHelper = function()
{
if (document.readyState != "complete")
{
window.setTimeout(window.__smartNav.updateHelper, 25);
return;
}
window.__smartNav.loadNewContent();
}
window.__smartNav.loadNewContent = function()
{
var sn = window.__smartNav;
var fd;
try { fd = frames["__hifSmartNav"].document; } catch (e) {return;}
if ((typeof(sn.sHif) != "undefined") && (sn.sHif != null))
{
sn.sHif.removeNode(true);
sn.sHif = null;
}
var hdm = document.getElementsByTagName("head")[0];
var hk = hdm.childNodes;
var tt = null;
var i;
for (i = hk.length - 1; i>= 0; i--)
{
if (hk[i].tagName == "TITLE")
{
tt = hk[i].outerHTML;
continue;
}
if (hk[i].tagName != "BASEFONT" || hk[i].innerHTML.length == 0)
hdm.removeChild(hdm.childNodes[i]);
}
var kids = fd.getElementsByTagName("head")[0].childNodes;
for (i = 0; i < kids.length; i++)
{
var tn = kids[i].tagName;
var k = document.createElement(tn);
k.id = kids[i].id;
k.mergeAttributes(kids[i]);
switch(tn)
{
case "TITLE":
if (tt == kids[i].outerHTML)
continue;
k.innerText = kids[i].text;
hdm.insertAdjacentElement("afterbegin", k);
continue;
case "BASEFONT" :
if (kids[i].innerHTML.length > 0)
continue;
break;
default:
var o = document.createElement("BODY");
o.innerHTML = "<BODY>" + kids[i].outerHTML + "</BODY>";
k = o.firstChild;
break;
}
if((typeof(k) != "undefined") && (k != null))
hdm.appendChild(k);
}
document.body.clearAttributes();
document.body.id = fd.body.id;
document.body.mergeAttributes(fd.body);
var newBodyLoad = fd.body.onload;
if ((typeof(newBodyLoad) != "undefined") && (newBodyLoad != null))
document.body.onload = newBodyLoad;
else
document.body.onload = sn._savedOnLoad;
var s = "<BODY>" + fd.body.innerHTML + "</BODY>";
if ((typeof(sn.hif) != "undefined") && (sn.hif != null))
{
var hifP = sn.hif.parentElement;
if ((typeof(hifP) != "undefined") && (hifP != null))
sn.sHif=hifP.removeChild(sn.hif);
}
document.body.innerHTML = s;
var sc = document.scripts;
for (i = 0; i < sc.length; i++)
{
sc[i].text = sc[i].text;
}
sn.hif = document.all("__hifSmartNav");
if ((typeof(sn.hif) != "undefined") && (sn.hif != null))
{
var hif = sn.hif;
sn.hifName = "__hifSmartNav" + (new Date()).getTime();
frames["__hifSmartNav"].name = sn.hifName;
sn.hifDoc = hif.contentWindow.document;
if (sn.ie5)
hif.parentElement.removeChild(hif);
window.setTimeout(sn.restoreFocus,0);
}
if (typeof(window.onload) == "string")
{
try { eval(window.onload) } catch (e) {};
}
else if ((typeof(window.onload) != "undefined") && (window.onload != null))
{
try { window.onload() } catch (e) {};
}
sn._savedOnLoad = null;
sn.attachForm();
};
window.__smartNav.restoreFocus = function()
{
if (window.__smartNav.inPost == true) return;
var curAe = document.activeElement;
var sAeId = window.__smartNav.ae;
if (((typeof(sAeId) == "undefined") || (sAeId == null)) ||
(typeof(curAe) != "undefined") && (curAe != null) && (curAe.id == sAeId || curAe.name == sAeId))
return;
var ae = document.all(sAeId);
if ((typeof(ae) == "undefined") || (ae == null)) return;
try { ae.focus(); } catch(e){};
}
window.__smartNav.saveHistory = function()
{
if ((typeof(window.__smartNav.hif) != "undefined") && (window.__smartNav.hif != null))
window.__smartNav.hif.removeNode();
if ((typeof(window.__smartNav.sHif) != "undefined") && (window.__smartNav.sHif != null)
&& (typeof(document.all[window.__smartNav.siHif]) != "undefined")
&& (document.all[window.__smartNav.siHif] != null)) {
document.all[window.__smartNav.siHif].insertAdjacentElement(
"BeforeBegin", window.__smartNav.sHif);
}
}
window.__smartNav.stopHif = function()
{
document.detachEvent("onstop", window.__smartNav.stopHif);
var sn = window.__smartNav;
if (((typeof(sn.hifDoc) == "undefined") || (sn.hifDoc == null)) &&
(typeof(sn.hif) != "undefined") && (sn.hif != null))
{
try {sn.hifDoc = sn.hif.contentWindow.document;}
catch(e){sn.hifDoc=null}
}
if (sn.hifDoc != null)
{
try {sn.hifDoc.execCommand("stop");} catch (e){}
}
}
window.__smartNav.init = function()
{
var sn = window.__smartNav;
window.__smartNav.form.__smartNavPostBack.value = 'true';
document.detachEvent("onstop", sn.stopHif);
document.attachEvent("onstop", sn.stopHif);
try { if (window.event.returnValue == false) return; } catch(e) {}
sn.inPost = true;
if ((typeof(document.activeElement) != "undefined") && (document.activeElement != null))
{
var ae = document.activeElement.id;
if (ae.length == 0)
ae = document.activeElement.name;
sn.ae = ae;
}
else
sn.ae = null;
try {document.selection.empty();} catch (e) {}
if ((typeof(sn.hif) == "undefined") || (sn.hif == null))
{
sn.hif = document.all("__hifSmartNav");
sn.hifDoc = sn.hif.contentWindow.document;
}
if ((typeof(sn.hifDoc) != "undefined") && (sn.hifDoc != null))
try {sn.hifDoc.designMode = "On";} catch(e){};
if ((typeof(sn.hif.parentElement) == "undefined") || (sn.hif.parentElement == null))
document.body.appendChild(sn.hif);
var hif = sn.hif;
hif.detachEvent("onload", sn.update);
hif.attachEvent("onload", sn.update);
window.__smartNav.fInit = true;
};
window.__smartNav.submit = function()
{
window.__smartNav.fInit = false;
try { window.__smartNav.init(); } catch(e) {}
if (window.__smartNav.fInit) {
window.__smartNav.form._submit();
}
};
window.__smartNav.attachForm = function()
{
var cf = document.forms;
for (var i=0; i<cf.length; i++)
{
if ((typeof(cf[i].__smartNavEnabled) != "undefined") && (cf[i].__smartNavEnabled != null))
{
window.__smartNav.form = cf[i];
window.__smartNav.form.insertAdjacentHTML("beforeEnd", "<input type='hidden' name='__smartNavPostBack' value='false' />");
break;
}
}
var snfm = window.__smartNav.form;
if ((typeof(snfm) == "undefined") || (snfm == null)) return false;
var sft = snfm.target;
if (sft.length != 0 && sft.indexOf("__hifSmartNav") != 0) return false;
var sfc = snfm.action.split("?")[0];
var url = window.location.href.split("?")[0];
if (url.charAt(url.length-1) != '/' && url.lastIndexOf(sfc) + sfc.length != url.length) return false;
if (snfm.__formAttached == true) return true;
snfm.__formAttached = true;
snfm.attachEvent("onsubmit", window.__smartNav.init);
snfm._submit = snfm.submit;
snfm.submit = window.__smartNav.submit;
snfm.target = window.__smartNav.hifName;
return true;
};
window.__smartNav.hifName = "__hifSmartNav" + (new Date()).getTime();
window.__smartNav.ie5 = navigator.appVersion.indexOf("MSIE 5") > 0;
var rc = window.__smartNav.attachForm();
var hif = document.all("__hifSmartNav");
if ((typeof(snSrc) == "undefined") || (snSrc == null)) {
if (typeof(window.dialogHeight) != "undefined") {
snSrc = "IEsmartnav1";
hif.src = snSrc;
} else {
snSrc = hif.src;
}
}
if (rc)
{
var fsn = frames["__hifSmartNav"];
fsn.name = window.__smartNav.hifName;
window.__smartNav.siHif = hif.sourceIndex;
try {
if (fsn.document.location != snSrc)
{
fsn.document.designMode = "On";
hif.attachEvent("onload",window.__smartNav.update);
window.__smartNav.hif = hif;
}
}
catch (e) { window.__smartNav.hif = hif; }
window.attachEvent("onbeforeunload", window.__smartNav.saveHistory);
}
else
window.__smartNav = null;
}
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.