code
stringlengths
1
2.08M
language
stringclasses
1 value
var autoDelete = function(){}; autoDelete.url = W_AJAX + 'common/delete/'; // URL для удаления поля autoDelete.manyUrl = W_AJAX + 'common/delete_by_ids/'; // URL для удаления поля // Иньциализация удаления autoDelete.init = function() { $('.autoDelete').live('click', function() { if (confirm("Уверены, что хотите удалить?")) { autoDelete.remove(this); } }); // autoDeleteWithCheck $('.adwc').live('click', function() { autoDelete.removeWithCheck(this); }); }; // Отправка запроса на удаление элемента с проверкой autoDelete.removeWithCheck = function(elem) { var args = arguments; $.post(autoDelete.url, { essenceType: $(elem).attr('essenceType'), essenceId: $(elem).attr('essenceId') }, function(data) { if (data['result'] == 'OK') { if (data['confirm_text']) { if (confirm(data['confirm_text'] + "\nУверены, что хотите удалить?")) { autoDelete.remove.apply(this, args); } } else { autoDelete.afterRemove(elem); } } else alert(data['error']); }, 'json'); }; // Отправка запроса на удаление элемента /**************************************/ /** autoDelete.remove([elem,] options) /** elem - первый аргумент, являющейся jQuery или DOM объектом(массивом) удаляемого(ых) элемента(ов). /** options - boolean - skipAfterRemove ? /** options - object /*********** parameters /*********** skipAfterRemove /**************************************/ autoDelete.remove = function(elem) { if(typeof elem == "undefined") return false; if(!(elem instanceof $) && !(elem instanceof HTMLElement)) arguments[1] = elem; var skipAfterRemove = typeof arguments[1] == 'boolean' ? arguments[1] : false, options = typeof arguments[1] == 'object' ? arguments[1] : {}, params = {essenceType: $(elem).attr('essencetype')}; if($(elem).length > 1){ params.essenceIds = '[' + $(elem).map(function(){ return "\"" + $(this).attr('essenceid') + "\"" }).get() + ']'; var url = autoDelete.manyUrl; }else{ params.essenceId = $(elem).attr('essenceid') var url = autoDelete.url; } params = $.extend(params, options.parameters); $.post(url, params, function(data) { if (data['result'] == 'OK') { if (data['confirm_text']) { data['confirm_text'] += "\nУверены, что хотите удалить?"; App.confirm(data['confirm_text'], function(){ $.post(autoDelete.url, $.extend(params, {needCheck: 0}), function(objData){ console.log(1); if ( !(skipAfterRemove || options.skipAfterRemove) ) {console.log(2);autoDelete.afterRemove(elem);} if(options.callback) {console.log(3);options.callback.call();} }, 'json'); }); //} } else { if ( !(skipAfterRemove || options.skipAfterRemove) ) autoDelete.afterRemove(elem); if(options.callback) options.callback.call(); } } else alert(data['error']); }, 'json'); }; autoDelete.afterRemove = function(elem) { // Действия после удаления if ($(elem).is('.autoDeleteBlock')) $(elem).remove(); else if ($(elem).parents('.autoDeleteBlock').length) $(elem).parents('.autoDeleteBlock:first').remove(); else if ($(elem).closest('.popups > li').length) $(elem).closePopup(); else $(elem).remove(); //eip.updateList(elem).remove(); }; $().ready(function() { autoDelete.init(); });
JavaScript
/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * See http://kelvinluck.com/assets/jquery/jScrollPane/ * $Id: jScrollPane.js 90 2010-01-25 03:52:10Z kelvin.luck $ */ /** * Replace the vertical scroll bars on any matched elements with a fancy * styleable (via CSS) version. With JS disabled the elements will * gracefully degrade to the browsers own implementation of overflow:auto. * If the mousewheel plugin has been included on the page then the scrollable areas will also * respond to the mouse wheel. * * @example jQuery(".scroll-pane").jScrollPane(); * * @name jScrollPane * @type jQuery * @param Object settings hash with options, described below. * scrollbarWidth - The width of the generated scrollbar in pixels * scrollbarMargin - The amount of space to leave on the side of the scrollbar in pixels * wheelSpeed - The speed the pane will scroll in response to the mouse wheel in pixels * showArrows - Whether to display arrows for the user to scroll with * arrowSize - The height of the arrow buttons if showArrows=true * animateTo - Whether to animate when calling scrollTo and scrollBy * dragMinHeight - The minimum height to allow the drag bar to be * dragMaxHeight - The maximum height to allow the drag bar to be * animateInterval - The interval in milliseconds to update an animating scrollPane (default 100) * animateStep - The amount to divide the remaining scroll distance by when animating (default 3) * maintainPosition- Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true) * tabIndex - The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0) * enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true) * animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false) * scrollbarOnLeft - Display the scrollbar on the left side? (needs stylesheet changes, see examples.html) * reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false) * topCapHeight - The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons * bottomCapHeight - The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons * observeHash - Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true) * @return jQuery * @cat Plugins/jScrollPane * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com) */ (function($) { $.jScrollPane = { active : [] }; $.fn.jScrollPane = function(settings) { settings = $.extend({}, $.fn.jScrollPane.defaults, settings); var rf = function() { return false; }; return this.each( function() { var $this = $(this); var paneEle = this; var currentScrollPosition = 0; var paneWidth; var paneHeight; var trackHeight; var trackOffset = settings.topCapHeight; var $container; if ($(this).parent().is('.jScrollPaneContainer')) { $container = $(this).parent(); currentScrollPosition = settings.maintainPosition ? $this.position().top : 0; var $c = $(this).parent(); paneWidth = $c.innerWidth(); paneHeight = $c.outerHeight(); $('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove(); $this.css({'top':0}); } else { $this.data('originalStyleTag', $this.attr('style')); // Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208] $this.css('overflow', 'hidden'); this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft'); this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0); paneWidth = $this.innerWidth(); paneHeight = $this.innerHeight(); $container = $('<div></div>') .attr({'className':'jScrollPaneContainer'}) .css( { 'height':paneHeight+'px', 'width':paneWidth+'px' } ); if (settings.enableKeyboardNavigation) { $container.attr( 'tabindex', settings.tabIndex ); } $this.wrap($container); $container = $this.parent(); // deal with text size changes (if the jquery.em plugin is included) // and re-initialise the scrollPane so the track maintains the // correct size $(document).bind( 'emchange', function(e, cur, prev) { $this.jScrollPane(settings); } ); } trackHeight = paneHeight; if (settings.reinitialiseOnImageLoad) { // code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad // except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size... // TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise? var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this); var loadedImages = []; if ($imagesToLoad.length) { $imagesToLoad.each(function(i, val) { $(this).bind('load readystatechange', function() { if($.inArray(i, loadedImages) == -1){ //don't double count images loadedImages.push(val); //keep a record of images we've seen $imagesToLoad = $.grep($imagesToLoad, function(n, i) { return n != val; }); $.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad); var s2 = $.extend(settings, {reinitialiseOnImageLoad:false}); $this.jScrollPane(s2); // re-initialise } }).each(function(i, val) { if(this.complete || this.complete===undefined) { //needed for potential cached images this.src = this.src; } }); }); }; } var p = this.originalSidePaddingTotal; var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p; var cssToApply = { 'height':'auto', 'width': realPaneWidth + 'px' }; if(settings.scrollbarOnLeft) { cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px'; } else { cssToApply.paddingRight = settings.scrollbarMargin + 'px'; } $this.css(cssToApply); var contentHeight = $this.outerHeight(); var percentInView = paneHeight / contentHeight; var isScrollable = percentInView < .99; $container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable'); if (isScrollable) { $container.append( $('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}), $('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append( $('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append( $('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}), $('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'}) ) ), $('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight}) ); var $track = $('>.jScrollPaneTrack', $container); var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container); var currentArrowDirection; var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug. var currentArrowInc; var whileArrowButtonDown = function() { if (currentArrowInc > 4 || currentArrowInc % 4 == 0) { positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier); } currentArrowInc++; }; if (settings.enableKeyboardNavigation) { $container.bind( 'keydown.jscrollpane', function(e) { switch (e.keyCode) { case 38: //up currentArrowDirection = -1; currentArrowInc = 0; whileArrowButtonDown(); currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100); return false; case 40: //down currentArrowDirection = 1; currentArrowInc = 0; whileArrowButtonDown(); currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100); return false; case 33: // page up case 34: // page down // TODO return false; default: } } ).bind( 'keyup.jscrollpane', function(e) { if (e.keyCode == 38 || e.keyCode == 40) { for (var i = 0; i < currentArrowTimerArr.length; i++) { clearInterval(currentArrowTimerArr[i]); } return false; } } ); } if (settings.showArrows) { var currentArrowButton; var currentArrowInterval; var onArrowMouseUp = function(event) { $('html').unbind('mouseup', onArrowMouseUp); currentArrowButton.removeClass('jScrollActiveArrowButton'); clearInterval(currentArrowInterval); }; var onArrowMouseDown = function() { $('html').bind('mouseup', onArrowMouseUp); currentArrowButton.addClass('jScrollActiveArrowButton'); currentArrowInc = 0; whileArrowButtonDown(); currentArrowInterval = setInterval(whileArrowButtonDown, 100); }; $container .append( $('<a></a>') .attr( { 'href':'javascript:;', 'className':'jScrollArrowUp', 'tabindex':-1 } ) .css( { 'width':settings.scrollbarWidth+'px', 'top':settings.topCapHeight + 'px' } ) .html('Scroll up') .bind('mousedown', function() { currentArrowButton = $(this); currentArrowDirection = -1; onArrowMouseDown(); this.blur(); return false; }) .bind('click', rf), $('<a></a>') .attr( { 'href':'javascript:;', 'className':'jScrollArrowDown', 'tabindex':-1 } ) .css( { 'width':settings.scrollbarWidth+'px', 'bottom':settings.bottomCapHeight + 'px' } ) .html('Scroll down') .bind('mousedown', function() { currentArrowButton = $(this); currentArrowDirection = 1; onArrowMouseDown(); this.blur(); return false; }) .bind('click', rf) ); var $upArrow = $('>.jScrollArrowUp', $container); var $downArrow = $('>.jScrollArrowDown', $container); } if (settings.arrowSize) { trackHeight = paneHeight - settings.arrowSize - settings.arrowSize; trackOffset += settings.arrowSize; } else if ($upArrow) { var topArrowHeight = $upArrow.height(); settings.arrowSize = topArrowHeight; trackHeight = paneHeight - topArrowHeight - $downArrow.height(); trackOffset += topArrowHeight; } trackHeight -= settings.topCapHeight + settings.bottomCapHeight; $track.css({'height': trackHeight+'px', top:trackOffset+'px'}); var $pane = $(this).css({'position':'absolute', 'overflow':'visible'}); var currentOffset; var maxY; var mouseWheelMultiplier; // store this in a seperate variable so we can keep track more accurately than just updating the css property.. var dragPosition = 0; var dragMiddle = percentInView*paneHeight/2; // pos function borrowed from tooltip plugin and adapted... var getPos = function (event, c) { var p = c == 'X' ? 'Left' : 'Top'; return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0; }; var ignoreNativeDrag = function() { return false; }; var initDrag = function() { ceaseAnimation(); currentOffset = $drag.offset(false); currentOffset.top -= dragPosition; maxY = trackHeight - $drag[0].offsetHeight; mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight; }; var onStartDrag = function(event) { initDrag(); dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top; $('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll); if ($.browser.msie) { $('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag); } return false; }; var onStopDrag = function() { $('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll); dragMiddle = percentInView*paneHeight/2; if ($.browser.msie) { $('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag); } }; var positionDrag = function(destY) { $container.scrollTop(0); destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY); dragPosition = destY; $drag.css({'top':destY+'px'}); var p = destY / maxY; $this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p); $pane.css({'top':((paneHeight-contentHeight)*p) + 'px'}); $this.trigger('scroll'); if (settings.showArrows) { $upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled'); $downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled'); } }; var updateScroll = function(e) { positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle); }; var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight); $drag.css( {'height':dragH+'px'} ).bind('mousedown', onStartDrag); var trackScrollInterval; var trackScrollInc; var trackScrollMousePos; var doTrackScroll = function() { if (trackScrollInc > 8 || trackScrollInc%4==0) { positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2))); } trackScrollInc ++; }; var onStopTrackClick = function() { clearInterval(trackScrollInterval); $('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove); }; var onTrackMouseMove = function(event) { trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle; }; var onTrackClick = function(event) { initDrag(); onTrackMouseMove(event); trackScrollInc = 0; $('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove); trackScrollInterval = setInterval(doTrackScroll, 100); doTrackScroll(); return false; }; $track.bind('mousedown', onTrackClick); $container.bind( 'mousewheel', function (event, delta) { delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ? -event.detail/3 : 0); initDrag(); ceaseAnimation(); var d = dragPosition; positionDrag(dragPosition - delta * mouseWheelMultiplier); var dragOccured = d != dragPosition; return !dragOccured; } ); var _animateToPosition; var _animateToInterval; function animateToPosition() { var diff = (_animateToPosition - dragPosition) / settings.animateStep; if (diff > 1 || diff < -1) { positionDrag(dragPosition + diff); } else { positionDrag(_animateToPosition); ceaseAnimation(); } } var ceaseAnimation = function() { if (_animateToInterval) { clearInterval(_animateToInterval); delete _animateToPosition; } }; var scrollTo = function(pos, preventAni) { if (typeof pos == "string") { // Legal hash values aren't necessarily legal jQuery selectors so we need to catch any // errors from the lookup... try { $e = $(pos, $this); } catch (err) { return; } if (!$e.length) return; pos = $e.offset().top - $this.offset().top; } ceaseAnimation(); var maxScroll = contentHeight - paneHeight; pos = pos > maxScroll ? maxScroll : pos; $this.data('jScrollPaneMaxScroll', maxScroll); var destDragPosition = pos/maxScroll * maxY; if (preventAni || !settings.animateTo) { positionDrag(destDragPosition); } else { $container.scrollTop(0); _animateToPosition = destDragPosition; _animateToInterval = setInterval(animateToPosition, settings.animateInterval); } }; $this[0].scrollTo = scrollTo; $this[0].scrollBy = function(delta) { var currentPos = -parseInt($pane.css('top')) || 0; scrollTo(currentPos + delta); }; initDrag(); scrollTo(-currentScrollPosition, true); // Deal with it when the user tabs to a link or form element within this scrollpane $('*', this).bind( 'focus', function(event) { var $e = $(this); // loop through parents adding the offset top of any elements that are relatively positioned between // the focused element and the jScrollPaneContainer so we can get the true distance from the top // of the focused element to the top of the scrollpane... var eleTop = 0; while ($e[0] != $this[0]) { eleTop += $e.position().top; $e = $e.offsetParent(); } var viewportTop = -parseInt($pane.css('top')) || 0; var maxVisibleEleTop = viewportTop + paneHeight; var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop; if (!eleInView) { var destPos = eleTop - settings.scrollbarMargin; if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom. destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight; } scrollTo(destPos); } } ); if (settings.observeHash) { if (location.hash && location.hash.length > 1) { setTimeout(function(){ scrollTo(location.hash); }, $.browser.safari ? 100 : 0); } // use event delegation to listen for all clicks on links and hijack them if they are links to // anchors within our content... $(document).bind('click', function(e){ $target = $(e.target); if ($target.is('a')) { var h = $target.attr('href'); if (h && h.substr(0, 1) == '#' && h.length > 1) { setTimeout(function(){ scrollTo(h, !settings.animateToInternalLinks); }, $.browser.safari ? 100 : 0); } } }); } // Deal with dragging and selecting text to make the scrollpane scroll... function onSelectScrollMouseDown(e) { $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove); $(document).bind('mouseup.jScrollPaneDragging', onSelectScrollMouseUp); } var textDragDistanceAway; var textSelectionInterval; function onTextSelectionInterval() { direction = textDragDistanceAway < 0 ? -1 : 1; $this[0].scrollBy(textDragDistanceAway / 2); } function clearTextSelectionInterval() { if (textSelectionInterval) { clearInterval(textSelectionInterval); textSelectionInterval = undefined; } } function onTextSelectionScrollMouseMove(e) { var offset = $this.parent().offset().top; var maxOffset = offset + paneHeight; var mouseOffset = getPos(e, 'Y'); textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0); if (textDragDistanceAway == 0) { clearTextSelectionInterval(); } else { if (!textSelectionInterval) { textSelectionInterval = setInterval(onTextSelectionInterval, 100); } } } function onSelectScrollMouseUp(e) { $(document) .unbind('mousemove.jScrollPaneDragging') .unbind('mouseup.jScrollPaneDragging'); clearTextSelectionInterval(); } $container.bind('mousedown.jScrollPane', onSelectScrollMouseDown); $.jScrollPane.active.push($this[0]); } else { $this.css( { 'height':paneHeight+'px', 'width':paneWidth-this.originalSidePaddingTotal+'px', 'padding':this.originalPadding } ); $this[0].scrollTo = $this[0].scrollBy = function() {}; // clean up listeners $this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane'); } } ); }; $.fn.jScrollPaneRemove = function() { $(this).each(function() { $this = $(this); var $c = $this.parent(); if ($c.is('.jScrollPaneContainer')) { $this.css( { 'top':'', 'height':'', 'width':'', 'padding':'', 'overflow':'', 'position':'' } ); $this.attr('style', $this.data('originalStyleTag')); $c.after($this).remove(); } }); }; $.fn.jScrollPane.defaults = { scrollbarWidth : 10, scrollbarMargin : 5, wheelSpeed : 18, showArrows : false, arrowSize : 0, animateTo : false, dragMinHeight : 1, dragMaxHeight : 99999, animateInterval : 100, animateStep: 3, maintainPosition: true, scrollbarOnLeft: false, reinitialiseOnImageLoad: false, tabIndex : 0, enableKeyboardNavigation: true, animateToInternalLinks: false, topCapHeight: 0, bottomCapHeight: 0, observeHash: true }; // clean up the scrollTo expandos $(window) .bind('unload', function() { var els = $.jScrollPane.active; for (var i=0; i<els.length; i++) { els[i].scrollTo = els[i].scrollBy = null; } } ); })(jQuery);
JavaScript
/* * jQuery UI Datepicker @VERSION * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Datepicker * * Depends: * ui.core.js */ (function($) { // hide the namespace $.extend($.ui, { datepicker: { version: "@VERSION" } }); var PROP_NAME = 'datepicker'; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday dateFormat: 'mm/dd/yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this.debug = false; // Change this to true to start debugging this._nextId = 0; // Next ID for a date picker instance this._inst = []; // List of instances indexed by ID this._curInst = null; // The current instance in use this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings clearText: 'Очистить', // Display text for clear link clearStatus: 'Стереть текущую дату', // Status text for clear link closeText: 'Закрыть', // Display text for close link closeStatus: 'Закрыть без сохранения', // Status text for close link prevText: '&#x3c;Пред', // Display text for previous month link prevStatus: 'Предыдущий месяц', // Status text for previous month link nextText: 'След&#x3e;', // Display text for next month link nextStatus: 'Следующий месяц', // Status text for next month link currentText: 'Сегодня', // Display text for current month link currentStatus: 'Текущий месяц', // Status text for current month link monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь', 'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'], // Names of months for drop-down and formatting monthNamesShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'], // For formatting monthStatus: 'Показать другой месяц', // Status text for selecting a month yearStatus: 'Показать другой год', // Status text for selecting a year weekHeader: 'Нед', // Header for the week of the year column weekStatus: 'Неделя года', // Status text for the week of the year column dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], // For formatting dayNamesShort: ['Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'], // For formatting dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'], // Column headings for days starting at Sunday dayStatus: 'Установить первым днем недели', // Status text for the day of the week selection dateStatus: 'Выбрать день, месяц, год', // Status text for the date selection dateFormat: 'dd.mm.yy', // See format options on parseDate firstDay: 1, // The first day of the week, Sun = 0, Mon = 1, ... initStatus: 'Выбрать дату', // Initial Status text on opening isRTL: false, // True if right-to-left language, false if left-to-right yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'show', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: '-10:+10', // Range of years to display in drop-down, // either relative to current year (-nn:+nn) or absolute (nnnn:nnnn) showOtherMonths: false, // True to show dates in other months, false to leave blank calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'normal', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false // True to show button panel, false to not show it }; $.extend(this._defaults, this.regional['']); this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>'); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) target.id = 'dp' + (++this.uuid); var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div $('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target) $.datepicker._hideDatepicker(); else $.datepicker._showDatepicker(target); return false; }); } input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); $.data(target, PROP_NAME, inst); }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst)); this._updateDatepicker(inst); this._updateAlternate(inst); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param dateText string - the initial date to display (in the current format) @param onSelect function - the function(dateText) to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, dateText, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { var id = 'dp' + (++this.uuid); this._dialogInput = $('<input type="text" id="' + id + '" size="1" style="position: absolute; top: -100px;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); this._dialogInput.val(dateText); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(null); } var date = this._getDateDatepicker(target); extendRemove(inst.settings, settings); this._setDateDatepicker(target, date); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @return Date - the current date */ _getDateDatepicker: function(target) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(null, ''); break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass + ', td.' + $.datepicker._currentClass, inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); else $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration')); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration')); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (event) { $.datepicker.log(event); } return true; }, /* Pop-up the date picker for a given input field. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); var beforeShow = $.datepicker._get(inst, 'beforeShow'); extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {})); $.datepicker._hideDatepicker(null, ''); $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim') || 'show'; var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { $.datepicker._datepickerShowing = true; var borders = $.datepicker._getBorders(inst.dpDiv); inst.dpDiv.find('iframe.ui-datepicker-cover'). // IE6- only css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); }; if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim](duration, postProcess); if (duration == '') postProcess(); if (inst.input[0].type != 'hidden') inst.input[0].focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { var self = this; var borders = $.datepicker._getBorders(inst.dpDiv); inst.dpDiv.empty().append(this._generateHTML(inst)) .find('iframe.ui-datepicker-cover') // IE6- only .css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) .end() .find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a') .bind('mouseout', function(){ $(this).removeClass('ui-state-hover'); if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover'); }) .bind('mouseover', function(){ if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) { $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); $(this).addClass('ui-state-hover'); if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover'); } }) .end() .find('.' + this._dayOverClass + ' a') .trigger('mouseover') .end(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); else inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst) $(inst.input[0]).focus(); }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft(); var viewHeight = document.documentElement.clientHeight + $(document).scrollTop(); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0; offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0; return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) { obj = obj.nextSibling; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker @param duration string - the duration over which to close the date picker */ _hideDatepicker: function(input, duration) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { duration = (duration != null ? duration : this._get(inst, 'duration')); var showAnim = this._get(inst, 'showAnim'); var postProcess = function() { $.datepicker._tidyDialog(inst); }; if (duration != '' && $.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess); if (duration == '') this._tidyDialog(inst); var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback this._datepickerShowing = false; this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } this._curInst = null; }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target); if (($target.parents('#' + $.datepicker._mainDivId).length == 0) && !$target.hasClass($.datepicker.markerClassName) && !$target.hasClass($.datepicker._triggerClass) && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI)) $.datepicker._hideDatepicker(null, ''); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst._selectingMonthYear = false; inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Restore input focus after not changing month/year. */ _clickMonthYear: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (inst.input && inst._selectingMonthYear && !$.browser.msie) inst.input[0].focus(); inst._selectingMonthYear = !inst._selectingMonthYear; }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(null, this._get(inst, 'duration')); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input[0].focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = (lookAhead(match) ? longNames : shortNames); for (var i = 0; i < names.length; i++) { if (value.substr(iValue, names[i].length) == names[i]) { iValue += names[i].length; return i + 1; } } throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/* return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', (date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000, 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst) { var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.input ? inst.input.val() : null; var date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); date = defaultDate; } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset, getDaysInMonth) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; date = (date == null ? defaultDate : (typeof date == 'string' ? offsetString(date, this._getDaysInMonth) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date))); date = (date && date.toString() == 'Invalid Date' ? defaultDate : date); if (date) { date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } return this._daylightSavingAdjust(date); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date) { var clear = !(date); var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; date = this._restrictMinMax(inst, this._determineDate(date, new Date())); inst.selectedDay = inst.currentDay = date.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear(); if (origMonth != inst.selectedMonth || origYear != inst.selectedYear) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group ui-datepicker-group-'; switch (col) { case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += 'middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = ''; for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = ''; for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = otherMonth || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' + inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions (otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> '; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" ' + 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' + 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : ''); // year selection if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var year = 0; var endYear = 0; if (years.length != 2) { year = drawYear - 10; endYear = drawYear + 10; } else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') { year = drawYear + parseInt(years[0], 10); endYear = drawYear + parseInt(years[1], 10); } else { year = parseInt(years[0], 10); endYear = parseInt(years[1], 10); } year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); html += '<select class="ui-datepicker-year" ' + 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' + 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (; year <= endYear; year++) { html += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } html += '</select>'; } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); return date; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - new Date(year, month, 32).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date( curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('#top').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "@VERSION"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window.DP_jQuery = $; })(jQuery);
JavaScript
/* * jQuery UI Datepicker @VERSION * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Datepicker * * Depends: * ui.core.js */ (function($) { // hide the namespace $.extend($.ui, { datepicker: { version: "@VERSION" } }); var PROP_NAME = 'datepicker'; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code /* this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday dateFormat: 'dd.mm.yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers };*/ this.debug = false; // Change this to true to start debugging this._nextId = 0; // Next ID for a date picker instance this._inst = []; // List of instances indexed by ID this._curInst = null; // The current instance in use this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings clearText: 'Очистить', // Display text for clear link clearStatus: 'Стереть текущую дату', // Status text for clear link closeText: 'Закрыть', // Display text for close link closeStatus: 'Закрыть без сохранения', // Status text for close link prevText: '&#x3c;Пред', // Display text for previous month link prevStatus: 'Предыдущий месяц', // Status text for previous month link nextText: 'След&#x3e;', // Display text for next month link nextStatus: 'Следующий месяц', // Status text for next month link currentText: 'Сегодня', // Display text for current month link currentStatus: 'Текущий месяц', // Status text for current month link monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь', 'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'], // Names of months for drop-down and formatting monthNamesShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'], // For formatting monthStatus: 'Показать другой месяц', // Status text for selecting a month yearStatus: 'Показать другой год', // Status text for selecting a year weekHeader: 'Нед', // Header for the week of the year column weekStatus: 'Неделя года', // Status text for the week of the year column dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], // For formatting dayNamesShort: ['Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'], // For formatting dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'], // Column headings for days starting at Sunday dayStatus: 'Установить первым днем недели', // Status text for the day of the week selection dateStatus: 'Выбрать день, месяц, год', // Status text for the date selection dateFormat: 'dd.mm.yy', // See format options on parseDate firstDay: 1, // The first day of the week, Sun = 0, Mon = 1, ... initStatus: 'Выбрать дату', // Initial Status text on opening isRTL: false, // True if right-to-left language, false if left-to-right yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'show', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: '-10:+10', // Range of years to display in drop-down, // either relative to current year (-nn:+nn) or absolute (nnnn:nnnn) showOtherMonths: false, // True to show dates in other months, false to leave blank calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'normal', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false // True to show button panel, false to not show it }; $.extend(this._defaults, this.regional['']); this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>'); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) target.id = 'dp' + (++this.uuid); var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div $('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (appendText) { inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); input[isRTL ? 'before' : 'after'](inst.append); } var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass). html(buttonImage == '' ? buttonText : $('<img/>').attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target) $.datepicker._hideDatepicker(); else $.datepicker._showDatepicker(target); return false; }); } input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); $.data(target, PROP_NAME, inst); }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst)); this._updateDatepicker(inst); this._updateAlternate(inst); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param dateText string - the initial date to display (in the current format) @param onSelect function - the function(dateText) to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, dateText, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance if (!inst) { var id = 'dp' + (++this.uuid); this._dialogInput = $('<input type="text" id="' + id + '" size="1" style="position: absolute; top: -100px;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); this._dialogInput.val(dateText); /* this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } */ if (!this._pos) { var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind('focus', this._showDatepicker). unbind('keydown', this._doKeyDown). unbind('keypress', this._doKeyPress). unbind('keyup', this._doKeyUp); } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter('button'). each(function() { this.disabled = false; }).end(). filter('img').css({opacity: '1.0', cursor: ''}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled'); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter('button'). each(function() { this.disabled = true; }).end(). filter('img').css({opacity: '0.5', cursor: 'default'}); } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled'); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true; } return false; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var inst = this._getInst(target); if (arguments.length == 2 && typeof name == 'string') { return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : (inst ? (name == 'all' ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(null); } var date = this._getDateDatepicker(target); extendRemove(inst.settings, settings); this._setDateDatepicker(target, date); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @return Date - the current date */ _getDateDatepicker: function(target) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(null, ''); break; // hide on tab out case 13: var sel = $('td.' + $.datepicker._dayOverClass + ', td.' + $.datepicker._currentClass, inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); else $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration')); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration')); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var inst = $.datepicker._getInst(event.target); try { var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (event) { $.datepicker.log(event); } return true; }, /* Pop-up the date picker for a given input field. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here return; var inst = $.datepicker._getInst(input); var beforeShow = $.datepicker._get(inst, 'beforeShow'); extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {})); $.datepicker._hideDatepicker(null, ''); $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop; } var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px'}); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim') || 'show'; var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { $.datepicker._datepickerShowing = true; var borders = $.datepicker._getBorders(inst.dpDiv); inst.dpDiv.find('iframe.ui-datepicker-cover'). // IE6- only css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); $(input).select(); }; if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim](duration, postProcess); if (duration == '') postProcess(); if (inst.input[0].type != 'hidden') inst.input[0].focus(); $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { var self = this; var borders = $.datepicker._getBorders(inst.dpDiv); inst.dpDiv.empty().append(this._generateHTML(inst)) .find('iframe.ui-datepicker-cover') // IE6- only .css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) .end() .find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a') .bind('mouseout', function(){ $(this).removeClass('ui-state-hover'); if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover'); }) .bind('mouseover', function(){ if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) { $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); $(this).addClass('ui-state-hover'); if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover'); } }) .end() .find('.' + this._dayOverClass + ' a') .trigger('mouseover') .end(); //$('body').append(inst.dpDiv); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; if (cols > 1) inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); else inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst) $(inst.input[0]).focus(); }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft(); var viewHeight = document.documentElement.clientHeight + $(document).scrollTop(); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0; if (!$.browser.msie) offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0; return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) { obj = obj.nextSibling; } var position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker @param duration string - the duration over which to close the date picker */ _hideDatepicker: function(input, duration) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { duration = (duration != null ? duration : this._get(inst, 'duration')); var showAnim = this._get(inst, 'showAnim'); var postProcess = function() { $.datepicker._tidyDialog(inst); }; if (duration != '' && $.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else if ($.browser.msie) inst.dpDiv.fadeOut("normal"); else inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess); if (duration == '') this._tidyDialog(inst); var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback this._datepickerShowing = false; this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv); } } this._inDialog = false; } this._curInst = null; }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target); if (($target.parents('#' + $.datepicker._mainDivId).length == 0) && !$target.hasClass($.datepicker.markerClassName) && !$target.hasClass($.datepicker._triggerClass) && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI)) $.datepicker._hideDatepicker(null, ''); }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst._selectingMonthYear = false; inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Restore input focus after not changing month/year. */ _clickMonthYear: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (inst.input && inst._selectingMonthYear && !$.browser.msie) inst.input[0].focus(); inst._selectingMonthYear = !inst._selectingMonthYear; }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(null, this._get(inst, 'duration')); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input[0].focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value var getNumber = function(match) { lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) throw 'Missing number at position ' + iValue; iValue += num[0].length; return parseInt(num[0], 10); }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = (lookAhead(match) ? longNames : shortNames); for (var i = 0; i < names.length; i++) { if (value.substr(iValue, names[i].length) == names[i]) { iValue += names[i].length; return i + 1; } } throw 'Unknown name at position ' + iValue; }; // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral(); } } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; // E.g. 31/02/* return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': output += formatNumber('o', (date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000, 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case '!': output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat); } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst) { var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.input ? inst.input.val() : null; var date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(event); date = defaultDate; } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }; var offsetString = function(offset, getDaysInMonth) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }; date = (date == null ? defaultDate : (typeof date == 'string' ? offsetString(date, this._getDaysInMonth) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date))); date = (date && date.toString() == 'Invalid Date' ? defaultDate : date); if (date) { date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } return this._daylightSavingAdjust(date); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date) { var clear = !(date); var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; date = this._restrictMinMax(inst, this._determineDate(date, new Date())); inst.selectedDay = inst.currentDay = date.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear(); if (origMonth != inst.selectedMonth || origYear != inst.selectedYear) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group ui-datepicker-group-'; switch (col) { case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += 'middle'; cornerClass = ''; break; } calender += '">'; } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = ''; for (var dow = 0; dow < 7; dow++) { // days of the week var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = ''; for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = otherMonth || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' + inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions (otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + '</tr>'; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender; } html += group; } html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> '; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" ' + 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' + 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>'; } monthHtml += '</select>'; } if (!showMonthAfterYear) html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : ''); // year selection if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display var years = this._get(inst, 'yearRange').split(':'); var year = 0; var endYear = 0; if (years.length != 2) { year = drawYear - 10; endYear = drawYear + 10; } else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') { year = drawYear + parseInt(years[0], 10); endYear = drawYear + parseInt(years[1], 10); } else { year = parseInt(years[0], 10); endYear = parseInt(years[1], 10); } year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); html += '<select class="ui-datepicker-year" ' + 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' + 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (; year <= endYear; year++) { html += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>'; } html += '</select>'; } html += this._get(inst, 'yearSuffix'); if (showMonthAfterYear) html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml; html += '</div>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); return date; }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - new Date(year, month, 32).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date( curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); } }); /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; /* Determine whether an object is an array. */ function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find('#top').append($.datepicker.dpDiv); $.datepicker.initialized = true; } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate')) return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') return $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker']. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "@VERSION"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window.DP_jQuery = $; })(jQuery);
JavaScript
/** * Ajax Autocomplete for jQuery, version 1.1.3 * (c) 2010 Tomas Kirda * * Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license. * For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/ * * Last Review: 04/19/2010 */ /*jslint onevar: true, evil: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */ /*global window: true, document: true, clearInterval: true, setInterval: true, jQuery: true */ (function($) { var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g'); function fnFormatResult(value, data, currentValue) { var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')'; return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>'); } function Autocomplete(el, options) { this.el = $(el); this.el.attr('autocomplete', 'off'); this.suggestions = []; this.data = []; this.counts = []; this.badQueries = []; this.selectedIndex = -1; this.currentValue = this.el.val(); this.intervalId = 0; this.cachedResponse = []; this.onChangeInterval = null; this.ignoreValueChange = false; this.serviceUrl = options.serviceUrl; this.isLocal = false; this.options = { autoSubmit: false, minChars: 1, maxHeight: 300, deferRequestBy: 0, width: 255, highlight: true, params: {}, fnFormatResult: fnFormatResult, delimiter: null, zIndex: 9999 }; this.initialize(); this.setOptions(options); } $.fn.autocomplete = function(options) { return new Autocomplete(this.get(0)||$('<input />'), options); }; Autocomplete.prototype = { killerFn: null, initialize: function() { var me, uid, autocompleteElId; me = this; uid = Math.floor(Math.random()*0x100000).toString(16); autocompleteElId = 'Autocomplete_' + uid; this.killerFn = function(e) { if ($(e.target).parents('.autocomplete').size() === 0) { me.killSuggestions(); me.disableKillerFn(); } }; if (!this.options.width) { this.options.width = this.el.width(); } this.mainContainerId = 'AutocompleteContainter_' + uid; $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body'); this.container = $('#' + autocompleteElId); this.fixPosition(); if (window.opera) { this.el.keypress(function(e) { me.onKeyPress(e); }); } else { this.el.keydown(function(e) { me.onKeyPress(e); }); } this.el.keyup(function(e) { me.onKeyUp(e); }); this.el.blur(function() { me.enableKillerFn(); }); this.el.focus(function() { me.fixPosition(); }); }, setOptions: function(options){ var o = this.options; $.extend(o, options); if(o.lookup){ this.isLocal = true; if($.isArray(o.lookup)){ o.lookup = { suggestions:o.lookup, data:[], counts:[] }; } } $('#'+this.mainContainerId).css({ zIndex:o.zIndex }); this.container.css({ maxHeight: o.maxHeight + 'px', width:o.width }); }, clearCache: function(){ this.cachedResponse = []; this.badQueries = []; }, disable: function(){ this.disabled = true; }, enable: function(){ this.disabled = false; }, fixPosition: function() { var offset = this.el.offset(); $('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + 'px', left: offset.left + 'px' }); }, enableKillerFn: function() { var me = this; $(document).bind('click', me.killerFn); }, disableKillerFn: function() { var me = this; $(document).unbind('click', me.killerFn); }, killSuggestions: function() { var me = this; this.stopKillSuggestions(); this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300); }, stopKillSuggestions: function() { window.clearInterval(this.intervalId); }, onKeyPress: function(e) { if (this.disabled || !this.enabled) { return; } // return will exit the function // and event will not be prevented switch (e.keyCode) { case 27: //KEY_ESC: this.el.val(this.currentValue); this.hide(); break; case 9: //KEY_TAB: case 13: //KEY_RETURN: if (this.selectedIndex === -1) { this.hide(); return; } this.select(this.selectedIndex); if(e.keyCode === 9){ return; } break; case 38: //KEY_UP: this.moveUp(); break; case 40: //KEY_DOWN: this.moveDown(); break; default: return; } e.stopImmediatePropagation(); e.preventDefault(); }, onKeyUp: function(e) { if(this.disabled){ return; } switch (e.keyCode) { case 38: //KEY_UP: case 40: //KEY_DOWN: return; } clearInterval(this.onChangeInterval); if (this.currentValue !== this.el.val()) { if (this.options.deferRequestBy > 0) { // Defer lookup in case when value changes very quickly: var me = this; this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy); } else { this.onValueChange(); } } }, onValueChange: function() { clearInterval(this.onChangeInterval); this.currentValue = this.el.val(); var q = this.getQuery(this.currentValue); this.selectedIndex = -1; if (this.ignoreValueChange) { this.ignoreValueChange = false; return; } if (q === '' || q.length < this.options.minChars) { this.hide(); } else { this.getSuggestions(q); } }, getQuery: function(val) { var d, arr; d = this.options.delimiter; if (!d) { return $.trim(val); } arr = val.split(d); return $.trim(arr[arr.length - 1]); }, getSuggestionsLocal: function(q) { var ret, arr, len, val, i; arr = this.options.lookup; len = arr.suggestions.length; ret = { suggestions:[], data:[], counts:[] }; q = q.toLowerCase(); for(i = 0; i < len; i++){ val = arr.suggestions[i]; if(val.toLowerCase().indexOf(q) === 0) { ret.suggestions.push(val); ret.data.push(arr.data[i]); ret.counts.push(arr.counts[i]); } } return ret; }, getSuggestions: function(q) { var cr, me; cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q]; if (cr && $.isArray(cr.suggestions)) { this.suggestions = cr.suggestions; this.data = cr.data; this.counts = cr.counts; if (cr.antiQuery.length) this.currentValue = cr.antiQuery; this.suggest(); } else if (!this.isBadQuery(q)) { me = this; me.options.params.query = q; $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text'); } }, isBadQuery: function(q) { var i = this.badQueries.length; while (i--) { if (q.indexOf(this.badQueries[i]) === 0) { return true; } } return false; }, hide: function() { this.enabled = false; this.selectedIndex = -1; this.container.hide(); }, suggest: function() { if (this.suggestions.length === 0) { this.hide(); return; } var me, len, div, f, v, i, s, mOver, mClick; me = this; len = this.suggestions.length; f = this.options.fnFormatResult; v = this.getQuery(this.currentValue); mOver = function(xi) { return function() { me.activate(xi); }; }; mClick = function(xi) { return function() { me.select(xi); }; }; this.container.hide().empty(); for (i = 0; i < len; i++) { s = this.suggestions[i]; d = this.data[i]; var isCountry = (occur(s, ',') == 0) ? true : false; var isHotel = (occur(d, 'hotel,') == 1) ? true : false; var isRegion = (occur(d, 'region,') == 1) ? true : false; div = $('<div class="' + (me.selectedIndex === i ? 'selected' : '') + (isCountry ? ' asCountry' : '') + (isHotel ? ' asHotel' : '') + (isRegion ? ' asRegion' : '') + '" title="' + s + '">' + f(s, d, v) + ' <span>(' + this.counts[i] + ')</span></div>'); div.mouseover(mOver(i)); div.click(mClick(i)); this.container.append(div); } this.enabled = true; this.container.show(); }, processResponse: function(text) { var response; try { response = eval('(' + text + ')'); } catch (err) { return; } if (!$.isArray(response.data)) { response.data = []; response.counts = []; } if(!this.options.noCache){ this.cachedResponse[response.query] = response; if (response.suggestions.length === 0) { this.badQueries.push(response.query); } } if (response.query.toLowerCase() === this.getQuery(this.currentValue).toLowerCase()) { if (response.antiQuery.length) this.currentValue = response.antiQuery; this.suggestions = response.suggestions; this.data = response.data; this.counts = response.counts; this.suggest(); } }, activate: function(index) { var divs, activeItem; divs = this.container.children(); // Clear previous selection: if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) { $(divs.get(this.selectedIndex)).removeClass('selected'); } this.selectedIndex = index; if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) { activeItem = divs.get(this.selectedIndex); $(activeItem).addClass('selected'); } return activeItem; }, deactivate: function(div, index) { //div.className = ''; if (this.selectedIndex === index) { this.selectedIndex = -1; } }, select: function(i) { var selectedValue, f; selectedValue = this.suggestions[i]; if (selectedValue) { this.el.val(selectedValue); if (this.options.autoSubmit) { f = this.el.parents('form'); if (f.length > 0) { f.get(0).submit(); } } this.ignoreValueChange = true; this.hide(); this.onSelect(i); } }, moveUp: function() { if (this.selectedIndex === -1) { return; } if (this.selectedIndex === 0) { //this.container.children().get(0).className = ''; this.selectedIndex = -1; this.el.val(this.currentValue); return; } this.adjustScroll(this.selectedIndex - 1); }, moveDown: function() { if (this.selectedIndex === (this.suggestions.length - 1)) { return; } this.adjustScroll(this.selectedIndex + 1); }, adjustScroll: function(i) { var activeItem, offsetTop, upperBound, lowerBound; activeItem = this.activate(i); offsetTop = activeItem.offsetTop; upperBound = this.container.scrollTop(); lowerBound = upperBound + this.options.maxHeight - 25; if (offsetTop < upperBound) { this.container.scrollTop(offsetTop); } else if (offsetTop > lowerBound) { this.container.scrollTop(offsetTop - this.options.maxHeight + 25); } this.el.val(this.getValue(this.suggestions[i])); }, onSelect: function(i) { var me, fn, s, d; me = this; fn = me.options.onSelect; s = me.suggestions[i]; d = me.data[i]; c = me.counts[i]; me.el.val(me.getValue(s)); if ($.isFunction(fn)) { fn(s, d, c, me.el); } }, getValue: function(value){ var del, currVal, arr, me; me = this; del = me.options.delimiter; if (!del) { return value; } currVal = me.currentValue; arr = currVal.split(del); if (arr.length === 1) { return value; } return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value; } }; }(jQuery));
JavaScript
/*! * jQuery Templates Plugin 1.0.0pre * http://github.com/jquery/jquery-tmpl * Requires jQuery 1.4.2 * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( jQuery, undefined ){ var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; function newTmplItem( options, parentItem, fn, data ) { // Returns a template item data structure for a new rendered instance of a template (a 'template item'). // The content field is a hierarchical array of strings and nested items (to be // removed and replaced by nodes field of dom elements, once inserted in DOM). var newItem = { data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}), _wrap: parentItem ? parentItem._wrap : null, tmpl: null, parent: parentItem || null, nodes: [], calls: tiCalls, nest: tiNest, wrap: tiWrap, html: tiHtml, update: tiUpdate }; if ( options ) { jQuery.extend( newItem, options, { nodes: [], parent: parentItem }); } if ( fn ) { // Build the hierarchical content to be used during insertion into DOM newItem.tmpl = fn; newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); newItem.key = ++itemKey; // Keep track of new template item, until it is stored as jQuery Data on DOM element (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; } return newItem; } // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems, parent = this.length === 1 && this[0].parentNode; appendToTmplItems = newTmplItems || {}; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); ret = this; } else { for ( i = 0, l = insert.length; i < l; i++ ) { cloneIndex = i; elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } cloneIndex = 0; ret = this.pushStack( ret, name, insert.selector ); } tmplItems = appendToTmplItems; appendToTmplItems = null; jQuery.tmpl.complete( tmplItems ); return ret; }; }); jQuery.fn.extend({ // Use first wrapped element as template markup. // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( data, options, parentItem ) { return jQuery.tmpl( this[0], data, options, parentItem ); }, // Find which rendered template item the first wrapped DOM element belongs to tmplItem: function() { return jQuery.tmplItem( this[0] ); }, // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. template: function( name ) { return jQuery.template( name, this[0] ); }, domManip: function( args, table, callback, options ) { if ( args[0] && jQuery.isArray( args[0] )) { var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem; while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {} if ( tmplItem && cloneIndex ) { dmArgs[2] = function( fragClone ) { // Handler called by oldManip when rendered template has been inserted into DOM. jQuery.tmpl.afterManip( this, fragClone, callback ); }; } oldManip.apply( this, dmArgs ); } else { oldManip.apply( this, arguments ); } cloneIndex = 0; if ( !appendToTmplItems ) { jQuery.tmpl.complete( newTmplItems ); } return this; } }); jQuery.extend({ // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }, // Return rendered template item for an element. tmplItem: function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }, // Set: // Use $.template( name, tmpl ) to cache a named template, // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. // Get: // Use $.template( name ) to access a cached template. // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) // will return the compiled template, without adding a name reference. // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent // to $.template( null, templateString ) template: function( name, tmpl ) { if (tmpl) { // Compile template and associate with name if ( typeof tmpl === "string" ) { // This is an HTML string being passed directly in. tmpl = buildTmplFn( tmpl ); } else if ( tmpl instanceof jQuery ) { tmpl = tmpl[0] || {}; } if ( tmpl.nodeType ) { // If this is a template block, use cached copy, or generate tmpl function and cache. tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); // Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space. // This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x. // To correct this, include space in tag: foo="${ x }" -> foo="value of x" } return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; } // Return named compiled template return name ? (typeof name !== "string" ? jQuery.template( null, name ): (jQuery.template[name] || // If not in map, and not containing at least on HTML tag, treat as a selector. // (If integrated with core, use quickExpr.exec) jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; }, encode: function( text ) { // Do HTML encoding replacing < > & and ' and " by corresponding entities. return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;"); } }); jQuery.extend( jQuery.tmpl, { tag: { "tmpl": { _default: { $2: "null" }, open: "if($notnull_1){__=__.concat($item.nest($1,$2));}" // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) // This means that {{tmpl foo}} treats foo as a template (which IS a function). // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. }, "wrap": { _default: { $2: "null" }, open: "$item.calls(__,$1,$2);__=[];", close: "call=$item.calls();__=call._.concat($item.wrap(call,__));" }, "each": { _default: { $2: "$index, $value" }, open: "if($notnull_1){$.each($1a,function($2){with(this){", close: "}});}" }, "if": { open: "if(($notnull_1) && $1a){", close: "}" }, "else": { _default: { $1: "true" }, open: "}else if(($notnull_1) && $1a){" }, "html": { // Unecoded expression evaluation. open: "if($notnull_1){__.push($1a);}" }, "=": { // Encoded expression evaluation. Abbreviated form is ${}. _default: { $1: "$data" }, open: "if($notnull_1){__.push($.encode($1a));}" }, "!": { // Comment tag. Skipped by parser open: "" } }, // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events complete: function( items ) { newTmplItems = {}; }, // Call this from code which overrides domManip, or equivalent // Manage cloning/storing template items etc. afterManip: function afterManip( elem, fragClone, callback ) { // Provides cloned fragment ready for fixup prior to and after insertion into DOM var content = fragClone.nodeType === 11 ? jQuery.makeArray(fragClone.childNodes) : fragClone.nodeType === 1 ? [fragClone] : []; // Return fragment to original caller (e.g. append) for DOM insertion callback.call( elem, fragClone ); // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. storeTmplItems( content ); cloneIndex++; } }); //========================== Private helper functions, used by code above ========================== function build( tmplItem, nested, content ) { // Convert hierarchical content into flat string array // and finally return array of fragments ready for DOM insertion var frag, ret = content ? jQuery.map( content, function( item ) { return (typeof item === "string") ? // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : // This is a child template item. Build nested template. build( item, tmplItem, item._ctnt ); }) : // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. tmplItem; if ( nested ) { return ret; } // top-level template ret = ret.join(""); // Support templates which have initial or final text nodes, or consist only of text // Also support HTML entities within the HTML markup. ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { frag = jQuery( middle ).get(); storeTmplItems( frag ); if ( before ) { frag = unencode( before ).concat(frag); } if ( after ) { frag = frag.concat(unencode( after )); } }); return frag ? frag : unencode( ret ); } function unencode( text ) { // Use createElement, since createTextNode will not render HTML entities correctly var el = document.createElement( "div" ); el.innerHTML = text; return jQuery.makeArray(el.childNodes); } // Generate a reusable function that will serve to render a template against data function buildTmplFn( markup ) { return new Function("jQuery","$item", // Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10). "var $=jQuery,call,__=[],$data=$item.data;" + // Introduce the data as local variables using with(){} "with($data){__.push('" + // Convert the template into pure JavaScript jQuery.trim(markup) .replace( /([\\'])/g, "\\$1" ) .replace( /[\r\t\n]/g, " " ) .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" ) .replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g, function( all, slash, type, fnargs, target, parens, args ) { var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; if ( !tag ) { throw "Unknown template tag: " + type; } def = tag._default || []; if ( parens && !/\w$/.test(target)) { target += parens; parens = ""; } if ( target ) { target = unescape( target ); args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); // Support for target being things like a.toLowerCase(); // In that case don't call with template item as 'this' pointer. Just evaluate... expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target; exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; } else { exprAutoFnDetect = expr = def.$1 || "null"; } fnargs = unescape( fnargs ); return "');" + tag[ slash ? "close" : "open" ] .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) .split( "$1a" ).join( exprAutoFnDetect ) .split( "$1" ).join( expr ) .split( "$2" ).join( fnargs || def.$2 || "" ) + "__.push('"; }) + "');}return __;" ); } function updateWrapped( options, wrapped ) { // Build the wrapped content. options._wrap = build( options, true, // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] ).join(""); } function unescape( args ) { return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; } function outerHtml( elem ) { var div = document.createElement("div"); div.appendChild( elem.cloneNode(true) ); return div.innerHTML; } // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. function storeTmplItems( content ) { var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; for ( i = 0, l = content.length; i < l; i++ ) { if ( (elem = content[i]).nodeType !== 1 ) { continue; } elems = elem.getElementsByTagName("*"); for ( m = elems.length - 1; m >= 0; m-- ) { processItemKey( elems[m] ); } processItemKey( elem ); } function processItemKey( el ) { var pntKey, pntNode = el, pntItem, tmplItem, key; // Ensure that each rendered template inserted into the DOM has its own template item, if ( (key = el.getAttribute( tmplItmAtt ))) { while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } if ( pntKey !== key ) { // The next ancestor with a _tmplitem expando is on a different key than this one. // So this is a top-level element within this template item // Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment. pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0; if ( !(tmplItem = newTmplItems[key]) ) { // The item is for wrapped content, and was copied from the temporary parent wrappedItem. tmplItem = wrappedItems[key]; tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] ); tmplItem.key = ++itemKey; newTmplItems[itemKey] = tmplItem; } if ( cloneIndex ) { cloneTmplItem( key ); } } el.removeAttribute( tmplItmAtt ); } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { // This was a rendered element, cloned during append or appendTo etc. // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. cloneTmplItem( tmplItem.key ); newTmplItems[tmplItem.key] = tmplItem; pntNode = jQuery.data( el.parentNode, "tmplItem" ); pntNode = pntNode ? pntNode.key : 0; } if ( tmplItem ) { pntItem = tmplItem; // Find the template item of the parent element. // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) while ( pntItem && pntItem.key != pntNode ) { // Add this element as a top-level node for this rendered template item, as well as for any // ancestor items between this item and the item of its parent element pntItem.nodes.push( el ); pntItem = pntItem.parent; } // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... delete tmplItem._ctnt; delete tmplItem._wrap; // Store template item as jQuery data on the element jQuery.data( el, "tmplItem", tmplItem ); } function cloneTmplItem( key ) { key = key + keySuffix; tmplItem = newClonedItems[key] = (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent )); } } } //---- Helper functions for template item ---- function tiCalls( content, tmpl, data, options ) { if ( !content ) { return stack.pop(); } stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); } function tiNest( tmpl, data, options ) { // nested template, using {{tmpl}} tag return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); } function tiWrap( call, wrapped ) { // nested template, using {{wrap}} tag var options = call.options || {}; options.wrapped = wrapped; // Apply the template, which may incorporate wrapped content, return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); } function tiHtml( filter, textOnly ) { var wrapped = this._wrap; return jQuery.map( jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), function(e) { return textOnly ? e.innerText || e.textContent : e.outerHTML || outerHtml(e); }); } function tiUpdate() { var coll = this.nodes; jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); jQuery( coll ).remove(); } })( jQuery );
JavaScript
jQuery.fn.daterange = function(input, startDateInput, endDateInput) { var $datepicker = $(this); var $input = $('#' + input); $input.focus(function() { calendar.showCalendar($input, $datepicker, 0); }); $(document).click(function(e){ var $parents = $(e.target).parents().add(e.target); if (!$parents.filter('.ui-datepicker-group').length && !$parents.filter('#' + input).length ) { $datepicker.hide(); } }); $datepicker.datepicker({ firstDay : 1, numberOfMonths: 2, minDate : new Date(), maxDate : '+1Y -1d', dateFormat: 'dd/mm/yy', beforeShowDay: function(date) { var dateString = date.getTime(); var text = ((dateString + 12 * 3600 * 1000) >= calendar.start && dateString <= calendar.end) ? dateString + ' highlight' : dateString; return [true, text, '']; }, onSelect: function (dateText, inst) { calendar.end = null; calendar.selectCount++; calendar.currentDate = calendar.getSelectedDate(inst); calendar.current = calendar.currentDate.getTime(); calendar.currentDate = dateText; if (calendar.selectCount < 2) { calendar.startDate = calendar.getSelectedDate(inst); calendar.start = calendar.startDate.getTime(); calendar.startDate = dateText; calendar.endDate = null; $datepicker.oneTime(1, function() { // подсветка $(".ui-datepicker-inline td a").live({ mouseenter: function() { if (calendar.selectCount) { var start = calendar.start; var end = calendar.getTimeClass(this); if (start > end) { end = calendar.start; start = calendar.getTimeClass(this); } $("td a").each(function (i) { var t = calendar.getTimeClass(this); if (t >= start && t <= end) { $(this).addClass('ui-state-active').removeClass('ui-state-highlight'); } }); } }, mouseleave: function() { $('td a').not('td a.' + calendar.start).removeClass('ui-state-active'); } }); }); } else{ calendar.selectCount = 0; calendar.endDate = calendar.getSelectedDate(inst); calendar.end = calendar.endDate.getTime(); calendar.endDate = dateText; if (calendar.start == calendar.end) { calendar.selectCount = 1; calendar.endDate = null; calendar.end = null; } else { if (calendar.start > calendar.end) { calendar.endDate = calendar.startDate; calendar.startDate = calendar.currentDate; calendar.end = calendar.start; calendar.start = calendar.current; } if (calendar.end - calendar.start > 30 * 24 * 3600 * 1000) { App.error(arrLang['Диапазон дат должен быть меньше 30 дней']); $input.val(''); $('#' + startDateInput).val(''); $('#' + endDateInput).val(''); calendar.endDate = null; calendar.startDate = null; calendar.end = null; calendar.start = null; calendar.selectCount = 0; } else { $input.val(calendar.getStartDate() + ' - ' + calendar.getEndDate()); $('#' + startDateInput).val(calendar.startDate); $('#' + endDateInput).val(calendar.endDate); $datepicker.oneTime(1, function() { $datepicker.hide(); $('.ui-datepicker-inline td a').removeClass('ui-state-active'); }); if (calendar.autoSearch) $input.closest('form').submit(); } } } } }).datepicker('setDate', new Date(calendar.start)); }; var calendar = { startDate: null, endDate: null, start: null, end: null, currentDate: new Date(), current: null, selectCount: 0, autoSearch: 0, getSelectedDate: function(inst){ return new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay); }, getStartDate: function() { var startDate = this.makeDate(this.startDate); return this.monthCase($.datepicker.formatDate('dd MM', startDate)); }, getEndDate: function() { var endDate = this.makeDate(this.endDate); return this.monthCase($.datepicker.formatDate('dd MM', endDate)); }, makeDate: function(date) { if (!date) return new Date(0); var arrDate = date.split('/'); return new Date(arrDate[2], arrDate[1] - 1, arrDate[0]); }, monthCase: function(date) { if (lang != 'ru') return date; var lastSymbol = date.substring(date.length - 1); if (lastSymbol == 'ь' || lastSymbol == 'й') return date.substring(0, date.length - 1) + 'я'; return date + 'а'; }, getTimeClass: function(elem) { var classes = $(elem).parent().attr('class'); if (classes == undefined) return null; var long = classes.match(/[0-9]+/); if (!long) return null; return parseInt(classes.match(/[0-9]+/)[0]); }, showCalendar: function(elem, datepicker, autoSearch) { var $input = $(elem); var $datepicker = $(datepicker); var top = $input.offset().top + $input.height() + 12; if ((top - $(window).scrollTop() + 201) > $(window).height()) top = $(window).height() + $(window).scrollTop() - 211; var left = $input.offset().left; if (left > $(window).width() - 497) left = $(window).width() - 497; $datepicker.css({'left':left, 'top': top}); $datepicker.datepicker(); $datepicker.show(); calendar.autoSearch = autoSearch; return !1; } };
JavaScript
/* * One Click Upload - jQuery Plugin * Copyright (c) 2008 Michael Mitchell - http://www.michaelmitchell.co.nz */ (function($){ $.fn.upload = function(options) { /** Merge the users options with our defaults */ options = $.extend({ name: 'file', enctype: 'multipart/form-data', action: '', autoSubmit: true, onSubmit: function() {}, onComplete: function() {}, onSelect: function() {}, params: {} }, options); return new $.ocupload(this, options); }, $.ocupload = function(element, options) { /** Fix scope problems */ var self = this; /** A unique id so we can find our elements later */ var id = new Date().getTime().toString().substr(8); /** Upload Iframe */ var iframe = $( '<iframe '+ 'id="iframe'+id+'" '+ 'name="iframe'+id+'"'+ '></iframe>' ).css({ display: 'none' }); /** Form */ var form = $( '<form '+ 'method="post" '+ 'enctype="'+options.enctype+'" '+ 'action="'+options.action+'" '+ 'target="iframe'+id+'"'+ '></form>' ).css({ margin: 0, padding: 0 }); /** File Input */ var input = $( '<input '+ 'name="'+options.name+'" '+ 'type="file" '+ '/>' ).css({ zIndex: '9999', position: 'relative', display: 'block', cursor: 'Pointer', marginLeft: -175+'px', opacity: 0 }); /** Put everything together */ element.wrap('<div></div>'); //container form.append(input); element.after(form); //element.append('<p>123</p>'); element.after(iframe); /** Find the container and make it nice and snug */ var container = element.parent().css({ position: 'relative', height: element.outerHeight()+'px', width: element.outerWidth()+'px', overflow: 'hidden', cursor: 'pointer', margin: 0, padding: 0 }); /** Put our file input in the right place */ input.css('marginTop', -container.height()-10+'px'); //input.css('width', 20 + container.width()+'px'); //input.css('height', 20 + container.height()+'px'); /** Move the input with the mouse to make sure it get clicked! */ container.mousemove(function(e){ input.css({ top: e.pageY-container.offset().top+'px', left: 20 + e.pageX-container.offset().left+'px' }); });/* container.mouseout(function(e){ input.css({ top: 0 + 'px', left: 0 + 'px' }); });*/ /** Watch for file selection */ input.change(function() { /** Do something when a file is selected. */ self.onSelect(); /** Submit the form automaticly after selecting the file */ if(self.autoSubmit) { self.submit(); } }); /** Methods */ $.extend(this, { autoSubmit: true, onSubmit: options.onSubmit, onComplete: options.onComplete, onSelect: options.onSelect, /** get filename */ filename: function() { return input.attr('value'); }, /** get/set params */ params: function(params) { var params = params ? params : false; if(params) { options.params = $.extend(options.params, params); } else { return options.params; } }, /** get/set name */ name: function(name) { var name = name ? name : false; if(name) { input.attr('name', value); } else { return input.attr('name'); } }, /** get/set action */ action: function(action) { var action = action ? action : false; if(action) { form.attr('action', action); } else { return form.attr('action'); } }, /** get/set enctype */ enctype: function(enctype) { var enctype = enctype ? enctype : false; if(enctype) { form.attr('enctype', enctype); } else { return form.attr('enctype'); } }, /** set options */ set: function(obj, value) { var value = value ? value : false; function option(action, value) { switch(action) { default: throw new Error('[jQuery.ocupload.set] \''+action+'\' is an invalid option.'); break; case 'name': self.name(value); break; case 'action': self.action(value); break; case 'enctype': self.enctype(value); break; case 'params': self.params(value); break; case 'autoSubmit': self.autoSubmit = value; break; case 'onSubmit': self.onSubmit = value; break; case 'onComplete': self.onComplete = value; break; case 'onSelect': self.onSelect = value; break; } } if(value) { option(obj, value); } else { $.each(obj, function(key, value) { option(key, value); }); } }, /** Submit the form */ submit: function() { /** Do something before we upload */ this.onSubmit(); /** add additional paramters before sending */ $.each(options.params, function(key, value) { form.append($( '<input '+ 'type="hidden" '+ 'name="'+key+'" '+ 'value="'+value+'" '+ '/>' )); }); /** Submit the actual form */ form.submit(); /** Do something after we are finished uploading */ iframe.unbind().load(function() { // Get a response from the server in plain text var myFrame = document.getElementById(iframe.attr('name')); var response = $(myFrame.contentWindow.document.body).text(); // Do something on complete self.onComplete(response); //done :D }); } }); } })(jQuery);
JavaScript
jQuery.fn.toggleText = function(a,b) { return this.html(this.html().replace(new RegExp("("+a+"|"+b+")", "m"), function(x){return(x==a)?b:a;})); } $.fn.documentSelection = function() { var element = this[0]; if ( element.contentWindow.document.selection ) return element.contentWindow.document.selection.createRange().text; else return element.contentWindow.getSelection().toString(); }; (function( $ ) { //Метод обращения к документу $.fn.document = function() { var element = this[0]; if ( element.nodeName.toLowerCase() == 'iframe' ) return element.contentWindow.document; /* return ( $.browser.msie ) ? document.frames[element.id].document : element.contentWindow.document // contentDocument; */ else return $(this); }; //Точка входа при создании WYSIWYG $.fn.wysiwyg = function( options ) {// Первое, куда мы попадаем //Создаем HTML для iFrame var options = $.extend({ debug : false, html : '<'+'?xml version="1.0" encoding="UTF-8"?'+'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" href="' + W_CSS + 'plugins/jquery.wysiwyg_in.css?v=2" type="text/css" media="screen" /></head><body class="' + options['bodyClass'] + '">INITIAL_CONTENT</body></html>' }, options); return this.each(function() { Wysiwyg(this, options); }); }; //Создает WYSIWYG, если его нет function Wysiwyg( element, options ) // вызывается из $.fn.wysiwyg (element - исходный элемент, options - переданные опции) { /* return this instanceof Wysiwyg ? this.init(element, options) : new Wysiwyg(element, options); */ if (this instanceof Wysiwyg) { // Если это один из объектов Wysiwyg this.init(element, options); // то проводим инициализацию } else { // Если это НЕ один из объектов Wysiwyg new Wysiwyg(element, options);// то создаем объект Wysiwyg с соответствующими параметрами } return this; } //Конструктор WYSIWYG $.extend(Wysiwyg.prototype, { original : null, options : {}, element : null, editor : null, init : function( element, options ) { options['wysiwygType'] = options['wysiwygType'] || false; // запоминаем тип редактора (служит для определения комплектации) options['isModeration'] = options['isModeration'] || false; // запоминаем тип редактора (служит для определения комплектации) options['bodyClass'] = options['bodyClass'] || ''; // запоминаем тип редактора (служит для определения комплектации) this.editor = element; //Запоминаем исходный элемент textarea this.options = options || {}; // запоминаем настройки var newX = element.width || element.clientWidth; //определяем ширину и высоту исходного элемента (textarea) var newY = element.height || element.clientHeight; if ( element.nodeName.toLowerCase() == 'textarea' ) {// если исходный элемент именно textarea this.original = element; // запоминаем орининальный элемент именно как исходный textarea var editor = this.editor = $('<iframe></iframe>').css({ minHeight : ( newY - 8 ).toString() + 'px', width : ( newX - 8 ).toString() + 'px' }).attr('id', $(element).attr('id') + 'IFrame'); if ( $.browser.msie ) { this.editor .css('height', ( newY ).toString() + 'px'); /** var editor = $('<span></span>').css({ width : ( newX - 8 ).toString() + 'px', height : ( newY - 8 ).toString() + 'px' }).attr('id', $(element).attr('id') + 'IFrame'); editor.outerHTML = this.editor.outerHTML; */ } } //Создаем панель var panel = this.panel = $('<ul></ul>').addClass('panel'); this.appendMenu('bold', {title: 'bold'}); this.appendMenu('italic', {title: 'italic'}); this.appendMenu('strikeThrough', {title: 'strikethrough'}); this.appendMenu('underline', {title: 'underlined'}); this.appendMenuSeparator(); this.appendMenu('justifyLeft', {title: 'left align'}); this.appendMenu('justifyCenter', {title: 'center alignment'}); this.appendMenu('justifyRight', {title: 'right align'}); this.appendMenu('justifyFull', {title: 'width adjustment'}); if (options['wysiwygType'] != 'comment' && false) { this.appendMenu('indent', {title: 'indent'}); this.appendMenu('outdent', {title: 'decrease indent'}); this.appendMenuSeparator(); this.appendMenu('subscript', {title: 'interlinear'}); this.appendMenu('superscript', {title: 'superior'}); } this.appendMenuSeparator(); this.appendMenu('undo', {title: 'cancel'}); this.appendMenu('redo', {title: 'return'}); this.appendMenuSeparator(); this.appendMenu('insertOrderedList', {title: 'numbered list'}); this.appendMenu('insertUnorderedList', {title: 'bulleted list'}); this.appendMenu('insertHorizontalRule', {title: 'line'}); if ( $.browser.msie ) { this.appendMenu('createLink', {title: 'hyperlink'}, null, function( self ) { self.editorDoc.execCommand('createLink', true, null); }); //this.appendMenu('insertImage', {title: 'вставить изображение'}, null, function( self ) { self.editorDoc.execCommand('insertImage', true, null); }); //this.appendMenu('insertImage', {title: 'вставить изображение'}); } else { this.appendMenu('createLink', {title: 'hyperlink'}, null, function( self ) { var szURL = prompt('Ingrese una URL', 'http://'); if ( szURL && szURL.length > 0 ) self.editorDoc.execCommand('createLink', false, szURL); }); //this.appendMenu('insertImage', {title: 'вставить изображение'}, null, function( self ) { var szURL = prompt('Ingrese una URL', 'http://'); if ( szURL && szURL.length > 0 ) self.editorDoc.execCommand('insertImage', false, szURL); }); //this.appendMenu('insertImage', {title: 'вставить изображение'}); } //Дополнительные кнопки на тот случай, если это не комментарий if (options['wysiwygType'] != 'comment') { //Дополнительные кнопки для модератора if(options['isModeration']) {//Кнопка вставки кнопки модерирования this.appendMenu('fill', {title: 'Moderate (paint the text)'}, null, function( self ) { self.editorDoc.execCommand("forecolor", false, "#f00301"); var tempSpan = $(self.editorDoc.body).find("span").add($(self.editorDoc.body).find("font")); $(tempSpan).each(function(){ if( ($(this).css("color") == 'rgb(240, 3, 1)') || ($(this).css("color") == '#f00301') ){ $(this).css('background', '#3c4046'); $(this).css('color', '#3c4046'); } }); if ($.browser.opera) $("#" + $(self.original).attr('id') + "IFrame").get(0).focus(); else $("#" + $(self.original).attr('id') + "IFrame").get(0).contentWindow.focus(); }); } //Кнопка вставки изображения this.appendMenu('insertImage', {title: 'insert image'}, null, function( self ) { }); if ( $.browser.mozilla ) { this.appendMenuSeparator(); var tempArr1 = new Array; var tempArr2 = new Array; var tempArr3 = new Array; tempArr1[0] = 'h1';tempArr1['title'] = 'first level header'; this.appendMenu('heading', tempArr1, 'h1'); tempArr2[0] = 'h2';tempArr2['title'] = 'second level header'; this.appendMenu('heading', tempArr2, 'h2'); tempArr3[0] = 'h3';tempArr3['title'] = 'third level header'; this.appendMenu('heading', tempArr3, 'h3'); } } if ( ( $.browser.msie ) ) { this.appendMenuSeparator(); this.appendMenu('cut', {title: 'cut'}); this.appendMenu('copy', {title: 'copy'}); this.appendMenu('paste', {title: 'paste'}); } if ( ( $.browser.mozilla || $.browser.opera ) ) { this.appendMenuSeparator(); this.appendMenu('increaseFontSize', {title: 'increase font size'}); this.appendMenu('decreaseFontSize', {title: 'decrease font size'}); } //Кнопка просмотра HTML кода this.appendMenuSeparator(); //if (options['wysiwygType'] != 'comment') { //if(options['isModeration']) { if(true) { this.appendMenu('html', {title: 'see HTML-code'}, null, function( self ) { if ( self.viewHTML ) { self.setContent( $(self.original).val() ); $(self.original).hide(); } else { self.saveContent(); $(self.original).show(); } self.viewHTML = !( self.viewHTML ); }); } //Кнопка отмены форматирования this.appendMenu('removeFormat', {title: 'remove format'}, null, function( self ) { self.editorDoc.execCommand('removeFormat', false, []); self.editorDoc.execCommand('unlink', false, []); }); //Сборка и настройка WYSIWYG this.element = $('<div></div>').css({ width : ( newX ).toString() + 'px' }).addClass('wysiwyg') .append(panel) //.append( $('<div><!-- --></div>').css({ clear : 'both' }) ) .append(editor); $(element) // .css('display', 'none') .hide() .before(this.element); this.viewHTML = false; this.initialHeight = newY - 8; this.initialContent = $(element).text(); this.initFrame(); this.initImageInsert(); if ( this.initialContent.length == 0 ) this.setContent('<br />'); }, //Инициализация фрейма initImageInsert : function() { var objWysiwyg = this; var objUserElement = objWysiwyg.element; var objIframe = $(objUserElement).find('iframe'); var mozillaAttr = ''; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Создание блока для вставки изображения - начало $(objUserElement).append(objWysiwyg.getImageInsertBlockHtml()); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Создание блока для вставки изображения - конец //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Клик на "выберите файл для загрузки" - начало $(objUserElement).find('#buttonForLoad').upload({ name: 'file', method: 'post', enctype: 'multipart/form-data', action: W_AJAX + 'wysiwyg/upload/', onSubmit: function() { //alert('submit'); $('#buttonForLoad').attr('loading', '1'); $('#imageInsertPreview').html('<img src="' + W_IMAGES + 'icons/ajax.gif" alt="" />'); }, onComplete: function(data) { //alert('complete'); //alert(data); var theImage = data; var src = theImage; //alert($('#buttonForLoad').attr('loading')); if($('#buttonForLoad').attr('loading') != '2') { $('#imageInsertPreview').html('<img src="' + theImage.replace('m_', 's_') + '" alt="" />'); $('#imageInsertLoadedSrc').val(theImage); $('#bigImageForLoad').html('<img name="myImage" src="' + theImage + '" onload="' + '$(\'#imageInsertWidth\').val(document.myImage.width);' + '$(\'#imageInsertHiddenWidth\').val(document.myImage.width);' + '$(\'#imageInsertHeight\').val(document.myImage.height);' + '$(\'#imageInsertHiddenHeight\').val(document.myImage.height);' + '$(\'#imageInsertWidth\').val(\'200\');if($(\'#imageInsertHiddenHeight\').val() == 0 || $(\'#imageInsertHiddenWidth\').val() == 0 || $(\'#imageInsertWidth\').val() == 0) { $(\'#imageInsertHeight\').val(0) } else {$(\'#imageInsertHeight\').val(intval($(\'#imageInsertWidth\').val() * $(\'#imageInsertHiddenHeight\').val() / $(\'#imageInsertHiddenWidth\').val()))};" alt="" />'); //alert(theImage); //alert(); } $('#buttonForLoad').attr('loading', '0'); } });/* */ //Клик на "выберите файл для загрузки" - конец //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $(objUserElement).find('#buttonForSave').click(function () { if($('#buttonForLoad').attr('loading') != '1') { var theImage = $('#imageInsertLoadedSrc').val(); if(theImage.length > 5) { var marginTop = intval($('#imageInsertMarginTop').val()); var marginRight = intval($('#imageInsertMarginRight').val()); var marginBottom = intval($('#imageInsertMarginBottom').val()); var marginLeft = intval($('#imageInsertMarginLeft').val()); var floatType = $('#imageInsertFloatType').val(); var imgWidth = intval($('#imageInsertWidth').val()); var imgHeight = intval($('#imageInsertHeight').val()); if ($.browser.opera ) { $(objIframe).get(0).focus(); } else{ $(objIframe).get(0).contentWindow.focus(); } if(mozillaAttr != '') { //$(objWysiwyg.editorDoc.body).find("img[src$=" + mozillaAttr + "]").remove(); $(objWysiwyg.editorDoc.body).find("img[src$=" + mozillaAttr + "]").attr('src', mozillaAttr + "_2"); objWysiwyg.insertHtmlToPosition('<img src="' + theImage + '" alt="" style="margin: ' + marginTop + 'px ' + marginRight + 'px ' + marginBottom + 'px ' + marginLeft + 'px;float:' + floatType + ';' + ((imgWidth > 0) && (imgHeight > 0) ? 'width:' + imgWidth + 'px;height:' + imgHeight + 'px;' : '') + '" />', mozillaAttr + "_2"); } else { objWysiwyg.insertHtmlToPosition('<img src="' + theImage + '" alt="" style="margin: ' + marginTop + 'px ' + marginRight + 'px ' + marginBottom + 'px ' + marginLeft + 'px;float:' + floatType + ';' + ((imgWidth > 0) && (imgHeight > 0) ? 'width:' + imgWidth + 'px;height:' + imgHeight + 'px;' : '') + '" />'); } $(objUserElement).find("#imageInsertMenu").hide(); tb_remove(); } else { alert('Сначала вам необходимо выбрать изображение. Воспользуйтесь иконкой в правом верхнем углу.'); } } else { alert('В данный момент идет загрузка изображения и вы не можете утвердить изменения. Попробуйте позже.'); } }); $(objUserElement).find('#imageInsertMenu').hide(); $(objWysiwyg.editorDoc.body).html(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Клик на иконку "Вставить изображение" - начало //$(objUserElement).find('.insertImage').attr('alt', '#TB_inline?height=300&width=400&inlineId=imageInsertMenu'); //$(objUserElement).find('.insertImage').attr('class', 'thickbox insertImage'); $(objUserElement).find('.insertImage').click(function () { $('#buttonForLoad').attr('loading', '2'); var iframeDocument = objIframe.document(); var editFrame; var selection = ''; var selectionType = ''; $('#imageInsertMarginTop').val(0); $('#imageInsertMarginRight').val(11); $('#imageInsertMarginBottom').val(5); $('#imageInsertMarginLeft').val(0); $('#imageInsertFloatType').val('left'); $('#imageInsertLoadedSrc').val(''); //alert('insert'); $('#imageInsertPreview').html(''); $('#imageInsertWidth').val(''); $('#imageInsertHeight').val(''); $('#imageInsertHiddenWidth').val(''); $('#imageInsertHiddenHeight').val(''); tb_show('Adjusting the picture', '#TB_inline?height=275&width=320', false); $("#TB_ajaxContent").html($(objUserElement).find("#imageInsertMenu").children()); $("#TB_window").css({display:"block"}); $("#TB_window").unload(function () { $(objUserElement).find("#imageInsertMenu").append( $("#TB_ajaxContent").children() ); // move elements back when you're finished }); { if($.browser.msie) { var iframeId = $(objIframe).attr('id'); editFrame = frames[iframeId].document;//Для IE selection = editFrame.selection; selectionType = selection.type; } else { editFrame = $(objUserElement).find('iframe').get(0).contentWindow; //Получаем селекшн selection = editFrame.getSelection(); } mozillaSelection = ''; mozillaAttr = ''; //Если селекшн не пустой if(selection == '' || selectionType == 'Control') { //alert('Попли в селекшн'); var startHtml = $(objWysiwyg.editorDoc.body).html(); var hiddenDot = W_IMAGES + 'dot/hidden_dot_for_wysiwyg_2.gif'; //Вставляем туда скрытую картинку objWysiwyg.insertHtmlToPosition('<img src="' + hiddenDot + '" alt="" />'); var finishHtml =$(objWysiwyg.editorDoc.body).html();; $(objWysiwyg.editorDoc.body).find("img[src$=hidden_dot_for_wysiwyg_2.gif]").remove(); var currentPosition; currentPosition = finishHtml.indexOf(hiddenDot); var firstPartEndPosition = finishHtml.lastIndexOf('<', currentPosition); //Определяем текст до вставленной кртинки var beforeHtml = finishHtml.substr(0, firstPartEndPosition); currentPosition = finishHtml.indexOf('>', currentPosition + 1); //Определяем текст после вставленной картинки var afterHtml = finishHtml.substr(currentPosition + 1); //О var selectedHtml = startHtml.substr(firstPartEndPosition, startHtml.length - afterHtml.length - beforeHtml.length); if(selectedHtml.length > 0) {// Если действительности какой-то текст выделен $(objWysiwyg.editorDoc.body).html(startHtml); if((selectedHtml.toLowerCase()).indexOf('<img') == 0) { // Если выделен тег img if (selectedHtml.indexOf('>') == selectedHtml.length - 1) { //Если выделен только тег img и больше ничего mozillaSelection = selectedHtml; currentPosition = selectedHtml.indexOf('src='); var src = selectedHtml.substr(currentPosition + 5, selectedHtml.indexOf('"', currentPosition + 5) - currentPosition - 5); mozillaAttr = src; var objImage = $(objWysiwyg.editorDoc.body).find("img[src$=" + src + "]").after(selectedHtml).remove(); if ($.browser.opera ) { $('#imageInsertMarginTop').val(intval(getMarginsByStrOfMargin($(objImage).css('margin'), 'top'))); $('#imageInsertMarginRight').val(intval(getMarginsByStrOfMargin($(objImage).css('margin'), 'right'))); $('#imageInsertMarginBottom').val(intval(getMarginsByStrOfMargin($(objImage).css('margin'), 'bottom'))); $('#imageInsertMarginLeft').val(intval(getMarginsByStrOfMargin($(objImage).css('margin'), 'left'))); $('#imageInsertWidth').val(intval($(objImage).css('width'))); $('#imageInsertHiddenWidth').val(intval($(objImage).get(0).width)); $('#imageInsertHeight').val(intval($(objImage).css('height'))); $('#imageInsertHiddenHeight').val(intval($(objImage).get(0).height)); } else { $('#imageInsertMarginTop').val(intval($(objImage).css('margin-top'))); $('#imageInsertMarginRight').val(intval($(objImage).css('margin-right'))); $('#imageInsertMarginBottom').val(intval($(objImage).css('margin-bottom'))); $('#imageInsertMarginLeft').val(intval($(objImage).css('margin-left'))); $('#imageInsertWidth').val(intval($(objImage).css('width'))); $('#imageInsertHiddenWidth').val(intval($(objImage).get(0).width)); $('#imageInsertHeight').val(intval($(objImage).css('height'))); $('#imageInsertHiddenHeight').val(intval($(objImage).get(0).height)); } //alert(src); $('#imageInsertFloatType').val($(objImage).css('float')); $('#imageInsertLoadedSrc').val($(objImage).attr('src')); //alert('<img src="' + $(objImage).attr('src') + '" alt="" style="width:50px;" />'); $('#imageInsertPreview').html('<img src="' + $(objImage).attr('src') + '" alt="" style="width:50px;" />'); } } } } else { } } this.blur(); }); //Клик на иконку "Вставить изображение - конец //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! }, //Инициализация фрейма initFrame : function() { this.editorDoc = $(this.editor).document(); this.editorDoc.open(); this.editorDoc.write( this.options.html.replace(/INITIAL_CONTENT/, this.initialContent) ); this.editorDoc.close(); this.editorDoc.contentEditable = 'true'; this.editorDoc.designMode = 'on'; }, getContent : function() { return $( $(this.editor).document() ).find('body').html(); }, setContent : function( newContent ) { $( $(this.editor).document() ).find('body').html(newContent); }, saveContent : function() { if ( this.original ) $(this.original).val( this.getContent() ); }, appendMenu : function( cmd, args, className, fn ) { var self = this; var args = args || []; var liEl = $('<li></li>'); if ($.browser.msie) { liEl.append( $('<a href="/" title="' + args['title'] + '" onclick="return false;"><!-- --></a>').addClass(className || cmd) ); } else { liEl.append( $('<a title="' + args['title'] + '" ><!-- --></a>').addClass(className || cmd) ); } if ($.browser.msie) { liEl.mousedown(function() { if ( fn ) { fn(self); } else { //Раньше здесь было только про обработку вставки изображения //alert('Вставка изображения в IE'); } }); } else{ /*Обработка функции не IE*/ liEl.click(function() { if ( fn ) { //alert(fn); fn(self); } else { //alert('команда форматирования вне IE'); self.editorDoc.execCommand(cmd, false, args); if ($.browser.opera ) { $("#" + $(self.original).attr('id') + "IFrame").get(0).focus(); } else{ $("#" + $(self.original).attr('id') + "IFrame").get(0).contentWindow.focus(); } } }); } liEl.appendTo( this.panel ); }, appendMenuSeparator : function() { $('<li class="separator"></li>').appendTo( this.panel ); }, getImageInsertBlockHtml : function() { return '' + '<div id="imageInsertMenu" style="position:absolute;top:30%;left:10%;border:1px solid #000000;">' + '<table cellspacing="0" cellpadding="0">' + '<tr>' + '<td colspan="2">' + //'<div style="height:35px;width:222px;cursor:Pointer;"><img src="' + W_IMAGES + 'button/load_image.gif" id="buttonForLoad" style="height:35px;width:222px;cursor:Pointer;" alt="" /></div>' + '</td>' + '<td rowspan="7" style="width:30px;"></td>' + '<td style="width:50px;text-align:center;padding-top:10px;">' + //'<div style="height:35px;width:222px;cursor:Pointer;"><img src="' + W_IMAGES + 'button/load_image.gif" id="buttonForLoad" style="height:35px;width:222px;cursor:Pointer;" alt="" /></div>' + '<div style="height:28px;width:32px;cursor:Pointer;margin:auto;"><img src="' + W_IMAGES + 'button/open_image.gif" id="buttonForLoad" style="height:28px;width:32px;cursor:Pointer;" alt="" /></div>' + '</td>' + '</tr>' + '<tr>' + '<td colspan="2"></td>' + '<td rowspan="6"><div id="imageInsertPreview"></div></td>' + '</tr>' + '<tr>' + '<td style="height:25px;width:100px;">Wrap:</td>' + '<td>'+ '<select value="" id="imageInsertFloatType">' + '<option value="none">no</option>' + '<option value="left">on the right side</option>' + '<option value="right">on the left side</option>' + '</select>' + '</td>' + '</tr>' + '<tr>' + '<td style="height:25px;">Top indent:</td>' + '<td><input type="text" style="width:30px;" maxlength="3" value="" id="imageInsertMarginTop" /> px</td>' + '</tr>' + '<tr>' + '<td style="height:25px;">Right indent:</td>' + '<td><input type="text" style="width:30px;" maxlength="3" value="" id="imageInsertMarginRight" /> px</td>' + '</tr>' + '<tr>' + '<td style="height:25px;">Bottom indent:</td>' + '<td><input type="text" style="width:30px;" maxlength="3" value="" id="imageInsertMarginBottom" /> px</td>' + '</tr>' + '<tr>' + '<td style="height:25px;">Left indent:</td>' + '<td><input type="text" style="width:30px;" maxlength="3" value="" id="imageInsertMarginLeft" /> px</td>' + '</tr>' + '<tr>' + '<td style="height:25px;">Width:</td>' + '<td><div style="width:0px;height:0px;overflow:hidden;" id="bigImageForLoad"></div><input type="text" style="width:30px;" maxlength="3" value="" id="imageInsertWidth" onkeyup="if($(\'#imageInsertHiddenHeight\').val() == 0 || $(\'#imageInsertHiddenWidth\').val() == 0 || $(\'#imageInsertWidth\').val() == 0) { $(\'#imageInsertHeight\').val(0) } else {$(\'#imageInsertHeight\').val(intval($(\'#imageInsertWidth\').val() * $(\'#imageInsertHiddenHeight\').val() / $(\'#imageInsertHiddenWidth\').val()))};" /><input type="hidden" style="width:30px;" maxlength="3" value="" id="imageInsertHiddenWidth" /> px</td>' + '</tr>' + '<tr>' + '<td style="height:25px;">Height:</td>' + '<td><input type="text" style="width:30px;" maxlength="3" value="" id="imageInsertHeight" onkeyup="if($(\'#imageInsertHiddenHeight\').val() == 0 || $(\'#imageInsertHiddenWidth\').val() == 0 || $(\'#imageInsertHeight\').val() == 0) { $(\'#imageInsertWidth\').val(0) } else {$(\'#imageInsertWidth\').val(intval($(\'#imageInsertHeight\').val() * $(\'#imageInsertHiddenWidth\').val() / $(\'#imageInsertHiddenHeight\').val()))};" /><input type="hidden" style="width:30px;" maxlength="3" value="" id="imageInsertHiddenHeight" /> px</td>' + '</tr>' + '<tr>' + //'<td><input type="hidden" style="width:30px;" maxlength="3" value="" id="imageInsertLoadedSrc" /></td>' + '<td style="text-align:center;padding-top:10px;" colspan="4"><input type="hidden" style="width:30px;" maxlength="3" value="" id="imageInsertLoadedSrc" /><img style="cursor:Pointer;width:60px;height:29px;" src="' + W_IMAGES + 'button/save.gif" id="buttonForSave" alt="" /></td>' + '</tr>' + '</table>' + '</div>'; }, insertHtmlToPosition : function(htmlToInsert, srcToRemove) { var objWysiwyg = this; var objUserElement = objWysiwyg.element; var objIframe = $(objUserElement).find('iframe'); // var selection = $(self.editor).documentSelection(); //Получаем текст текущего выделения //if ( selection.length > 0 ) if(true) { //alert("Text is selected"); //alert('вставка'); var startSrcText = $(objWysiwyg.editorDoc.body).html(); //Сохраняем весь исходный текст до обработки //alert(startSrcText); if(startSrcText == '<br>'){ $(objWysiwyg.editorDoc.body).html(htmlToInsert + '<br>') } else { if(srcToRemove == undefined) { if ($.browser.opera) $(objIframe).get(0).focus(); else $(objIframe).get(0).contentWindow.focus(); objWysiwyg.editorDoc.execCommand("insertImage", false, W_IMAGES + "dot/hidden_dot_for_wysiwyg.gif"); $(objWysiwyg.editorDoc.body).find("img[src$=hidden_dot_for_wysiwyg.gif]").after(htmlToInsert); $(objWysiwyg.editorDoc.body).find("img[src$=hidden_dot_for_wysiwyg.gif]").remove(); } else { $(objWysiwyg.editorDoc.body).find("img[src$=" + srcToRemove + "]").after(htmlToInsert); $(objWysiwyg.editorDoc.body).find("img[src$=" + srcToRemove + "]").remove(); } } /*objWysiwyg.editorDoc.execCommand("forecolor", false, "#f00302"); //Красим выделенный текст в красный цвет var tempRedSpans = $(objWysiwyg.editorDoc.body).find("img[src$=hidden_dot_for_wysiwyg.gif]").filter(function () { return ($(this).css("color") == 'rgb(240, 3, 2)') || ($(this).css("color") == '#f00302'); }); //Получаем все раскрашенные span'ы*/ // alert("'Red point'"); /*var isWrongSelectionExists = 0; var parentCut; $(tempRedSpans).each(function() { parentCut = $(this).parents("cut"); if ($(parentCut).length > 0) { $(this).replaceWith($(this).html()); //Если есть выделенные каты, их мы заменем их содержимым var tempRedInnerCuts = $(self.editorDoc.body).find("cut").filter(function () { return ($(this).css("color") == 'rgb(240, 3, 2)') || ($(this).css("color") == '#f00302'); }); $(tempRedInnerCuts).each(function () { $(this).children("span").each(function() { $(this).replaceWith($(this).html()); }); $(this).replaceWith($(this).html()); }); isWrongSelectionExists = isWrongSelectionExists | 1; return this; } });*/ } } }); })(jQuery); $(document).ready(function() { $('.wysiwygComment').each(function(i) { $(this).wysiwyg({ debug : true, wysiwygType : 'comment' }); var curElement = $(this); $(this).parents('form').submit( function() { $(curElement).val($( $('#' + $(curElement).attr('id') + 'IFrame').document() ).find('body').html()); }); }); $('.wysiwygAdmin').each(function(i) { var isModeration = false; if($(this).attr('isModeration') == '1') isModeration = true; var bodyClass = ''; if($(this).attr('bodyClass')) bodyClass = $(this).attr('bodyClass'); $(this).wysiwyg({ debug : true, wysiwygType : 'admin', isModeration : isModeration, bodyClass : bodyClass }); var curElement = $(this); $(this).parents('form').submit( function() { $(curElement).val($( $('#' + $(curElement).attr('id') + 'IFrame').document() ).find('body').html()); }); }); });
JavaScript
/*! * jQuery Form Plugin * version: 2.96 (16-FEB-2012) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr('method'); action = this.attr('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var qx,n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file:enabled[value]', this); // [value] (issue #113) var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = !!(hasFileInputs && fileInputs.get(0).files && window.FormData); log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { fileUploadIframe(a); }); } else { fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { options.progress = options.progress || $.noop; fileUploadXhr(a); } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { if (a[i].type == 'file') continue; formdata.append(a[i].name, a[i].value); } $form.find('input:file:enabled').each(function(){ var name = $(this).attr('name'), files = this.files; if (name) { for (var i=0; i < files.length; i++) formdata.append(name, files[i]); } }); if (options.extraData) { for (var k in options.extraData) formdata.append(k, options.extraData[k]) } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: 'POST' }); //s.context = s.context || s; s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { o.data = formdata; if(xhr.upload) { // unfortunately, jQuery doesn't expose this prop (http://bugs.jquery.com/ticket/10190) xhr.upload.onprogress = function(event) { o.progress(event.position, event.total); }; } if(beforeSend) beforeSend.call(o, xhr, options); }; $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var useProp = !!$.fn.prop; if (a) { if ( useProp ) { // ensure that every serialized input is still enabled for (i=0; i < a.length; i++) { el = $(form[a[i].name]); el.prop('disabled', false); } } else { for (i=0; i < a.length; i++) { el = $(form[a[i].name]); el.removeAttr('disabled'); } }; } if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr('name'); if (n == null) $io.attr('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, status); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document; return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); timeoutHandle && clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n]) .appendTo(form)[0]); } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } try { doc = getDoc(io); } catch(ex) { log('cannot access response document: ', ex); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (e) { status = 'parsererror'; xhr.error = errMsg = (e || status); } } catch (e) { log('error caught: ',e); status = 'error'; xhr.error = errMsg = (e || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg == undefined) errMsg = xhr.statusText; s.error && s.error.call(s.context, xhr, status, errMsg); g && $.event.trigger("ajaxError", [xhr, s, errMsg]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } } function captureSubmittingElement(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v, type: el.type}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea' || (includeHidden && /hidden/.test(t)) ) { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } }; })(jQuery);
JavaScript
$(document).ready(function() { if ($.browser.msie) { $(window).scroll(function () { $('#modalPopup').css({'top': $(window).scrollTop(), 'left' : 0}); $('.popUpBox').css({'top': $(window).scrollTop() + $(window).height()/2}); }); $(window).resize(function () { $('#modalPopup').css({'width': $(window).width(), 'height' :$(window).height()}); $('.popUpBox').css({'top': $(window).scrollTop() + $(window).height()/2, 'left': $(window).width()/2}); }); } }); /* * popUpBox 1.1 * By Dmitri Kouzma (http://kouzma.ru) * Copyright (c) 2010 Dmitri Kouzma * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ jQuery.fn.popUpBox = function(options) { // Определяем настройки окна var horisontalPosition = options['horisontalPosition'] || 'center'; var verticalPosition = options['verticalPosition'] || 'top'; var horisontalOffset = parseInt(options['horisontalOffset']) || 0; var verticalOffset = parseInt(options['verticalOffset']) || 20; var width = options['width'] || false; var simpleBorder = options['simpleBorder'] || false; var title = options['title'] || null; var inlineId = options['inlineId'] || null; var html = options['html'] || null; var url = options['url'] || null; var useHidding = options['useHidding'] || false; // Использовать или нет затухание блока var hideAfter = options['hideAfter'] || 2000; // Время, через которое блок начнет затухать var hideTime = options['hideTime'] || 5000; // Время за которое блок исчезнет var modal = options['modal'] || false; var absCenter = options['absCenter'] || false; var popUpId = options['popUpId'] || null; var beforeClose = options['beforeClose'] || null; /* this.afterClose = function() { console(5); };*/ //Подгатавливаем контент для окна var strContentInHtml; if (html) { strContentInHtml = html; } else { if (inlineId) { strContentInHtml = $("#" + inlineId).html(); } else { if (url) { var thisEl = this; $.ajax({ type: "GET", url: W_AJAX + "getCalendar/?month=12year=2009", success: function(responseText){ options['html'] = responseText; $(thisEl).popUpBox(options); } }); return this; } else return this; } } var strTitleHtml = title ? ('<div class="popUpBoxHeader">' + '<span class="popUpBoxHeaderText">' + title + '</span>' + '</div>') : ''; var strHtml = '<div' + (popUpId ? ' id="' + popUpId + '"' : '' ) + ' class="popUpBox' + (simpleBorder ? ' simpleBorder' : '' ) + '"' + (width ? 'style="width:' + width + 'px;"' : '') + '><div class="popUpBoxIn">' + strTitleHtml + '<div class="popUpBoxContent">' + strContentInHtml + '</div>' + '</div></div>'; //Определяем позиции var top = $(this).offset().top; var left = $(this).offset().left; var parentWidth = $(this).width(); var parentHeight = $(this).height(); var block = $(strHtml).appendTo('body').hide(); var blockWidth = $(block).width(); var blockHeight = $(block).height(); if (!absCenter) { //Сдвигаем блок, в зависимости от настроек позиционирования switch (horisontalPosition) { case 'center': left += (parentWidth - blockWidth) / 2 + horisontalOffset; break; case 'right': left += parentWidth + horisontalOffset; break; case 'left': left -= (blockWidth + horisontalOffset); break; default: left += (parentWidth - blockWidth) / 2 + horisontalOffset; break; } switch (verticalPosition) { case 'center': case 'middle': top += (parentHeight - blockHeight) / 2 + verticalOffset; break; case 'bottom': top += parentHeight + verticalOffset; break; case 'top': top -= (blockHeight + verticalOffset); break; default: top += parentHeight + verticalOffset; break; } //Настраиваем позиционирование блока $(block).css('position', 'absolute').css('top', top + 'px').css('left', left + 'px').css('z-index', '1000'); } else { var fullWidth = width + 24; var fullHeight = $('.popUpBox').height() + 24; if (verticalPosition == 'top') $(block).css('top', '10px').css('left', '50%').css('z-index', '1000').css('margin-left', '-' + (fullWidth / 2) + 'px'); else $(block)/*.css('position', 'fixed')*/.css('top', '50%').css('left', '50%').css('z-index', '1000').css('margin-left', '-' + (fullWidth / 2) + 'px').css('margin-top', '-' + (fullHeight / 2) + 'px'); if ($.browser.msie) { $(block).css('height', '1px'); } } if (modal) { modalBlock = $('<div id="modalPopup">.</div>').appendTo('body'); //$(modalBlock).css({height:$('html').height()+40, width:$('html').width()+40, left:-20, top:-20}); } //Добавляем рамку, при необходимости if (!simpleBorder) $(block).append('<div class="pub_t"></div><div class="pub_r"></div><div class="pub_b"></div><div class="pub_l">.</div><div class="pub_tl"></div><div class="pub_tr"></div><div class="pub_bl"></div><div class="pub_br"></div>'); //Устраняем html блока, из которого осуществлялось копирование контента if (!html && inlineId) { $("#" + inlineId).html(''); $(block).append('<div class="pub_close" title="Close" onclick="' + beforeClose + ';$(\'#' + inlineId + '\').html($(this).parent().find(\'.popUpBoxContent\').html());$(this).parent().remove();$(\'#modalPopup\').remove();"></div>'); } else { $(block).append('<div class="pub_close" title="Close" onclick="' + beforeClose + ';$(this).parent().remove();$(this).parent().remove();$(\'#modalPopup\').remove();"></div>'); } //Показываем окно $(block).show(); if ($.browser.msie) { $('#modalPopup').css({'top': $(window).scrollTop(), 'left' : 0}); $('.popUpBox').css({'top': $(window).scrollTop() + $(window).height()/2}); } // Скрываем элемент по таймеру при необходимости if (useHidding) { $(block).oneTime(hideAfter, function() { $(this).fadeOut(hideTime, function () { // Восстанавливаем для скрытого блока его содержимое if (!html && inlineId) { $("#" + inlineId).html(''); $('#' + inlineId).html($(this).parent().find('.popUpBoxContent')); } // Удаляем сам всплывающий блок $(block).remove(); $('#modalPopup').remove(); }); }); } return this; }; $(document).ready(function(){ popUpBoxInit(); }); function popUpBoxInit() { popUpBoxInitElement('a.pub, a.popUpBox'); }; function popUpBoxInitElement(pubElement) { $(pubElement).click(function () { var title = this.title || this.name || null; var url = this.href || this.alt; var optionsString = url.replace(/^[^\?]+\??/,''); var options = pub_parseOptions( optionsString ); options['title'] = title; options['url'] = url; this.blur(); $(this).popUpBox( options ); return false; }); }; function pub_parseOptions ( optionsString ) { var options = {}; if ( ! optionsString ) {return options;}// return empty object var Pairs = optionsString.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); options[key] = val; } return options; };
JavaScript
/// <reference path="../../../lib/jquery-1.2.6.js" /> /* Masked Input plugin for jQuery Copyright (c) 2007-2009 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.2.2 (03/09/2009 22:39:06) */ (function($) { var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask"; var iPhone = (window.orientation != undefined); $.mask = { //Predefined character definitions definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '*': "[A-Za-z0-9]" } }; $.fn.extend({ //Helper Function for Caret positioning caret: function(begin, end) { if (this.length == 0) return; if (typeof begin == 'number') { end = (typeof end == 'number') ? end : begin; return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(begin, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } }); } else { if (this[0].setSelectionRange) { begin = this[0].selectionStart; end = this[0].selectionEnd; } else if (document.selection && document.selection.createRange) { var range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { if (!mask && this.length > 0) { var input = $(this[0]); var tests = input.data("tests"); return $.map(input.data("buffer"), function(c, i) { return tests[i] ? c : null; }).join(''); } settings = $.extend({ placeholder: "_", completed: null }, settings); var defs = $.mask.definitions; var tests = []; var partialPosition = mask.length; var firstNonMaskPos = null; var len = mask.length; $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if(firstNonMaskPos==null) firstNonMaskPos = tests.length - 1; } else { tests.push(null); } }); return this.each(function() { var input = $(this); var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c }); var ignore = false; //Variable for ignoring control keys var focusText = input.val(); input.data("buffer", buffer).data("tests", tests); function seekNext(pos) { while (++pos <= len && !tests[pos]); return pos; }; function shiftL(pos) { while (!tests[pos] && --pos >= 0); for (var i = pos; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; var j = seekNext(i); if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; } else break; } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, pos)); }; function shiftR(pos) { for (var i = pos, c = settings.placeholder; i < len; i++) { if (tests[i]) { var j = seekNext(i); var t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) c = t; else break; } } }; function keydownEvent(e) { var pos = $(this).caret(); var k = e.keyCode; ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41)); //delete selection before proceeding if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46)) clearBuffer(pos.begin, pos.end); //backspace, delete, and escape get special treatment if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete shiftL(pos.begin + (k == 46 ? 0 : -1)); return false; } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); return false; } }; function keypressEvent(e) { if (ignore) { ignore = false; //Fixes Mac FF bug on backspace return (e.keyCode == 8) ? false : null; } e = e || window.event; var k = e.charCode || e.keyCode || e.which; var pos = $(this).caret(); if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore return true; } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters var p = seekNext(pos.begin - 1); if (p < len) { var c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); var next = seekNext(p); $(this).caret(next); if (settings.completed && next == len) settings.completed.call(input); } } } return false; }; function clearBuffer(start, end) { for (var i = start; i < end && i < len; i++) { if (tests[i]) buffer[i] = settings.placeholder; } }; function writeBuffer() { return input.val(buffer.join('')).val(); }; function checkVal(allow) { //try to place characters where they belong var test = input.val(); var lastMatch = -1; for (var i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { var c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) break; } else if (buffer[i] == test[pos] && i!=partialPosition) { pos++; lastMatch = i; } } if (!allow && lastMatch + 1 < partialPosition) { input.val(""); clearBuffer(0, len); } else if (allow || lastMatch + 1 >= partialPosition) { writeBuffer(); if (!allow) input.val(input.val().substring(0, lastMatch + 1)); } return (partialPosition ? i : firstNonMaskPos); }; if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData("buffer") .removeData("tests"); }) .bind("focus.mask", function() { focusText = input.val(); var pos = checkVal(); writeBuffer(); setTimeout(function() { if (pos == mask.length) input.caret(0, pos); else input.caret(pos); }, 0); }) .bind("blur.mask", function() { checkVal(); if (input.val() != focusText) input.change(); }) .bind("keydown.mask", keydownEvent) .bind("keypress.mask", keypressEvent) .bind(pasteEventName, function() { setTimeout(function() { input.caret(checkVal(true)); }, 0); }); checkVal(); //Perform initial check for existing values }); } }); })(jQuery);
JavaScript
/* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan <stevenlevithan.com> * MIT license * * Includes enhancements by Scott Trenda <scott.trenda.net> * and Kris Kowal <cixar.com/~kris.kowal/> * * 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 to dateFormat.masks.default. */ var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/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 (val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : 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: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; 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 dd 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", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "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, utc) { return dateFormat(this, mask, utc); };
JavaScript
/** * */ validate = { showErrors: function(errors) { // Отобржает набор ошибок из ассоциативного массива var errText = ''; for(var name in errors) { var $input = $('#Booking_' + name); if ($input.length) this.showError($input, errors[name]); else errText += errors[name] + "\n"; } if (errText) App.error(errText); }, showError: function($input, message) { // Отображает ошибку рядом с полем if ($input.is(':visible')) var $elem = $input; else { if ($input.is('select')) var $elem = $input.next(); else var $elem = $input.prev(); } $('<div class=\"inputError\" data-input-id="' + $input.attr('id') + '">' + message + '</div>').prependTo('body') .css({'z-index':2, left:$elem.offset().left + $elem.width() + 20, top:$elem.offset().top + 8}); }, validateCard: function(cn) { // Проверяет кредитную карту на валидность var odd = new Array(); var even = new Array(); for(var x in cn) { if(x % 2 == 0) odd.push(cn[x]); else even.push(cn[x]); } for(var x in odd) { var tmp = odd[x] * 2; if(tmp <= 9) odd[x] = tmp; else { var s = String(tmp); odd[x] = (s[0] - 0) + (s[1] - 0); } } var summa = 0; for(var x in odd) { summa += odd[x]; } for(var x in even) { summa += even[x] - 0; } if (summa % 10 == 0) return true; else return false; } }; jQuery.fn.validate = function() { $('.inputError').remove(); var validated = true; var elems = $(this).find('input, select').add(this).filter('input, select'); elems.bind('focus change', function() { var id = $(this).attr('id'); $('.inputError[data-input-id=' + id + ']').fadeOut(); }); elems.each(function() { var message = null; var $input = $(this); var value = $input.val(); if ($input.hasClass('vRequired')) { if (!value) { message = 'Поле должно быть заполнено'; } } if ($input.hasClass('vName')) { if (value.length < 1 || value.length > 25) { message = 'Длина поля должна быть от 1 до 25 символов'; } } if ($input.hasClass('vFullName')) { if (value.length < 3 || value.length > 50) { message = 'Длина поля должна быть от 3 до 50 символов'; } } if ($input.hasClass('vPhone')) { if (value.length < 8 || value.length > 24) { message = 'Длина поля должна быть от 8 до 24 символа'; } } if ($input.hasClass('vEMail')) { if (value.length < 1 || value.length > 50) { message = 'Длина поля должна быть от 1 до 50 символов'; } if (!(/^[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+?\.[A-Za-z0-9]{2,6}$/gi).test(value)) { message = 'E-Mail введен неверно'; } } if ($input.hasClass('vExpirity')) { if (value.length != 5) { message = 'Длина поля должна быть 5 символов'; } if (!(/^[\d]{2}\/[\d]{2}$/gi).test(value)) { message = 'Поле должно иметь формат 00/00'; } else { var arrValue = value.split('/'); if (parseInt(arrValue[0]) > 12) { message = 'Неверно указан месяц'; } if (parseInt(arrValue[1]) < 12 || parseInt(arrValue[1]) > 30) { message = 'Неверно указан год'; } } } if ($input.hasClass('vCvc')) { if (value.length < 3 || value.length > 4) { message = 'Длина поля должна быть 3-4 символа'; } if (!(/^[\d]{3,4}$/gi).test(value)) { message = 'В поле должны быть 3-4 цифры'; } } if ($input.hasClass('vCreditCard')) { if (!(/^[\d]{16}$/gi).test(value)) { message = 'В поле должны быть 16 цифр'; } if (!validate.validateCard($(this).val())) { message = 'Неверный номер карты'; } } if (message) { validated = false; // Показываем ошибку validate.showError($input, message); } }); return validated; };
JavaScript
var debug = new Array(); $().ready(function() { $('body') .ajaxComplete(function(event, XMLHttpRequest, ajaxOptions){ var expr = new RegExp('tmpl', 'i'); var textFind = ajaxOptions.url.search(expr) != -1; if (!textFind) { try { var jsonText = $.parseJSON(XMLHttpRequest.responseText); debug[debug.length] = jsonText.debug; } catch (e) { debug[debug.length] = new Object(); debug[debug.length - 1]['trace'] = XMLHttpRequest.responseText; } if (debug[debug.length - 1] != undefined) { debug[debug.length - 1]['name'] = ajaxOptions.url; debug[debug.length - 1]['post'] = ajaxOptions.data; debug[debug.length - 1]['result'] = XMLHttpRequest.responseText; } } }); $('.debugCollapse').live('click', function(){ if ($(this).next().is(':visible')) { $(this).next().hide(); if ($(this).text().substr(0, 1) == '–') $(this).text('+' + $(this).text().substr(1)); } else { $(this).next().show(); if ($(this).text().substr(0, 1) == '+') $(this).text('–' + $(this).text().substr(1)); } }); }); function jDebug() { if ($('#jDebug:visible').length) $('#jDebug').remove(); else { var retText = ''; for (var i = 0; i < debug.length; i++) { retText += '<p class="debugCollapse"><b>+ ' + debug[i]['name'] + '</b></p>'; retText += '<div class="debugHidden">'; retText += debug[i]['trace']; retText += '</div>'; } $('body').append('<div id="jDebug"></div>'); $('#jDebug').append( retText ); $('.debugHidden').hide(); } }
JavaScript
/// jquery.dataset v0.1.0 -- HTML5 dataset jQuery plugin /// http://orangesoda.net/jquery.dataset.html /// Copyright (c) 2009, Ben Weaver. All rights reserved. /// This software is issued "as is" under a BSD license /// <http://orangesoda.net/license.html>. All warrenties disclaimed. /// The HTML5 specification allows elements to have custom data /// attributes that are prefixed with `data-'. They may be /// conveniently accessed through an element's `dataset' property. /// This plugin provides similar functionality. /// /// The methods in the plugin are designed to be similar to the /// built-in `attr' and `data' methods. All names are without the /// `data-' prefix. // /// These methods are defined: /// /// dataset() /// Return an object with all custom attribute (name, value) items. /// /// dataset(name) /// Return the value of the attribute `data-NAME'. /// /// dataset(name, value) /// Set the value of attribtue `data-NAME' to VALUE. /// /// dataset({...}) /// Set many custom attributes at once. /// /// removeDataset(name) /// Remove the attribute `data-NAME'. /// /// removeDataset([n1, n2, ...]) /// Remove the attributes `data-N1', `data-N2', ... (function($) { var PREFIX = 'data-', PATTERN = /^data\-(.*)$/; function dataset(name, value) { if (value !== undefined) { // dataset(name, value): set the NAME attribute to VALUE. return this.attr(PREFIX + name, value); } switch (typeof name) { case 'string': // dataset(name): get the value of the NAME attribute. return this.attr(PREFIX + name); case 'object': // dataset(items): set the values of all (name, value) items. return set_items.call(this, name); case 'undefined': // dataset(): return a mapping of (name, value) items for the // first element. return get_items.call(this); default: throw 'dataset: invalid argument ' + name; } } function get_items() { return this.foldAttr(function(index, attr, result) { var match = PATTERN.exec(this.name); if (match) result[match[1]] = this.value; }); } function set_items(items) { for (var key in items) { this.attr(PREFIX + key, items[key]); } return this; } function remove(name) { if (typeof name == 'string') { // Remove a single attribute; return this.removeAttr(PREFIX + name); } return remove_names(name); } function remove_names(obj) { var idx, length = obj && obj.length; // For any object, remove attributes named by the keys. if (length === undefined) { for (idx in obj) { this.removeAttr(PREFIX + idx); } } // For an array, remove attributes named by the values. else { for (idx = 0; idx < length; idx++) { this.removeAttr(PREFIX + obj[idx]); } } return this; } $.fn.dataset = dataset; $.fn.removeDataset = remove_names; })(jQuery); (function($) { function each_attr(proc) { if (this.length > 0) { $.each(this[0].attributes, proc); } return this; } function fold_attr(proc, acc) { return fold((this.length > 0) && this[0].attributes, proc, acc); } /* * A left-fold operator. The behavior is the same as $.each(), * but the callback is called with the accumulator as the third * argument. The default accumulator is an empty object. */ function fold(object, proc, acc) { var length = object && object.length; // The default accumulator is an empty object. if (acc === undefined) acc = {}; // Returning an empty accumulator when OBJECT is "false" // makes FOLD more composable. if (!object) return acc; // Check to see if OBJECT is an array. if (length !== undefined) { for (var i = 0, value = object[i]; (i < length) && (proc.call(value, i, value, acc) !== false); value = object[++i]) { } } // Object is a map of (name, value) items. else { for (var name in object) { if (proc.call(object[name], name, object[name], acc) === false) break; } } return acc; } function fold_jquery(proc, acc) { if (acc === undefined) acc = []; return fold(this, proc, acc); } $.fn.eachAttr = each_attr; $.fn.foldAttr = fold_attr; $.fn.fold = fold_jquery; $.fold = fold; })(jQuery);
JavaScript
var calendar = {}; var today = new Date; var startArr = today.getDate() + "/" + (today.getMonth() + 1) + "/" + today.getFullYear(); var margin = 0; var actualArr; var actualDep; var actDateArr; var actualDateArr; var arrActualArr; var dateActualArr; var actDateDep; var actualDateDep; var startDep; var calendarEnd = new Date(today.getTime()+365*24*60*60*1000); calendarEnd = calendarEnd.getDate() + "/" + (calendarEnd.getMonth() + 1) + "/" + calendarEnd.getFullYear(); var calendarEndDep = new Date(today.getTime()+29*24*60*60*1000); calendarEndDep = calendarEndDep.getDate() + "/" + (calendarEndDep.getMonth() + 1) + "/" + calendarEndDep.getFullYear(); var message_1 = arrLang['Неверная дата']; var message_2 = arrLang['Неверная дата']; var message_3 = arrLang['Неверная дата']; $(document).ready(function() { calendar.makeDates('date_arr', 'date_dep'); calendar.set(startArr, calendarEnd, actualArr, 'date_arr', 'arrDateFunction', message_1, message_2, message_3, 'errorClass'); calendar.set(startDep, calendarEndDep, actualDep, 'date_dep', 'depDateFunction', message_1, message_2, message_3, 'errorClass'); }); /** * Навешиваем datepicker и обработку ручного ввода и ошибок */ calendar.set = function(dateStart, dateEnd, dateActual, fieldId, functionName, earlyText, lateText, wrongText, errorClass) { if (!$('#' + fieldId).length) return !1; // -- Преобразуем даты -- dateStart = calendar.makeDate(dateStart); dateEnd = calendar.makeDate(dateEnd); dateActual = calendar.makeDate(dateActual); // -- Подключаем datepicker -- $('#' + fieldId).datepicker({ setDate: dateActual, dateFormat: 'dd/mm/yy', showOn: 'both', minDate : dateStart, maxDate : dateEnd, buttonImage: W_IMAGES + 'icons/cal.png', buttonImageOnly: true, numberOfMonths: 2, showButtonPanel: true, rangeSelect: true, onSelect: function(date, inst) { $(this).next().next('.' + errorClass).remove(); window[functionName](date, inst); //window[functionName](); } }).datepicker('setDate', dateActual); // -- Проверка вводимой в поле даты -- $('#' + fieldId).keyup(function() { $("#text_" + fieldId).text(''); if ($('#' + fieldId).val().length != 10) { $("#text_" + fieldId).text(wrongText); return !1; } var arrDate = $('#' + fieldId).val().split('/'); if (arrDate.length != 3) { $("#text_" + fieldId).text(wrongText); return !1; } var date = new Date(arrDate[2], arrDate[1] - 1, arrDate[0]); if (date.getTime() < dateStart.getTime()) { $("#text_" + fieldId).text(earlyText); return !1; } if (date.getTime() > dateEnd.getTime()) { $("text_" + fieldId).text(lateText); return !1; } window[functionName]($('#' + fieldId).val(), $(this)); }); }; // -- END of calendar.set -- /** * Проверка на наличие ошибок */ calendar.errorsExist = function(arrErrorClasses) { for (var errorClass in arrErrorClasses) { if ($('.' + arrErrorClasses[errorClass]).length) return 1; } return !1; }; /** * Создаем объект даты из строки вида "18/05/2012" */ calendar.makeDate = function(date) { if (!date) return new Date(0); var arrDate = date.split('/'); return new Date(arrDate[2], arrDate[1] - 1, arrDate[0]); }; /** * Формируем даты для инициализации datePicker */ calendar.makeDates = function(fieldArrId, fieldDepId) { // Дата заезда if ($('#' + fieldArrId).val()) actualArr = $('#' + fieldArrId).val(); else actualArr = null; if (calendar.makeDate(actualArr).getTime() < new Date().getTime()) { actDateArr = today.getTime() + parseInt(margin)*24*60*60*1000; actualDateArr = new Date(actDateArr); actualArr = actualDateArr.getDate()+ "/" +(actualDateArr.getMonth()+1)+ "/" +actualDateArr.getFullYear(); //dateActualArr = calendar.makeDate(actualArr); } // Дата отъезда if ($('#' + fieldDepId).val()) actualDep = $('#' + fieldDepId).val(); else actualDep = null; if (calendar.makeDate(actualDep).getTime() < calendar.makeDate(actualArr).getTime() + 24*60*60*1000) { actDateDep = calendar.makeDate(actualArr).getTime() + 24*60*60*1000; actualDateDep = new Date(actDateDep); actualDep = actualDateDep.getDate() + "/" + (actualDateDep.getMonth()+1) + "/" + actualDateDep.getFullYear(); } // Дата начала отсчета для отъезда (дата заезда + 1 день) var startDateDep = calendar.makeDate(actualArr); startDateDep = new Date(startDateDep.getTime() + 24 * 60 * 60 * 1000); startDep = startDateDep.getDate() + "/" + (startDateDep.getMonth()+1) + "/" + startDateDep.getFullYear(); calendarEndDep = new Date(startDateDep.getTime()+29*24*60*60*1000); calendarEndDep = calendarEndDep.getDate() + "/" + (calendarEndDep.getMonth() + 1) + "/" + calendarEndDep.getFullYear(); }; /** * Функция для обработки выбора даты заезда * @param date - выбранная дата * @param object - объект datepicker */ function arrDateFunction(date, object) { var arrDate = new Date(object.currentYear, object.currentMonth, object.currentDay); var fieldId = (object.id.substr(0, object.id.length - 3) + 'dep'); var depDate = calendar.makeDate($('#' + fieldId).val()); var dep_time = arrDate.getTime() + 24 * 60 * 60 * 1000; if (dep_time > depDate.getTime()) depDate = new Date(dep_time); var dateStart = calendar.makeDate($('#' + object.id).val()); dateStart = new Date(dateStart.getTime() + 24 * 60 * 60 * 1000); var dateEnd = new Date(dateStart.getTime() + 24 * 60 * 60 * 1000 * 29); // Меняем дату и начало отсчета для даты отъезда $('#' + fieldId).val('').datepicker('option', 'minDate', dateStart).datepicker('setDate', depDate) .datepicker('option', 'maxDate', dateEnd); }; function depDateFunction(){};
JavaScript
/** * jQuery Cookie plugin * * Copyright (c) 2010 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ jQuery.cookie = function (key, value, options) { // key and at least value given, set cookie... if (arguments.length > 1 && String(value) !== "[object Object]") { options = jQuery.extend({}, options); if (value === null || value === undefined) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = String(value); return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || {}; var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent; return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null; };
JavaScript
/** * jQuery-Plugin "preloadCssImages" * by Scott Jehl, scott@filamentgroup.com * http://www.filamentgroup.com * reference article: http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/ * demo page: http://www.filamentgroup.com/examples/preloadImages/index_v2.php * * Copyright (c) 2008 Filament Group, Inc * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses. * * Version: 5.0, 10.31.2008 * Changelog: * 02.20.2008 initial Version 1.0 * 06.04.2008 Version 2.0 : removed need for any passed arguments. Images load from any and all directories. * 06.21.2008 Version 3.0 : Added options for loading status. Fixed IE abs image path bug (thanks Sam Pohlenz). * 07.24.2008 Version 4.0 : Added support for @imported CSS (credit: http://marcarea.com/). Fixed support in Opera as well. * 10.31.2008 Version: 5.0 : Many feature and performance enhancements from trixta * -------------------------------------------------------------------- */ ;jQuery.preloadCssImages = function(settings){ settings = jQuery.extend({ statusTextEl: null, statusBarEl: null, errorDelay: 999, // handles 404-Errors in IE simultaneousCacheLoading: 2 }, settings); var allImgs = [], loaded = 0, imgUrls = [], thisSheetRules, errorTimer; function onImgComplete(){ clearTimeout(errorTimer); if (imgUrls && imgUrls.length && imgUrls[loaded]) { loaded++; if (settings.statusTextEl) { var nowloading = (imgUrls[loaded]) ? 'Now Loading: <span>' + imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length - 1] : 'Loading complete'; // wrong status-text bug fixed jQuery(settings.statusTextEl).html('<span class="numLoaded">' + loaded + '</span> of <span class="numTotal">' + imgUrls.length + '</span> loaded (<span class="percentLoaded">' + (loaded / imgUrls.length * 100).toFixed(0) + '%</span>) <span class="currentImg">' + nowloading + '</span></span>'); } if (settings.statusBarEl) { var barWidth = jQuery(settings.statusBarEl).width(); jQuery(settings.statusBarEl).css('background-position', -(barWidth - (barWidth * loaded / imgUrls.length).toFixed(0)) + 'px 50%'); } loadImgs(); } } function loadImgs(){ //only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...) // otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads if(imgUrls && imgUrls.length && imgUrls[loaded]){ var img = new Image(); //new img obj img.src = imgUrls[loaded]; //set src either absolute or rel to css dir if(!img.complete){ jQuery(img).bind('error load onreadystatechange', onImgComplete); } else { onImgComplete(); } errorTimer = setTimeout(onImgComplete, settings.errorDelay); // handles 404-Errors in IE } } function parseCSS(sheets, urls) { var w3cImport = false, imported = [], importedSrc = [], baseURL; var sheetIndex = sheets.length; while(sheetIndex--){//loop through each stylesheet var cssPile = '';//create large string of all css rules in sheet if(urls && urls[sheetIndex]){ baseURL = urls[sheetIndex]; } else { var csshref = (sheets[sheetIndex].href) ? sheets[sheetIndex].href : 'window.location.href'; var baseURLarr = csshref.split('/');//split href at / to make array baseURLarr.pop();//remove file path from baseURL array baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir) if (baseURL) { baseURL += '/'; //tack on a / if needed } } if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){ thisSheetRules = (sheets[sheetIndex].cssRules) ? //->>> http://www.quirksmode.org/dom/w3c_css.html sheets[sheetIndex].cssRules : //w3 sheets[sheetIndex].rules; //ie var ruleIndex = thisSheetRules.length; while(ruleIndex--){ if(thisSheetRules[ruleIndex].style && thisSheetRules[ruleIndex].style.cssText){ var text = thisSheetRules[ruleIndex].style.cssText; if(text.toLowerCase().indexOf('url') != -1){ // only add rules to the string if you can assume, to find an image, speed improvement cssPile += text; // thisSheetRules[ruleIndex].style.cssText instead of thisSheetRules[ruleIndex].cssText is a huge speed improvement } } else if(thisSheetRules[ruleIndex].styleSheet) { imported.push(thisSheetRules[ruleIndex].styleSheet); w3cImport = true; } } } //parse cssPile for image urls var tmpImage = cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename" / '"' for opera-bugfix if(tmpImage){ var i = tmpImage.length; while(i--){ // handle baseUrl here for multiple stylesheets in different folders bug var imgSrc = (tmpImage[i].charAt(0) == '/' || tmpImage[i].match('://')) ? // protocol-bug fixed tmpImage[i] : baseURL + tmpImage[i]; if(jQuery.inArray(imgSrc, imgUrls) == -1){ imgUrls.push(imgSrc); } } } if(!w3cImport && sheets[sheetIndex].imports && sheets[sheetIndex].imports.length) { for(var iImport = 0, importLen = sheets[sheetIndex].imports.length; iImport < importLen; iImport++){ var iHref = sheets[sheetIndex].imports[iImport].href; iHref = iHref.split('/'); iHref.pop(); iHref = iHref.join('/'); if (iHref) { iHref += '/'; //tack on a / if needed } var iSrc = (iHref.charAt(0) == '/' || iHref.match('://')) ? // protocol-bug fixed iHref : baseURL + iHref; importedSrc.push(iSrc); imported.push(sheets[sheetIndex].imports[iImport]); } } }//loop if(imported.length){ parseCSS(imported, importedSrc); return false; } var downloads = settings.simultaneousCacheLoading; while( downloads--){ setTimeout(loadImgs, downloads); } } parseCSS(document.styleSheets); return imgUrls; }; $(document).ready(function(){ $.preloadCssImages(); });
JavaScript
/** * jQuery.timers - Timer abstractions for jQuery * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com) * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/). * Date: 2009/02/08 * * @author Blair Mitchelmore * @version 1.1.2 * **/ jQuery.fn.extend({ everyTime: function(interval, label, fn, times, belay) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, times, belay); }); }, oneTime: function(interval, label, fn) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, 1); }); }, stopTime: function(label, fn) { return this.each(function() { jQuery.timer.remove(this, label, fn); }); } }); jQuery.event.special jQuery.extend({ timer: { global: [], guid: 1, dataKey: "jQuery.timer", regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/, powers: { // Yeah this is major overkill... 'ms': 1, 'cs': 10, 'ds': 100, 's': 1000, 'das': 10000, 'hs': 100000, 'ks': 1000000 }, timeParse: function(value) { if (value == undefined || value == null) return null; var result = this.regex.exec(jQuery.trim(value.toString())); if (result[2]) { var num = parseFloat(result[1]); var mult = this.powers[result[2]] || 1; return num * mult; } else { return value; } }, add: function(element, interval, label, fn, times, belay) { var counter = 0; if (jQuery.isFunction(label)) { if (!times) times = fn; fn = label; label = interval; } interval = jQuery.timer.timeParse(interval); if (typeof interval != 'number' || isNaN(interval) || interval <= 0) return; if (times && times.constructor != Number) { belay = !!times; times = 0; } times = times || 0; belay = belay || false; var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {}); if (!timers[label]) timers[label] = {}; fn.timerID = fn.timerID || this.guid++; var handler = function() { if (belay && this.inProgress) return; this.inProgress = true; if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn); this.inProgress = false; }; handler.timerID = fn.timerID; if (!timers[label][fn.timerID]) timers[label][fn.timerID] = window.setInterval(handler,interval); this.global.push( element ); }, remove: function(element, label, fn) { var timers = jQuery.data(element, this.dataKey), ret; if ( timers ) { if (!label) { for ( label in timers ) this.remove(element, label, fn); } else if ( timers[label] ) { if ( fn ) { if ( fn.timerID ) { window.clearInterval(timers[label][fn.timerID]); delete timers[label][fn.timerID]; } } else { for ( var fn in timers[label] ) { window.clearInterval(timers[label][fn]); delete timers[label][fn]; } } for ( ret in timers[label] ) break; if ( !ret ) { ret = null; delete timers[label]; } } for ( ret in timers ) break; if ( !ret ) jQuery.removeData(element, this.dataKey); } } } }); jQuery(window).bind("unload", function() { jQuery.each(jQuery.timer.global, function(index, item) { jQuery.timer.remove(item); }); });
JavaScript
(function ($) { $.fn.keyboard = function () { $k.bind(this, arguments); return this; }; $.keyboard = function () { $k.bind($(document), arguments); return this; }; var $k = { setup : { 'strict' : true, 'event' : 'keydown', 'preventDefault' : false }, keys : { cont : [], getCodes : function () { var codes = []; for (var i = 0; i < $k.keys.cont.length; i++) { codes.push($k.keys.cont[i].keyCode); } return codes; }, add : function (e) { if (e.keyCode == 0) { // throw 'ZeroKeyCodeException'; } else { $k.keys.rm(e); $k.keys.cont.push(e); $k.keys.dump(); } }, rm : function (e) { for (var i = 0; i < $k.keys.cont.length; i++) { if ($k.keys.cont[i].keyCode == e.keyCode) { $k.keys.cont.splice(i, 1); return; } } }, clear : function () { $k.keys.cont = []; }, dump : function () { } }, keyCodes : { // Alphabet a:65, b:66, c:67, d:68, e:69, f:70, g:71, h:72, i:73, j:74, k:75, l:76, m:77, n:78, o:79, p:80, q:81, r:82, s:83, t:84, u:85, v:86, w:87, x:88, y:89, z:90, // Numbers n0:48, n1:49, n2:50, n3:51, n4:52, n5:53, n6:54, n7:55, n8:56, n9:57, // Controls tab: 9, enter:13, shift:16, backspace:8, ctrl:17, alt :18, esc :27, space :32, menu:93, pause:19, cmd :91, insert :45, home:36, pageup :33, 'delete':46, end :35, pagedown:34, // F* f1:112, f2:113, f3:114, f4 :115, f5 :116, f6 :117, f7:118, f8:119, f9:120, f10:121, f11:122, f12:123, // numpad np0: 96, np1: 97, np2: 98, np3: 99, np4:100, np5:101, np6:102, np7:103, np8:104, np9:105, npslash:11,npstar:106,nphyphen:109,npplus:107,npdot:110, // Lock capslock:20, numlock:144, scrolllock:145, // Symbols equals: 61, hyphen :109, coma :188, dot:190, gravis:192, backslash:220, sbopen:219, sbclose:221, slash :191, semicolon: 59, apostrophe : 222, // Arrows aleft:37, aup: 38, aright:39, adown:40 }, parseArgs : function (args) { if (typeof args[0] == 'object') { return { setup : args[0] }; } else { var secondIsFunc = (typeof args[1] == 'function'); var isDelete = !secondIsFunc && (typeof args[2] != 'function'); var argsObj = {}; argsObj.keys = args[0]; if ($.isArray(argsObj.keys)) { argsObj.keys = argsObj.keys.join(' '); } if (isDelete) { argsObj.isDelete = true; } else { argsObj.func = secondIsFunc ? args[1] : args[2]; argsObj.cfg = secondIsFunc ? args[2] : args[1]; if (typeof argsObj.cfg != 'object') { argsObj.cfg = {}; } argsObj.cfg = $.extend(clone($k.setup), argsObj.cfg); } return argsObj; } }, getIndex : function (keyCodes, order) { return (order == 'strict') ? 's.' + keyCodes.join('.') : 'f.' + clone(keyCodes).sort().join('.'); }, getIndexCode : function (index) { if ($k.keyCodes[index]) { return $k.keyCodes[index]; } else { throw 'No such index: «' + index + '»'; } }, getRange : function (title) { var c = $k.keyCodes; var f = arguments.callee; switch (title) { case 'letters' : return range (c['a'] , c['z']); case 'numbers' : return range (c['n0'] , c['n9']); case 'numpad' : return range (c['np0'], c['np9']); case 'fkeys' : return range (c['f1'] , c['f12']); case 'arrows' : return range (c['aleft'], c['adown']); case 'symbols' : return [ c.equals, c.hyphen, c.coma, c.dot, c.gravis, c.backslash, c.sbopen, c.sbclose, c.slash, c.semicolon, c.apostrophe, c.npslash, c.npstar, c.nphyphen,c.npplus,c.npdot ]; case 'allnum' : return f('numbers').concat(f('numpad')); case 'printable': return f('letters').concat( f('allnum') .concat( f('symbols'))); default : throw 'No such range: «' + title + '»'; } }, stringGetCodes : function (str) { var parts; str = str.toLowerCase(); if (str.match(/^\[[\w\d\s\|\)\(\-]*\]$/i)) { // [ space | (letters) | (n4-n7) ] var codes = []; parts = str .substring(1, str.length-1) .replace(/\s/, '') .split('|'); for (var i = 0; i < parts.length; i++) { var p = $k.stringGetCodes(parts[i]); codes = codes.concat(p); } return codes; } else if (str.match(/^\([\w\d\s\-]*\)$/i)) { // (n4-n7) parts = str .substring(1, str.length-1) .replace(/\s/, '') .split('-'); if(parts.length == 2) { return range( $k.getIndexCode(parts[0]), $k.getIndexCode(parts[1]) ); } else { return $k.getRange(parts[0]); } } else { return [$k.getIndexCode(str)]; } }, getCodes : function (keys) { // ['shift', 'ctrl'] => [16, 17] var keycodes = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!isNaN(key)) { // is_numeric key = [1 * key]; } else if (typeof key == 'string') { key = $k.stringGetCodes(key); } else { throw 'Wrong key type: «' + (typeof key) + '»'; } keycodes.push(key); } return keycodes; }, parseKeysString : function (str) { var parts = str.split(','); for (var i = 0; i < parts.length; i++) { var string = $.trim(parts[i]); parts[i] = {}; parts[i].order = string.indexOf('+') >= 0 ? 'strict' : 'float'; parts[i].codes = $k.getCodes( string.split(parts[i].order == 'strict' ? '+' : ' ') ); parts[i].index = $k.getIndex(parts[i].codes, parts[i].order); parts[i].group = i; } return parts; }, match : function (bind) { var k, i, matched, cur = undefined; var cont = $k.keys.getCodes(); var codes = clone(bind.keys.codes); var eventIndexes = []; if (codes.length == 0) { return false; } if (bind.keys.order == 'strict') { for (i = 0; i < cont.length; i++) { if (!codes.length) { break; } if (cur === undefined) { cur = codes.shift(); } if (inArray(cont[i], cur)) { cur = undefined; eventIndexes.push(i); } else if (bind.cfg.strict) { return false; } } return (codes.length === 0 && cur === undefined) ? eventIndexes : false; } else { for (i = 0; i < codes.length; i++) { matched = false; for (k = 0; k < codes[i].length; k++) { cur = $.inArray(codes[i][k], cont); if (cur >= 0) { eventIndexes.push(cur); matched = true; break; } } if (!matched) { return false; } } if (bind.cfg.strict) { for (i = 0; i < cont.length; i++) { matched = false; for (k in codes) { if (inArray(cont[i], codes[k])) { matched = true; break; } } if (!matched) { return false; } } } return eventIndexes; } }, hasCurrent : function (bind, e) { var last = bind.keys.codes.length - 1; return (bind.keys.order == 'strict') ? inArray (e.keyCode, bind.keys.codes[last]) : inArrayR (e.keyCode, bind.keys.codes); }, checkBinds : function ($obj, e) { var ei, okb = $obj.keyboardBinds; for (var i in okb) { var bind = okb[i]; if (bind.cfg.event == e.originalEvent.type) { ei = $k.match(bind); if ( ei && $k.hasCurrent(bind, e) ) { var backup = $obj.keyboardFunc; var events = []; for (var k in ei) { events.push($k.keys.cont[ei[k]]); } $obj.keyboardFunc = bind.func; $obj.keyboardFunc(events, bind); $obj.keyboardFunc = backup; if (bind.cfg.preventDefault) { e.preventDefault(); } } } } }, bind : function ($obj, args) { args = $k.parseArgs(args); if (args.setup) { $k.setup = $.extend($k.setup, args.setup); } else { if (!$obj.keyboardBinds) { $obj.keyboardBinds = {}; $obj .keydown(function (e) { $k.keys.add(e); $k.checkBinds($obj, e); }) .keyup(function (e) { $k.checkBinds($obj, e); }); } // {keys, func, cfg} var parts = $k.parseKeysString(args.keys); for (var i = 0; i < parts.length; i++) { if (args.keys.isDelete) { $obj.keyboardBinds[parts[i].index] = undefined; } else { $obj.keyboardBinds[parts[i].index] = clone(args); $obj.keyboardBinds[parts[i].index].keys = parts[i]; } } } }, init : function () { $(document) .keydown ( $k.keys.add ) .keyup (function (e) { setTimeout(function () { $k.keys.rm(e); }, 0); }) .blur ( $k.keys.clear ); } }; var inArrayR = function (value, array) { for (var i = 0; i < array.length; i++) { if (typeof array[i] == 'object' || $.isArray(array[i])) { if (inArrayR(value, array[i])) { return true; } } else if (value == array[i]) { return true; } } return false; }; var inArray = function (value, array) { return ($.inArray(value, array) != -1); }; var range = function (from, to) { var r = []; do { r.push(from); } while (from++ < to); return r; }; var clone = function (obj) { var newObj, i; if ($.isArray(obj)) { newObj = []; for (i = 0; i < obj.length; i++) { newObj[i] = (typeof obj[i] == 'object' || $.isArray(obj[i])) ? clone(obj[i]) : obj[i]; } } else { newObj = {}; for (i in obj) { newObj[i] = (typeof obj[i] == 'object' || $.isArray(obj[i])) ? clone(obj[i]) : obj[i]; } } return newObj; }; $k.init(); })(jQuery);
JavaScript
/** * @class eli18n * Javascript applications localization * * @param Object o - class options. Object. {textdomain : 'имя_группы_сообщений', messages : {textdomain1 : {}[, textdomain2 : {}]...}} * * Usage: * * var msgs = { Hello : 'Превэд', 'Hello %user' : 'Превед %user' }; * //load messages and set default textdomain * var translator = new eli18n( {textdomain : 'test', messages : {test : msgs}} ) * window.console.log(translator.translate('Hello')); * window.console.log(translator.format('Hello %user', {user : 'David Blain'})) * // create new textdomain * translator.load({test2 : {'Goodbye' : 'Ja, deva mata!'} }) * // and use it, without changing default one * window.console.log(translator.translate('Goodbye', 'test2')); * * @author: Dmitry (dio) Levashov dio@std42.ru * license: BSD license **/ function eli18n(o) { /** * Get/set default textdomain * * @param String d new textdomain name * @return String default textdomain **/ this.textdomain = function(d) { return this.messages[d] ? this._domain = d : this._domain; } o && o.messages && this.load(o.messages); o && o.textdomain && this.textdomain(o.textdomain); } eli18n.prototype = new function() { /** * @var Object messages (key - messages in English or message handler, value - message in selected language) **/ this.messages = {}; /** * @var String default textdomain **/ this._domain = ''; /** * Load new messages * * @param Object msgs - messages (key - textdomain name, value - messages Object) * @return Object this **/ this.load = function(msgs) { if (typeof(msgs) == 'object') { for (var d in msgs) { var _msgs = msgs[d]; if (typeof(_msgs) == 'object') { if (!this.messages[d]) { this.messages[d] = {}; } for (var k in _msgs) { if (typeof(_msgs[k]) == 'string') { this.messages[d][k] = _msgs[k]; } } } } } return this; } /** * Return translated message, if message exists in required or default textdomain, otherwise returns original message * * @param String msg - message * @param String d - textdomain. If empty, default textdomain will be used * @return String translated message **/ this.translate = function(msg, d) { var d = d && this.messages[d] ? d : this._domain; return this.messages[d] && this.messages[d][msg] ? this.messages[d][msg] : msg; } /** * Translate message and replace placeholders (%placeholder) * * @param String msg - message * @param Object replacement for placeholders (keys - placeholders name without leading %, values - replacements) * @param String d - textdomain. If empty, default textdomain will be used * @return String translated message **/ this.format = function(msg, data, d) { msg = this.translate(msg, d); if (typeof(data) == 'object') { for (var i in data) { msg = msg.replace('%'+i, this.translate(data[i], d)); } } return msg; } } /** * @class elDialogForm * Wraper for jquery.ui.dialog and jquery.ui.tabs * Create form in dialog. You can decorate it as you wish - with tabs or/and tables * * Usage: * var d = new elDialogForm(opts) * d.append(['Field name: ', $('<input type="text" name="f1" />')]) * .separator() * .append(['Another field name: ', $('<input type="text" name="f2" />')]) * .open() * will create dialog with pair text field separated by horizontal rule * Calling append() with 2 additional arguments ( d.append([..], null, true)) * - will create table in dialog and put text inputs and labels in table cells * * Dialog with tabs: * var d = new elDialogForm(opts) * d.tab('first', 'First tab label) * .tab('second', 'Second tab label) * .append(['Field name: ', $('<input type="text" name="f1" />')], 'first', true) - add label and input to first tab in table (table will create automagicaly) * .append(['Field name 2: ', $('<input type="text" name="f2" />')], 'second', true) - same in secon tab * * Options: * class - css class for dialog * submit - form submit event callback. Accept 2 args - event and this object * ajaxForm - arguments for ajaxForm, if needed (dont forget include jquery.form.js) * tabs - arguments for ui.tabs * dialog - arguments for ui.dialog * name - hidden text field in wich selected value will saved * * Notice! * When close dialog, it will destroing insead of dialog('close'). Reason - strange bug with tabs in dialog on secondary opening. * * @author: Dmitry Levashov (dio) dio@std42.ru * **/ function elDialogForm(o) { var self = this; var defaults = { 'class' : 'el-dialogform', submit : function(e, d) { d.close(); }, form : { action : window.location.href, method : 'post' }, ajaxForm : null, validate : null, spinner : 'Loading', tabs : { active: 0, selected : 0 }, tabPrefix : 'el-df-tab-', dialog : { title : 'dialog', autoOpen : false, modal : true, resizable : false, closeOnEscape : true, buttons : { Cancel : function() { self.close(); }, Ok : function() { self.form.trigger('submit'); } } } }; this.opts = jQuery.extend(true, {}, defaults, o); this.opts.dialog.close = function() { self.close(); } // this.opts.dialog.autoOpen = true; if (this.opts.rtl) { this.opts['class'] += ' el-dialogform-rtl'; } if (o && o.dialog && o.dialog.buttons && typeof(o.dialog.buttons) == 'object') { this.opts.dialog.buttons = o.dialog.buttons; } this.ul = null; this.tabs = {}; this._table = null; this.dialog = jQuery('<div />').addClass(this.opts['class']).dialog(this.opts.dialog); this.message = jQuery('<div class="el-dialogform-message rounded-5" />').hide().appendTo(this.dialog); this.error = jQuery('<div class="el-dialogform-error rounded-5" />').hide().appendTo(this.dialog); this.spinner = jQuery('<div class="spinner" />').hide().appendTo(this.dialog); this.content = jQuery('<div class="el-dialogform-content" />').appendTo(this.dialog) this.form = jQuery('<form />').attr(this.opts.form).appendTo(this.content); if (this.opts.submit) { this.form.bind('submit', function(e) { self.opts.submit(e, self) }) } if (this.opts.ajaxForm && jQuery.fn.ajaxForm) { this.form.ajaxForm(this.opts.ajaxForm); } if (this.opts.validate) { this.form.validate(this.opts.validate); } this.option = function(name, value) { return this.dialog.dialog('option', name, value) } this.showError = function(msg, hideContent) { this.hideMessage(); this.hideSpinner(); this.error.html(msg).show(); hideContent && this.content.hide(); return this; } this.hideError= function() { this.error.text('').hide(); this.content.show(); return this; } this.showSpinner = function(txt) { this.error.hide(); this.message.hide(); this.content.hide(); this.spinner.text(txt||this.opts.spinner).show(); this.option('buttons', {}); return this; } this.hideSpinner = function() { this.content.show(); this.spinner.hide(); return this; } this.showMessage = function(txt, hideContent) { this.hideError(); this.hideSpinner(); this.message.html(txt||'').show(); hideContent && this.content.hide(); return this; } this.hideMessage = function() { this.message.hide(); this.content.show(); return this; } /** * Create new tab * @param string id - tab id * @param string title - tab name * @return elDialogForm **/ this.tab = function(id, title) { id = this.opts.tabPrefix+id; if (!this.ul) { this.ul = jQuery('<ul />').prependTo(this.form); } jQuery('<li />').append(jQuery('<a />').attr('href', '#'+id).html(title)).appendTo(this.ul); this.tabs[id] = {tab : jQuery('<div />').attr('id', id).addClass('tab').appendTo(this.form), table : null}; return this; } /** * Create new table * @param string id tab id, if set - table will create in tab, otherwise - in dialog * @return elDialogForm **/ this.table = function(id) { id = id && id.indexOf(this.opts.tabPrefix) == -1 ? this.opts.tabPrefix+id : id; if (id && this.tabs && this.tabs[id]) { this.tabs[id].table = jQuery('<table />').appendTo(this.tabs[id].tab); } else { this._table = jQuery('<table />').appendTo(this.form); } return this; } /** * Append html, dom nodes or jQuery objects to dialog or tab * @param array|object|string data object(s) to append to dialog * @param string tid tab id, if adding to tab * @param bool t if true - data will added in table (creating automagicaly) * @return elDialogForm **/ this.append = function(data, tid, t) { tid = tid ? 'el-df-tab-'+tid : ''; if (!data) { return this; } if (tid && this.tabs[tid]) { if (t) { !this.tabs[tid].table && this.table(tid); var tr = jQuery('<tr />').appendTo(this.tabs[tid].table); if (!jQuery.isArray(data)) { tr.append(jQuery('<td />').append(data)); } else { for (var i=0; i < data.length; i++) { tr.append(jQuery('<td />').append(data[i])); }; } } else { if (!jQuery.isArray(data)) { this.tabs[tid].tab.append(data) } else { for (var i=0; i < data.length; i++) { this.tabs[tid].tab.append(data[i]); }; } } } else { if (!t) { if (!jQuery.isArray(data)) { this.form.append(data); } else { for (var i=0; i < data.length; i++) { this.form.append(data[i]); }; } } else { if (!this._table) { this.table(); } var tr = jQuery('<tr />').appendTo(this._table); if (!jQuery.isArray(data)) { tr.append(jQuery('<td />').append(data)); } else { for (var i=0; i < data.length; i++) { tr.append(jQuery('<td />').append(data[i])); }; } } } return this; } /** * Append separator (div class="separator") to dialog or tab * @param string tid tab id, if adding to tab * @return elDialogForm **/ this.separator = function(tid) { tid = 'el-df-tab-'+tid; if (this.tabs && this.tabs[tid]) { this.tabs[tid].tab.append(jQuery('<div />').addClass('separator')); this.tabs[tid].table && this.table(tid); } else { this.form.append(jQuery('<div />').addClass('separator')); } return this; } /** * Open dialog window * @return elDialogForm **/ this.open = function() { var self = this; this.ul && this.form.tabs(this.opts.tabs); setTimeout(function() { self.dialog.find(':text') .keydown(function(e) { if (e.keyCode == 13) { e.preventDefault() self.form.submit(); } }) .filter(':first')[0].focus() }, 200); this.dialog.dialog('open'); return this; } /** * Close dialog window and destroy content * @return void **/ this.close = function() { if (typeof(this.opts.close) == 'function') { this.opts.close(); } this.dialog.dialog('destroy')//.remove(); } } /** * elColorPicker. JQuery plugin * Create drop-down colors palette. * * Usage: * $(selector).elColorPicker(opts) * * set color after init: * var c = $(selector).elColorPicker(opts) * c.val('#ffff99) * * Get selected color: * var color = c.val(); * * Notice! * Palette created only after first click on element (lazzy loading) * * Options: * colors - colors array (by default display 256 web safe colors) * color - current (selected) color * class - css class for display "button" (element on wich plugin was called) * paletteClass - css class for colors palette * palettePosition - string indicate where palette will created: * 'inner' - palette will attach to element (acceptable in most cases) * 'outer' - palette will attach to document.body. * Use, when create color picker inside element with overflow == 'hidden', for example in ui.dialog * update - function wich update button view on select color (by default set selected color as background) * change - callback, called when color was selected (by default write color to console.log) * name - hidden text field in wich selected color value will saved * * @author: Dmitry Levashov (dio) dio@std42.ru * **/ (function($) { $.fn.elColorPicker = function(o) { var self = this; var opts = $.extend({}, $.fn.elColorPicker.defaults, o); this.hidden = $('<input type="hidden" />').attr('name', opts.name).val(opts.color||'').appendTo(this); this.palette = null; this.preview = null; this.input = null; function setColor(c) { self.val(c); opts.change && opts.change(self.val()); self.palette.slideUp(); } function init() { self.palette = $('<div />').addClass(opts.paletteClass+' rounded-3'); for (var i=0; i < opts.colors.length; i++) { $('<div />') .addClass('color') .css('background-color', opts.colors[i]) .attr({title : opts.colors[i], unselectable : 'on'}) .appendTo(self.palette) .mouseenter(function() { var v = $(this).attr('title'); self.input.val(v); self.preview.css('background-color', v); }) .click(function(e) { e.stopPropagation(); setColor($(this).attr('title')); }); }; self.input = $('<input type="text" />') .addClass('rounded-3') .attr('size', 8) .click(function(e) { e.stopPropagation(); $(this).focus(); }) .keydown(function(e) { if (e.ctrlKey || e.metaKey) { return true; } var k = e.keyCode; // on esc - close palette if (k == 27) { return self.mouseleave(); } // allow input only hex color value if (k!=8 && k != 13 && k!=46 && k!=37 && k != 39 && (k<48 || k>57) && (k<65 || k > 70)) { return false; } var c = $(this).val(); if (c.length == 7 || c.length == 0) { if (k == 13) { e.stopPropagation(); e.preventDefault(); setColor(c); self.palette.slideUp(); } if (e.keyCode != 8 && e.keyCode != 46 && k!=37 && k != 39) { return false; } } }) .keyup(function(e) { var c = $(this).val(); c.length == 7 && /^#[0-9abcdef]{6}$/i.test(c) && self.val(c); }); self.preview = $('<div />') .addClass('preview rounded-3') .click(function(e) { e.stopPropagation(); setColor(self.input.val()); }); self.palette .append($('<div />').addClass('clearfix')) .append($('<div />').addClass('panel').append(self.input).append(self.preview)); if (opts.palettePosition == 'outer') { self.palette.hide() .appendTo(self.parents('body').eq(0)) .mouseleave(function() { if (!self.palette.is(':animated')) { $(this).slideUp(); self.val(self.val()); } }); self.mouseleave(function(e) { if (e.relatedTarget != self.palette.get(0)) { if (!self.palette.is(':animated')) { self.palette.slideUp(); self.val(self.val()); } } }) } else { self.append(self.palette.hide()) .mouseleave(function(e) { self.palette.slideUp(); self.val(self.val()); }); } self.val(self.val()); } this.empty().addClass(opts['class']+' rounded-3') .css({'position' : 'relative', 'background-color' : opts.color||''}) .click(function(e) { if (!self.hasClass('disabled')) { !self.palette && init(); if (opts.palettePosition == 'outer' && self.palette.css('display') == 'none') { var o = $(this).offset(); var w = self.palette.width(); var l = self.parents('body').width() - o.left >= w ? o.left : o.left + $(this).outerWidth() - w; self.palette.css({left : l+'px', top : o.top+$(this).height()+1+'px'}); } self.palette.slideToggle(); } }); this.val = function(v) { if (!v && v!=='') { return this.hidden.val(); } else { this.hidden.val(v); if (opts.update) { opts.update(this.hidden.val()); } else { this.css('background-color', v); } if (self.palette) { self.preview.css('background-color', v); self.input.val(v); } } return this; } return this; } $.fn.elColorPicker.defaults = { 'class' : 'el-colorpicker', paletteClass : 'el-palette', palettePosition : 'inner', name : 'color', color : '', update : null, change : function(c) { }, colors : [ '#ffffff', '#cccccc', '#999999', '#666666', '#333333', '#000000', '#ffcccc', '#cc9999', '#996666', '#663333', '#330000', '#ff9999', '#cc6666', '#cc3333', '#993333', '#660000', '#ff6666', '#ff3333', '#ff0000', '#cc0000', '#990000', '#ff9966', '#ff6633', '#ff3300', '#cc3300', '#993300', '#ffcc99', '#cc9966', '#cc6633', '#996633', '#663300', '#ff9933', '#ff6600', '#ff9900', '#cc6600', '#cc9933', '#ffcc66', '#ffcc33', '#ffcc00', '#cc9900', '#996600', '#ffffcc', '#cccc99', '#999966', '#666633', '#333300', '#ffff99', '#cccc66', '#cccc33', '#999933', '#666600', '#ffff66', '#ffff33', '#ffff00', '#cccc00', '#999900', '#ccff66', '#ccff33', '#ccff00', '#99cc00', '#669900', '#ccff99', '#99cc66', '#99cc33', '#669933', '#336600', '#99ff33', '#99ff00', '#66ff00', '#66cc00', '#66cc33', '#99ff66', '#66ff33', '#33ff00', '#33cc00', '#339900', '#ccffcc', '#99cc99', '#669966', '#336633', '#003300', '#99ff99', '#66cc66', '#33cc33', '#339933', '#006600', '#66ff66', '#33ff33', '#00ff00', '#00cc00', '#009900', '#66ff99', '#33ff66', '#00ff33', '#00cc33', '#009933', '#99ffcc', '#66cc99', '#33cc66', '#339966', '#006633', '#33ff99', '#00ff66', '#00ff99', '#00cc66', '#33cc99', '#66ffcc', '#33ffcc', '#00ffcc', '#00cc99', '#009966', '#ccffff', '#99cccc', '#669999', '#336666', '#003333', '#99ffff', '#66cccc', '#33cccc', '#339999', '#006666', '#66cccc', '#33ffff', '#00ffff', '#00cccc', '#009999', '#66ccff', '#33ccff', '#00ccff', '#0099cc', '#006699', '#99ccff', '#6699cc', '#3399cc', '#336699', '#003366', '#3399ff', '#0099ff', '#0066ff', '#066ccc', '#3366cc', '#6699ff', '#3366ff', '#0033ff', '#0033cc', '#003399', '#ccccff', '#9999cc', '#666699', '#333366', '#000033', '#9999ff', '#6666cc', '#3333cc', '#333399', '#000066', '#6666ff', '#3333ff', '#0000ff', '#0000cc', '#009999', '#9966ff', '#6633ff', '#3300ff', '#3300cc', '#330099', '#cc99ff', '#9966cc', '#6633cc', '#663399', '#330066', '#9933ff', '#6600ff', '#9900ff', '#6600cc', '#9933cc', '#cc66ff', '#cc33ff', '#cc00ff', '#9900cc', '#660099', '#ffccff', '#cc99cc', '#996699', '#663366', '#330033', '#ff99ff', '#cc66cc', '#cc33cc', '#993399', '#660066', '#ff66ff', '#ff33ff', '#ff00ff', '#cc00cc', '#990099', '#ff66cc', '#ff33cc', '#ff00cc', '#cc0099', '#990066', '#ff99cc', '#cc6699', '#cc3399', '#993366', '#660033', '#ff3399', '#ff0099', '#ff0066', '#cc0066', '#cc3366', '#ff6699', '#ff3366', '#ff0033', '#cc0033', '#990033' ] }; })(jQuery); /** * jQuery plugin. Create group of text input, elSelect and elColorPicker. * Allow input border-width, border-style and border-color. Used in elRTE * * @author: Dmitry Levashov (dio) dio@std42.ru **/ (function($) { $.fn.elBorderSelect = function(o) { var $self = this; var self = this.eq(0); var opts = $.extend({}, $.fn.elBorderSelect.defaults, o); var width = $('<input type="text" />') .attr({'name' : opts.name+'[width]', size : 3}).css('text-align', 'right') .change(function() { $self.change(); }); var color = $('<div />').css('position', 'relative') .elColorPicker({ 'class' : 'el-colorpicker ui-icon ui-icon-pencil', name : opts.name+'[color]', palettePosition : 'outer', change : function() { $self.change(); } }); var style = $('<div />').elSelect({ tpl : '<div style="border-bottom:4px %val #000;width:100%;margin:7px 0"> </div>', tpls : { '' : '%label'}, maxHeight : opts.styleHeight || null, select : function() { $self.change(); }, src : { '' : 'none', solid : 'solid', dashed : 'dashed', dotted : 'dotted', 'double' : 'double', groove : 'groove', ridge : 'ridge', inset : 'inset', outset : 'outset' } }); self.empty() .addClass(opts['class']) .attr('name', opts.name||'') .append( $('<table />').attr('cellspacing', 0).append( $('<tr />') .append($('<td />').append(width).append(' px')) .append($('<td />').append(style)) .append($('<td />').append(color)) ) ); function rgb2hex(str) { function hex(x) { hexDigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8","9", "a", "b", "c", "d", "e", "f"]; return !x ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x% 16]; } var rgb = (str||'').match(/\(([0-9]{1,3}),\s*([0-9]{1,3}),\s*([0-9]{1,3})\)/); return rgb ? "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]) : ''; } function toPixels(num) { if (!num) { return num; } var m = num.match(/([0-9]+\.?[0-9]*)\s*(px|pt|em|%)/); if (m) { num = m[1]; unit = m[2]; } if (num[0] == '.') { num = '0'+num; } num = parseFloat(num); if (isNaN(num)) { return ''; } var base = parseInt($(document.body).css('font-size')) || 16; switch (unit) { case 'em': return parseInt(num*base); case 'pt': return parseInt(num*base/12); case '%' : return parseInt(num*base/100); } return num; } this.change = function() { opts.change && opts.change(this.val()); } this.val = function(v) { var w, s, c, b, m; if (!v && v !== '') { w = parseInt(width.val()); w = !isNaN(w) ? w+'px' : ''; s = style.val(); c = color.val(); return { width : w, style : s, color : c, css : $.trim(w+' '+s+' '+c) } } else { b = ''; if (v.nodeName || v.css) { if (!v.css) { v = $(v); } b = v.css('border'); if ((b = v.css('border'))) { w = s = c = b; } else { w = v.css('border-width'); s = v.css('border-style'); c = v.css('border-color'); } } else { w = v.width||''; s = v.style||''; c = v.color||''; } width.val(toPixels(w)); m = s ? s.match(/(solid|dashed|dotted|double|groove|ridge|inset|outset)/i) :''; style.val(m ? m[1] : ''); color.val(c.indexOf('#') === 0 ? c : rgb2hex(c)); return this; } } this.val(opts.value); return this; } $.fn.elBorderSelect.defaults = { name : 'el-borderselect', 'class' : 'el-borderselect', value : {}, change : null } })(jQuery); /** * jQuery plugin. Create group of text input fields and selects for setting padding/margin. Used in elRTE * * @author: Dmitry Levashov (dio) dio@std42.ru **/ (function($) { $.fn.elPaddingInput = function(o) { var self = this; var opts = $.extend({}, $.fn.elPaddingInput.defaults, {name : this.attr('name')}, o); this.regexps = { main : new RegExp(opts.type == 'padding' ? 'padding\s*:\s*([^;"]+)' : 'margin\s*:\s*([^;"]+)', 'im'), left : new RegExp(opts.type == 'padding' ? 'padding-left\s*:\s*([^;"]+)' : 'margin-left\s*:\s*([^;"]+)', 'im'), top : new RegExp(opts.type == 'padding' ? 'padding-top\s*:\s*([^;"]+)' : 'margin-top\s*:\s*([^;"]+)', 'im'), right : new RegExp(opts.type == 'padding' ? 'padding-right\s*:\s*([^;"]+)' : 'margin-right\s*:\s*([^;"]+)', 'im'), bottom : new RegExp(opts.type == 'padding' ? 'padding-bottom\s*:\s*([^;"]+)' : 'margin-bottom\s*:\s*([^;"]+)', 'im') }; $.each(['left', 'top', 'right', 'bottom'], function() { self[this] = $('<input type="text" />') .attr('size', 3) .css('text-align', 'right') .css('border-'+this, '2px solid red') .bind('change', function() { $(this).val(parseNum($(this).val())); change(); }) .attr('name', opts.name+'['+this+']'); }); $.each(['uleft', 'utop', 'uright', 'ubottom'], function() { self[this] = $('<select />') .append('<option value="px">px</option>') .append('<option value="em">em</option>') .append('<option value="pt">pt</option>') .bind('change', function() { change(); }) .attr('name', opts.name+'['+this+']'); if (opts.percents) { self[this].append('<option value="%">%</option>'); } }); this.empty().addClass(opts['class']) .append(this.left).append(this.uleft).append(' x ') .append(this.top).append(this.utop).append(' x ') .append(this.right).append(this.uright).append(' x ') .append(this.bottom).append(this.ubottom); this.val = function(v) { if (!v && v!=='') { var l = parseNum(this.left.val()); var t = parseNum(this.top.val()); var r = parseNum(this.right.val()); var b = parseNum(this.bottom.val()); var ret = { left : l=='auto' || l==0 ? l : (l!=='' ? l+this.uleft.val() : ''), top : t=='auto' || t==0 ? t : (t!=='' ? t+this.utop.val() : ''), right : r=='auto' || r==0 ? r : (r!=='' ? r+this.uright.val() : ''), bottom : b=='auto' || b==0 ? b : (b!=='' ? b+this.ubottom.val() : ''), css : '' }; if (ret.left!=='' && ret.right!=='' && ret.top!=='' && ret.bottom!=='') { if (ret.left == ret.right && ret.top == ret.bottom) { ret.css = ret.top+' '+ret.left; } else{ ret.css = ret.top+' '+ret.right+' '+ret.bottom+' '+ret.left; } } return ret; } else { if (v.nodeName || v.css) { if (!v.css) { v = $(v); } var val = {left : '', top : '', right: '', bottom : ''}; var style = (v.attr('style')||'').toLowerCase(); if (style) { style = $.trim(style); var m = style.match(this.regexps.main); if (m) { var tmp = $.trim(m[1]).replace(/\s+/g, ' ').split(' ', 4); val.top = tmp[0]; val.right = tmp[1] && tmp[1]!=='' ? tmp[1] : val.top; val.bottom = tmp[2] && tmp[2]!=='' ? tmp[2] : val.top; val.left = tmp[3] && tmp[3]!=='' ? tmp[3] : val.right; } else { $.each(['left', 'top', 'right', 'bottom'], function() { var name = this.toString(); m = style.match(self.regexps[name]); if (m) { val[name] = m[1]; } }); } } var v = val; } $.each(['left', 'top', 'right', 'bottom'], function() { var name = this.toString(); self[name].val(''); self['u'+name].val(); if (typeof(v[name]) != 'undefined' && v[name] !== null) { v[name] = v[name].toString(); var _v = parseNum(v[name]); self[name].val(_v); var m = v[name].match(/(px|em|pt|%)/i); self['u'+name].val(m ? m[1] : 'px'); } }); return this; } } function parseNum(num) { num = $.trim(num.toString()); if (num[0] == '.') { num = '0'+num; } n = parseFloat(num); return !isNaN(n) ? n : (num == 'auto' ? num : ''); } function change() { opts.change && opts.change(self); } this.val(opts.value); return this; } $.fn.elPaddingInput.defaults = { name : 'el-paddinginput', 'class' : 'el-paddinginput', type : 'padding', value : {}, percents : true, change : null } })(jQuery); /** * elSelect JQuery plugin * Replacement for select input * Allow to put any html and css decoration in drop-down list * * Usage: * $(selector).elSelect(opts) * * set value after init: * var c = $(selector).elSelect(opts) * c.val('some value') * * Get selected value: * var val = c.val(); * * Notice! * 1. When called on multiply elements, elSelect create drop-down list only for fist element * 2. Elements list created only after first click on element (lazzy loading) * * Options: * src - object with pairs value:label to create drop-down list * value - current (selected) value * class - css class for display "button" (element on wich plugin was called) * listClass - css class for drop down elements list * select - callback, called when value was selected (by default write value to console.log) * name - hidden text field in wich selected value will saved * maxHeight - elements list max height (if height greater - scroll will appear) * tpl - template for element in list (contains 2 vars: %var - for src key, %label - for src[val] ) * labelTpl - template for label (current selected element) (contains 2 placeholders: %var - for src key, %label - for src[val] ) * * @author: Dmitry Levashov (dio) dio@std42.ru **/ (function($) { $.fn.elSelect = function(o) { var $self = this; var self = this.eq(0); var opts = $.extend({}, $.fn.elSelect.defaults, o); var hidden = $('<input type="hidden" />').attr('name', opts.name); var label = $('<label />').attr({unselectable : 'on'}).addClass('rounded-left-3'); var list = null; var ieWidth = null; if (self.get(0).nodeName == 'SELECT') { opts.src = {}; self.children('option').each(function() { opts.src[$(this).val()] = $(this).text(); }); opts.value = self.val(); opts.name = self.attr('name'); self.replaceWith((self = $('<div />'))); } if (!opts.value || !opts.src[opts.val]) { opts.value = null; var i = 0; for (var v in opts.src) { if (i++ == 0) { opts.value = v; } } } this.val = function(v) { if (!v && v!=='') { return hidden.val(); } else { if (opts.src[v]) { hidden.val(v); updateLabel(v); if (list) { list.children().each(function() { if ($(this).attr('name') == v) { $(this).addClass('active'); } else { $(this).removeClass('active'); } }); } } return this; } } // update label content function updateLabel(v) { var tpl = opts.labelTpl || opts.tpls[v] || opts.tpl; label.html(tpl.replace(/%val/g, v).replace(/%label/, opts.src[v])).children().attr({unselectable : 'on'}); } // init "select" self.empty() .addClass(opts['class']+' rounded-3') .attr({unselectable : 'on'}) .append(hidden) .append(label) .hover( function() { $(this).addClass('hover') }, function() { $(this).removeClass('hover') } ) .click(function(e) { !list && init(); list.slideToggle(); // stupid ie inherit width from parent if ($.browser.msie && !ieWidth) { list.children().each(function() { ieWidth = Math.max(ieWidth, $(this).width()); }); if (ieWidth > list.width()) { list.width(ieWidth+40); } } }); this.val(opts.value); // create drop-down list function init() { // not ul because of ie is stupid with mouseleave in it :( list = $('<div />') .addClass(opts.listClass+' rounded-3') .hide() .appendTo(self.mouseleave(function(e) { list.slideUp(); })); for (var v in opts.src) { var tpl = opts.tpls[v] || opts.tpl; $('<div />') .attr('name', v) .append( $(tpl.replace(/%val/g, v).replace(/%label/g, opts.src[v])).attr({unselectable : 'on'}) ) .appendTo(list) .hover( function() { $(this).addClass('hover') }, function() { $(this).removeClass('hover') } ) .click(function(e) { e.stopPropagation(); e.preventDefault(); var v = $(this).attr('name'); $self.val(v); opts.select(v); list.slideUp(); }); }; var w = self.outerWidth(); if (list.width() < w) { list.width(w); } var h = list.height(); if (opts.maxHeight>0 && h>opts.maxHeight) { list.height(opts.maxHeight); } $self.val(hidden.val()); } return this; } $.fn.elSelect.defaults = { name : 'el-select', 'class' : 'el-select', listClass : 'list', labelTpl : null, tpl : '<%val>%label</%val>', tpls : {}, value : null, src : {}, select : function(v) { window.console && window.console.log && window.console.log('selected: '+v); }, maxHeight : 410 } })(jQuery); /* * elRTE - WSWING editor for web * * Usage: * var opts = { * .... // see elRTE.options.js * } * var editor = new elRTE($('#my-id').get(0), opts) * or * $('#my-id').elrte(opts) * * $('#my-id) may be textarea or any DOM Element with text * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru */ (function($) { elRTE = function(target, opts) { if (!target || !target.nodeName) { return alert('elRTE: argument "target" is not DOM Element'); } var self = this, html; this.version = '1.3'; this.build = '2011-06-23'; this.options = $.extend(true, {}, this.options, opts); this.browser = $.browser; this.target = $(target); this.lang = (''+this.options.lang); this._i18n = new eli18n({textdomain : 'rte', messages : { rte : this.i18Messages[this.lang] || {}} }); this.rtl = !!(/^(ar|fa|he)$/.test(this.lang) && this.i18Messages[this.lang]); if (this.rtl) { this.options.cssClass += ' el-rte-rtl'; } this.toolbar = $('<div class="toolbar"/>'); this.iframe = document.createElement('iframe'); this.iframe.setAttribute('frameborder', 0); // fixes IE border // this.source = $('<textarea />').hide(); this.workzone = $('<div class="workzone"/>').append(this.iframe).append(this.source); this.statusbar = $('<div class="statusbar"/>'); this.tabsbar = $('<div class="tabsbar"/>'); this.editor = $('<div class="'+this.options.cssClass+'" />').append(this.toolbar).append(this.workzone).append(this.statusbar).append(this.tabsbar); this.doc = null; this.$doc = null; this.window = null; this.utils = new this.utils(this); this.dom = new this.dom(this); this.filter = new this.filter(this) /** * Sync iframes/textareas height with workzone height * * @return void */ this.updateHeight = function() { self.workzone.add(self.iframe).add(self.source).height(self.workzone.height()); } /** * Turn editor resizable on/off if allowed * * @param Boolean * @return void **/ this.resizable = function(r) { var self = this; if (this.options.resizable && $.fn.resizable) { if (r) { this.editor.resizable({handles : 'se', alsoResize : this.workzone, minWidth :300, minHeight : 200 }).bind('resize', self.updateHeight); } else { this.editor.resizable('destroy').unbind('resize', self.updateHeight); } } } /* attach editor to document */ this.editor.insertAfter(target); /* init editor textarea */ var content = ''; if (target.nodeName == 'TEXTAREA') { this.source = this.target; this.source.insertAfter(this.iframe).hide(); content = this.target.val(); } else { this.source = $('<textarea />').insertAfter(this.iframe).hide(); content = this.target.hide().html(); } this.source.attr('name', this.target.attr('name')||this.target.attr('id')); content = $.trim(content); if (!content) { content = ' '; } /* add tabs */ if (this.options.allowSource) { this.tabsbar.append('<div class="tab editor rounded-bottom-7 active">'+self.i18n('Editor')+'</div><div class="tab source rounded-bottom-7">'+self.i18n('Source')+'</div><div class="clearfix" style="clear:both"/>') .children('.tab').click(function(e) { if (!$(this).hasClass('active')) { self.tabsbar.children('.tab').toggleClass('active'); self.workzone.children().toggle(); if ($(this).hasClass('editor')) { self.updateEditor(); self.window.focus(); self.ui.update(true); } else { self.updateSource(); self.source.focus(); if ($.browser.msie) { // @todo } else { self.source[0].setSelectionRange(0, 0); } self.ui.disable(); self.statusbar.empty(); } } }); } this.window = this.iframe.contentWindow; this.doc = this.iframe.contentWindow.document; this.$doc = $(this.doc); /* put content into iframe */ html = '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; $.each(self.options.cssfiles, function() { html += '<link rel="stylesheet" type="text/css" href="'+this+'" />'; }); this.doc.open(); var s = this.filter.wysiwyg(content), cl = this.rtl ? ' class="el-rte-rtl"' : ''; this.doc.write(self.options.doctype+html+'</head><body'+cl+'>'+(s)+'</body></html>'); this.doc.close(); /* make iframe editable */ if ($.browser.msie) { this.doc.body.contentEditable = true; } else { try { this.doc.designMode = "on"; } catch(e) { } this.doc.execCommand('styleWithCSS', false, this.options.styleWithCSS); } if (this.options.height>0) { this.workzone.height(this.options.height); } if (this.options.width>0) { this.editor.width(this.options.width); } this.updateHeight(); this.resizable(true); this.window.focus(); this.history = new this.history(this); /* init selection object */ this.selection = new this.selection(this); /* init buttons */ this.ui = new this.ui(this); /* bind updateSource to parent form submit */ this.target.parents('form').bind('submit.elfinder', function(e) { self.source.parents('form').find('[name="el-select"]').remove() self.beforeSave(); }); // on tab press - insert \t and prevent move focus this.source.bind('keydown', function(e) { if (e.keyCode == 9) { e.preventDefault(); if ($.browser.msie) { var r = document.selection.createRange(); r.text = "\t"+r.text; this.focus(); } else { var before = this.value.substr(0, this.selectionStart), after = this.value.substr(this.selectionEnd); this.value = before+"\t"+after; this.setSelectionRange(before.length+1, before.length+1); } } }); $(this.doc.body).bind('dragend', function(e) { setTimeout(function() { try { self.window.focus(); var bm = self.selection.getBookmark(); self.selection.moveToBookmark(bm); self.ui.update(); } catch(e) { } }, 200); }); this.typing = false; this.lastKey = null; /* update buttons on click and keyup */ this.$doc.bind('mouseup', function() { self.typing = false; self.lastKey = null; self.ui.update(); }) .bind('keyup', function(e) { if ((e.keyCode >= 8 && e.keyCode <= 13) || (e.keyCode>=32 && e.keyCode<= 40) || e.keyCode == 46 || (e.keyCode >=96 && e.keyCode <= 111)) { self.ui.update(); } }) .bind('keydown', function(e) { if ((e.metaKey || e.ctrlKey) && e.keyCode == 65) { self.ui.update(); } else if (e.keyCode == 13) { var n = self.selection.getNode(); // self.log(n) if (self.dom.selfOrParent(n, /^PRE$/)) { self.selection.insertNode(self.doc.createTextNode("\r\n")); return false; } else if ($.browser.safari && e.shiftKey) { self.selection.insertNode(self.doc.createElement('br')) return false; } } if ((e.keyCode>=48 && e.keyCode <=57) || e.keyCode==61 || e.keyCode == 109 || (e.keyCode>=65 && e.keyCode<=90) || e.keyCode==188 ||e.keyCode==190 || e.keyCode==191 || (e.keyCode>=219 && e.keyCode<=222)) { if (!self.typing) { self.history.add(true); } self.typing = true; self.lastKey = null; } else if (e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 32 || e.keyCode == 13) { if (e.keyCode != self.lastKey) { self.history.add(true); } self.lastKey = e.keyCode; self.typing = false; } if (e.keyCode == 32 && $.browser.opera) { self.selection.insertNode(self.doc.createTextNode(" ")); return false } }) .bind('paste', function(e) { if (!self.options.allowPaste) { // paste denied e.stopPropagation(); e.preventDefault(); } else { var n = $(self.dom.create('div'))[0], r = self.doc.createTextNode('_'); self.history.add(true); self.typing = true; self.lastKey = null; n.appendChild(r); self.selection.deleteContents().insertNode(n); self.selection.select(r); setTimeout(function() { if (n.parentNode) { // clean sandbox content $(n).html(self.filter.proccess('paste', $(n).html())); r = n.lastChild; self.dom.unwrap(n); if (r) { self.selection.select(r); self.selection.collapse(false); } } else { // smth wrong - clean all doc n.parentNode && n.parentNode.removeChild(n); self.val(self.filter.proccess('paste', self.filter.wysiwyg2wysiwyg($(self.doc.body).html()))); self.selection.select(self.doc.body.firstChild); self.selection.collapse(true); } $(self.doc.body).mouseup(); // to activate history buutons }, 15); } }); if ($.browser.msie) { this.$doc.bind('keyup', function(e) { if (e.keyCode == 86 && (e.metaKey||e.ctrlKey)) { self.history.add(true); self.typing = true; self.lastKey = null; self.selection.saveIERange(); self.val(self.filter.proccess('paste', self.filter.wysiwyg2wysiwyg($(self.doc.body).html()))); self.selection.restoreIERange(); $(self.doc.body).mouseup(); this.ui.update(); } }); } if ($.browser.safari) { this.$doc.bind('click', function(e) { $(self.doc.body).find('.elrte-webkit-hl').removeClass('elrte-webkit-hl'); if (e.target.nodeName == 'IMG') { $(e.target).addClass('elrte-webkit-hl'); } }).bind('keyup', function(e) { $(self.doc.body).find('.elrte-webkit-hl').removeClass('elrte-webkit-hl'); }) } this.window.focus(); this.destroy = function() { this.updateSource(); this.target.is('textarea') ? this.target.val($.trim(this.source.val())) : this.target.html($.trim(this.source.val())); this.editor.remove(); this.target.show().parents('form').unbind('submit.elfinder'); } } /** * Return message translated to selected language * * @param string msg message text in english * @return string **/ elRTE.prototype.i18n = function(msg) { return this._i18n.translate(msg); } /** * Display editor * * @return void **/ elRTE.prototype.open = function() { this.editor.show(); } /** * Hide editor and display elements on wich editor was created * * @return void **/ elRTE.prototype.close = function() { this.editor.hide(); } elRTE.prototype.updateEditor = function() { this.val(this.source.val()); } elRTE.prototype.updateSource = function() { this.source.val(this.filter.source($(this.doc.body).html())); } /** * Return edited text * * @return String **/ elRTE.prototype.val = function(v) { if (typeof(v) == 'string') { v = ''+v; if (this.source.is(':visible')) { this.source.val(this.filter.source2source(v)); } else { if ($.browser.msie) { this.doc.body.innerHTML = '<br />'+this.filter.wysiwyg(v); this.doc.body.removeChild(this.doc.body.firstChild); } else { this.doc.body.innerHTML = this.filter.wysiwyg(v); } } } else { if (this.source.is(':visible')) { return this.filter.source2source(this.source.val()).trim(); } else { return this.filter.source($(this.doc.body).html()).trim(); } } } elRTE.prototype.beforeSave = function() { this.source.val($.trim(this.val())||''); } /** * Submit form * * @return void **/ elRTE.prototype.save = function() { this.beforeSave(); this.editor.parents('form').submit(); } elRTE.prototype.log = function(msg) { if (window.console && window.console.log) { window.console.log(msg); } } elRTE.prototype.i18Messages = {}; $.fn.elrte = function(o, v) { var cmd = typeof(o) == 'string' ? o : '', ret; this.each(function() { if (!this.elrte) { this.elrte = new elRTE(this, typeof(o) == 'object' ? o : {}); } switch (cmd) { case 'open': case 'show': this.elrte.open(); break; case 'close': case 'hide': this.elrte.close(); break; case 'updateSource': this.elrte.updateSource(); break; case 'destroy': this.elrte.destroy(); } }); if (cmd == 'val') { if (!this.length) { return ''; } else if (this.length == 1) { return v ? this[0].elrte.val(v) : this[0].elrte.val(); } else { ret = {} this.each(function() { ret[this.elrte.source.attr('name')] = this.elrte.val(); }); return ret; } } return this; } })(jQuery); /* * DOM utilites for elRTE * * @author: Dmitry Levashov (dio) dio@std42.ru */ (function($) { elRTE.prototype.dom = function(rte) { this.rte = rte; var self = this; this.regExp = { textNodes : /^(A|ABBR|ACRONYM|ADDRESS|B|BDO|BIG|BLOCKQUOTE|CAPTION|CENTER|CITE|CODE|DD|DEL|DFN|DIV|DT|EM|FIELDSET|FONT|H[1-6]|I|INS|KBD|LABEL|LEGEND|LI|MARQUEE|NOBR|NOEMBED|P|PRE|Q|SAMP|SMALL|SPAN|STRIKE|STRONG|SUB|SUP|TD|TH|TT|VAR)$/, textContainsNodes : /^(A|ABBR|ACRONYM|ADDRESS|B|BDO|BIG|BLOCKQUOTE|CAPTION|CENTER|CITE|CODE|DD|DEL|DFN|DIV|DL|DT|EM|FIELDSET|FONT|H[1-6]|I|INS|KBD|LABEL|LEGEND|LI|MARQUEE|NOBR|NOEMBED|OL|P|PRE|Q|SAMP|SMALL|SPAN|STRIKE|STRONG|SUB|SUP|TABLE|THEAD|TBODY|TFOOT|TD|TH|TR|TT|UL|VAR)$/, block : /^(APPLET|BLOCKQUOTE|BR|CAPTION|CENTER|COL|COLGROUP|DD|DIV|DL|DT|H[1-6]|EMBED|FIELDSET|LI|MARQUEE|NOBR|OBJECT|OL|P|PRE|TABLE|THEAD|TBODY|TFOOT|TD|TH|TR|UL)$/, selectionBlock : /^(APPLET|BLOCKQUOTE|BR|CAPTION|CENTER|COL|COLGROUP|DD|DIV|DL|DT|H[1-6]|EMBED|FIELDSET|LI|MARQUEE|NOBR|OBJECT|OL|P|PRE|TD|TH|TR|UL)$/, header : /^H[1-6]$/, formElement : /^(FORM|INPUT|HIDDEN|TEXTAREA|SELECT|BUTTON)$/ }; /********************************************************/ /* Утилиты */ /********************************************************/ /** * Возвращает body редактируемого документа * * @return Element **/ this.root = function() { return this.rte.body; } this.create = function(t) { return this.rte.doc.createElement(t); } /** * Return node for bookmark with unique ID * * @return DOMElement **/ this.createBookmark = function() { var b = this.rte.doc.createElement('span'); b.id = 'elrte-bm-'+Math.random().toString().substr(2); $(b).addClass('elrtebm elrte-protected'); return b; } /** * Вовращает индекс элемента внутри родителя * * @param Element n нода * @return integer **/ this.indexOf = function(n) { var ndx = 0; n = $(n); while ((n = n.prev()) && n.length) { ndx++; } return ndx; } /** * Вовращает значение аттрибута в нижнем регистре (ох уж этот IE) * * @param Element n нода * @param String attr имя аттрибута * @return string **/ this.attr = function(n, attr) { var v = ''; if (n.nodeType == 1) { v = $(n).attr(attr); if (v && attr != 'src' && attr != 'href' && attr != 'title' && attr != 'alt') { v = v.toString().toLowerCase(); } } return v||''; } /** * Вовращает ближайший общий контейнер для 2-х эл-тов * * @param Element n нода1 * @param Element n нода2 * @return Element **/ this.findCommonAncestor = function(n1, n2) { if (!n1 || !n2) { return this.rte.log('dom.findCommonAncestor invalid arguments'); } if (n1 == n2) { return n1; } else if (n1.nodeName == 'BODY' || n2.nodeName == 'BODY') { return this.rte.doc.body; } var p1 = $(n1).parents(), p2 = $(n2).parents(), l = p2.length-1, c = p2[l]; for (var i = p1.length - 1; i >= 0; i--, l--){ if (p1[i] == p2[l]) { c = p1[i]; } else { break; } }; return c; } /** * Вовращает TRUE, если нода пустая * пустой считаем ноды: * - текстовые эл-ты, содержащие пустую строку или тег br * - текстовые ноды с пустой строкой * * @param DOMElement n нода * @return bool **/ this.isEmpty = function(n) { if (n.nodeType == 1) { return this.regExp.textNodes.test(n.nodeName) ? $.trim($(n).text()).length == 0 : false; } else if (n.nodeType == 3) { return /^(TABLE|THEAD|TFOOT|TBODY|TR|UL|OL|DL)$/.test(n.parentNode.nodeName) || n.nodeValue == '' || ($.trim(n.nodeValue).length== 0 && !(n.nextSibling && n.previousSibling && n.nextSibling.nodeType==1 && n.previousSibling.nodeType==1 && !this.regExp.block.test(n.nextSibling.nodeName) && !this.regExp.block.test(n.previousSibling.nodeName) )); } return true; } /********************************************************/ /* Перемещение по DOM */ /********************************************************/ /** * Вовращает следующую соседнюю ноду (не включаются текстовые ноды не создающие значимые пробелы между инлайн элементами) * * @param DOMElement n нода * @return DOMElement **/ this.next = function(n) { while (n.nextSibling && (n = n.nextSibling)) { if (n.nodeType == 1 || (n.nodeType == 3 && !this.isEmpty(n))) { return n; } } return null; } /** * Вовращает предыдующую соседнюю ноду (не включаются текстовые ноды не создающие значимые пробелы между инлайн элементами) * * @param DOMElement n нода * @return DOMElement **/ this.prev = function(n) { while (n.previousSibling && (n = n.previousSibling)) { if (n.nodeType == 1 || (n.nodeType ==3 && !this.isEmpty(n))) { return n; } } return null; } this.isPrev = function(n, prev) { while ((n = this.prev(n))) { if (n == prev) { return true; } } return false; } /** * Вовращает все следующие соседнии ноды (не включаются текстовые ноды не создающие значимые пробелы между инлайн элементами) * * @param DOMElement n нода * @return Array **/ this.nextAll = function(n) { var ret = []; while ((n = this.next(n))) { ret.push(n); } return ret; } /** * Вовращает все предыдующие соседнии ноды (не включаются текстовые ноды не создающие значимые пробелы между инлайн элементами) * * @param DOMElement n нода * @return Array **/ this.prevAll = function(n) { var ret = []; while ((n = this.prev(n))) { ret.push(n); } return ret; } /** * Вовращает все следующие соседнии inline ноды (не включаются текстовые ноды не создающие значимые пробелы между инлайн элементами) * * @param DOMElement n нода * @return Array **/ this.toLineEnd = function(n) { var ret = []; while ((n = this.next(n)) && n.nodeName != 'BR' && n.nodeName != 'HR' && this.isInline(n)) { ret.push(n); } return ret; } /** * Вовращает все предыдующие соседнии inline ноды (не включаются текстовые ноды не создающие значимые пробелы между инлайн элементами) * * @param DOMElement n нода * @return Array **/ this.toLineStart = function(n) { var ret = []; while ((n = this.prev(n)) && n.nodeName != 'BR' && n.nodeName != 'HR' && this.isInline(n) ) { ret.unshift(n); } return ret; } /** * Вовращает TRUE, если нода - первый непустой эл-т внутри родителя * * @param Element n нода * @return bool **/ this.isFirstNotEmpty = function(n) { while ((n = this.prev(n))) { if (n.nodeType == 1 || (n.nodeType == 3 && $.trim(n.nodeValue)!='' ) ) { return false; } } return true; } /** * Вовращает TRUE, если нода - последний непустой эл-т внутри родителя * * @param Element n нода * @return bool **/ this.isLastNotEmpty = function(n) { while ((n = this.next(n))) { if (!this.isEmpty(n)) { return false; } } return true; } /** * Вовращает TRUE, если нода - единственный непустой эл-т внутри родителя * * @param DOMElement n нода * @return bool **/ this.isOnlyNotEmpty = function(n) { return this.isFirstNotEmpty(n) && this.isLastNotEmpty(n); } /** * Вовращает последний непустой дочерний эл-т ноды или FALSE * * @param Element n нода * @return Element **/ this.findLastNotEmpty = function(n) { this.rte.log('findLastNotEmpty Who is here 0_o'); if (n.nodeType == 1 && (l = n.lastChild)) { if (!this.isEmpty(l)) { return l; } while (l.previousSibling && (l = l.previousSibling)) { if (!this.isEmpty(l)) { return l; } } } return false; } /** * Возвращает TRUE, если нода "inline" * * @param DOMElement n нода * @return bool **/ this.isInline = function(n) { if (n.nodeType == 3) { return true; } else if (n.nodeType == 1) { n = $(n); var d = n.css('display'); var f = n.css('float'); return d == 'inline' || d == 'inline-block' || f == 'left' || f == 'right'; } return true; } /********************************************************/ /* Поиск элементов */ /********************************************************/ this.is = function(n, f) { if (n && n.nodeName) { if (typeof(f) == 'string') { f = this.regExp[f]||/.?/; } if (f instanceof RegExp && n.nodeName) { return f.test(n.nodeName); } else if (typeof(f) == 'function') { return f(n); } } return false; } /** * Вовращает элемент(ы) отвечающие условиям поиска * * @param DOMElement||Array n нода * @param RegExp||String filter фильтр условия поиска (RegExp или имя ключа this.regExp или *) * @return DOMElement||Array **/ this.filter = function(n, filter) { var ret = [], i; if (!n.push) { return this.is(n, filter) ? n : null; } for (i=0; i < n.length; i++) { if (this.is(n[i], filter)) { ret.push(n[i]); } }; return ret; } /** * Вовращает массив родительских элементов, отвечающих условиям поиска * * @param DOMElement n нода, родителей, которой ищем * @param RegExp||String filter фильтр условия поиска (RegExp или имя ключа this.regExp или *) * @return Array **/ this.parents = function(n, filter) { var ret = []; while (n && (n = n.parentNode) && n.nodeName != 'BODY' && n.nodeName != 'HTML') { if (this.is(n, filter)) { ret.push(n); } } return ret; } /** * Вовращает ближайший родительский эл-т, отвечающий условиям поиска * * @param DOMElement n нода, родителя, которой ищем * @param RegExp||String f фильтр условия поиска (RegExp или имя ключа this.regExp или *) * @return DOMElement **/ this.parent = function(n, f) { return this.parents(n, f)[0] || null; } /** * Вовращает или саму ноду или ее ближайшего родителя, если выполняются условия sf для самой ноды или pf для родителя * * @param DOMElement n нода, родителя, которой ищем * @param RegExp||String sf фильтр условия для самой ноды * @param RegExp||String pf фильтр условия для родителя * @return DOMElement **/ this.selfOrParent = function(n, sf, pf) { return this.is(n, sf) ? n : this.parent(n, pf||sf); } /** * Вовращает родительскую ноду - ссылку * * @param Element n нода * @return Element **/ this.selfOrParentLink = function(n) { n = this.selfOrParent(n, /^A$/); return n && n.href ? n : null; } /** * Вовращает TRUE, если нода - anchor * * @param Element n нода * @return bool **/ this.selfOrParentAnchor = function(n) { n = this.selfOrParent(n, /^A$/); return n && !n.href && n.name ? n : null; } /** * Вовращает массив дочерних ссылок * * @param DOMElement n нода * @return Array **/ this.childLinks = function(n) { var res = []; $('a[href]', n).each(function() { res.push(this); }); return res; } this.selectionHas = function(f) { var n = this.rte.selection.cloneContents(), i; if (n && n.childNodes && n.childNodes.length) { for (i=0; i < n.childNodes.length; i++) { if (typeof(f) == 'function') { if (f(n.childNodes[i])) { return true; } } else if (n instanceof RegExp) { if (f.test(n.childNodes[i].nodeName)) { return true; } } }; } return false; } /********************************************************/ /* Изменения DOM */ /********************************************************/ /** * Оборачивает одну ноду другой * * @param DOMElement n оборачиваемая нода * @param DOMElement w нода обертка или имя тега * @return DOMElement **/ this.wrap = function(n, w) { n = $.isArray(n) ? n : [n]; w = w.nodeName ? w : this.create(w); if (n[0] && n[0].nodeType && n[0].parentNode) { w = n[0].parentNode.insertBefore(w, n[0]); $(n).each(function() { if (this!=w) { w.appendChild(this); } }); } return w; } /** * Replace node with its contents * * @param DOMElement n node * @return void **/ this.unwrap = function(n) { if (n && n.parentNode) { while (n.firstChild) { n.parentNode.insertBefore(n.firstChild, n); } n.parentNode.removeChild(n); } } /** * Оборачивает все содержимое ноды * * @param DOMElement n оборачиваемая нода * @param DOMElement w нода обертка или имя тега * @return DOMElement **/ this.wrapContents = function(n, w) { w = w.nodeName ? w : this.create(w); for (var i=0; i < n.childNodes.length; i++) { w.appendChild(n.childNodes[i]); }; n.appendChild(w); return w; } this.cleanNode = function(n) { if (n.nodeType != 1) { return; } if (/^(P|LI)$/.test(n.nodeName) && (l = this.findLastNotEmpty(n)) && l.nodeName == 'BR') { $(l).remove(); } $n = $(n); $n.children().each(function() { this.cleanNode(this); }); if (n.nodeName != 'BODY' && !/^(TABLE|TR|TD)$/.test(n) && this.isEmpty(n)) { return $n.remove(); } if ($n.attr('style') === '') { $n.removeAttr('style'); } if (this.rte.browser.safari && $n.hasClass('Apple-span')) { $n.removeClass('Apple-span'); } if (n.nodeName == 'SPAN' && !$n.attr('style') && !$n.attr('class') && !$n.attr('id')) { $n.replaceWith($n.html()); } } this.cleanChildNodes = function(n) { var cmd = this.cleanNode; $(n).children().each(function() { cmd(this); }); } /********************************************************/ /* Таблицы */ /********************************************************/ this.tableMatrix = function(n) { var mx = []; if (n && n.nodeName == 'TABLE') { var max = 0; function _pos(r) { for (var i=0; i<=max; i++) { if (!mx[r][i]) { return i; } }; } $(n).find('tr').each(function(r) { if (!$.isArray(mx[r])) { mx[r] = []; } $(this).children('td,th').each(function() { var w = parseInt($(this).attr('colspan')||1); var h = parseInt($(this).attr('rowspan')||1); var i = _pos(r); for (var y=0; y<h; y++) { for (var x=0; x<w; x++) { var _y = r+y; if (!$.isArray(mx[_y])) { mx[_y] = []; } var d = x==0 && y==0 ? this : (y==0 ? x : "-"); mx[_y][i+x] = d; } }; max= Math.max(max, mx[r].length); }); }); } return mx; } this.indexesOfCell = function(n, tbm) { for (var rnum=0; rnum < tbm.length; rnum++) { for (var cnum=0; cnum < tbm[rnum].length; cnum++) { if (tbm[rnum][cnum] == n) { return [rnum, cnum]; } }; }; } this.fixTable = function(n) { if (n && n.nodeName == 'TABLE') { var tb = $(n); //tb.find('tr:empty').remove(); var mx = this.tableMatrix(n); var x = 0; $.each(mx, function() { x = Math.max(x, this.length); }); if (x==0) { return tb.remove(); } // for (var i=0; i<mx.length; i++) { // this.rte.log(mx[i]); // } for (var r=0; r<mx.length; r++) { var l = mx[r].length; //this.rte.log(r+' : '+l) if (l==0) { //this.rte.log('remove: '+tb.find('tr').eq(r)) tb.find('tr').eq(r).remove(); // tb.find('tr').eq(r).append('<td>remove</td>') } else if (l<x) { var cnt = x-l; var row = tb.find('tr').eq(r); for (i=0; i<cnt; i++) { row.append('<td>&nbsp;</td>'); } } } } } this.tableColumn = function(n, ext, fix) { n = this.selfOrParent(n, /^TD|TH$/); var tb = this.selfOrParent(n, /^TABLE$/); ret = []; info = {offset : [], delta : []}; if (n && tb) { fix && this.fixTable(tb); var mx = this.tableMatrix(tb); var _s = false; var x; for (var r=0; r<mx.length; r++) { for (var _x=0; _x<mx[r].length; _x++) { if (mx[r][_x] == n) { x = _x; _s = true; break; } } if (_s) { break; } } // this.rte.log('matrix'); // for (var i=0; i<mx.length; i++) { // this.rte.log(mx[i]); // } if (x>=0) { for(var r=0; r<mx.length; r++) { var tmp = mx[r][x]||null; if (tmp) { if (tmp.nodeName) { ret.push(tmp); if (ext) { info.delta.push(0); info.offset.push(x); } } else { var d = parseInt(tmp); if (!isNaN(d) && mx[r][x-d] && mx[r][x-d].nodeName) { ret.push(mx[r][x-d]); if (ext) { info.delta.push(d); info.offset.push(x); } } } } } } } return !ext ? ret : {column : ret, info : info}; } } })(jQuery); (function($) { /** * @class Filter - clean editor content * @param elRTE editor instance * @author Dmitry (dio) Levashov, dio@std42.ru */ elRTE.prototype.filter = function(rte) { var self = this, n = $('<span/>').addClass('elrtetesturl').appendTo(document.body)[0]; // media replacement image base url this.url = (typeof(n.currentStyle )!= "undefined" ? n.currentStyle['backgroundImage'] : document.defaultView.getComputedStyle(n, null)['backgroundImage']).replace(/^url\((['"]?)([\s\S]+\/)[\s\S]+\1\)$/i, "$2"); $(n).remove(); this.rte = rte; // flag - return xhtml tags? this.xhtml = /xhtml/i.test(rte.options.doctype); // boolean attributes this.boolAttrs = rte.utils.makeObject('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'.split(',')); // tag regexp this.tagRegExp = /<(\/?)([\w:]+)((?:\s+[a-z\-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*\/?>/g; // this.tagRegExp = /<(\/?)([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*\/?>/g; // opened tag regexp this.openTagRegExp = /<([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*\/?>/g; // attributes regexp this.attrRegExp = /(\w+)(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^\s]+))?/g; // script tag regexp this.scriptRegExp = /<script([^>]*)>([\s\S]*?)<\/script>/gi; // style tag regexp this.styleRegExp = /(<style([^>]*)>[\s\S]*?<\/style>)/gi; // link tag regexp this.linkRegExp = /(<link([^>]+)>)/gi; // cdata regexp this.cdataRegExp = /<!\[CDATA\[([\s\S]+)\]\]>/g; // object tag regexp this.objRegExp = /<object([^>]*)>([\s\S]*?)<\/object>/gi; // embed tag regexp this.embRegExp = /<(embed)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*>/gi; // param tag regexp this.paramRegExp = /<(param)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*>/gi; // iframe tag regexp this.iframeRegExp = /<iframe([^>]*)>([\s\S]*?)<\/iframe>/gi; // yandex maps regexp this.yMapsRegExp = /<div\s+([^>]*id\s*=\s*('|")?YMapsID[^>]*)>/gi; // google maps regexp this.gMapsRegExp = /<iframe\s+([^>]*src\s*=\s*"http:\/\/maps\.google\.\w+[^>]*)>([\s\S]*?)<\/iframe>/gi; // video hostings url regexp this.videoHostRegExp = /^(http:\/\/[\w\.]*)?(youtube|vimeo|rutube).*/i; // elrte services classes regexp this.serviceClassRegExp = /<(\w+)([^>]*class\s*=\s*"[^>]*elrte-[^>]*)>\s*(<\/\1>)?/gi; this.pagebreakRegExp = /<(\w+)([^>]*style\s*=\s*"[^>]*page-break[^>]*)>\s*(<\/\1>)?/gi; this.pbRegExp = new RegExp('<!-- pagebreak -->', 'gi'); // allowed tags this.allowTags = rte.options.allowTags.length ? rte.utils.makeObject(rte.options.allowTags) : null; // denied tags this.denyTags = rte.options.denyTags.length ? rte.utils.makeObject(rte.options.denyTags) : null; // deny attributes this.denyAttr = rte.options.denyAttr ? rte.utils.makeObject(rte.options.denyAttr) : null; // deny attributes for pasted html this.pasteDenyAttr = rte.options.pasteDenyAttr ? rte.utils.makeObject(rte.options.pasteDenyAttr) : null; // font sizes to convert size attr into css property this.fontSize = ['medium', 'xx-small', 'small', 'medium','large','x-large','xx-large' ]; // font families regexp to detect family by font name this.fontFamily = { 'sans-serif' : /^(arial|tahoma|verdana)$/i, 'serif' : /^(times|times new roman)$/i, 'monospace' : /^courier$/i } // scripts storage this.scripts = {}; // cached chains of rules this._chains = {}; // cache chains $.each(this.chains, function(n) { self._chains[n] = []; $.each(this, function(i, r) { typeof(self.rules[r]) == 'function' && self._chains[n].push(self.rules[r]); }); }); /** * filtering through required chain * * @param String chain name * @param String html-code * @return String **/ this.proccess = function(chain, html) { // remove whitespace at the begin and end html = $.trim(html).replace(/^\s*(&nbsp;)+/gi, '').replace(/(&nbsp;|<br[^>]*>)+\s*$/gi, ''); // pass html through chain $.each(this._chains[chain]||[], function() { html = this.call(self, html); }); html = html.replace(/\t/g, ' ').replace(/\r/g, '').replace(/\s*\n\s*\n+/g, "\n")+' '; return $.trim(html) ? html : ' '; } /** * wrapper for "wysiwyg" chain filtering * * @param String * @return String **/ this.wysiwyg = function(html) { return this.proccess('wysiwyg', html); } /** * wrapper for "source" chain filtering * * @param String * @return String **/ this.source = function(html) { return this.proccess('source', html); } /** * wrapper for "source2source" chain filtering * * @param String * @return String **/ this.source2source = function(html) { return this.proccess('source2source', html); } /** * wrapper for "wysiwyg2wysiwyg" chain filtering * * @param String * @return String **/ this.wysiwyg2wysiwyg = function(html) { return this.proccess('wysiwyg2wysiwyg', html); } /** * Parse attributes from string into object * * @param String string of attributes * @return Object **/ this.parseAttrs = function(s) { var a = {}, b = this.boolAttrs, m = s.match(this.attrRegExp), t, n, v; // this.rte.log(s) // this.rte.log(m) m && $.each(m, function(i, s) { t = s.split('='); n = $.trim(t[0]).toLowerCase(); if (t.length>2) { t.shift(); v = t.join('='); } else { v = b[n] ||t[1]||''; } a[n] = $.trim(v).replace(/^('|")(.*)(\1)$/, "$2"); }); a.style = this.rte.utils.parseStyle(a.style); // rte.log(a.style) a['class'] = this.rte.utils.parseClass(a['class']||'') return a; } /** * Restore attributes string from hash * * @param Object attributes hash * @return String **/ this.serializeAttrs = function(a, c) { var s = [], self = this; $.each(a, function(n, v) { if (n=='style') { v = self.rte.utils.serializeStyle(v, c); } else if (n=='class') { // self.rte.log(v) // self.rte.log(self.rte.utils.serializeClass(v)) v = self.rte.utils.serializeClass(v); } v && s.push(n+'="'+v+'"'); }); return s.join(' '); } /** * Remove/replace denied attributes/style properties * * @param Object attributes hash * @param String tag name to wich attrs belongs * @return Object **/ this.cleanAttrs = function(a, t) { var self = this, ra = this.replaceAttrs; // remove safari and mso classes $.each(a['class'], function(n) { /^(Apple-style-span|mso\w+)$/i.test(n) && delete a['class'][n]; }); function value(v) { return v+(/\d$/.test(v) ? 'px' : ''); } $.each(a, function(n, v) { // replace required attrs with css ra[n] && ra[n].call(self, a, t); // remove/fix mso styles if (n == 'style') { $.each(v, function(sn, sv) { switch (sn) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": a.style[sn.replace(/^mso-|-alt$/g, '')] = value(sv); delete a.style[sn]; break; case "horiz-align": a.style['text-align'] = sv; delete a.style[sn]; break; case "vert-align": a.style['vertical-align'] = sv; delete a.style[sn]; break; case "font-color": case "mso-foreground": a.style.color = sv; delete a.style[sn]; break; case "mso-background": case "mso-highlight": a.style.background = sv; delete a.style[sn]; break; case "mso-default-height": a.style['min-height'] = value(sv); delete a.style[sn]; break; case "mso-default-width": a.style['min-width'] = value(sv); delete a.style[sn]; break; case "mso-padding-between-alt": a.style['border-collapse'] = 'separate'; a.style['border-spacing'] = value(sv); delete a.style[sn]; break; case "text-line-through": if (sv.match(/(single|double)/i)) { a.style['text-decoration'] = 'line-through'; } delete a.style[sn]; break; case "mso-zero-height": if (sv == 'yes') { a.style.display = 'none'; } delete a.style[sn]; break; case 'font-weight': if (sv == 700) { a.style['font-weight'] = 'bold'; } break; default: if (sn.match(/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/)) { delete a.style[sn] } } }); } }); return a; } } // rules to replace tags elRTE.prototype.filter.prototype.replaceTags = { b : { tag : 'strong' }, big : { tag : 'span', style : {'font-size' : 'large'} }, center : { tag : 'div', style : {'text-align' : 'center'} }, i : { tag : 'em' }, font : { tag : 'span' }, nobr : { tag : 'span', style : {'white-space' : 'nowrap'} }, menu : { tag : 'ul' }, plaintext : { tag : 'pre' }, s : { tag : 'strike' }, small : { tag : 'span', style : {'font-size' : 'small'}}, u : { tag : 'span', style : {'text-decoration' : 'underline'} }, xmp : { tag : 'pre' } } // rules to replace attributes elRTE.prototype.filter.prototype.replaceAttrs = { align : function(a, n) { switch (n) { case 'img': a.style[a.align.match(/(left|right)/) ? 'float' : 'vertical-align'] = a.align; break; case 'table': if (a.align == 'center') { a.style['margin-left'] = a.style['margin-right'] = 'auto'; } else { a.style['float'] = a.align; } break; default: a.style['text-align'] = a.align; } delete a.align; }, border : function(a) { !a.style['border-width'] && (a.style['border-width'] = (parseInt(a.border)||1)+'px'); !a.style['border-style'] && (a.style['border-style'] = 'solid'); delete a.border; }, bordercolor : function(a) { !a.style['border-color'] && (a.style['border-color'] = a.bordercolor); delete a.bordercolor; }, background : function(a) { !a.style['background-image'] && (a.style['background-image'] = 'url('+a.background+')'); delete a.background; }, bgcolor : function(a) { !a.style['background-color'] && (a.style['background-color'] = a.bgcolor); delete a.bgcolor; }, clear : function(a) { a.style.clear = a.clear == 'all' ? 'both' : a.clear; delete a.clear; }, color : function(a) { !a.style.color && (a.style.color = a.color); delete a.color; }, face : function(a) { var f = a.face.toLowerCase(); $.each(this.fontFamily, function(n, r) { if (f.match(r)) { a.style['font-family'] = f+','+n; } }); delete a.face; }, hspace : function(a, n) { if (n == 'img') { var v = parseInt(a.hspace)||0; !a.style['margin-left'] && (a.style['margin-left'] = v+'px'); !a.style['margin-right'] && (a.style['margin-right'] = v+'px') delete a.hspace; } }, size : function(a, n) { if (n != 'input') { a.style['font-size'] = this.fontSize[parseInt(a.size)||0]||'medium'; delete a.size; } }, valign : function(a) { if (!a.style['vertical-align']) { a.style['vertical-align'] = a.valign; } delete a.valign; }, vspace : function(a, n) { if (n == 'img') { var v = parseInt(a.vspace)||0; !a.style['margin-top'] && (a.style['margin-top'] = v+'px'); !a.style['margin-bottom'] && (a.style['margin-bottom'] = v+'px') delete a.hspace; } } } // rules collection elRTE.prototype.filter.prototype.rules = { /** * If this.rte.options.allowTags is set - remove all except this ones * * @param String html code * @return String **/ allowedTags : function(html) { var a = this.allowTags; return a ? html.replace(this.tagRegExp, function(t, c, n) { return a[n.toLowerCase()] ? t : ''; }) : html; }, /** * If this.rte.options.denyTags is set - remove all deny tags * * @param String html code * @return String **/ deniedTags : function(html) { var d = this.denyTags; return d ? html.replace(this.tagRegExp, function(t, c, n) { return d[n.toLowerCase()] ? '' : t }) : html; }, /** * Replace not allowed tags/attributes * * @param String html code * @return String **/ clean : function(html) { var self = this, rt = this.replaceTags, ra = this.replaceAttrs, da = this.denyAttr, n; html = html.replace(/<!DOCTYPE([\s\S]*)>/gi, '') .replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>") .replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s&nbsp;]*)<\/span>/gi, "$1") .replace(/(<p[^>]*>\s*<\/p>|<p[^>]*\/>)/gi, '<br>') .replace(/(<\/p>)(?:\s*<br\s*\/?>\s*|\s*&nbsp;\s*)+\s*(<p[^>]*>)/gi, function(t, b, e) { return b+"\n"+e; }) .replace(this.tagRegExp, function(t, c, n, a) { n = n.toLowerCase(); if (c) { return '</'+(rt[n] ? rt[n].tag : n)+'>'; } // self.rte.log(t) // create attributes hash and clean it a = self.cleanAttrs(self.parseAttrs(a||''), n); // self.rte.log(a) if (rt[n]) { rt[n].style && $.extend(a.style, rt[n].style); n = rt[n].tag; } da && $.each(a, function(na) { if (da[na]) { delete a[na]; } }); a = self.serializeAttrs(a); // self.rte.log(a) return '<'+n+(a?' ':'')+a+'>'; }); n = $('<div>'+html+'</div>'); // remove empty spans and merge nested spans n.find('span:not([id]):not([class])').each(function() { var t = $(this); if (!t.attr('style')) { $.trim(t.html()).length ? self.rte.dom.unwrap(this) : t.remove(); // t.children().length ? self.rte.dom.unwrap(this) : t.remove(); } }).end().find('span span:only-child').each(function() { var t = $(this), p = t.parent().eq(0), tid = t.attr('id'), pid = p.attr('id'), id, s, c; if (self.rte.dom.isOnlyNotEmpty(this) && (!tid || !pid)) { c = $.trim(p.attr('class')+' '+t.attr('class')) c && p.attr('class', c); s = self.rte.utils.serializeStyle($.extend(self.rte.utils.parseStyle($(this).attr('style')||''), self.rte.utils.parseStyle($(p).attr('style')||''))); s && p.attr('style', s); id = tid||pid; id && p.attr('id', id); this.firstChild ? $(this.firstChild).unwrap() : t.remove(); } }) .end().find('a[name]').each(function() { $(this).addClass('elrte-protected elrte-anchor'); }); return n.html() }, /** * Clean pasted html * * @param String html code * @return String **/ cleanPaste : function(html) { var self = this, d = this.pasteDenyAttr; html = html .replace(this.scriptRegExp, '') .replace(this.styleRegExp, '') .replace(this.linkRegExp, '') .replace(this.cdataRegExp, '') .replace(/\<\!--[\s\S]*?--\>/g, ''); if (this.rte.options.pasteOnlyText) { html = html.replace(this.tagRegExp, function(t, c, n) { return /br/i.test(n) || (c && /h[1-6]|p|ol|ul|li|div|blockquote|tr/i) ? '<br>' : ''; }).replace(/(&nbsp;|<br[^>]*>)+\s*$/gi, ''); } else if (d) { html = html.replace(this.openTagRegExp, function(t, n, a) { a = self.parseAttrs(a); $.each(a, function(an) { if (d[an]) { delete a[an]; } }); a = self.serializeAttrs(a, true); return '<'+n+(a?' ':'')+a+'>'; }); } return html; }, /** * Replace script/style/media etc with placeholders * * @param String html code * @return String **/ replace : function(html) { var self = this, r = this.rte.options.replace||[], n; // custom replaces if set if (r.length) { $.each(r, function(i, f) { if (typeof(f) == 'function') { html = f.call(self, html); } }); } /** * Return media replacement - img html code * * @param Object object to store in rel attr * @param String media mime-type * @return String **/ function img(o, t) { var s = src(), c = s && self.videoHostRegExp.test(s) ? s.replace(self.videoHostRegExp, "$2") : t.replace(/^\w+\/(.+)/, "$1"), w = parseInt((o.obj ? o.obj.width || o.obj.style.width : 0)||(o.embed ? o.embed.width || o.embed.style.width : 0))||150, h = parseInt((o.obj ? o.obj.height || o.obj.style.height : 0)||(o.embed ? o.embed.height || o.embed.style.height : 0))||100, id = 'media'+Math.random().toString().substring(2), style ='', l; // find media src function src() { if (o.embed && o.embed.src) { return o.embed.src; } if (o.params && o.params.length) { l = o.params.length; while (l--) { if (o.params[l].name == 'src' || o.params[l].name == 'movie') { return o.params[l].value; } } } } if (o.obj && o.obj.style && o.obj.style['float']) { style = ' style="float:'+o.obj.style['float']+'"'; } self.scripts[id] = o; return '<img src="'+self.url+'pixel.gif" class="elrte-media elrte-media-'+c+' elrte-protected" title="'+(s ? self.rte.utils.encode(s) : '')+'" rel="'+id+'" width="'+w+'" height="'+h+'"'+style+'>'; } html = html .replace(this.styleRegExp, "<!-- ELRTE_COMMENT$1 -->") .replace(this.linkRegExp, "<!-- ELRTE_COMMENT$1-->") .replace(this.cdataRegExp, "<!--[CDATA[$1]]-->") .replace(this.scriptRegExp, function(t, a, s) { var id; if (self.denyTags.script) { return ''; } id = 'script'+Math.random().toString().substring(2); a = self.parseAttrs(a); !a.type && (a.type = 'text/javascript'); self.scripts[id] = '<script '+self.serializeAttrs(a)+">"+s+"</script>"; return '<!-- ELRTE_SCRIPT:'+(id)+' -->'; }) .replace(this.yMapsRegExp, function(t, a) { a = self.parseAttrs(a); a['class']['elrte-yandex-maps'] = 'elrte-yandex-maps'; a['class']['elrte-protected'] = 'elrte-protected'; return '<div '+self.serializeAttrs(a)+'>'; }) .replace(this.gMapsRegExp, function(t, a) { var id = 'gmaps'+Math.random().toString().substring(2), w, h; a = self.parseAttrs(a); w = parseInt(a.width||a.style.width||100); h = parseInt(a.height||a.style.height||100); self.scripts[id] = t; return '<img src="'+self.url+'pixel.gif" class="elrte-google-maps elrte-protected" id="'+id+'" style="width:'+w+'px;height:'+h+'px">'; }) .replace(this.objRegExp, function(t, a, c) { var m = c.match(self.embRegExp), o = { obj : self.parseAttrs(a), embed : m && m.length ? self.parseAttrs(m[0].substring(7)) : null, params : [] }, i = self.rte.utils.mediaInfo(o.embed ? o.embed.type||'' : '', o.obj.classid||''); if (i) { if ((m = c.match(self.paramRegExp))) { $.each(m, function(i, p) { o.params.push(self.parseAttrs(p.substring(6))); }); } !o.obj.classid && (o.obj.classid = i.classid[0]); !o.obj.codebase && (o.obj.codebase = i.codebase); o.embed && !o.embed.type && (o.embed.type = i.type); // ie bug with empty attrs o.obj.width == '1' && delete o.obj.width; o.obj.height == '1' && delete o.obj.height; if (o.embed) { o.embed.width == '1' && delete o.embed.width; o.embed.height == '1' && delete o.embed.height; } return img(o, i.type); } return t; }) .replace(this.embRegExp, function(t, n, a) { var a = self.parseAttrs(a), i = self.rte.utils.mediaInfo(a.type||''); // ie bug with empty attrs a.width == '1' && delete a.width; a.height == '1' && delete a.height; return i ? img({ embed : a }, i.type) : t; }) .replace(this.iframeRegExp, function(t, a) { var a = self.parseAttrs(a); var w = a.style.width || (parseInt(a.width) > 1 ? parseInt(a.width)+'px' : '100px'); var h = a.style.height || (parseInt(a.height) > 1 ? parseInt(a.height)+'px' : '100px'); var id = 'iframe'+Math.random().toString().substring(2); self.scripts[id] = t; var img = '<img id="'+id+'" src="'+self.url+'pixel.gif" class="elrte-protected elrte-iframe" style="width:'+w+'; height:'+h+'">'; return img; }) .replace(this.vimeoRegExp, function(t, n, a) { a = self.parseAttrs(a); delete a.frameborder; a.width == '1' && delete a.width; a.height == '1' && delete a.height; a.type = 'application/x-shockwave-flash'; return img({ embed : a }, 'application/x-shockwave-flash'); }) .replace(/<\/(embed|param)>/gi, '') .replace(this.pbRegExp, function() { return '<img src="'+self.url+'pixel.gif" class="elrte-protected elrte-pagebreak">'; }); n = $('<div>'+html+'</div>'); // remove empty spans and merge nested spans // n.find('span:not([id]):not([class])').each(function() { // var t = $(this); // // if (!t.attr('style')) { // $.trim(t.html()).length ? self.rte.dom.unwrap(this) : t.remove(); // // t.children().length ? self.rte.dom.unwrap(this) : t.remove(); // } // }).end().find('span span:only-child').each(function() { // var t = $(this), // p = t.parent().eq(0), // tid = t.attr('id'), // pid = p.attr('id'), id, s, c; // // if (self.rte.dom.is(this, 'onlyChild') && (!tid || !pid)) { // c = $.trim(p.attr('class')+' '+t.attr('class')) // c && p.attr('class', c); // s = self.rte.utils.serializeStyle($.extend(self.rte.utils.parseStyle($(this).attr('style')||''), self.rte.utils.parseStyle($(p).attr('style')||''))); // s && p.attr('style', s); // id = tid||pid; // id && p.attr('id', id); // this.firstChild ? $(this.firstChild).unwrap() : t.remove(); // } // }) // .end().find('a[name]').each(function() { // $(this).addClass('elrte-anchor'); // }); if (!this.rte.options.allowTextNodes) { // wrap inline nodes with p var dom = this.rte.dom, nodes = [], w = []; if ($.browser.msie) { for (var i = 0; i<n[0].childNodes.length; i++) { nodes.push(n[0].childNodes[i]) } } else { nodes = Array.prototype.slice.call(n[0].childNodes); } function wrap() { if (w.length && dom.filter(w, 'notEmpty').length) { dom.wrap(w, document.createElement('p')); } w = []; } $.each(nodes, function(i, n) { if (dom.is(n, 'block')) { wrap(); } else { if (w.length && n.previousSibling != w[w.length-1]) { wrap(); } w.push(n); } }); wrap(); } return n.html(); }, /** * Restore script/style/media etc from placeholders * * @param String html code * @return String **/ restore : function(html) { var self =this, r = this.rte.options.restore||[]; // custom restore if set if (r.length) { $.each(r, function(i, f) { if (typeof(f) == 'function') { html = f.call(self, html); } }); } html = html .replace(/\<\!--\[CDATA\[([\s\S]*?)\]\]--\>/gi, "<![CDATA[$1]]>") .replace(/\<\!--\s*ELRTE_SCRIPT\:\s*(script\d+)\s*--\>/gi, function(t, n) { if (self.scripts[n]) { t = self.scripts[n]; delete self.scripts[n]; } return t||''; }) .replace(/\<\!-- ELRTE_COMMENT([\s\S]*?) --\>/gi, "$1") .replace(this.serviceClassRegExp, function(t, n, a, e) { var a = self.parseAttrs(a), j, o = ''; // alert(t) if (a['class']['elrte-google-maps']) { var t = ''; if (self.scripts[a.id]) { t = self.scripts[a.id]; delete self.scripts[a.id] } return t; } else if (a['class']['elrte-iframe']) { return self.scripts[a.id] || ''; } else if (a['class']['elrtebm']) { return ''; } else if (a['class']['elrte-media']) { // alert(a.rel) // return '' // j = a.rel ? JSON.parse(self.rte.utils.decode(a.rel)) : {}; j = self.scripts[a.rel]||{}; j.params && $.each(j.params, function(i, p) { o += '<param '+self.serializeAttrs(p)+">\n"; }); j.embed && (o+='<embed '+self.serializeAttrs(j.embed)+">"); j.obj && (o = '<object '+self.serializeAttrs(j.obj)+">\n"+o+"\n</object>\n"); return o||t; } else if (a['class']['elrte-pagebreak']) { return '<!-- pagebreak -->'; } $.each(a['class'], function(n) { if (/^elrte-\w+/i.test(n)) { delete(a['class'][n]); } // /^elrte\w+/i.test(n) && delete(a['class'][n]); }); return '<'+n+' '+self.serializeAttrs(a)+'>'+(e||''); }); return html; }, /** * compact styles and move tags and attributes names in lower case(for ie&opera) * * @param String html code * return String **/ compactStyles : function(html) { var self = this; return html.replace(this.tagRegExp, function(t, c, n, a) { a = !c && a ? self.serializeAttrs(self.parseAttrs(a), true) : ''; return '<'+c+n.toLowerCase()+(a?' ':'')+a+'>'; }); }, /** * return xhtml tags * * @param String html code * return String **/ xhtmlTags : function(html) { return this.xhtml ? html.replace(/<(img|hr|br|embed|param|link|area)([^>]*\/*)>/gi, "<$1$2 />") : html; } } /** * Chains configuration * Default chains * wysiwyg - proccess html from source for wysiwyg editor mode * source - proccess html from wysiwyg for source editor mode * paste - clean pasted html * wysiwyg2wysiwyg - ciclyc rule to clean html from wysiwyg for wysiwyg paste * source2source - ciclyc rule to clean html from source for source paste * deniedTags is in the end of chain to protect google maps iframe from removed **/ elRTE.prototype.filter.prototype.chains = { wysiwyg : ['replace', 'clean', 'allowedTags', 'deniedTags', 'compactStyles'], source : ['clean', 'allowedTags', 'restore', 'compactStyles', 'xhtmlTags'], paste : ['clean', 'allowedTags', 'cleanPaste', 'replace', 'deniedTags', 'compactStyles'], wysiwyg2wysiwyg : ['clean', 'allowedTags', 'restore', 'replace', 'deniedTags', 'compactStyles'], source2source : ['clean', 'allowedTags', 'replace', 'deniedTags', 'restore', 'compactStyles', 'xhtmlTags'] } })(jQuery); (function($) { elRTE.prototype.history = function(rte) { this.rte = rte; this._prev = [] this._next = []; this.add = function() { if (this.rte.options.historyLength>0 && this._prev.length>= this.rte.options.historyLength) { this._prev.slice(this.rte.options.historyLength); } var b = this.rte.selection.getBookmark(); this._prev.push([$(this.rte.doc.body).html(), b]); this.rte.selection.moveToBookmark(b); // this._prev.push($(this.rte.doc.body).html()); this._next = []; } this.back = function() { if (this._prev.length) { var b = this.rte.selection.getBookmark(), data = this._prev.pop(); this._next.push([$(this.rte.doc.body).html(), b]); $(this.rte.doc.body).html(data[0]); this.rte.selection.moveToBookmark(data[1]); } } this.fwd = function() { if (this._next.length) { var b = this.rte.selection.getBookmark(), data = this._next.pop(); this._prev.push([$(this.rte.doc.body).html(), b]); $(this.rte.doc.body).html(data[0]); this.rte.selection.moveToBookmark(data[1]); } } this.canBack = function() { return this._prev.length; } this.canFwd = function() { return this._next.length; } } })(jQuery);/* * elRTE configuration * * @param doctype - doctype for editor iframe * @param cssClass - css class for editor * @param cssFiles - array of css files, witch will inlude in iframe * @param height - not used now (may be deleted in future) * @param lang - interface language (requires file in i18n dir) * @param toolbar - name of toolbar to load * @param absoluteURLs - convert files and images urls to absolute or not * @param allowSource - is source editing allowing * @param stripWhiteSpace - strip лишние whitespaces/tabs or not * @param styleWithCSS - use style=... instead of strong etc. * @param fmAllow - allow using file manger (elFinder) * @param fmOpen - callback for open file manager * @param buttons - object with pairs of buttons classes names and titles (when create new button, you have to add iys name here) * @param panels - named groups of buttons * @param panelNames - title of panels (required for one planned feature) * @param toolbars - named redy to use toolbals (you may combine your own toolbar) * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru */ (function($) { elRTE.prototype.options = { doctype : '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">', cssClass : 'el-rte', cssfiles : [], height : null, resizable : true, lang : 'en', toolbar : 'normal', absoluteURLs : true, allowSource : true, stripWhiteSpace : true, styleWithCSS : false, fmAllow : true, fmOpen : null, /* if set all other tag will be removed */ allowTags : [], /* if set this tags will be removed */ denyTags : ['applet', 'base', 'basefont', 'bgsound', 'blink', 'body', 'col', 'colgroup', 'isindex', 'frameset', 'html', 'head', 'meta', 'marquee', 'noframes', 'noembed', 'o:p', 'title', 'xml'], denyAttr : [], /* on paste event this attributes will removed from pasted html */ pasteDenyAttr : ['id', 'name', 'class', 'style', 'language', 'onclick', 'ondblclick', 'onhover', 'onkeup', 'onkeydown', 'onkeypress'], /* If false - all text nodes will be wrapped by paragraph tag */ allowTextNodes : true, /* allow browser specific styles like -moz|-webkit|-o */ allowBrowsersSpecStyles : false, /* allow paste content into editor */ allowPaste : true, /* if true - only text will be pasted (not in ie) */ pasteOnlyText : false, /* user replacement rules */ replace : [], /* user restore rules */ restore : [], pagebreak : '<div style="page-break-after: always;"></div>', //'<!-- pagebreak -->', buttons : { 'save' : 'Save', 'copy' : 'Copy', 'cut' : 'Cut', 'css' : 'Css style and class', 'paste' : 'Paste', 'pastetext' : 'Paste only text', 'pasteformattext' : 'Paste formatted text', 'removeformat' : 'Clean format', 'undo' : 'Undo last action', 'redo' : 'Redo previous action', 'bold' : 'Bold', 'italic' : 'Italic', 'underline' : 'Underline', 'strikethrough' : 'Strikethrough', 'superscript' : 'Superscript', 'subscript' : 'Subscript', 'justifyleft' : 'Align left', 'justifyright' : 'Ailgn right', 'justifycenter' : 'Align center', 'justifyfull' : 'Align full', 'indent' : 'Indent', 'outdent' : 'Outdent', 'rtl' : 'Right to left', 'ltr' : 'Left to right', 'forecolor' : 'Font color', 'hilitecolor' : 'Background color', 'formatblock' : 'Format', 'fontsize' : 'Font size', 'fontname' : 'Font', 'insertorderedlist' : 'Ordered list', 'insertunorderedlist' : 'Unordered list', 'horizontalrule' : 'Horizontal rule', 'blockquote' : 'Blockquote', 'div' : 'Block element (DIV)', 'link' : 'Link', 'unlink' : 'Delete link', 'anchor' : 'Bookmark', 'image' : 'Image', 'pagebreak' : 'Page break', 'smiley' : 'Smiley', 'flash' : 'Flash', 'table' : 'Table', 'tablerm' : 'Delete table', 'tableprops' : 'Table properties', 'tbcellprops' : 'Table cell properties', 'tbrowbefore' : 'Insert row before', 'tbrowafter' : 'Insert row after', 'tbrowrm' : 'Delete row', 'tbcolbefore' : 'Insert column before', 'tbcolafter' : 'Insert column after', 'tbcolrm' : 'Delete column', 'tbcellsmerge' : 'Merge table cells', 'tbcellsplit' : 'Split table cell', 'docstructure' : 'Toggle display document structure', 'elfinder' : 'Open file manager', 'fullscreen' : 'Toggle full screen mode', 'nbsp' : 'Non breakable space', 'stopfloat' : 'Stop element floating', 'about' : 'About this software' }, panels : { eol : [], // special panel, insert's a new line in toolbar save : ['save'], copypaste : ['copy', 'cut', 'paste', 'pastetext', 'pasteformattext', 'removeformat', 'docstructure'], undoredo : ['undo', 'redo'], style : ['bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript'], colors : ['forecolor', 'hilitecolor'], alignment : ['justifyleft', 'justifycenter', 'justifyright', 'justifyfull'], indent : ['outdent', 'indent'], format : ['formatblock', 'fontsize', 'fontname'], lists : ['insertorderedlist', 'insertunorderedlist'], elements : ['horizontalrule', 'blockquote', 'div', 'stopfloat', 'css', 'nbsp', 'smiley', 'pagebreak'], direction : ['ltr', 'rtl'], links : ['link', 'unlink', 'anchor'], images : ['image'], media : ['image', 'flash'], tables : ['table', 'tableprops', 'tablerm', 'tbrowbefore', 'tbrowafter', 'tbrowrm', 'tbcolbefore', 'tbcolafter', 'tbcolrm', 'tbcellprops', 'tbcellsmerge', 'tbcellsplit'], elfinder : ['elfinder'], fullscreen : ['fullscreen', 'about'] }, toolbars : { tiny : ['style'], compact : ['save', 'undoredo', 'style', 'alignment', 'lists', 'links', 'fullscreen'], normal : ['save', 'copypaste', 'undoredo', 'style', 'alignment', 'colors', 'indent', 'lists', 'links', 'elements', 'images', 'fullscreen'], complete : ['save', 'copypaste', 'undoredo', 'style', 'alignment', 'colors', 'format', 'indent', 'lists', 'links', 'elements', 'media', 'fullscreen'], maxi : ['save', 'copypaste', 'undoredo', 'elfinder', 'style', 'alignment', 'direction', 'colors', 'format', 'indent', 'lists', 'links', 'elements', 'media', 'tables', 'fullscreen'], eldorado : ['save', 'copypaste', 'elfinder', 'undoredo', 'style', 'alignment', 'colors', 'format', 'indent', 'lists', 'links', 'elements', 'media', 'tables', 'fullscreen'] }, panelNames : { save : 'Save', copypaste : 'Copy/Pase', undoredo : 'Undo/Redo', style : 'Text styles', colors : 'Colors', alignment : 'Alignment', indent : 'Indent/Outdent', format : 'Text format', lists : 'Lists', elements : 'Misc elements', direction : 'Script direction', links : 'Links', images : 'Images', media : 'Media', tables : 'Tables', elfinder : 'File manager (elFinder)' } }; })(jQuery); /** * @class selection - elRTE utils for working with text selection * * @param elRTE rte объект-редактор * * @author: Dmitry Levashov (dio) dio@std42.ru **/ (function($) { elRTE.prototype.selection = function(rte) { this.rte = rte; var self = this; this.w3cRange = null; var start, end, node, bm; $(this.rte.doc) .keyup(function(e) { if (e.ctrlKey || e.metaKey || (e.keyCode >= 8 && e.keyCode <= 13) || (e.keyCode>=32 && e.keyCode<= 40) || e.keyCode == 46 || (e.keyCode >=96 && e.keyCode <= 111)) { self.cleanCache(); } }) .mousedown(function(e) { // self.rte.log(e) if (e.target.nodeName == 'HTML') { start = self.rte.doc.body; } else { start = e.target; } end = node = null; }) .mouseup(function(e) { if (e.target.nodeName == 'HTML') { end = self.rte.doc.body; } else { end = e.target; } end = e.target; node = null; }).click(); /** * возвращает selection * * @return Selection **/ function selection() { return self.rte.window.getSelection ? self.rte.window.getSelection() : self.rte.window.document.selection; } /** * Вспомогательная функция * Возвращает самого верхнего родителя, отвечающего условию - текущая нода - его единственная непустая дочерняя нода * * @param DOMElement n нода, для которой ищем родителя * @param DOMElement p если задана - нода, выше которой не поднимаемся * @param String s строна поиска (left||right||null) * @return DOMElement **/ function realSelected(n, p, s) { while (n.nodeName != 'BODY' && n.parentNode && n.parentNode.nodeName != 'BODY' && (p ? n!== p && n.parentNode != p : 1) && ((s=='left' && self.rte.dom.isFirstNotEmpty(n)) || (s=='right' && self.rte.dom.isLastNotEmpty(n)) || (self.rte.dom.isFirstNotEmpty(n) && self.rte.dom.isLastNotEmpty(n))) ) { n = n.parentNode; } return n; } /** * Возвращает TRUE, если выделение "схлопнуто" * * @return bool **/ this.collapsed = function() { return this.getRangeAt().isCollapsed(); } /** * "Схлопывает" выделение * * @param bool toStart схлопнуть к начальной точке * @return void **/ this.collapse = function(st) { var s = selection(), r = this.getRangeAt(); r.collapse(st?true:false); if (!$.browser.msie) { s.removeAllRanges(); s.addRange(r); } return this; } /** * Возвращает TextRange * Для нормальных браузеров - нативный range * для "самизнаетечего" - эмуляцию w3c range * * @return range|w3cRange **/ this.getRangeAt = function(updateW3cRange) { if (this.rte.browser.msie) { if (!this.w3cRange) { this.w3cRange = new this.rte.w3cRange(this.rte); } updateW3cRange && this.w3cRange.update(); return this.w3cRange; } var s = selection(); var r = s.rangeCount > 0 ? s.getRangeAt(0) : this.rte.doc.createRange(); r.getStart = function() { return this.startContainer.nodeType==1 ? this.startContainer.childNodes[Math.min(this.startOffset, this.startContainer.childNodes.length-1)] : this.startContainer; } r.getEnd = function() { return this.endContainer.nodeType==1 ? this.endContainer.childNodes[ Math.min(this.startOffset == this.endOffset ? this.endOffset : this.endOffset-1, this.endContainer.childNodes.length-1)] : this.endContainer; } r.isCollapsed = function() { return this.collapsed; } return r; } this.saveIERange = function() { if ($.browser.msie) { bm = this.getRangeAt().getBookmark(); } } this.restoreIERange = function() { $.browser.msie && bm && this.getRangeAt().moveToBookmark(bm); } this.cloneContents = function() { var n = this.rte.dom.create('div'), r, c, i; if ($.browser.msie) { try { r = this.rte.window.document.selection.createRange(); } catch(e) { r = this.rte.doc.body.createTextRange(); } $(n).html(r.htmlText); } else { c = this.getRangeAt().cloneContents(); for (i=0; i<c.childNodes.length; i++) { n.appendChild(c.childNodes[i].cloneNode(true)); } } return n; } /** * Выделяет ноды * * @param DOMNode s нода начала выделения * @param DOMNode e нода конца выделения * @return selection **/ this.select = function(s, e) { e = e||s; if (this.rte.browser.msie) { var r = this.rte.doc.body.createTextRange(), r1 = r.duplicate(), r2 = r.duplicate(); r1.moveToElementText(s); r2.moveToElementText(e); r.setEndPoint('StartToStart', r1); r.setEndPoint('EndToEnd', r2); r.select(); } else { var sel = selection(), r = this.getRangeAt(); r.setStartBefore(s); r.setEndAfter(e); sel.removeAllRanges(); sel.addRange(r); } return this.cleanCache(); } /** * Выделяет содержимое ноды * * @param Element n нода * @return selection **/ this.selectContents = function(n) { var r = this.getRangeAt(); if (n && n.nodeType == 1) { if (this.rte.browser.msie) { r.range(); r.r.moveToElementText(n.parentNode); r.r.select(); } else { try { r.selectNodeContents(n); } catch (e) { return this.rte.log('unable select node contents '+n); } var s = selection(); s.removeAllRanges(); s.addRange(r); } } return this; } this.deleteContents = function() { if (!$.browser.msie) { this.getRangeAt().deleteContents(); } return this; } /** * Вставляет ноду в текущее выделение * * @param Element n нода * @return selection **/ this.insertNode = function(n, collapse) { if (collapse && !this.collapsed()) { this.collapse(); } if (this.rte.browser.msie) { var html = n.nodeType == 3 ? n.nodeValue : $(this.rte.dom.create('span')).append($(n)).html(); var r = this.getRangeAt(); r.insertNode(html); } else { var r = this.getRangeAt(); r.insertNode(n); r.setStartAfter(n); r.setEndAfter(n); var s = selection(); s.removeAllRanges(); s.addRange(r); } return this.cleanCache(); } /** * Вставляет html в текущее выделение * * @param Element n нода * @return selection **/ this.insertHtml = function(html, collapse) { if (collapse && !this.collapsed()) { this.collapse(); } if (this.rte.browser.msie) { this.getRangeAt().range().pasteHTML(html); } else { var n = $(this.rte.dom.create('span')).html(html||'').get(0); this.insertNode(n); $(n).replaceWith($(n).html()); } return this.cleanCache(); } /** * Вставляет ноду в текущее выделение * * @param Element n нода * @return selection **/ this.insertText = function(text, collapse) { var n = this.rte.doc.createTextNode(text); return this.insertHtml(n.nodeValue); } this.getBookmark = function() { this.rte.window.focus(); var r, r1, r2, _s, _e, s = this.rte.dom.createBookmark(), e = this.rte.dom.createBookmark(); if ($.browser.msie) { try { r = this.rte.window.document.selection.createRange(); } catch(e) { r = this.rte.doc.body.createTextRange(); } if (r.item) { var n = r.item(0); r = this.rte.doc.body.createTextRange(); r.moveToElementText(n); } r1 = r.duplicate(); r2 = r.duplicate(); _s = this.rte.dom.create('span'); _e = this.rte.dom.create('span'); _s.appendChild(s); _e.appendChild(e); r1.collapse(true); r1.pasteHTML(_s.innerHTML); r2.collapse(false); r2.pasteHTML(_e.innerHTML); } else { var sel = selection(); var r = sel.rangeCount > 0 ? sel.getRangeAt(0) : this.rte.doc.createRange(); // r = this.getRangeAt(); r1 = r.cloneRange(); r2 = r.cloneRange(); // this.insertNode(this.rte.dom.create('hr')) // return r2.collapse(false); r2.insertNode(e); r1.collapse(true); r1.insertNode(s); this.select(s, e); } return [s.id, e.id]; } this.moveToBookmark = function(b) { this.rte.window.focus(); if (b && b.length==2) { var s = this.rte.doc.getElementById(b[0]), e = this.rte.doc.getElementById(b[1]), sel, r; if (s && e) { this.select(s, e); if (this.rte.dom.next(s) == e) { this.collapse(true); } if (!$.browser.msie) { sel = selection(); r = sel.rangeCount > 0 ? sel.getRangeAt(0) : this.rte.doc.createRange(); sel.removeAllRanges(); sel.addRange(r); } s.parentNode.removeChild(s); e.parentNode.removeChild(e); } } return this; } this.removeBookmark = function(b) { this.rte.window.focus(); if (b.length==2) { var s = this.rte.doc.getElementById(b[0]), e = this.rte.doc.getElementById(b[1]); if (s && e) { s.parentNode.removeChild(s); e.parentNode.removeChild(e); } } } /** * Очищает кэш * * @return selection **/ this.cleanCache = function() { start = end = node = null; return this; } /** * Возвращает ноду начала выделения * * @return DOMElement **/ this.getStart = function() { if (!start) { var r = this.getRangeAt(); start = r.getStart(); } return start; } /** * Возвращает ноду конца выделения * * @return DOMElement **/ this.getEnd = function() { if (!end) { var r = this.getRangeAt(); end = r.getEnd(); } return end; } /** * Возвращает выбраную ноду (общий контейнер всех выбранных нод) * * @return Element **/ this.getNode = function() { if (!node) { node = this.rte.dom.findCommonAncestor(this.getStart(), this.getEnd()); } return node; } /** * Возвращает массив выбранных нод * * @param Object o параметры получения и обработки выбраных нод * @return Array **/ this.selected = function(o) { var opts = { collapsed : false, // вернуть выделение, даже если оно схлопнуто blocks : false, // блочное выделение filter : false, // фильтр результатов wrap : 'text', // что оборачиваем tag : 'span' // во что оборачиваем } opts = $.extend({}, opts, o); // блочное выделение - ищем блочную ноду, но не таблицу if (opts.blocks) { var n = this.getNode(), _n = null; if (_n = this.rte.dom.selfOrParent(n, 'selectionBlock') ) { return [_n]; } } var sel = this.selectedRaw(opts.collapsed, opts.blocks); var ret = []; var buffer = []; var ndx = null; // оборачиваем ноды в буффере function wrap() { function allowParagraph() { for (var i=0; i < buffer.length; i++) { if (buffer[i].nodeType == 1 && (self.rte.dom.selfOrParent(buffer[i], /^P$/) || $(buffer[i]).find('p').length>0)) { return false; } }; return true; } if (buffer.length>0) { var tag = opts.tag == 'p' && !allowParagraph() ? 'div' : opts.tag; var n = self.rte.dom.wrap(buffer, tag); ret[ndx] = n; ndx = null; buffer = []; } } // добавляем ноды в буффер function addToBuffer(n) { if (n.nodeType == 1) { if (/^(THEAD|TFOOT|TBODY|COL|COLGROUP|TR)$/.test(n.nodeName)) { $(n).find('td,th').each(function() { var tag = opts.tag == 'p' && $(this).find('p').length>0 ? 'div' : opts.tag; var n = self.rte.dom.wrapContents(this, tag); return ret.push(n); }) } else if (/^(CAPTION|TD|TH|LI|DT|DD)$/.test(n.nodeName)) { var tag = opts.tag == 'p' && $(n).find('p').length>0 ? 'div' : opts.tag; var n = self.rte.dom.wrapContents(n, tag); return ret.push(n); } } var prev = buffer.length>0 ? buffer[buffer.length-1] : null; if (prev && prev != self.rte.dom.prev(n)) { wrap(); } buffer.push(n); if (ndx === null) { ndx = ret.length; ret.push('dummy'); // заглушка для оборачиваемых элементов } } if (sel.nodes.length>0) { for (var i=0; i < sel.nodes.length; i++) { var n = sel.nodes[i]; // первую и посл текстовые ноды разрезаем, если необходимо if (n.nodeType == 3 && (i==0 || i == sel.nodes.length-1) && $.trim(n.nodeValue).length>0) { if (i==0 && sel.so>0) { n = n.splitText(sel.so); } if (i == sel.nodes.length-1 && sel.eo>0) { n.splitText(i==0 && sel.so>0 ? sel.eo - sel.so : sel.eo); } } switch (opts.wrap) { // оборачиваем только текстовые ноды с br case 'text': if ((n.nodeType == 1 && n.nodeName == 'BR') || (n.nodeType == 3 && $.trim(n.nodeValue).length>0)) { addToBuffer(n); } else if (n.nodeType == 1) { ret.push(n); } break; // оборачиваем все инлайн элементы case 'inline': if (this.rte.dom.isInline(n)) { addToBuffer(n); } else if (n.nodeType == 1) { ret.push(n); } break; // оборачиваем все case 'all': if (n.nodeType == 1 || !this.rte.dom.isEmpty(n)) { addToBuffer(n); } break; // ничего не оборачиваем default: if (n.nodeType == 1 || !this.rte.dom.isEmpty(n)) { ret.push(n); } } }; wrap(); } if (ret.length) { this.rte.window.focus(); this.select(ret[0], ret[ret.length-1]); } return opts.filter ? this.rte.dom.filter(ret, opts.filter) : ret; } this.dump = function(ca, s, e, so, eo) { var r = this.getRangeAt(); this.rte.log('commonAncestorContainer'); this.rte.log(ca || r.commonAncestorContainer); // this.rte.log('commonAncestorContainer childs num') // this/rte.log((ca||r.commonAncestorContainer).childNodes.length) this.rte.log('startContainer'); this.rte.log(s || r.startContainer); this.rte.log('startOffset: '+(so>=0 ? so : r.startOffset)); this.rte.log('endContainer'); this.rte.log(e||r.endContainer); this.rte.log('endOffset: '+(eo>=0 ? eo : r.endOffset)); } /** * Возвращает массив выбранных нод, как есть * * @param bool возвращать если выделение схлопнуто * @param bool "блочное" выделение (текстовые ноды включаются полностью, не зависимо от offset) * @return Array **/ this.selectedRaw = function(collapsed, blocks) { var res = {so : null, eo : null, nodes : []}; var r = this.getRangeAt(true); var ca = r.commonAncestorContainer; var s, e; // start & end nodes var sf = false; // start node fully selected var ef = false; // end node fully selected // возвращает true, если нода не текстовая или выделена полностью function isFullySelected(n, s, e) { if (n.nodeType == 3) { e = e>=0 ? e : n.nodeValue.length; return (s==0 && e==n.nodeValue.length) || $.trim(n.nodeValue).length == $.trim(n.nodeValue.substring(s, e)).length; } return true; } // возвращает true, если нода пустая или в ней не выделено ни одного непробельного символа function isEmptySelected(n, s, e) { if (n.nodeType == 1) { return self.rte.dom.isEmpty(n); } else if (n.nodeType == 3) { return $.trim(n.nodeValue.substring(s||0, e>=0 ? e : n.nodeValue.length)).length == 0; } return true; } //this.dump() // начальная нода if (r.startContainer.nodeType == 1) { if (r.startOffset<r.startContainer.childNodes.length) { s = r.startContainer.childNodes[r.startOffset]; res.so = s.nodeType == 1 ? null : 0; } else { s = r.startContainer.childNodes[r.startOffset-1]; res.so = s.nodeType == 1 ? null : s.nodeValue.length; } } else { s = r.startContainer; res.so = r.startOffset; } // выделение схлопнуто if (r.collapsed) { if (collapsed) { // блочное выделение if (blocks) { s = realSelected(s); if (!this.rte.dom.isEmpty(s) || (s = this.rte.dom.next(s))) { res.nodes = [s]; } // добавляем инлайн соседей if (this.rte.dom.isInline(s)) { res.nodes = this.rte.dom.toLineStart(s).concat(res.nodes, this.rte.dom.toLineEnd(s)); } // offset для текстовых нод if (res.nodes.length>0) { res.so = res.nodes[0].nodeType == 1 ? null : 0; res.eo = res.nodes[res.nodes.length-1].nodeType == 1 ? null : res.nodes[res.nodes.length-1].nodeValue.length; } } else if (!this.rte.dom.isEmpty(s)) { res.nodes = [s]; } } return res; } // конечная нода if (r.endContainer.nodeType == 1) { e = r.endContainer.childNodes[r.endOffset-1]; res.eo = e.nodeType == 1 ? null : e.nodeValue.length; } else { e = r.endContainer; res.eo = r.endOffset; } // this.rte.log('select 1') //this.dump(ca, s, e, res.so, res.eo) // начальная нода выделена полностью - поднимаемся наверх по левой стороне if (s.nodeType == 1 || blocks || isFullySelected(s, res.so, s.nodeValue.length)) { // this.rte.log('start text node is fully selected') s = realSelected(s, ca, 'left'); sf = true; res.so = s.nodeType == 1 ? null : 0; } // конечная нода выделена полностью - поднимаемся наверх по правой стороне if (e.nodeType == 1 || blocks || isFullySelected(e, 0, res.eo)) { // this.rte.log('end text node is fully selected') e = realSelected(e, ca, 'right'); ef = true; res.eo = e.nodeType == 1 ? null : e.nodeValue.length; } // блочное выделение - если ноды не элементы - поднимаемся к родителю, но ниже контейнера if (blocks) { if (s.nodeType != 1 && s.parentNode != ca && s.parentNode.nodeName != 'BODY') { s = s.parentNode; res.so = null; } if (e.nodeType != 1 && e.parentNode != ca && e.parentNode.nodeName != 'BODY') { e = e.parentNode; res.eo = null; } } // если контенер выделен полностью, поднимаемся наверх насколько можно if (s.parentNode == e.parentNode && s.parentNode.nodeName != 'BODY' && (sf && this.rte.dom.isFirstNotEmpty(s)) && (ef && this.rte.dom.isLastNotEmpty(e))) { // this.rte.log('common parent') s = e = s.parentNode; res.so = s.nodeType == 1 ? null : 0; res.eo = e.nodeType == 1 ? null : e.nodeValue.length; } // начальная нода == конечной ноде if (s == e) { // this.rte.log('start is end') if (!this.rte.dom.isEmpty(s)) { res.nodes.push(s); } return res; } // this.rte.log('start 2') //this.dump(ca, s, e, res.so, res.eo) // находим начальную и конечную точки - ноды из иерархии родителей начальной и конечно ноды, у которых родитель - контейнер var sp = s; while (sp.nodeName != 'BODY' && sp.parentNode !== ca && sp.parentNode.nodeName != 'BODY') { sp = sp.parentNode; } //this.rte.log(s.nodeName) // this.rte.log('start point') // this.rte.log(sp) var ep = e; // this.rte.log(ep) while (ep.nodeName != 'BODY' && ep.parentNode !== ca && ep.parentNode.nodeName != 'BODY') { // this.rte.log(ep) ep = ep.parentNode; } // this.rte.log('end point') // this.rte.log(ep) // если начальная нода не пустая - добавляем ее if (!isEmptySelected(s, res.so, s.nodeType==3 ? s.nodeValue.length : null)) { res.nodes.push(s); } // поднимаемся от начальной ноды до начальной точки var n = s; while (n !== sp) { var _n = n; while ((_n = this.rte.dom.next(_n))) { res.nodes.push(_n); } n = n.parentNode; } // от начальной точки до конечной точки n = sp; while ((n = this.rte.dom.next(n)) && n!= ep ) { // this.rte.log(n) res.nodes.push(n); } // поднимаемся от конечной ноды до конечной точки, результат переворачиваем var tmp = []; n = e; while (n !== ep) { var _n = n; while ((_n = this.rte.dom.prev(_n))) { tmp.push(_n); } n = n.parentNode; } if (tmp.length) { res.nodes = res.nodes.concat(tmp.reverse()); } // если конечная нода не пустая и != начальной - добавляем ее if (!isEmptySelected(e, 0, e.nodeType==3 ? res.eo : null)) { res.nodes.push(e); } if (blocks) { // добавляем инлайн соседей слева if (this.rte.dom.isInline(s)) { res.nodes = this.rte.dom.toLineStart(s).concat(res.nodes); res.so = res.nodes[0].nodeType == 1 ? null : 0; } // добавляем инлайн соседей справа if (this.rte.dom.isInline(e)) { res.nodes = res.nodes.concat(this.rte.dom.toLineEnd(e)); res.eo = res.nodes[res.nodes.length-1].nodeType == 1 ? null : res.nodes[res.nodes.length-1].nodeValue.length; } } // все радуются! :) return res; } } })(jQuery);/** * @class elRTE User interface controller * * @param elRTE rte объект-редактор * * @author: Dmitry Levashov (dio) dio@std42.ru * @todo: this.domElem.removeClass('disabled') - move to ui.update; * @todo: add dom and selection as button members * Copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui = function(rte) { this.rte = rte; this._buttons = []; var self = this, tb = this.rte.options.toolbars[rte.options.toolbar && rte.options.toolbars[rte.options.toolbar] ? rte.options.toolbar : 'normal'], tbl = tb.length, p, pname, pl, n, c, b, i; // add prototype to all buttons for (i in this.buttons) { if (this.buttons.hasOwnProperty(i) && i != 'button') { this.buttons[i].prototype = this.buttons.button.prototype; } } // create buttons and put on toolbar while (tbl--) { first = (tbl == 0 ? true : false); if (tb[tbl - 1] == 'eol') { first = true; } pname = tb[tbl]; // special 'end of line' panel, starts next panel on a new line if (pname == 'eol') { $(this.rte.doc.createElement('br')).prependTo(this.rte.toolbar); continue; } p = $('<ul class="panel-'+pname+(first ? ' first' : '')+'" />').prependTo(this.rte.toolbar); p.bind('mousedown', function(e) { e.preventDefault(); }) pl = this.rte.options.panels[pname].length; while (pl--) { n = this.rte.options.panels[pname][pl]; c = this.buttons[n] || this.buttons.button; this._buttons.push((b = new c(this.rte, n))); p.prepend(b.domElem); } } this.update(); this.disable = function() { $.each(self._buttons, function() { !this.active && this.domElem.addClass('disabled'); }); } } /** * Обновляет кнопки - вызывает метод update() для каждой кнопки * * @return void **/ elRTE.prototype.ui.prototype.update = function(cleanCache) { cleanCache && this.rte.selection.cleanCache(); var n = this.rte.selection.getNode(), p = this.rte.dom.parents(n, '*'), rtl = this.rte.rtl, sep = rtl ? ' &laquo; ' : ' &raquo; ', path = '', name, i; function _name(n) { var name = n.nodeName.toLowerCase(); n = $(n) if (name == 'img') { if (n.hasClass('elrte-media')) { name = 'media'; } else if (n.hasClass('elrte-google-maps')) { name = 'google map'; } else if (n.hasClass('elrte-yandex-maps')) { name = 'yandex map'; } else if (n.hasClass('elrte-pagebreak')) { name = 'pagebreak'; } } return name; } if (n && n.nodeType == 1 && n.nodeName != 'BODY') { p.unshift(n); } if (!rtl) { p = p.reverse(); } for (i=0; i < p.length; i++) { path += (i>0 ? sep : '')+_name(p[i]); } this.rte.statusbar.html(path); $.each(this._buttons, function() { this.update(); }); this.rte.window.focus(); } elRTE.prototype.ui.prototype.buttons = { /** * @class кнопка на toolbar редактора * реализует поведение по умолчанию и является родителем для других кнопок * * @param elRTE rte объект-редактор * @param String name название кнопки (команда исполняемая document.execCommand()) **/ button : function(rte, name) { var self = this; this.rte = rte; this.active = false; this.name = name; this.val = null; this.domElem = $('<li style="-moz-user-select:-moz-none" class="'+name+' rounded-3" name="'+name+'" title="'+this.rte.i18n(this.rte.options.buttons[name] || name)+'" unselectable="on" />') .hover( function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); } ) .click( function(e) { e.stopPropagation(); e.preventDefault(); if (!$(this).hasClass('disabled')) { // try{ self.command(); // } catch(e) { // self.rte.log(e) // } } self.rte.window.focus(); }); } } /** * Обработчик нажатия на кнопку на тулбаре. Выполнение команды или открытие окна|меню и тд * * @return void **/ elRTE.prototype.ui.prototype.buttons.button.prototype.command = function() { this.rte.history.add(); try { this.rte.doc.execCommand(this.name, false, this.val); } catch(e) { return this.rte.log('commands failed: '+this.name); } this.rte.ui.update(true); } /** * Обновляет состояние кнопки * * @return void **/ elRTE.prototype.ui.prototype.buttons.button.prototype.update = function() { try { if (!this.rte.doc.queryCommandEnabled(this.name)) { return this.domElem.addClass('disabled'); } else { this.domElem.removeClass('disabled'); } } catch (e) { return; } try { if (this.rte.doc.queryCommandState(this.name)) { this.domElem.addClass('active'); } else { this.domElem.removeClass('active'); } } catch (e) { } } })(jQuery); /* * Misc utils for elRTE * * @param Object rte - editor * @todo Подумать, что из этого реально нужно и навести порядок. Возможно часть перенести в ellib * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru */ (function($) { elRTE.prototype.utils = function(rte) { this.rte = rte; this.url = null; // domo arigato, Steave, http://blog.stevenlevithan.com/archives/parseuri this.reg = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; this.baseURL = ''; this.path = ''; /** * entities map **/ this.entities = {'&' : '&amp;', '"' : '&quot;', '<' : '&lt;', '>' : '&gt;'}; /** * entities regexp **/ this.entitiesRegExp = /[<>&\"]/g; /** * media info **/ this.media = [{ type : 'application/x-shockwave-flash', classid : ['clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'], codebase : 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' }, { type : 'application/x-director', classid : ['clsid:166b1bca-3f9c-11cf-8075-444553540000'], codebase : 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0' }, { type : 'application/x-mplayer2', classid : ['clsid:6bf52a52-394a-11d3-b153-00c04f79faa6', 'clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95', 'clsid:05589fa1-c356-11ce-bf01-00aa0055595a'], codebase : 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' }, { type : 'video/quicktime', classid : ['clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b'], codebase : 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0' }, { type : 'audio/x-pn-realaudio-plugin', classid : ['clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa'], codebase : 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' }]; // rgb color regexp this.rgbRegExp = /\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*/i; // regexp to detect color in border/background properties this.colorsRegExp = /aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|rgb\s*\([^\)]+\)/i; // web safe colors this.colors = { aqua : '#00ffff', black : '#000000', blue : '#0000ff', fuchsia : '#ff00ff', gray : '#808080', green : '#008000', lime : '#00ff00', maroon : '#800000', navy : '#000080', olive : '#808000', orange : '#ffa500', purple : '#800080', red : '#ff0000', silver : '#c0c0c0', teal : '#008080', white : '#fffffff', yellow : '#ffff00' } var self = this; this.rgb2hex = function(str) { return this.color2Hex(''+str) } this.toPixels = function(num) { var m = num.match(/([0-9]+\.?[0-9]*)\s*(px|pt|em|%)/); if (m) { num = m[1]; unit = m[2]; } if (num[0] == '.') { num = '0'+num; } num = parseFloat(num); if (isNaN(num)) { return ''; } var base = parseInt($(document.body).css('font-size')) || 16; switch (unit) { case 'em': return parseInt(num*base); case 'pt': return parseInt(num*base/12); case '%' : return parseInt(num*base/100); } return num; } // TODO: add parse rel path ../../etc this.absoluteURL = function(url) { !this.url && this._url(); url = $.trim(url); if (!url) { return ''; } // ссылки на якоря не переводим в абс if (url[0] == '#') { return url; } var u = this.parseURL(url); if (!u.host && !u.path && !u.anchor) { //this.rte.log('Invalid URL: '+url) return ''; } if (!this.rte.options.absoluteURLs) { return url; } if (u.protocol) { //this.rte.log('url already absolute: '+url); return url; } if (u.host && (u.host.indexOf('.')!=-1 || u.host == 'localhost')) { //this.rte.log('no protocol'); return this.url.protocol+'://'+url; } if (url[0] == '/') { url = this.baseURL+url; } else { if (url.indexOf('./') == 0) { url = url.substring(2); } url = this.baseURL+this.path+url; } return url; } this.parseURL = function(url) { var u = url.match(this.reg); var ret = {}; $.each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(i) { ret[this] = u[i]; }); if (!ret.host.match(/[a-z0-9]/i)) { ret.host = ''; } return ret; } this.trimEventCallback = function(c) { c = c ? c.toString() : ''; return $.trim(c.replace(/\r*\n/mg, '').replace(/^function\s*on[a-z]+\s*\(\s*event\s*\)\s*\{(.+)\}$/igm, '$1')); } this._url = function() { this.url = this.parseURL(window.location.href); this.baseURL = this.url.protocol+'://'+(this.url.userInfo ? parts.userInfo+'@' : '')+this.url.host+(this.url.port ? ':'+this.url.port : ''); this.path = !this.url.file ? this.url.path : this.url.path.substring(0, this.url.path.length - this.url.file.length); } /** * Create object (map) from array * * @param Array * @return Object **/ this.makeObject = function(o) { var m = {}; $.each(o, function(i, e) { m[e] = e; }); return m; } /** * Encode entities in string * * @param String * @return String **/ this.encode = function(s) { var e = this.entities; return (''+s).replace(this.entitiesRegExp, function(c) { return e[c]; }); } /** * Decode entities in string * * @param String * @return String **/ this.decode = function(s) { return $('<div/>').html(s||'').text(); } /** * Parse style string into object * * @param String * @return Object **/ this.parseStyle = function(s) { var st = {}, a = this.rte.options.allowBrowsersSpecStyles, t, n, v, p; if (typeof(s) == 'string' && s.length) { $.each(s.replace(/&quot;/gi, "'").split(';'), function(i, str) { if ((p = str.indexOf(':')) !== -1) { n = $.trim(str.substr(0, p)); v = $.trim(str.substr(p+1)) if (n == 'color' || n == 'background-color') { v = v.toLowerCase(); } if (n && v && (a || n.substring(0, 1) != '-')) { st[n] = v; } } }); } return st; } /** * Compact some style properties and convert colors in hex * * @param Object * @return Object **/ this.compactStyle = function(s) { var self = this; if (s.border == 'medium none') { delete s.border; } $.each(s, function(n, v) { if (/color$/i.test(n)) { s[n] = self.color2Hex(v); } else if (/^(border|background)$/i.test(n)) { s[n] = v.replace(self.colorsRegExp, function(m) { return self.color2Hex(m); }); } }); if (s['border-width']) { s.border = s['border-width']+' '+(s['border-style']||'solid')+' '+(s['border-color']||'#000'); delete s['border-width']; delete s['border-style']; delete s['border-color']; } if (s['background-image']) { s.background = (s['background-color']+' ')||''+s['background-image']+' '+s['background-position']||'0 0'+' '+s['background-repeat']||'repeat'; delete s['background-image']; delete['background-image']; delete['background-position']; delete['background-repeat']; } if (s['margin-top'] && s['margin-right'] && s['margin-bottom'] && s['margin-left']) { s.margin = s['margin-top']+' '+s['margin-right']+' '+s['margin-bottom']+' '+s['margin-left']; delete s['margin-top']; delete s['margin-right']; delete s['margin-bottom']; delete s['margin-left']; } if (s['padding-top'] && s['padding-right'] && s['padding-bottom'] && s['padding-left']) { s.padding = s['padding-top']+' '+s['padding-right']+' '+s['padding-bottom']+' '+s['padding-left']; delete s['padding-top']; delete s['padding-right']; delete s['padding-bottom']; delete s['padding-left']; } if (s['list-style-type'] || s['list-style-position'] || s['list-style-image']) { s['list-style'] = $.trim(s['list-style-type']||' '+s['list-style-position']||''+s['list-style-image']||''); delete s['list-style-type']; delete s['list-style-position']; delete s['list-style-image']; } return s; } /** * Serialize style object into string * * @param Object style map * @param Boolean flag - compact style? * @return String **/ this.serializeStyle = function(o, c) { var s = []; // c=true $.each(c ? this.compactStyle(o) : o, function(n, v) { v && s.push(n+':'+v); }); return s.join(';'); } /** * Parse class string into object * * @param String * @return Object **/ this.parseClass = function(c) { c = $.trim(c); // this.rte.log(c) return c.length ? this.makeObject(c.split(/\s+/)) : {}; return c.length ? c.split(/\s+/) : []; } /** * Serialize class object into string * * @param Object * @return String **/ this.serializeClass = function(c) { // return c.join(' ') var s = []; // this.rte.log(c) var rte = this.rte $.each(c, function(n) { s.push(n); // rte.log(typeof(n)) }); return s.join(' '); } /** * Return required media type info * * @param String mimetype * @param String classid * @return Object **/ this.mediaInfo = function(t, c) { var l = this.media.length; while (l--) { if (t === this.media[l].type || (c && $.inArray(c, this.media[l].classid) != -1)) { return this.media[l]; } } } /** * Return color hex value * * @param String color name or rgb * @return String **/ this.color2Hex = function(c) { var m; c = c||''; if (c.indexOf('#') === 0) { return c; } function hex(s) { s = parseInt(s).toString(16); return s.length > 1 ? s : '0' + s; }; if (this.colors[c]) { return this.colors[c]; } if ((m = c.match(this.rgbRegExp))) { return '#'+hex(m[1])+hex(m[2])+hex(m[3]); } return ''; } } })(jQuery);/** * @class w3cRange - w3c text range emulation for "strange" browsers * * @param elRTE rte объект-редактор * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.w3cRange = function(rte) { var self = this; this.rte = rte; this.r = null; this.collapsed = true; this.startContainer = null; this.endContainer = null; this.startOffset = 0; this.endOffset = 0; this.commonAncestorContainer = null; this.range = function() { try { this.r = this.rte.window.document.selection.createRange(); } catch(e) { this.r = this.rte.doc.body.createTextRange(); } return this.r; } this.insertNode = function(html) { this.range(); self.r.collapse(false) var r = self.r.duplicate(); r.pasteHTML(html); } this.getBookmark = function() { this.range(); if (this.r.item) { var n = this.r.item(0); this.r = this.rte.doc.body.createTextRange(); this.r.moveToElementText(n); } return this.r.getBookmark(); } this.moveToBookmark = function(bm) { this.rte.window.focus(); this.range().moveToBookmark(bm); this.r.select(); } /** * Обновляет данные о выделенных нодах * * @return void **/ this.update = function() { function _findPos(start) { var marker = '\uFEFF'; var ndx = offset = 0; var r = self.r.duplicate(); r.collapse(start); var p = r.parentElement(); if (!p || p.nodeName == 'HTML') { return {parent : self.rte.doc.body, ndx : ndx, offset : offset}; } r.pasteHTML(marker); childs = p.childNodes; for (var i=0; i < childs.length; i++) { var n = childs[i]; if (i>0 && (n.nodeType!==3 || childs[i-1].nodeType !==3)) { ndx++; } if (n.nodeType !== 3) { offset = 0; } else { var pos = n.nodeValue.indexOf(marker); if (pos !== -1) { offset += pos; break; } offset += n.nodeValue.length; } }; r.moveStart('character', -1); r.text = ''; return {parent : p, ndx : Math.min(ndx, p.childNodes.length-1), offset : offset}; } this.range(); this.startContainer = this.endContainer = null; if (this.r.item) { this.collapsed = false; var i = this.r.item(0); this.setStart(i.parentNode, this.rte.dom.indexOf(i)); this.setEnd(i.parentNode, this.startOffset+1); } else { this.collapsed = this.r.boundingWidth == 0; var start = _findPos(true); var end = _findPos(false); start.parent.normalize(); end.parent.normalize(); start.ndx = Math.min(start.ndx, start.parent.childNodes.length-1); end.ndx = Math.min(end.ndx, end.parent.childNodes.length-1); if (start.parent.childNodes[start.ndx].nodeType && start.parent.childNodes[start.ndx].nodeType == 1) { this.setStart(start.parent, start.ndx); } else { this.setStart(start.parent.childNodes[start.ndx], start.offset); } if (end.parent.childNodes[end.ndx].nodeType && end.parent.childNodes[end.ndx].nodeType == 1) { this.setEnd(end.parent, end.ndx); } else { this.setEnd(end.parent.childNodes[end.ndx], end.offset); } // this.dump(); this.select(); } return this; } this.isCollapsed = function() { this.range(); this.collapsed = this.r.item ? false : this.r.boundingWidth == 0; return this.collapsed; } /** * "Схлопывает" выделение * * @param bool toStart - схлопывать выделение к началу или к концу * @return void **/ this.collapse = function(toStart) { this.range(); if (this.r.item) { var n = this.r.item(0); this.r = this.rte.doc.body.createTextRange(); this.r.moveToElementText(n); } this.r.collapse(toStart); this.r.select(); this.collapsed = true; } this.getStart = function() { this.range(); if (this.r.item) { return this.r.item(0); } var r = this.r.duplicate(); r.collapse(true); var s = r.parentElement(); return s && s.nodeName == 'BODY' ? s.firstChild : s; } this.getEnd = function() { this.range(); if (this.r.item) { return this.r.item(0); } var r = this.r.duplicate(); r.collapse(false); var e = r.parentElement(); return e && e.nodeName == 'BODY' ? e.lastChild : e; } /** * Устанавливает начaло выделения на указаную ноду * * @param Element node нода * @param Number offset отступ от начала ноды * @return void **/ this.setStart = function(node, offset) { this.startContainer = node; this.startOffset = offset; if (this.endContainer) { this.commonAncestorContainer = this.rte.dom.findCommonAncestor(this.startContainer, this.endContainer); } } /** * Устанавливает конец выделения на указаную ноду * * @param Element node нода * @param Number offset отступ от конца ноды * @return void **/ this.setEnd = function(node, offset) { this.endContainer = node; this.endOffset = offset; if (this.startContainer) { this.commonAncestorContainer = this.rte.dom.findCommonAncestor(this.startContainer, this.endContainer); } } /** * Устанавливает начaло выделения перед указаной нодой * * @param Element node нода * @return void **/ this.setStartBefore = function(n) { if (n.parentNode) { this.setStart(n.parentNode, this.rte.dom.indexOf(n)); } } /** * Устанавливает начaло выделения после указаной ноды * * @param Element node нода * @return void **/ this.setStartAfter = function(n) { if (n.parentNode) { this.setStart(n.parentNode, this.rte.dom.indexOf(n)+1); } } /** * Устанавливает конец выделения перед указаной нодой * * @param Element node нода * @return void **/ this.setEndBefore = function(n) { if (n.parentNode) { this.setEnd(n.parentNode, this.rte.dom.indexOf(n)); } } /** * Устанавливает конец выделения после указаной ноды * * @param Element node нода * @return void **/ this.setEndAfter = function(n) { if (n.parentNode) { this.setEnd(n.parentNode, this.rte.dom.indexOf(n)+1); } } /** * Устанавливает новое выделение после изменений * * @return void **/ this.select = function() { // thanks tinymice authors function getPos(n, o) { if (n.nodeType != 3) { return -1; } var c ='\uFEFF'; var val = n.nodeValue; var r = self.rte.doc.body.createTextRange(); n.nodeValue = val.substring(0, o) + c + val.substring(o); r.moveToElementText(n.parentNode); r.findText(c); var p = Math.abs(r.moveStart('character', -0xFFFFF)); n.nodeValue = val; return p; }; this.r = this.rte.doc.body.createTextRange(); var so = this.startOffset; var eo = this.endOffset; var s = this.startContainer.nodeType == 1 ? this.startContainer.childNodes[Math.min(so, this.startContainer.childNodes.length - 1)] : this.startContainer; var e = this.endContainer.nodeType == 1 ? this.endContainer.childNodes[Math.min(so == eo ? eo : eo - 1, this.endContainer.childNodes.length - 1)] : this.endContainer; if (this.collapsed) { if (s.nodeType == 3) { var p = getPos(s, so); this.r.move('character', p); } else { this.r.moveToElementText(s); this.r.collapse(true); } } else { var r = this.rte.doc.body.createTextRange(); var sp = getPos(s, so); var ep = getPos(e, eo); if (s.nodeType == 3) { this.r.move('character', sp); } else { this.r.moveToElementText(s); } if (e.nodeType == 3) { r.move('character', ep); } else { r.moveToElementText(e); } this.r.setEndPoint('EndToEnd', r); } try { this.r.select(); } catch(e) { } if (r) { r = null; } } this.dump = function() { this.rte.log('collapsed: '+this.collapsed); //this.rte.log('commonAncestorContainer: '+this.commonAncestorContainer.nodeName||'#text') this.rte.log('startContainer: '+(this.startContainer ? this.startContainer.nodeName : 'non')); this.rte.log('startOffset: '+this.startOffset); this.rte.log('endContainer: '+(this.endContainer ? this.endContainer.nodeName : 'none')); this.rte.log('endOffset: '+this.endOffset); } } })(jQuery); (function($) { elRTE.prototype.ui.prototype.buttons.about = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.active = true; this.command = function() { var opts, d, txt; opts = { rtl : rte.rtl, submit : function(e, d) { d.close(); }, dialog : { width : 560, title : this.rte.i18n('About this software'), buttons : { Ok : function() { $(this).dialog('destroy'); } } } } txt = '<div class="elrte-logo"></div><h3>'+this.rte.i18n('About elRTE')+'</h3><br clear="all"/>' +'<div class="elrte-ver">'+this.rte.i18n('Version')+': '+this.rte.version+' ('+this.rte.build+')</div>' +'<div class="elrte-ver">jQuery: '+$('<div/>').jquery+'</div>' +'<div class="elrte-ver">jQueryUI: '+$.ui.version+'</div>' +'<div class="elrte-ver">'+this.rte.i18n('Licence')+': BSD Licence</div>' +'<p>' +this.rte.i18n('elRTE is an open-source JavaScript based WYSIWYG HTML-editor.')+'<br/>' +this.rte.i18n('Main goal of the editor - simplify work with text and formating (HTML) on sites, blogs, forums and other online services.')+'<br/>' +this.rte.i18n('You can use it in any commercial or non-commercial projects.') +'</p>' +'<h4>'+this.rte.i18n('Authors')+'</h4>' +'<table class="elrte-authors">' +'<tr><td>Dmitry (dio) Levashov &lt;dio@std42.ru&gt;</td><td>'+this.rte.i18n('Chief developer')+'</td></tr>' +'<tr><td>Troex Nevelin &lt;troex@fury.scancode.ru&gt;</td><td>'+this.rte.i18n('Developer, tech support')+'</td></tr>' +'<tr><td>Valentin Razumnyh &lt;content@std42.ru&gt;</td><td>'+this.rte.i18n('Interface designer')+'</td></tr>' +'<tr><td>Tawfek Daghistani &lt;tawfekov@gmail.com&gt;</td><td>'+this.rte.i18n('RTL support')+'</td></tr>' +(this.rte.options.lang != 'en' ? '<tr><td>'+this.rte.i18n('_translator')+'</td><td>'+this.rte.i18n('_translation')+'</td></tr>' : '') +'</table>' +'<div class="elrte-copy">Copyright &copy; 2009-2011, <a href="http://www.std42.ru">Studio 42</a></div>' +'<div class="elrte-copy">'+this.rte.i18n('For more information about this software visit the')+' <a href="http://elrte.org">'+this.rte.i18n('elRTE website')+'.</a></div>' +'<div class="elrte-copy">Twitter: <a href="http://twitter.com/elrte_elfinder">elrte_elfinder</a></div>'; d = new elDialogForm(opts); d.append(txt); d.open(); } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class кнопка - Закладка (открывает диалоговое окно) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.anchor = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.input = $('<input type="text" />').attr('name', 'anchor').attr('size', '16') var self = this; this.command = function() { var opts = { rtl : this.rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); d.close(); self.set(); }, dialog : { title : this.rte.i18n('Bookmark') } } this.anchor = this.rte.dom.selfOrParentAnchor(this.rte.selection.getEnd()) || rte.dom.create('a'); !this.rte.selection.collapsed() && this.rte.selection.collapse(false); this.input.val($(this.anchor).addClass('elrte-anchor').attr('name')); this.rte.selection.saveIERange(); var d = new elDialogForm(opts); d.append([this.rte.i18n('Bookmark name'), this.input], null, true).open(); setTimeout(function() { self.input.focus()}, 20); } this.update = function() { var n = this.rte.selection.getNode(); if (this.rte.dom.selfOrParentLink(n)) { this.domElem.addClass('disabled'); } else if (this.rte.dom.selfOrParentAnchor(n)) { this.domElem.removeClass('disabled').addClass('active'); } else { this.domElem.removeClass('disabled').removeClass('active'); } } this.set = function() { var n = $.trim(this.input.val()); if (n) { this.rte.history.add(); if (!this.anchor.parentNode) { this.rte.selection.insertHtml('<a name="'+n+'" title="'+this.rte.i18n('Bookmark')+': '+n+'" class="elrte-anchor"></a>'); } else { this.anchor.name = n; this.anchor.title = this.rte.i18n('Bookmark')+': '+n; } } else if (this.anchor.parentNode) { this.rte.history.add(); this.anchor.parentNode.removeChild(this.anchor); } } } })(jQuery); /** * @class кнопка - Цитата * Если выделение схлопнуто и находится внутри цитаты - она удаляется * Новые цитаты создаются только из несхлопнутого выделения * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.blockquote = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { var n, nodes; this.rte.history.add(); if (this.rte.selection.collapsed() && (n = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^BLOCKQUOTE$/))) { $(n).replaceWith($(n).html()); } else { nodes = this.rte.selection.selected({wrap : 'all', tag : 'blockquote'}); nodes.length && this.rte.selection.select(nodes[0], nodes[nodes.length-1]); } this.rte.ui.update(true); } this.update = function() { if (this.rte.selection.collapsed()) { if (this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^BLOCKQUOTE$/)) { this.domElem.removeClass('disabled').addClass('active'); } else { this.domElem.addClass('disabled').removeClass('active'); } } else { this.domElem.removeClass('disabled active'); } } } })(jQuery); /** * @class кнопки "копировать/вырезать/вставить" * в firefox показывает предложение нажать Ctl+c, в остальных - копирует * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.copy = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { if (this.rte.browser.mozilla) { try { this.rte.doc.execCommand(this.name, false, null); } catch (e) { var s = ' Ctl + C'; if (this.name == 'cut') { s = ' Ctl + X'; } else if (this.name == 'paste') { s = ' Ctl + V'; } var opts = { dialog : { title : this.rte.i18n('Warning'), buttons : { Ok : function() { $(this).dialog('close'); } } } } var d = new elDialogForm(opts); d.append(this.rte.i18n('This operation is disabled in your browser on security reason. Use shortcut instead.')+': '+s).open(); } } else { this.constructor.prototype.command.call(this); } } } elRTE.prototype.ui.prototype.buttons.cut = elRTE.prototype.ui.prototype.buttons.copy; elRTE.prototype.ui.prototype.buttons.paste = elRTE.prototype.ui.prototype.buttons.copy; })(jQuery);(function($) { elRTE.prototype.ui.prototype.buttons.css = function(rte, name) { var self = this; this.constructor.prototype.constructor.call(this, rte, name); this.cssStyle = $('<input type="text" size="42" name="style" />'); this.cssClass = $('<input type="text" size="42" name="class" />'); this.elementID = $('<input type="text" size="42" name="id" />'); this.command = function() { var n = this.node(), opts; this.rte.selection.saveIERange(); if (n) { var opts = { submit : function(e, d) { e.stopPropagation(); e.preventDefault(); d.close(); self.set(); }, dialog : { title : this.rte.i18n('Style'), width : 450, resizable : true, modal : true } } this.cssStyle.val($(n).attr('style')); this.cssClass.val($(n).attr('class')); this.elementID.val($(n).attr('id')); var d = new elDialogForm(opts); d.append([this.rte.i18n('Css style'), this.cssStyle], null, true) d.append([this.rte.i18n('Css class'), this.cssClass], null, true) d.append([this.rte.i18n('ID'), this.elementID], null, true) d.open(); setTimeout(function() { self.cssStyle.focus() }, 20) } } this.set = function() { var n = this.node(); this.rte.selection.restoreIERange(); if (n) { $(n).attr('style', this.cssStyle.val()); $(n).attr('class', this.cssClass.val()); $(n).attr('id', this.elementID.val()); this.rte.ui.update(); } } this.node = function() { var n = this.rte.selection.getNode(); if (n.nodeType == 3) { n = n.parentNode; } return n.nodeType == 1 && n.nodeName != 'BODY' ? n : null; } this.update = function() { this.domElem.toggleClass('disabled', this.node()?false:true); } } })(jQuery); (function($) { /** * @class button - right to left direction (not work yet with text nodes in body) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru **/ elRTE.prototype.ui.prototype.buttons.rtl = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { var n = this.rte.selection.getNode(), self = this; if ($(n).attr('dir') == 'rtl' || $(n).parents('[dir="rtl"]').length || $(n).find('[dir="rtl"]').length) { $(n).removeAttr('dir'); $(n).parents('[dir="rtl"]').removeAttr('dir'); $(n).find('[dir="rtl"]').removeAttr('dir'); } else { if (this.rte.dom.is(n, 'textNodes') && this.rte.dom.is(n, 'block')) { $(n).attr('dir', 'rtl'); } else { $.each(this.rte.dom.parents(n, 'textNodes'), function(i, n) { if (self.rte.dom.is(n, 'block')) { $(n).attr('dir', 'rtl'); return false; } }); } } this.rte.ui.update(); } this.update = function() { var n = this.rte.selection.getNode(); this.domElem.removeClass('disabled'); if ($(n).attr('dir') == 'rtl' || $(n).parents('[dir="rtl"]').length || $(n).find('[dir="rtl"]').length) { this.domElem.addClass('active'); } else { this.domElem.removeClass('active'); } } } /** * @class button - left to right direction (not work yet with text nodes in body) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru **/ elRTE.prototype.ui.prototype.buttons.ltr = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { var n = this.rte.selection.getNode(), self = this; if ($(n).attr('dir') == 'ltr' || $(n).parents('[dir="ltr"]').length || $(n).find('[dir="ltr"]').length) { $(n).removeAttr('dir'); $(n).parents('[dir="ltr"]').removeAttr('dir'); $(n).find('[dir="ltr"]').removeAttr('dir'); } else { if (this.rte.dom.is(n, 'textNodes') && this.rte.dom.is(n, 'block')) { $(n).attr('dir', 'ltr'); } else { $.each(this.rte.dom.parents(n, 'textNodes'), function(i, n) { if (self.rte.dom.is(n, 'block')) { $(n).attr('dir', 'ltr'); return false; } }); } } this.rte.ui.update(); } this.update = function() { var n = this.rte.selection.getNode(); this.domElem.removeClass('disabled'); if ($(n).attr('dir') == 'ltr' || $(n).parents('[dir="ltr"]').length || $(n).find('[dir="ltr"]').length) { this.domElem.addClass('active'); } else { this.domElem.removeClass('active'); } } } })(jQuery);/** * @class кнопка - DIV * Если выделение схлопнуто и находится внутри div'a - он удаляется * Новые div'ы создаются только из несхлопнутого выделения * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.div = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { var n, nodes; this.rte.history.add(); if (this.rte.selection.collapsed()) { n = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^DIV$/); if (n) { $(n).replaceWith($(n).html()); } } else { nodes = this.rte.selection.selected({wrap : 'all', tag : 'div'}); nodes.length && this.rte.selection.select(nodes[0], nodes[nodes.length-1]); } this.rte.ui.update(true); } this.update = function() { if (this.rte.selection.collapsed()) { if (this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^DIV$/)) { this.domElem.removeClass('disabled').addClass('active'); } else { this.domElem.addClass('disabled active'); } } else { this.domElem.removeClass('disabled active'); } } } })(jQuery); /** * @class кнопка - Включение/выключение показа структуры документа * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.docstructure = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { this.domElem.toggleClass('active'); $(this.rte.doc.body).toggleClass('el-rte-structure'); } this.command(); this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class button - open elfinder window (not needed for image or link buttons).Used in ELDORADO.CMS for easy file manipulations. * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.elfinder = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this, rte = this.rte; this.command = function() { if (self.rte.options.fmAllow && typeof(self.rte.options.fmOpen) == 'function') { self.rte.options.fmOpen( function(url) { var name = decodeURIComponent(url.split('/').pop().replace(/\+/g, " ")); if (rte.selection.collapsed()) { rte.selection.insertHtml('<a href="'+url+'" >'+name+'</a>'); } else { rte.doc.execCommand('createLink', false, url); } } ); } } this.update = function() { if (self.rte.options.fmAllow && typeof(self.rte.options.fmOpen) == 'function') { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery); (function($) { elRTE.prototype.ui.prototype.buttons.flash = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.swf = null; this.placeholder = null; this.src = { url : $('<input type="text" name="url" />').css('width', '99%'), type : $('<select name="type"/>') .append('<option value="application/x-shockwave-flash">Flash</option>') .append('<option value="video/quicktime">Quicktime movie</option>') .append('<option value="application/x-mplayer2">Windows media</option>'), width : $('<input type="text" />').attr('size', 5).css('text-align', 'right'), height : $('<input type="text" />').attr('size', 5).css('text-align', 'right'), wmode : $('<select />') .append($('<option />').val('').text(this.rte.i18n('Not set', 'dialogs'))) .append($('<option />').val('transparent').text(this.rte.i18n('Transparent'))), align : $('<select />') .append($('<option />').val('').text(this.rte.i18n('Not set', 'dialogs'))) .append($('<option />').val('left' ).text(this.rte.i18n('Left'))) .append($('<option />').val('right' ).text(this.rte.i18n('Right'))) .append($('<option />').val('top' ).text(this.rte.i18n('Top'))) .append($('<option />').val('text-top' ).text(this.rte.i18n('Text top'))) .append($('<option />').val('middle' ).text(this.rte.i18n('middle'))) .append($('<option />').val('baseline' ).text(this.rte.i18n('Baseline'))) .append($('<option />').val('bottom' ).text(this.rte.i18n('Bottom'))) .append($('<option />').val('text-bottom').text(this.rte.i18n('Text bottom'))), margin : $('<div />') } this.command = function() { var n = this.rte.selection.getEnd(), opts, url='', w='', h='', f, a, d, mid, o, wm; this.rte.selection.saveIERange(); this.src.margin.elPaddingInput({ type : 'margin' }); this.placeholder = null; this.swf = null; if ($(n).hasClass('elrte-media') && (mid = $(n).attr('rel')) && this.rte.filter.scripts[mid]) { this.placeholder = $(n); o = this.rte.filter.scripts[mid]; url = ''; if (o.embed && o.embed.src) { url = o.embed.src; } if (o.params && o.params.length) { l = o.params.length; while (l--) { if (o.params[l].name == 'src' || o.params[l].name == 'movie') { url = o.params[l].value; } } } if (o.embed) { w = o.embed.width||parseInt(o.embed.style.width)||''; h = o.embed.height||parseInt(o.embed.style.height)||''; wm = o.embed.wmode||''; } else if (o.obj) { w = o.obj.width||parseInt(o.obj.style.width)||''; h = o.obj.height||parseInt(o.obj.style.height)||''; wm = o.obj.wmode||''; } if (o.obj) { f = o.obj.style['float']||''; a = o.obj.style['vertical-align']||''; } else if (o.embed) { f = o.embed.style['float']||''; a = o.embed.style['vertical-align']||''; } this.src.margin.val(n); this.src.type.val(o.embed ? o.embed.type : ''); } if ($(n).hasClass('elrte-swf-placeholder')) { this.placeholder = $(n); url = $(n).attr('rel'); w = parseInt($(n).css('width'))||''; h = parseInt($(n).css('height'))||''; f = $(n).css('float'); a = $(n).css('vertical-align'); this.src.margin.val(n); this.src.wmode.val($(n).attr('wmode')); } this.src.url.val(url); this.src.width.val(w); this.src.height.val(h); this.src.align.val(f||a); this.src.wmode.val(wm); var opts = { rtl : this.rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.set(); d.close(); }, dialog : { width : 580, position : 'top', title : this.rte.i18n('Flash') } } var d = new elDialogForm(opts); if (this.rte.options.fmAllow && this.rte.options.fmOpen) { var src = $('<span />').append(this.src.url.css('width', '85%')) .append( $('<span />').addClass('ui-state-default ui-corner-all') .css({'float' : 'right', 'margin-right' : '3px'}) .attr('title', self.rte.i18n('Open file manger')) .append($('<span />').addClass('ui-icon ui-icon-folder-open')) .click( function() { self.rte.options.fmOpen( function(url) { self.src.url.val(url).change(); } ); }) .hover(function() {$(this).addClass('ui-state-hover')}, function() { $(this).removeClass('ui-state-hover')}) ); } else { var src = this.src.url; } d.append([this.rte.i18n('URL'), src], null, true); d.append([this.rte.i18n('Type'), this.src.type], null, true); d.append([this.rte.i18n('Size'), $('<span />').append(this.src.width).append(' x ').append(this.src.height).append(' px')], null, true) d.append([this.rte.i18n('Wmode'), this.src.wmode], null, true); d.append([this.rte.i18n('Alignment'), this.src.align], null, true); d.append([this.rte.i18n('Margins'), this.src.margin], null, true); d.open(); // setTimeout( function() {self.src.url.focus()}, 100) var fs = $('<fieldset />').append($('<legend />').text(this.rte.i18n('Preview'))) d.append(fs, 'main'); var frame = document.createElement('iframe'); $(frame).attr('src', '#').addClass('el-rte-preview').appendTo(fs); html = this.rte.options.doctype+'<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body style="padding:0;margin:0;font-size:9px"> Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin</body></html>'; frame.contentWindow.document.open(); frame.contentWindow.document.write(html); frame.contentWindow.document.close(); this.frame = frame.contentWindow.document; this.preview = $(frame.contentWindow.document.body); this.src.type.change(function() { self.src.url.change(); }); this.src.width.change(function() { if (self.swf) { var w = parseInt($(this).val())||''; $(this).val(w); self.swf.css('width', w); self.swf.children('embed').css('width', w); } else { $(this).val(''); } }); this.src.height.change(function() { if (self.swf) { var h = parseInt($(this).val())||''; $(this).val(h); self.swf.css('height', h); self.swf.children('embed').css('height', h); } else { $(this).val(''); } }); this.src.wmode.change(function() { if (self.swf) { var wm = $(this).val(); if (wm) { self.swf.attr('wmode', wm); self.swf.children('embed').attr('wmode', wm); } else { self.swf.removeAttr('wmode'); self.swf.children('embed').removeAttr('wmode'); } } }); this.src.align.change(function() { var v = $(this).val(), f = v=='left' || v=='right'; if (self.swf) { self.swf.css({ 'float' : f ? v : '', 'vertical-align' : f ? '' : v }); } else { $(this).val(''); } }); this.src.margin.change(function() { if (self.swf) { var m = self.src.margin.val(); if (m.css) { self.swf.css('margin', m.css); } else { self.swf.css('margin-top', m.top); self.swf.css('margin-right', m.right); self.swf.css('margin-bottom', m.bottom); self.swf.css('margin-left', m.left); } } }); this.src.url.change(function() { var url = self.rte.utils.absoluteURL($(this).val()), i, swf; if (url) { i = self.rte.utils.mediaInfo(self.src.type.val()); if (!i) { i = self.rte.util.mediaInfo('application/x-shockwave-flash'); } swf = '<object classid="'+i.classid+'" codebase="'+i.codebase+'"><param name="src" value="'+url+'" /><embed quality="high" src="'+url+'" type="'+i.type+'"></object>'; self.preview.children('object').remove().end().prepend(swf); self.swf = self.preview.children('object').eq(0); } else if (self.swf){ self.swf.remove(); self.swf = null; } self.src.width.trigger('change'); self.src.height.trigger('change'); self.src.align.trigger('change'); }).trigger('change'); }; this.set = function() { self.swf = null var url = this.rte.utils.absoluteURL(this.src.url.val()), w = parseInt(this.src.width.val()) || '', h = parseInt(this.src.height.val()) || '', wm = this.src.wmode.val(), a = this.src.align.val(), f = a == 'left' || a == 'right' ? a : '', mid = this.placeholder ? this.placeholder.attr('rel') : '', o, _o, c, m = this.src.margin.val(), margin; if (!url) { if (this.placeholder) { this.placeholder.remove(); delete this.rte.filter.scripts[mid]; } } else { i = self.rte.utils.mediaInfo(self.src.type.val()); if (!i) { i = self.rte.util.mediaInfo('application/x-shockwave-flash'); } c = this.rte.filter.videoHostRegExp.test(url) ? url.replace(this.rte.filter.videoHostRegExp, "$2") : i.type.replace(/^\w+\/(.+)/, "$1"); o = { obj : { classid : i.classid[0], codebase : i.codebase, style : {} }, params :[ { name : 'src', value : url } ], embed :{ src : url, type : i.type, quality : 'high', wmode : wm, style : {} } }; if (w) { o.obj.width = w; o.embed.width = w; } if (h) { o.obj.height = h; o.embed.height = h; } if (f) { o.obj.style['float'] = f; } else if (a) { o.obj.style['vertical-align'] = a; } if (m.css) { margin = { margin : m.css }; } else { margin = { 'margin-top' : m.top, 'margin-right' : m.right, 'margin-bottom' : m.bottom, 'margin-left' : m.left }; } o.obj.style = $.extend({}, o.obj.style, margin); if (this.placeholder && mid) { _o = this.rte.filter.scripts[mid]||{}; o = $.extend(true, _o, o); delete o.obj.style.width; delete o.obj.style.height; delete o.embed.style.width; delete o.embed.style.height; this.rte.filter.scripts[mid] = o; this.placeholder.removeAttr('class'); } else { var id = 'media'+Math.random().toString().substring(2); this.rte.filter.scripts[id] = o; this.placeholder = $(this.rte.dom.create('img')).attr('rel', id).attr('src', this.rte.filter.url+'pixel.gif'); var ins = true; } this.placeholder.attr('title', this.rte.utils.encode(url)).attr('width', w||150).attr('height', h||100).addClass('elrte-protected elrte-media elrte-media-'+c).css(o.obj.style); if (f) { this.placeholder.css('float', f).css('vertical-align', ''); } else if (a) { this.placeholder.css('float', '').css('vertical-align', a); } else { this.placeholder.css('float', '').css('vertical-align', ''); } if (ins) { this.rte.window.focus(); this.rte.selection.restoreIERange(); this.rte.selection.insertNode(this.placeholder.get(0)); } } } this.update = function() { this.domElem.removeClass('disabled'); var n = this.rte.selection.getNode(); this.domElem.toggleClass('active', n && n.nodeName == 'IMG' && $(n).hasClass('elrte-media')) } } })(jQuery);/** * @class drop-down menu - font-family for selected text * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.fontname = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; var opts = { tpl : '<span style="font-family:%val">%label</span>', select : function(v) { self.set(v); }, src : { '' : this.rte.i18n('Font'), 'andale mono,sans-serif' : 'Andale Mono', 'arial,helvetica,sans-serif' : 'Arial', 'arial black,gadget,sans-serif' : 'Arial Black', 'book antiqua,palatino,sans-serif' : 'Book Antiqua', 'comic sans ms,cursive' : 'Comic Sans MS', 'courier new,courier,monospace' : 'Courier New', 'georgia,palatino,serif' : 'Georgia', 'helvetica,sans-serif' : 'Helvetica', 'impact,sans-serif' : 'Impact', 'lucida console,monaco,monospace' : 'Lucida console', 'lucida sans unicode,lucida grande,sans-serif' : 'Lucida grande', 'tahoma,sans-serif' : 'Tahoma', 'times new roman,times,serif' : 'Times New Roman', 'trebuchet ms,lucida grande,verdana,sans-serif' : 'Trebuchet MS', 'verdana,geneva,sans-serif' : 'Verdana' } } this.select = this.domElem.elSelect(opts); this.command = function() { } this.set = function(size) { this.rte.history.add(); var nodes = this.rte.selection.selected({filter : 'textContainsNodes'}); $.each(nodes, function() { $this = /^(THEAD|TFOOT|TBODY|COL|COLGROUP|TR)$/.test(this.nodeName) ? $(this).find('td,th') : $(this); $(this).css('font-family', size).find('[style]').css('font-family', ''); }); this.rte.ui.update(); } this.update = function() { this.domElem.removeClass('disabled'); var n = this.rte.selection.getNode(); if (n.nodeType != 1) { n = n.parentNode; } var v = $(n).css('font-family'); v = v ? v.toString().toLowerCase().replace(/,\s+/g, ',').replace(/'|"/g, '') : ''; this.select.val(opts.src[v] ? v : ''); } } })(jQuery);/** * @class drop-down menu - font size for selected text * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.fontsize = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; var opts = { labelTpl : '%label', tpl : '<span style="font-size:%val;line-height:1.2em">%label</span>', select : function(v) { self.set(v); }, src : { '' : this.rte.i18n('Font size'), 'xx-small' : this.rte.i18n('Small (8pt)'), 'x-small' : this.rte.i18n('Small (10px)'), 'small' : this.rte.i18n('Small (12pt)'), 'medium' : this.rte.i18n('Normal (14pt)'), 'large' : this.rte.i18n('Large (18pt)'), 'x-large' : this.rte.i18n('Large (24pt)'), 'xx-large' : this.rte.i18n('Large (36pt)') } } this.select = this.domElem.elSelect(opts); this.command = function() { } this.set = function(size) { this.rte.history.add(); var nodes = this.rte.selection.selected({filter : 'textContainsNodes'}); $.each(nodes, function() { $this = /^(THEAD|TFOOT|TBODY|COL|COLGROUP|TR)$/.test(this.nodeName) ? $(this).find('td,th') : $(this); $this.css('font-size', size).find("[style]").css('font-size', ''); }); this.rte.ui.update(); } this.update = function() { this.domElem.removeClass('disabled'); var n = this.rte.selection.getNode(); this.select.val((m = this.rte.dom.attr(n, 'style').match(/font-size:\s*([^;]+)/i)) ? m[1] : ''); } } })(jQuery);/** * @class color pallete for text color and background * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.forecolor = function(rte, name) { var self = this; this.constructor.prototype.constructor.call(this, rte, name); var opts = { 'class' : '', palettePosition : 'outer', color : this.defaultColor, update : function(c) { self.indicator.css('background-color', c); }, change : function(c) { self.set(c) } } this.defaultColor = this.name == 'forecolor' ? '#000000' : '#ffffff'; this.picker = this.domElem.elColorPicker(opts); this.indicator = $('<div />').addClass('color-indicator').prependTo(this.domElem); this.command = function() { } this.set = function(c) { if (!this.rte.selection.collapsed()) { this.rte.history.add(); var nodes = this.rte.selection.selected({collapse : false, wrap : 'text'}), css = this.name == 'forecolor' ? 'color' : 'background-color'; $.each(nodes, function() { if (/^(THEAD|TBODY|TFOOT|TR)$/.test(this.nodeName)) { $(this).find('td,th').each(function() { $(this).css(css, c).find('*').css(css, ''); }) } else { $(this).css(css, c).find('*').css(css, ''); } }); this.rte.ui.update(true); } } this.update = function() { this.domElem.removeClass('disabled'); var n = this.rte.selection.getNode(); this.picker.val(this.rte.utils.rgb2hex($(n.nodeType != 1 ? n.parentNode : n).css(this.name == 'forecolor' ? 'color' : 'background-color'))||this.defaultColor) } } elRTE.prototype.ui.prototype.buttons.hilitecolor = elRTE.prototype.ui.prototype.buttons.forecolor; })(jQuery);/** * @class drop-down menu - formatting text block * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.formatblock = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var cmd = this.rte.browser.msie ? function(v) { self.val = v; self.constructor.prototype.command.call(self); } : function(v) { self.ieCommand(v); } var self = this; var opts = { labelTpl : '%label', tpls : {'' : '%label'}, select : function(v) { self.formatBlock(v); }, src : { 'span' : this.rte.i18n('Format'), //'h1' : this.rte.i18n('Heading 1'), 'h2' : this.rte.i18n('Heading 2'), 'h3' : this.rte.i18n('Heading 3'), 'h4' : this.rte.i18n('Heading 4'), 'h5' : this.rte.i18n('Heading 5'), 'h6' : this.rte.i18n('Heading 6'), 'p' : this.rte.i18n('Paragraph'), 'address' : this.rte.i18n('Address'), 'pre' : this.rte.i18n('Preformatted'), 'div' : this.rte.i18n('Normal (DIV)') } } this.select = this.domElem.elSelect(opts); this.command = function() { } this.formatBlock = function(v) { function format(n, tag) { function replaceChilds(p) { $(p).find('h1,h2,h3,h4,h5,h6,p,address,pre').each(function() { $(this).replaceWith($(this).html()); }); return p; } if (/^(LI|DT|DD|TD|TH|CAPTION)$/.test(n.nodeName)) { !self.rte.dom.isEmpty(n) && self.rte.dom.wrapContents(replaceChilds(n), tag); } else if (/^(UL|OL|DL|TABLE)$/.test(n.nodeName)) { self.rte.dom.wrap(n, tag); } else { !self.rte.dom.isEmpty(n) && $(replaceChilds(n)).replaceWith( $(self.rte.dom.create(tag)).html($(n).html())); } } this.rte.history.add(); var tag = v.toUpperCase(), i, n, $n, c = this.rte.selection.collapsed(), bm = this.rte.selection.getBookmark(), nodes = this.rte.selection.selected({ collapsed : true, blocks : true, filter : 'textContainsNodes', wrap : 'inline', tag : 'span' }) l = nodes.length, s = $(nodes[0]).prev(), e = $(nodes[nodes.length-1]).next(); while (l--) { n = nodes[l]; $n = $(n); if (tag == 'DIV' || tag == 'SPAN') { if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(n.nodeName)) { $n.replaceWith($(this.rte.dom.create('div')).html($n.html()||'')); } } else { if (/^(THEAD|TBODY|TFOOT|TR)$/.test(n.nodeName)) { $n.find('td,th').each(function() { format(this, tag); }); } else if (n.nodeName != tag) { format(n, tag); } } } this.rte.selection.moveToBookmark(bm); this.rte.ui.update(true); } this.update = function() { this.domElem.removeClass('disabled'); var n = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^(H[1-6]|P|ADDRESS|PRE)$/); this.select.val(n ? n.nodeName.toLowerCase() : 'span'); } } })(jQuery); /** * @class button - switch to fullscreen mode and back * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.fullscreen = function(rte, name) { var self = this; this.constructor.prototype.constructor.call(this, rte, name); this.active = true; this.editor = rte.editor; this.wz = rte.workzone; this.height = 0; this.delta = 0; this._class = 'el-fullscreen'; setTimeout(function() { self.height = self.wz.height(); self.delta = self.editor.outerHeight()-self.height; }, 50); /** * Update editor height on window resize in fullscreen view * **/ function resize() { self.wz.height($(window).height()-self.delta); self.rte.updateHeight(); } this.command = function() { var w = $(window), e = this.editor, p = e.parents().filter(function(i, n) { return !/^(html|body)$/i.test(n.nodeName) && $(n).css('position') == 'relative'; }), wz = this.wz, c = this._class, f = e.hasClass(c), rte = this.rte, s = this.rte.selection, m = $.browser.mozilla, b, h; function save() { if (m) { b = s.getBookmark(); } } function restore() { if (m) { self.wz.children().toggle(); self.rte.source.focus(); self.wz.children().toggle(); s.moveToBookmark(b); } } save(); p.css('position', f ? 'relative' : 'static'); if (f) { e.removeClass(c); wz.height(this.height); w.unbind('resize', resize); this.domElem.removeClass('active'); } else { e.addClass(c).removeAttr('style'); wz.height(w.height() - this.delta).css('width', '100%'); w.bind('resize', resize); this.domElem.addClass('active'); } rte.updateHeight(); rte.resizable(f); restore(); } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class button - horizontal rule (open dialog window) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.horizontalrule = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.src = { width : $('<input type="text" />').attr({'name' : 'width', 'size' : 4}).css('text-align', 'right'), wunit : $('<select />').attr('name', 'wunit') .append($('<option />').val('%').text('%')) .append($('<option />').val('px').text('px')) .val('%'), height : $('<input type="text" />').attr({'name' : 'height', 'size' : 4}).css('text-align', 'right'), bg : $('<div />'), border : $('<div />'), 'class' : $('<input type="text" />').css('width', '100%'), style : $('<input type="text" />').css('width', '100%') } this.command = function() { this.src.bg.elColorPicker({palettePosition : 'outer', 'class' : 'el-colorpicker ui-icon ui-icon-pencil'}); var n = this.rte.selection.getEnd(); this.hr = n.nodeName == 'HR' ? $(n) : $(rte.doc.createElement('hr')).css({width : '100%', height : '1px'}); this.src.border.elBorderSelect({styleHeight : 73, value : this.hr}); var _w = this.hr.css('width') || this.hr.attr('width'); this.src.width.val(parseInt(_w) || 100); this.src.wunit.val(_w.indexOf('px') != -1 ? 'px' : '%'); this.src.height.val( this.rte.utils.toPixels(this.hr.css('height') || this.hr.attr('height')) || 1) ; this.src.bg.val(this.rte.utils.color2Hex(this.hr.css('background-color'))); this.src['class'].val(this.rte.dom.attr(this.hr, 'class')); this.src.style.val(this.rte.dom.attr(this.hr, 'style')); var opts = { rtl : this.rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.set(); d.close(); }, dialog : { title : this.rte.i18n('Horizontal rule') } } var d = new elDialogForm(opts); d.append([this.rte.i18n('Width'), $('<span />').append(this.src.width).append(this.src.wunit) ], null, true) .append([this.rte.i18n('Height'), $('<span />').append(this.src.height).append(' px')], null, true) .append([this.rte.i18n('Border'), this.src.border], null, true) .append([this.rte.i18n('Background'), this.src.bg], null, true) .append([this.rte.i18n('Css class'), this.src['class']], null, true) .append([this.rte.i18n('Css style'), this.src.style], null, true) .open(); } this.update = function() { this.domElem.removeClass('disabled'); if (this.rte.selection.getEnd().nodeName == 'HR') { this.domElem.addClass('active'); } else { this.domElem.removeClass('active'); } } this.set = function() { this.rte.history.add(); !this.hr.parentNode && this.rte.selection.insertNode(this.hr.get(0)); var attr = { noshade : true, style : this.src.style.val() } var b = this.src.border.val(); var css = { width : (parseInt(this.src.width.val()) || 100)+this.src.wunit.val(), height : parseInt(this.src.height.val()) || 1, 'background-color' : this.src.bg.val(), border : b.width && b.style ? b.width+' '+b.style+' '+b.color : '' } this.hr.removeAttr('class') .removeAttr('style') .removeAttr('width') .removeAttr('height') .removeAttr('align') .attr(attr) .css(css); if (this.src['class'].val()) { this.hr.attr('class', this.src['class'].val()); } this.rte.ui.update() } } })(jQuery); /** * @class button - insert/edit image (open dialog window) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.image = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this, rte = self.rte, proportion = 0, width = 0, height = 0, bookmarks = null, reset = function(nosrc) { $.each(self.src, function(i, elements) { $.each(elements, function(n, el) { if (n == 'src' && nosrc) { return; } el.val(''); }); }); }, values = function(img) { $.each(self.src, function(i, elements) { $.each(elements, function(n, el) { var val, w, c, s, border; if (n == 'width') { val = img.width(); } else if (n == 'height') { val = img.height(); } else if (n == 'border') { val = ''; border = img.css('border') || rte.utils.parseStyle(img.attr('style')).border || ''; if (border) { w = border.match(/(\d(px|em|%))/); c = border.match(/(#[a-z0-9]+)/); val = { width : w ? w[1] : border, style : border, color : rte.utils.color2Hex(c ? c[1] : border) } } } else if (n == 'margin') { val = img; } else if (n == 'align') { val = img.css('float'); if (val != 'left' && val != 'right') { val = img.css('vertical-align'); } }else { val = img.attr(n)||''; } if (i == 'events') { val = rte.utils.trimEventCallback(val); } el.val(val); }); }); }, preview = function() { var src = self.src.main.src.val(); reset(true); if (!src) { self.preview.children('img').remove(); self.prevImg = null; } else { if (self.prevImg) { self.prevImg .removeAttr('src') .removeAttr('style') .removeAttr('class') .removeAttr('id') .removeAttr('title') .removeAttr('alt') .removeAttr('longdesc'); $.each(self.src.events, function(name, input) { self.prevImg.removeAttr(name); }); } else { self.prevImg = $('<img/>').prependTo(self.preview); } self.prevImg.load(function() { self.prevImg.unbind('load'); setTimeout(function() { width = self.prevImg.width(); height = self.prevImg.height(); proportion = (width/height).toFixed(2); self.src.main.width.val(width); self.src.main.height.val(height); }, 100); }) .attr('src', src); } }, size = function(e) { var w = parseInt(self.src.main.width.val())||0, h = parseInt(self.src.main.height.val())||0; if (self.prevImg) { if (w && h) { if (e.target === self.src.main.width[0]) { h = parseInt(w/proportion); } else { w = parseInt(h*proportion); } } else { w = width; h = height; } self.src.main.height.val(h); self.src.main.width.val(w); self.prevImg.width(w).height(h); self.src.adv.style.val(self.prevImg.attr('style')); } } ; this.img = null; this.prevImg = null; this.preview = $('<div class="elrte-image-preview"/>').text('Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin'); this.init = function() { this.labels = { main : 'Properies', link : 'Link', adv : 'Advanced', events : 'Events', id : 'ID', 'class' : 'Css class', style : 'Css style', longdesc : 'Detail description URL', href : 'URL', target : 'Open in', title : 'Title' } this.src = { main : { src : $('<input type="text" />').css('width', '100%').change(preview), title : $('<input type="text" />').css('width', '100%'), alt : $('<input type="text" />').css('width', '100%'), width : $('<input type="text" />').attr('size', 5).css('text-align', 'right').change(size), height : $('<input type="text" />').attr('size', 5).css('text-align', 'right').change(size), margin : $('<div />').elPaddingInput({ type : 'margin', change : function() { var margin = self.src.main.margin.val(); if (self.prevImg) { if (margin.css) { self.prevImg.css('margin', margin.css) } else { self.prevImg.css({ 'margin-left' : margin.left, 'margin-top' : margin.top, 'margin-right' : margin.right, 'margin-bottom' : margin.bottom }); } } } }), align : $('<select />').css('width', '100%') .append($('<option />').val('').text(this.rte.i18n('Not set', 'dialogs'))) .append($('<option />').val('left' ).text(this.rte.i18n('Left'))) .append($('<option />').val('right' ).text(this.rte.i18n('Right'))) .append($('<option />').val('top' ).text(this.rte.i18n('Top'))) .append($('<option />').val('text-top' ).text(this.rte.i18n('Text top'))) .append($('<option />').val('middle' ).text(this.rte.i18n('middle'))) .append($('<option />').val('baseline' ).text(this.rte.i18n('Baseline'))) .append($('<option />').val('bottom' ).text(this.rte.i18n('Bottom'))) .append($('<option />').val('text-bottom').text(this.rte.i18n('Text bottom'))) .change(function() { var val = $(this).val(), css = { 'float' : '', 'vertical-align' : '' }; if (self.prevImg) { if (val == 'left' || val == 'right') { css['float'] = val; css['vertical-align'] = ''; } else if (val) { css['float'] = ''; css['vertical-align'] = val; } self.prevImg.css(css); } }) , border : $('<div />').elBorderSelect({ name : 'border', change : function() { var border = self.src.main.border.val(); if (self.prevImg) { self.prevImg.css('border', border.width ? border.width+' '+border.style+' '+border.color : ''); } } }) }, adv : {}, events : {} } $.each(['id', 'class', 'style', 'longdesc'], function(i, name) { self.src.adv[name] = $('<input type="text" style="width:100%" />'); }); this.src.adv['class'].change(function() { if (self.prevImg) { self.prevImg.attr('class', $(this).val()); } }); this.src.adv.style.change(function() { if (self.prevImg) { self.prevImg.attr('style', $(this).val()); values(self.prevImg); } }); $.each( ['onblur', 'onfocus', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onmouseleave', 'onkeydown', 'onkeypress', 'onkeyup'], function() { self.src.events[this] = $('<input type="text" style="width:100%"/>'); }); } this.command = function() { !this.src && this.init(); var img, opts = { rtl : rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.set(); dialog.close(); }, close : function() { bookmarks && rte.selection.moveToBookmark(bookmarks) }, dialog : { autoOpen : false, width : 500, position : 'top', title : rte.i18n('Image'), resizable : true, open : function() { $.fn.resizable && $(this).parents('.ui-dialog:first').resizable('option', 'alsoResize', '.elrte-image-preview'); } } }, dialog = new elDialogForm(opts), fm = !!rte.options.fmOpen, src = fm ? $('<div class="elrte-image-src-fm"><span class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-folder-open"/></span></div>') .append(this.src.main.src.css('width', '87%')) : this.src.main.src; ; reset(); this.preview.children('img').remove(); this.prevImg = null; img = rte.selection.getEnd(); this.img = img.nodeName == 'IMG' && !$(img).is('.elrte-protected') ? $(img) : $('<img/>'); bookmarks = rte.selection.getBookmark(); if (fm) { src.children('.ui-state-default') .click( function() { rte.options.fmOpen( function(url) { self.src.main.src.val(url).change() } ); }) .hover(function() { $(this).toggleClass('ui-state-hover'); }); } dialog.tab('main', this.rte.i18n('Properies')) .append([this.rte.i18n('Image URL'), src], 'main', true) .append([this.rte.i18n('Title'), this.src.main.title], 'main', true) .append([this.rte.i18n('Alt text'), this.src.main.alt], 'main', true) .append([this.rte.i18n('Size'), $('<span />').append(this.src.main.width).append(' x ').append(this.src.main.height).append(' px')], 'main', true) .append([this.rte.i18n('Alignment'), this.src.main.align], 'main', true) .append([this.rte.i18n('Margins'), this.src.main.margin], 'main', true) .append([this.rte.i18n('Border'), this.src.main.border], 'main', true) dialog.append($('<fieldset><legend>'+this.rte.i18n('Preview')+'</legend></fieldset>').append(this.preview), 'main'); $.each(this.src, function(tabname, elements) { if (tabname == 'main') { return; } dialog.tab(tabname, rte.i18n(self.labels[tabname])); $.each(elements, function(name, el) { self.src[tabname][name].val(tabname == 'events' ? rte.utils.trimEventCallback(self.img.attr(name)) : self.img.attr(name)||''); dialog.append([rte.i18n(self.labels[name] || name), self.src[tabname][name]], tabname, true); }); }); dialog.open(); if (this.img.attr('src')) { values(this.img); this.prevImg = this.img.clone().prependTo(this.preview); proportion = (this.img.width()/this.img.height()).toFixed(2); width = parseInt(this.img.width()); height = parseInt(this.img.height()); } } this.set = function() { var src = this.src.main.src.val(), link; this.rte.history.add(); bookmarks && rte.selection.moveToBookmark(bookmarks); if (!src) { link = rte.dom.selfOrParentLink(this.img[0]); link && link.remove(); return this.img.remove(); } !this.img[0].parentNode && (this.img = $(this.rte.doc.createElement('img'))); this.img.attr('src', src) .attr('style', this.src.adv.style.val()); $.each(this.src, function(i, elements) { $.each(elements, function(name, el) { var val = el.val(), style; switch (name) { case 'width': self.img.css('width', val); break; case 'height': self.img.css('height', val); break; case 'align': self.img.css(val == 'left' || val == 'right' ? 'float' : 'vertical-align', val); break; case 'margin': if (val.css) { self.img.css('margin', val.css); } else { self.img.css({ 'margin-left' : val.left, 'margin-top' : val.top, 'margin-right' : val.right, 'margin-bottom' : val.bottom }); } break; case 'border': if (!val.width) { val = ''; } else { val = 'border:'+val.css+';'+$.trim((self.img.attr('style')||'').replace(/border\-[^;]+;?/ig, '')); name = 'style'; self.img.attr('style', val) return; } break; case 'src': case 'style': return; default: val ? self.img.attr(name, val) : self.img.removeAttr(name); } }); }); !this.img[0].parentNode && rte.selection.insertNode(this.img[0]); this.rte.ui.update(); } this.update = function() { this.domElem.removeClass('disabled'); var n = this.rte.selection.getEnd(), $n = $(n); if (n.nodeName == 'IMG' && !$n.hasClass('elrte-protected')) { this.domElem.addClass('active'); } else { this.domElem.removeClass('active'); } } } })(jQuery); /** * @class Увеличение отступа * списки - если выделен один элемент - увеличивается вложенность списка, в остальных случаях - padding у родительского ul|ol * Если таблица выделена полностью - ей добавляется margin, если частично - увеличивается padding для ячеек * * @param elRTE rte объект-редактор * @param String name название кнопки * * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.indent = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { this.rte.history.add(); var nodes = this.rte.selection.selected({collapsed : true, blocks : true, wrap : 'inline', tag : 'p'}); function indent(n) { var css = /(IMG|HR|TABLE|EMBED|OBJECT)/.test(n.nodeName) ? 'margin-left' : 'padding-left'; var val = self.rte.dom.attr(n, 'style').indexOf(css) != -1 ? parseInt($(n).css(css))||0 : 0; $(n).css(css, val+40+'px'); } for (var i=0; i < nodes.length; i++) { if (/^(TABLE|THEAD|TFOOT|TBODY|COL|COLGROUP|TR)$/.test(nodes[i].nodeName)) { $(nodes[i]).find('td,th').each(function() { indent(this); }); } else if (/^LI$/.test(nodes[i].nodeName)) { var n = $(nodes[i]); $(this.rte.dom.create(nodes[i].parentNode.nodeName)) .append($(this.rte.dom.create('li')).html(n.html()||'')).appendTo(n.html('&nbsp;')); } else { indent(nodes[i]); } }; this.rte.ui.update(); } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class button - justify text * * @param elRTE rte объект-редактор * @param String name название кнопки * * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.justifyleft = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.align = this.name == 'justifyfull' ? 'justify' : this.name.replace('justify', ''); this.command = function() { var s = this.rte.selection.selected({collapsed:true, blocks : true, tag : 'div'}), l = s.length; l && this.rte.history.add(); while (l--) { this.rte.dom.filter(s[l], 'textNodes') && $(s[l]).css('text-align', this.align); } this.rte.ui.update(); } this.update = function() { var s = this.rte.selection.getNode(), n = s.nodeName == 'BODY' ? s : this.rte.dom.selfOrParent(s, 'textNodes')||(s.parentNode && s.parentNode.nodeName == 'BODY' ? s.parentNode : null); if (n) { this.domElem.removeClass('disabled').toggleClass('active', $(n).css('text-align') == this.align); } else { this.domElem.addClass('disabled'); } } } elRTE.prototype.ui.prototype.buttons.justifycenter = elRTE.prototype.ui.prototype.buttons.justifyleft; elRTE.prototype.ui.prototype.buttons.justifyright = elRTE.prototype.ui.prototype.buttons.justifyleft; elRTE.prototype.ui.prototype.buttons.justifyfull = elRTE.prototype.ui.prototype.buttons.justifyleft; })(jQuery); /** * @class button - insert/edit link (open dialog window) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.link = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.img = false; this.bm; function init() { self.labels = { id : 'ID', 'class' : 'Css class', style : 'Css style', dir : 'Script direction', lang : 'Language', charset : 'Charset', type : 'Target MIME type', rel : 'Relationship page to target (rel)', rev : 'Relationship target to page (rev)', tabindex : 'Tab index', accesskey : 'Access key' } self.src = { main : { href : $('<input type="text" />'), title : $('<input type="text" />'), anchor : $('<select />').attr('name', 'anchor'), target : $('<select />') .append($('<option />').text(self.rte.i18n('In this window')).val('')) .append($('<option />').text(self.rte.i18n('In new window (_blank)')).val('_blank')) // .append($('<option />').text(self.rte.i18n('In new parent window (_parent)')).val('_parent')) // .append($('<option />').text(self.rte.i18n('In top frame (_top)')).val('_top')) }, popup : { use : $('<input type="checkbox" />'), url : $('<input type="text" />' ).val('http://'), name : $('<input type="text" />' ), width : $('<input type="text" />' ).attr({size : 6, title : self.rte.i18n('Width')} ).css('text-align', 'right'), height : $('<input type="text" />' ).attr({size : 6, title : self.rte.i18n('Height')}).css('text-align', 'right'), left : $('<input type="text" />' ).attr({size : 6, title : self.rte.i18n('Left')} ).css('text-align', 'right'), top : $('<input type="text" />' ).attr({size : 6, title : self.rte.i18n('Top')} ).css('text-align', 'right'), location : $('<input type="checkbox" />'), menubar : $('<input type="checkbox" />'), toolbar : $('<input type="checkbox" />'), scrollbars : $('<input type="checkbox" />'), status : $('<input type="checkbox" />'), resizable : $('<input type="checkbox" />'), dependent : $('<input type="checkbox" />'), retfalse : $('<input type="checkbox" />').attr('checked', true) }, adv : { id : $('<input type="text" />'), 'class' : $('<input type="text" />'), style : $('<input type="text" />'), dir : $('<select />') .append($('<option />').text(self.rte.i18n('Not set')).val('')) .append($('<option />').text(self.rte.i18n('Left to right')).val('ltr')) .append($('<option />').text(self.rte.i18n('Right to left')).val('rtl')), lang : $('<input type="text" />'), charset : $('<input type="text" />'), type : $('<input type="text" />'), rel : $('<input type="text" />'), rev : $('<input type="text" />'), tabindex : $('<input type="text" />'), accesskey : $('<input type="text" />') }, events : {} } $.each( ['onblur', 'onfocus', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onmouseleave', 'onkeydown', 'onkeypress', 'onkeyup'], function() { self.src.events[this] = $('<input type="text" />'); }); $.each(self.src, function() { for (var n in this) { // this[n].attr('name', n); var t = this[n].attr('type'); if (!t || (t == 'text' && !this[n].attr('size')) ) { this[n].css('width', '100%'); } } }); } this.command = function() { var n = this.rte.selection.getNode(), sel, i, v, opts, l, r, link, href, s; !this.src && init(); // this.rte.selection.saveIERange(); this.bm = this.rte.selection.getBookmark(); function isLink(n) { return n.nodeName == 'A' && n.href; } this.link = this.rte.dom.selfOrParentLink(n); if (!this.link) { sel = $.browser.msie ? this.rte.selection.selected() : this.rte.selection.selected({wrap : false}); if (sel.length) { for (i=0; i < sel.length; i++) { if (isLink(sel[i])) { this.link = sel[i]; break; } }; if (!this.link) { this.link = this.rte.dom.parent(sel[0], isLink) || this.rte.dom.parent(sel[sel.length-1], isLink); } } } this.link = this.link ? $(this.link) : $(this.rte.doc.createElement('a')); this.img = n.nodeName == 'IMG' ? n : null; this.updatePopup(); this.src.main.anchor.empty(); $('a[href!=""][name]', this.rte.doc).each(function() { var n = $(this).attr('name'); self.src.main.anchor.append($('<option />').val(n).text(n)); }); if (this.src.main.anchor.children().length) { this.src.main.anchor.prepend($('<option />').val('').text(this.rte.i18n('Select bookmark')) ) .change(function() { var v = $(this).val(); if (v) { self.src.main.href.val('#'+v); } }); } opts = { rtl : this.rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.set(); d.close(); }, tabs : { show : function(e, ui) { if (ui.index==3) { self.updateOnclick(); } } }, close : function() {self.rte.browser.msie && self.rte.selection.restoreIERange(); }, dialog : { width : 'auto', width : 430, title : this.rte.i18n('Link') } } d = new elDialogForm(opts); l = $('<div />') .append( $('<label />').append(this.src.popup.location).append(this.rte.i18n('Location bar'))) .append( $('<label />').append(this.src.popup.menubar).append(this.rte.i18n('Menu bar'))) .append( $('<label />').append(this.src.popup.toolbar).append(this.rte.i18n('Toolbar'))) .append( $('<label />').append(this.src.popup.scrollbars).append(this.rte.i18n('Scrollbars'))); r = $('<div />') .append( $('<label />').append(this.src.popup.status).append(this.rte.i18n('Status bar'))) .append( $('<label />').append(this.src.popup.resizable).append(this.rte.i18n('Resizable'))) .append( $('<label />').append(this.src.popup.dependent).append(this.rte.i18n('Depedent'))) .append( $('<label />').append(this.src.popup.retfalse).append(this.rte.i18n('Add return false'))); d.tab('main', this.rte.i18n('Properies')) .tab('popup', this.rte.i18n('Popup')) .tab('adv', this.rte.i18n('Advanced')) .tab('events', this.rte.i18n('Events')) .append($('<label />').append(this.src.popup.use).append(this.rte.i18n('Open link in popup window')), 'popup') .separator('popup') .append([this.rte.i18n('URL'), this.src.popup.url], 'popup', true) .append([this.rte.i18n('Window name'), this.src.popup.name], 'popup', true) .append([this.rte.i18n('Window size'), $('<span />').append(this.src.popup.width).append(' x ').append(this.src.popup.height).append(' px')], 'popup', true) .append([this.rte.i18n('Window position'), $('<span />').append(this.src.popup.left).append(' x ').append(this.src.popup.top).append(' px')], 'popup', true) .separator('popup') .append([l, r], 'popup', true); link = this.link.get(0); href = this.rte.dom.attr(link, 'href'); this.src.main.href.val(href).change(function() { $(this).val(self.rte.utils.absoluteURL($(this).val())); }); if (this.rte.options.fmAllow && this.rte.options.fmOpen) { var s = $('<span />').append(this.src.main.href.css('width', '87%')) .append( $('<span />').addClass('ui-state-default ui-corner-all') .css({'float' : 'right', 'margin-right' : '3px'}) .attr('title', self.rte.i18n('Open file manger')) .append($('<span />').addClass('ui-icon ui-icon-folder-open')) .click( function() { self.rte.options.fmOpen( function(url) { self.src.main.href.val(url).change(); } ); }) .hover(function() {$(this).addClass('ui-state-hover')}, function() { $(this).removeClass('ui-state-hover')}) ); d.append([this.rte.i18n('Link URL'), s], 'main', true); } else { d.append([this.rte.i18n('Link URL'), this.src.main.href], 'main', true); } this.src.main.href.change(); d.append([this.rte.i18n('Title'), this.src.main.title.val(this.rte.dom.attr(link, 'title'))], 'main', true); if (this.src.main.anchor.children().length) { d.append([this.rte.i18n('Bookmark'), this.src.main.anchor.val(href)], 'main', true) } if (!(this.rte.options.doctype.match(/xhtml/) && this.rte.options.doctype.match(/strict/))) { d.append([this.rte.i18n('Target'), this.src.main.target.val(this.link.attr('target')||'')], 'main', true); } for (var n in this.src.adv) { this.src.adv[n].val(this.rte.dom.attr(link, n)); d.append([this.rte.i18n(this.labels[n] ? this.labels[n] : n), this.src.adv[n]], 'adv', true); } for (var n in this.src.events) { var v = this.rte.utils.trimEventCallback(this.rte.dom.attr(link, n)); this.src.events[n].val(v); d.append([this.rte.i18n(this.labels[n] ? this.labels[n] : n), this.src.events[n]], 'events', true); } this.src.popup.use.change(function() { var c = $(this).attr('checked'); $.each(self.src.popup, function() { if ($(this).attr('name') != 'use') { if (c) { $(this).removeAttr('disabled'); } else { $(this).attr('disabled', true); } } }) }); this.src.popup.use.change(); d.open(); } this.update = function() { var n = this.rte.selection.getNode(); // var t = this.rte.dom.selectionHas(function(n) { return n.nodeName == 'A' && n.href; }); // this.rte.log(t) if (this.rte.dom.selfOrParentLink(n)) { this.domElem.removeClass('disabled').addClass('active'); } else if (this.rte.dom.selectionHas(function(n) { return n.nodeName == 'A' && n.href; })) { this.domElem.removeClass('disabled').addClass('active'); } else if (!this.rte.selection.collapsed() || n.nodeName == 'IMG') { this.domElem.removeClass('disabled active'); } else { this.domElem.addClass('disabled').removeClass('active'); } } this.updatePopup = function() { var onclick = ''+this.link.attr('onclick'); // onclick = onclick ? $.trim(onclick.toString()) : '' if ( onclick.length>0 && (m = onclick.match(/window.open\('([^']+)',\s*'([^']*)',\s*'([^']*)'\s*.*\);\s*(return\s+false)?/))) { this.src.popup.use.attr('checked', 'on') this.src.popup.url.val(m[1]); this.src.popup.name.val(m[2]); if ( /location=yes/.test(m[3]) ) { this.src.popup.location.attr('checked', true); } if ( /menubar=yes/.test(m[3]) ) { this.src.popup.menubar.attr('checked', true); } if ( /toolbar=yes/.test(m[3]) ) { this.src.popup.toolbar.attr('checked', true); } if ( /scrollbars=yes/.test(m[3]) ) { this.src.popup.scrollbars.attr('checked', true); } if ( /status=yes/.test(m[3]) ) { this.src.popup.status.attr('checked', true); } if ( /resizable=yes/.test(m[3]) ) { this.src.popup.resizable.attr('checked', true); } if ( /dependent=yes/.test(m[3]) ) { this.src.popup.dependent.attr('checked', true); } if ((_m = m[3].match(/width=([^,]+)/))) { this.src.popup.width.val(_m[1]); } if ((_m = m[3].match(/height=([^,]+)/))) { this.src.popup.height.val(_m[1]); } if ((_m = m[3].match(/left=([^,]+)/))) { this.src.popup.left.val(_m[1]); } if ((_m = m[3].match(/top=([^,]+)/))) { this.src.popup.top.val(_m[1]); } if (m[4]) { this.src.popup.retfalse.attr('checked', true); } } else { $.each(this.src.popup, function() { var $this = $(this); if ($this.attr('type') == 'text') { $this.val($this.attr('name') == 'url' ? 'http://' : ''); } else { if ($this.attr('name') == 'retfalse') { this.attr('checked', true); } else { $this.removeAttr('checked'); } } }); } } this.updateOnclick = function () { var url = this.src.popup.url.val(); if (this.src.popup.use.attr('checked') && url) { var params = ''; if (this.src.popup.location.attr('checked')) { params += 'location=yes,'; } if (this.src.popup.menubar.attr('checked')) { params += 'menubar=yes,'; } if (this.src.popup.toolbar.attr('checked')) { params += 'toolbar=yes,'; } if (this.src.popup.scrollbars.attr('checked')) { params += 'scrollbars=yes,'; } if (this.src.popup.status.attr('checked')) { params += 'status=yes,'; } if (this.src.popup.resizable.attr('checked')) { params += 'resizable=yes,'; } if (this.src.popup.dependent.attr('checked')) { params += 'dependent=yes,'; } if (this.src.popup.width.val()) { params += 'width='+this.src.popup.width.val()+','; } if (this.src.popup.height.val()) { params += 'height='+this.src.popup.height.val()+','; } if (this.src.popup.left.val()) { params += 'left='+this.src.popup.left.val()+','; } if (this.src.popup.top.val()) { params += 'top='+this.src.popup.top.val()+','; } if (params.length>0) { params = params.substring(0, params.length-1) } var retfalse = this.src.popup.retfalse.attr('checked') ? 'return false;' : ''; var onclick = "window.open('"+url+"', '"+$.trim(this.src.popup.name.val())+"', '"+params+"'); "+retfalse; this.src.events.onclick.val(onclick); if (!this.src.main.href.val()) { this.src.main.href.val('#'); } } else { var v = this.src.events.onclick.val(); v = v.replace(/window\.open\([^\)]+\)\s*;?\s*return\s*false\s*;?/i, ''); this.src.events.onclick.val(v); } } this.set = function() { var href, fakeURL; this.updateOnclick(); this.rte.selection.moveToBookmark(this.bm); // this.rte.selection.restoreIERange(); this.rte.history.add(); href = this.rte.utils.absoluteURL(this.src.main.href.val()); if (!href) { // this.link.parentNode && this.rte.doc.execCommand('unlink', false, null); var bm = this.rte.selection.getBookmark(); this.rte.dom.unwrap(this.link[0]); this.rte.selection.moveToBookmark(bm); } else { if (this.img && this.img.parentNode) { this.link = $(this.rte.dom.create('a')).attr('href', href); this.rte.dom.wrap(this.img, this.link[0]); } else if (!this.link[0].parentNode) { fakeURL = '#--el-editor---'+Math.random(); this.rte.doc.execCommand('createLink', false, fakeURL); this.link = $('a[href="'+fakeURL+'"]', this.rte.doc); this.link.each(function() { var $this = $(this); // удаляем ссылки вокруг пустых элементов if (!$.trim($this.html()) && !$.trim($this.text())) { $this.replaceWith($this.text()); // сохраняем пробелы :) } }); } this.src.main.href.val(href); for (var tab in this.src) { if (tab != 'popup') { for (var n in this.src[tab]) { if (n != 'anchors') { var v = $.trim(this.src[tab][n].val()); if (v) { this.link.attr(n, v); } else { this.link.removeAttr(n); } } } } }; this.img && this.rte.selection.select(this.img); } this.rte.ui.update(true); } } })(jQuery); /** * @class button - insert non breakable space * Если выделение схлопнуто и находится внутри div'a - он удаляется * Новые div'ы создаются только из несхлопнутого выделения * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.nbsp = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { this.rte.history.add(); this.rte.selection.insertHtml('&nbsp;', true); this.rte.window.focus(); this.rte.ui.update(); } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class button - outdent text * уменьшает padding/margin/самомнение ;) * * @param elRTE rte объект-редактор * @param String name название кнопки * @todo decrease lists nesting level! * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.outdent = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { var v = this.find(); if (v.node) { this.rte.history.add(); $(v.node).css(v.type, (v.val>40 ? v.val-40 : 0)+'px'); this.rte.ui.update(); } } this.find = function(n) { function checkNode(n) { var ret = {type : '', val : 0}; var s; if ((s = self.rte.dom.attr(n, 'style'))) { ret.type = s.indexOf('padding-left') != -1 ? 'padding-left' : (s.indexOf('margin-left') != -1 ? 'margin-left' : ''); ret.val = ret.type ? parseInt($(n).css(ret.type))||0 : 0; } return ret; } var n = this.rte.selection.getNode(); var ret = checkNode(n); if (ret.val) { ret.node = n; } else { $.each(this.rte.dom.parents(n, '*'), function() { ret = checkNode(this); if (ret.val) { ret.node = this; return ret; } }) } return ret; } this.update = function() { var v = this.find(); if (v.node) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery); (function($) { elRTE.prototype.ui.prototype.buttons.pagebreak = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); // prevent resize $(this.rte.doc.body).bind('mousedown', function(e) { if ($(e.target).hasClass('elrte-pagebreak')) { e.preventDefault(); } }) this.command = function() { this.rte.selection.insertHtml('<img src="'+this.rte.filter.url+'pixel.gif" class="elrte-protected elrte-pagebreak"/>', false); } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery);/** * @class button - insert formatted text (open dialog window) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.pasteformattext = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.iframe = $(document.createElement('iframe')).addClass('el-rte-paste-input'); this.doc = null; var self = this; this.command = function() { this.rte.selection.saveIERange(); var self = this, opts = { submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.paste(); d.close(); }, dialog : { width : 500, title : this.rte.i18n('Paste formatted text') } }, d = new elDialogForm(opts); d.append(this.iframe).open(); this.doc = this.iframe.get(0).contentWindow.document; html = this.rte.options.doctype +'<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; html += '</head><body> <br /> </body></html>'; this.doc.open(); this.doc.write(html); this.doc.close(); if (!this.rte.browser.msie) { try { this.doc.designMode = "on"; } catch(e) { } } else { this.doc.body.contentEditable = true; } setTimeout(function() { self.iframe[0].contentWindow.focus(); }, 50); } this.paste = function() { $(this.doc.body).find('[class]').removeAttr('class'); var html = $.trim($(this.doc.body).html()); if (html) { this.rte.history.add(); this.rte.selection.restoreIERange(); this.rte.selection.insertHtml(this.rte.filter.wysiwyg2wysiwyg(this.rte.filter.proccess('paste', html))); this.rte.ui.update(true); } } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class кнопка "вставить только текст" * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.pastetext = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.input = $('<textarea />').addClass('el-rte-paste-input'); var self = this; this.command = function() { this.rte.browser.msie && this.rte.selection.saveIERange(); var opts = { submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.paste(); d.close(); }, dialog : { width : 500, title : this.rte.i18n('Paste only text') } } var d = new elDialogForm(opts); d.append(this.input).open(); } this.paste = function() { var txt = $.trim(this.input.val()); if (txt) { this.rte.history.add(); this.rte.browser.msie && this.rte.selection.restoreIERange(); this.rte.selection.insertText(txt.replace(/\r?\n/g, '<br />'), true); this.rte.ui.update(true); } this.input.val(''); } this.update = function() { this.domElem.removeClass('disabled'); } } })(jQuery); /** * @class button - save editor content (submit form) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.save = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.active = true; this.command = function() { this.rte.save(); } this.update = function() { } } })(jQuery); /** * @class button - insert smiley (open dialog window) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: eSabbath * **/ (function($) { elRTE.prototype.ui.prototype.buttons.smiley = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.img = null; this.url = this.rte.filter.url+'smileys/'; this.smileys = { 'smile' : 'smile.png', 'happy' : 'happy.png', 'tongue' : 'tongue.png', 'surprised' : 'surprised.png', 'waii' : 'waii.png', 'wink' : 'wink.png', 'evilgrin' : 'evilgrin.png', 'grin' : 'grin.png', 'unhappy' : 'unhappy.png' }; this.width = 120; this.command = function() { var self = this, url = this.url, d, opts, img; this.rte.browser.msie && this.rte.selection.saveIERange(); opts = { dialog : { height : 120, width : this.width, title : this.rte.i18n('Smiley'), buttons : {} } } d = new elDialogForm(opts); $.each(this.smileys, function(name, img) { d.append($('<img src="'+url+img+'" title="'+name+'" id="'+name+'" class="el-rte-smiley"/>').click(function() { self.set(this.id, d); })); }); d.open(); } this.update = function() { this.domElem.removeClass('disabled'); this.domElem.removeClass('active'); } this.set = function(s, d) { this.rte.browser.msie && this.rte.selection.restoreIERange(); if (this.smileys[s]) { this.img = $(this.rte.doc.createElement('img')); this.img.attr({ src : this.url + this.smileys[s], title : s, alt : s }); this.rte.selection.insertNode(this.img.get(0)); this.rte.ui.update(); } d.close(); } } })(jQuery); /** * @class button - stops elements floating. Insert div with style="clear:all" * Если выделение схлопнуто и находится внутри div'a с аттрибутом или css clear - он удаляется * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.stopfloat = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.find = function() { if (this.rte.selection.collapsed()) { var n = this.rte.dom.selfOrParent(this.rte.selection.getEnd(), /^DIV$/); if (n && (this.rte.dom.attr(n, 'clear') || $(n).css('clear') != 'none')) { return n; } } } this.command = function() { var n; if ((n = this.find())) { var n = $(n); this.rte.history.add(); if (!n.children().length && !$.trim(n.text()).length) { n.remove(); } else { n.removeAttr('clear').css('clear', ''); } } else { this.rte.history.add(); this.rte.selection.insertNode($(this.rte.dom.create('div')).css('clear', 'both').get(0), true); } this.rte.ui.update(true); } this.update = function() { this.domElem.removeClass('disabled'); if (this.find()) { this.domElem.addClass('active'); } else { this.domElem.removeClass('active'); } } } })(jQuery);/** * @class button - create/edit table (open dialog window) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * Copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.table = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.src = null; this.labels = null; function init() { self.labels = { main : 'Properies', adv : 'Advanced', events : 'Events', id : 'ID', 'class' : 'Css class', style : 'Css style', dir : 'Script direction', summary : 'Summary', lang : 'Language', href : 'URL' } self.src = { main : { caption : $('<input type="text" />'), rows : $('<input type="text" />').attr('size', 5).val(2), cols : $('<input type="text" />').attr('size', 5).val(2), width : $('<input type="text" />').attr('size', 5), wunit : $('<select />') .append($('<option />').val('%').text('%')) .append($('<option />').val('px').text('px')), height : $('<input type="text" />').attr('size', 5), hunit : $('<select />') .append($('<option />').val('%').text('%')) .append($('<option />').val('px').text('px')), align : $('<select />') .append($('<option />').val('').text(self.rte.i18n('Not set'))) .append($('<option />').val('left').text(self.rte.i18n('Left'))) .append($('<option />').val('center').text(self.rte.i18n('Center'))) .append($('<option />').val('right').text(self.rte.i18n('Right'))), spacing : $('<input type="text" />').attr('size', 5), padding : $('<input type="text" />').attr('size', 5), border : $('<div />'), // frame : $('<select />') // .append($('<option />').val('void').text(self.rte.i18n('No'))) // .append($('<option />').val('border').text(self.rte.i18n('Yes'))), rules : $('<select />') .append($('<option />').val('none').text(self.rte.i18n('No'))) .append($('<option />').val('all').text(self.rte.i18n('Cells'))) .append($('<option />').val('groups').text(self.rte.i18n('Groups'))) .append($('<option />').val('rows').text(self.rte.i18n('Rows'))) .append($('<option />').val('cols').text(self.rte.i18n('Columns'))), margin : $('<div />'), bg : $('<div />'), bgimg : $('<input type="text" />').css('width', '90%') }, adv : { id : $('<input type="text" />'), summary : $('<input type="text" />'), 'class' : $('<input type="text" />'), style : $('<input type="text" />'), dir : $('<select />') .append($('<option />').text(self.rte.i18n('Not set')).val('')) .append($('<option />').text(self.rte.i18n('Left to right')).val('ltr')) .append($('<option />').text(self.rte.i18n('Right to left')).val('rtl')), lang : $('<input type="text" />') }, events : {} } $.each(self.src, function() { for (var n in this) { this[n].attr('name', n); var t = this[n].get(0).nodeName; if (t == 'INPUT' && n != 'bgimg') { this[n].css(this[n].attr('size') ? {'text-align' : 'right'} : {width : '100%'}); } else if (t == 'SELECT' && n!='wunit' && n!='hunit') { this[n].css('width', '100%'); } } }); $.each( ['onblur', 'onfocus', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onmouseleave', 'onkeydown', 'onkeypress', 'onkeyup'], function() { self.src.events[this] = $('<input type="text" />').css('width', '100%'); }); self.src.main.align.change(function() { var v = $(this).val(); if (v == 'center') { self.src.main.margin.val({left : 'auto', right : 'auto'}); } else { var m = self.src.main.margin.val(); if (m.left == 'auto' && m.right == 'auto') { self.src.main.margin.val({left : '', right : ''}); } } }); self.src.main.bgimg.change(function() { var t = $(this); t.val(self.rte.utils.absoluteURL(t.val())); }) } this.command = function() { var n = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^TABLE$/); if (this.name == 'table') { this.table = $(this.rte.doc.createElement('table')); } else { this.table = n ? $(n) : $(this.rte.doc.createElement('table')); } !this.src && init(); this.src.main.border.elBorderSelect({styleHeight : 117}); this.src.main.bg.elColorPicker({palettePosition : 'outer', 'class' : 'el-colorpicker ui-icon ui-icon-pencil'}); this.src.main.margin.elPaddingInput({ type : 'margin', value : this.table}); if (this.table.parents().length) { this.src.main.rows.val('').attr('disabled', true); this.src.main.cols.val('').attr('disabled', true); } else { this.src.main.rows.val(2).removeAttr('disabled'); this.src.main.cols.val(2).removeAttr('disabled'); } var w = this.table.css('width') || this.table.attr('width'); this.src.main.width.val(parseInt(w)||''); this.src.main.wunit.val(w.indexOf('px') != -1 ? 'px' : '%'); var h = this.table.css('height') || this.table.attr('height'); this.src.main.height.val(parseInt(h)||''); this.src.main.hunit.val(h && h.indexOf('px') != -1 ? 'px' : '%'); var f = this.table.css('float'); this.src.main.align.val(''); if (f == 'left' || f == 'right') { this.src.main.align.val(f); } else { var ml = this.table.css('margin-left'); var mr = this.table.css('margin-right'); if (ml == 'auto' && mr == 'auto') { this.src.main.align.val('center'); } } this.src.main.border.val(this.table); //this.src.main.frame.val(this.table.attr('frame')); this.src.main.rules.val(this.rte.dom.attr(this.table.get(0), 'rules')); this.src.main.bg.val(this.table.css('background-color')); var bgimg = (this.table.css('background-image')||'').replace(/url\(([^\)]+)\)/i, "$1"); this.src.main.bgimg.val(bgimg!='none' ? bgimg : ''); var opts = { rtl : this.rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.set(); d.close(); }, dialog : { width : 530, title : this.rte.i18n('Table') } } var d = new elDialogForm(opts); for (var tab in this.src) { d.tab(tab, this.rte.i18n(this.labels[tab])); if (tab == 'main') { var t1 = $('<table />') .append($('<tr />').append('<td>'+this.rte.i18n('Rows')+'</td>').append($('<td />').append(this.src.main.rows))) .append($('<tr />').append('<td>'+this.rte.i18n('Columns')+'</td>').append($('<td />').append(this.src.main.cols))); var t2 = $('<table />') .append($('<tr />').append('<td>'+this.rte.i18n('Width')+'</td>').append($('<td />').append(this.src.main.width).append(this.src.main.wunit))) .append($('<tr />').append('<td>'+this.rte.i18n('Height')+'</td>').append($('<td />').append(this.src.main.height).append(this.src.main.hunit))); var t3 = $('<table />') .append($('<tr />').append('<td>'+this.rte.i18n('Spacing')+'</td>').append($('<td />').append(this.src.main.spacing.val(this.table.attr('cellspacing')||'')))) .append($('<tr />').append('<td>'+this.rte.i18n('Padding')+'</td>').append($('<td />').append(this.src.main.padding.val(this.table.attr('cellpadding')||'')))); d.append([this.rte.i18n('Caption'), this.src.main.caption.val(this.table.find('caption').eq(0).text() || '')], 'main', true) .separator('main') .append([t1, t2, t3], 'main', true) .separator('main') .append([this.rte.i18n('Border'), this.src.main.border], 'main', true) //.append([this.rte.i18n('Frame'), this.src.main.frame], 'main', true) .append([this.rte.i18n('Inner borders'), this.src.main.rules], 'main', true) .append([this.rte.i18n('Alignment'), this.src.main.align], 'main', true) .append([this.rte.i18n('Margins'), this.src.main.margin], 'main', true) .append([this.rte.i18n('Background'), $('<span />').append($('<span />').css({'float' : 'left', 'margin-right' : '3px'}).append(this.src.main.bg)).append(this.src.main.bgimg)], 'main', true) } else { for (var name in this.src[tab]) { var v = this.rte.dom.attr(this.table, name); if (tab == 'events') { v = this.rte.utils.trimEventCallback(v); } d.append([this.rte.i18n(this.labels[name] ? this.labels[name] : name), this.src[tab][name].val(v)], tab, true); } } } d.open(); } this.set = function() { if (!this.table.parents().length) { var r = parseInt(this.src.main.rows.val()) || 0; var c = parseInt(this.src.main.cols.val()) || 0; if (r<=0 || c<=0) { return; } this.rte.history.add(); var b = $(this.rte.doc.createElement('tbody')).appendTo(this.table); for (var i=0; i < r; i++) { var tr = '<tr>'; for (var j=0; j < c; j++) { tr += '<td>&nbsp;</td>'; } b.append(tr+'</tr>'); }; // var tr = $(this.rte.doc.createElement('tr')); // // for (var i=0; i < c; i++) { // tr.append($(this.rte.doc.createElement('td')).html('&nbsp;')); // }; // // for (var i=0; i<r; i++) { // b.append(tr.clone(true)); // }; // this.rte.selection.insertNode(this.table.get(0), true); } else { this.table .removeAttr('width') .removeAttr('height') .removeAttr('border') .removeAttr('align') .removeAttr('bordercolor') .removeAttr('bgcolor') .removeAttr('cellspacing') .removeAttr('cellpadding') .removeAttr('frame') .removeAttr('rules') .removeAttr('style'); } var cap = $.trim(this.src.main.caption.val()); if (cap) { if (!this.table.children('caption').length) { this.table.prepend('<caption />' ); } this.table.children('caption').text(cap); } else { this.table.children('caption').remove(); } for (var tab in this.src) { if (tab != 'main') { for (var n in this.src[tab]) { var v = $.trim(this.src[tab][n].val()); if (v) { this.table.attr(n, v); } else { this.table.removeAttr(n); } } } } var spacing, padding, rules; if ((spacing = parseInt(this.src.main.spacing.val())) && spacing>=0) { this.table.attr('cellspacing', spacing); } if ((padding = parseInt(this.src.main.padding.val())) && padding>=0) { this.table.attr('cellpadding', padding); } if ((rules = this.src.main.rules.val())) { this.table.attr('rules', rules); } var w = parseInt(this.src.main.width.val()) || '', h = parseInt(this.src.main.height.val()) || '', i = $.trim(this.src.main.bgimg.val()), b = this.src.main.border.val(), m = this.src.main.margin.val(), f = this.src.main.align.val(); this.table.css({ width : w ? w+this.src.main.wunit.val() : '', height : h ? h+this.src.main.hunit.val() : '', border : $.trim(b.width+' '+b.style+' '+b.color), 'background-color' : this.src.main.bg.val(), 'background-image' : i ? 'url('+i+')' : '' }); if (m.css) { this.table.css('margin', m.css); } else { this.table.css({ 'margin-top' : m.top, 'margin-right' : m.right, 'margin-bottom' : m.bottom, 'margin-left' : m.left }); } if ((f=='left' || f=='right') && this.table.css('margin-left')!='auto' && this.table.css('margin-right')!='auto') { this.table.css('float', f); } if (!this.table.attr('style')) { this.table.removeAttr('style'); } if (!this.table.parents().length) { this.rte.selection.insertNode(this.table.get(0), true); } this.rte.ui.update(); } this.update = function() { this.domElem.removeClass('disabled'); if (this.name == 'tableprops' && !this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^TABLE$/)) { this.domElem.addClass('disabled').removeClass('active'); } } } elRTE.prototype.ui.prototype.buttons.tableprops = elRTE.prototype.ui.prototype.buttons.table; })(jQuery); /** * @class button - remove table * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tablerm = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { var t = this.rte.dom.parent(this.rte.selection.getNode(), /^TABLE$/); // t && $(t).remove(); if (t) { this.rte.history.add(); $(t).remove(); } this.rte.ui.update(true); } this.update = function() { if (this.rte.dom.parent(this.rte.selection.getNode(), /^TABLE$/)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery); /** * @class button - table cell properties * * @param elRTE rte объект-редактор * @param String name название кнопки * * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tbcellprops = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.src = null; this.labels = null; function init() { self.labels = { main : 'Properies', adv : 'Advanced', events : 'Events', id : 'ID', 'class' : 'Css class', style : 'Css style', dir : 'Script direction', lang : 'Language' } self.src = { main : { type : $('<select />').css('width', '100%') .append($('<option />').val('td').text(self.rte.i18n('Data'))) .append($('<option />').val('th').text(self.rte.i18n('Header'))), width : $('<input type="text" />').attr('size', 4), wunit : $('<select />') .append($('<option />').val('%').text('%')) .append($('<option />').val('px').text('px')), height : $('<input type="text" />').attr('size', 4), hunit : $('<select />') .append($('<option />').val('%').text('%')) .append($('<option />').val('px').text('px')), align : $('<select />').css('width', '100%') .append($('<option />').val('').text(self.rte.i18n('Not set'))) .append($('<option />').val('left').text(self.rte.i18n('Left'))) .append($('<option />').val('center').text(self.rte.i18n('Center'))) .append($('<option />').val('right').text(self.rte.i18n('Right'))) .append($('<option />').val('justify').text(self.rte.i18n('Justify'))), border : $('<div />'), padding : $('<div />'), bg : $('<div />'), bgimg : $('<input type="text" />').css('width', '90%'), apply : $('<select />').css('width', '100%') .append($('<option />').val('').text(self.rte.i18n('Current cell'))) .append($('<option />').val('row').text(self.rte.i18n('All cells in row'))) .append($('<option />').val('column').text(self.rte.i18n('All cells in column'))) .append($('<option />').val('table').text(self.rte.i18n('All cells in table'))) }, adv : { id : $('<input type="text" />'), 'class' : $('<input type="text" />'), style : $('<input type="text" />'), dir : $('<select />').css('width', '100%') .append($('<option />').text(self.rte.i18n('Not set')).val('')) .append($('<option />').text(self.rte.i18n('Left to right')).val('ltr')) .append($('<option />').text(self.rte.i18n('Right to left')).val('rtl')), lang : $('<input type="text" />') }, events : {} } $.each(self.src, function() { for (var n in this) { this[n].attr('name', n); if (this[n].attr('type') == 'text' && !this[n].attr('size') && n!='bgimg') { this[n].css('width', '100%') } } }); $.each( ['onblur', 'onfocus', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onmouseleave', 'onkeydown', 'onkeypress', 'onkeyup'], function() { self.src.events[this] = $('<input type="text" />').css('width', '100%'); }); } this.command = function() { !this.src && init(); this.cell = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^(TD|TH)$/); if (!this.cell) { return; } this.src.main.type.val(this.cell.nodeName.toLowerCase()); this.cell = $(this.cell); this.src.main.border.elBorderSelect({styleHeight : 117, value : this.cell}); this.src.main.bg.elColorPicker({palettePosition : 'outer', 'class' : 'el-colorpicker ui-icon ui-icon-pencil'}); this.src.main.padding.elPaddingInput({ value : this.cell}); var w = this.cell.css('width') || this.cell.attr('width'); this.src.main.width.val(parseInt(w)||''); this.src.main.wunit.val(w.indexOf('px') != -1 ? 'px' : '%'); var h = this.cell.css('height') || this.cell.attr('height'); this.src.main.height.val(parseInt(h)||''); this.src.main.hunit.val(h.indexOf('px') != -1 ? 'px' : '%'); this.src.main.align.val(this.cell.attr('align') || this.cell.css('text-align')); this.src.main.bg.val(this.cell.css('background-color')); var bgimg = this.cell.css('background-image'); this.src.main.bgimg.val(bgimg && bgimg!='none' ? bgimg.replace(/url\(([^\)]+)\)/i, "$1") : ''); this.src.main.apply.val(''); var opts = { rtl : this.rte.rtl, submit : function(e, d) { e.stopPropagation(); e.preventDefault(); self.set(); d.close(); }, dialog : { width : 520, title : this.rte.i18n('Table cell properties') } } var d = new elDialogForm(opts); for (var tab in this.src) { d.tab(tab, this.rte.i18n(this.labels[tab])); if (tab == 'main') { d.append([this.rte.i18n('Width'), $('<span />').append(this.src.main.width).append(this.src.main.wunit)], 'main', true) .append([this.rte.i18n('Height'), $('<span />').append(this.src.main.height).append(this.src.main.hunit)], 'main', true) .append([this.rte.i18n('Table cell type'), this.src.main.type], 'main', true) .append([this.rte.i18n('Border'), this.src.main.border], 'main', true) .append([this.rte.i18n('Alignment'), this.src.main.align], 'main', true) .append([this.rte.i18n('Paddings'), this.src.main.padding], 'main', true) .append([this.rte.i18n('Background'), $('<span />').append($('<span />').css({'float' : 'left', 'margin-right' : '3px'}).append(this.src.main.bg)).append(this.src.main.bgimg)], 'main', true) .append([this.rte.i18n('Apply to'), this.src.main.apply], 'main', true); } else { for (var name in this.src[tab]) { var v = this.cell.attr(name) || ''; if (tab == 'events') { v = this.rte.utils.trimEventCallback(v); } d.append([this.rte.i18n(this.labels[name] ? this.labels[name] : name), this.src[tab][name].val(v)], tab, true); } } } d.open() } this.set = function() { // $(t).remove(); var target = this.cell, apply = this.src.main.apply.val(); switch (this.src.main.apply.val()) { case 'row': target = this.cell.parent('tr').children('td,th'); break; case 'column': target = $(this.rte.dom.tableColumn(this.cell.get(0))); break; case 'table': target = this.cell.parents('table').find('td,th'); break; } for (var tab in this.src) { if (tab != 'main') { for (var n in this.src[tab]) { var v = $.trim(this.src[tab][n].val()); if (v) { target.attr(n, v); } else { target.removeAttr(n); } } } } target.removeAttr('width') .removeAttr('height') .removeAttr('border') .removeAttr('align') .removeAttr('bordercolor') .removeAttr('bgcolor'); var t = this.src.main.type.val(); var w = parseInt(this.src.main.width.val()) || ''; var h = parseInt(this.src.main.height.val()) || ''; var i = $.trim(this.src.main.bgimg.val()); var b = this.src.main.border.val(); var css = { 'width' : w ? w+this.src.main.wunit.val() : '', 'height' : h ? h+this.src.main.hunit.val() : '', 'background-color' : this.src.main.bg.val(), 'background-image' : i ? 'url('+i+')' : '', 'border' : $.trim(b.width+' '+b.style+' '+b.color), 'text-align' : this.src.main.align.val() || '' }; var p = this.src.main.padding.val(); if (p.css) { css.padding = p.css; } else { css['padding-top'] = p.top; css['padding-right'] = p.right; css['padding-bottom'] = p.bottom; css['padding-left'] = p.left; } target = target.get(); $.each(target, function() { var type = this.nodeName.toLowerCase(); var $this = $(this); if (type != t) { var attr = {} for (var i in self.src.adv) { var v = $this.attr(i) if (v) { attr[i] = v.toString(); } } for (var i in self.src.events) { var v = $this.attr(i) if (v) { attr[i] = v.toString(); } } var colspan = $this.attr('colspan')||1; var rowspan = $this.attr('rowspan')||1; if (colspan>1) { attr.colspan = colspan; } if (rowspan>1) { attr.rowspan = rowspan; } $this.replaceWith($('<'+t+' />').html($this.html()).attr(attr).css(css) ); } else { $this.css(css); } }); this.rte.ui.update(); } this.update = function() { if (this.rte.dom.parent(this.rte.selection.getNode(), /^TABLE$/)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery);/** * @class button - table cells merge * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tbcellsmerge = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; function selectedCells() { var c1 = self.rte.dom.selfOrParent(self.rte.selection.getStart(), /^(TD|TH)$/); var c2 = self.rte.dom.selfOrParent(self.rte.selection.getEnd(), /^(TD|TH)$/); if (c1 && c2 && c1!=c2 && $(c1).parents('table').get(0) == $(c2).parents('table').get(0)) { return [c1, c2]; } return null; } this.command = function() { var cells = selectedCells(); if (cells) { var _s = this.rte.dom.indexOf($(cells[0]).parent('tr').get(0)); var _e = this.rte.dom.indexOf($(cells[1]).parent('tr').get(0)); var ro = Math.min(_s, _e); // row offset var rl = Math.max(_s, _e) - ro + 1; // row length var _c1 = this.rte.dom.tableColumn(cells[0], true, true); var _c2 = this.rte.dom.tableColumn(cells[1], true); var _i1 = $.inArray(cells[0], _c1.column); var _i2 = $.inArray(cells[1], _c2.column); var colBegin = _c1.info.offset[_i1] < _c2.info.offset[_i2] ? _c1 : _c2; var colEnd = _c1.info.offset[_i1] >= _c2.info.offset[_i2] ? _c1 : _c2; var length = 0; var target = null; var html = ''; this.rte.history.add(); var rows = $($(cells[0]).parents('table').eq(0).find('tr').get().slice(ro, ro+rl)) .each( function(i) { var _l = html.length; var accept = false; $(this).children('td,th').each(function() { var $this = $(this); var inBegin = $.inArray(this, colBegin.column); var inEnd = $.inArray(this, colEnd.column); if (inBegin!=-1 || inEnd!=-1) { accept = inBegin!=-1 && inEnd==-1; var len = parseInt($this.attr('colspan')||1) if (i == 0) { length += len; } if (inBegin!=-1 && i>0) { var delta = colBegin.info.delta[inBegin]; if (delta>0) { if ($this.css('text-align') == 'left') { var cell = $this.clone(true); $this.html('&nbsp;'); } else { var cell = $this.clone().html('&nbsp;'); } cell.removeAttr('colspan').removeAttr('id').insertBefore(this); if (delta>1) { cell.attr('colspan', delta); } } } if (inEnd!=-1) { var delta = colEnd.info.delta[inEnd]; if (len-delta>1) { var cp = len-delta-1; if ($this.css('text-align') == 'right') { var cell = $this.clone(true); $this.html('&nbsp;'); } else { var cell = $this.clone().html('&nbsp;'); } cell.removeAttr('colspan').removeAttr('id').insertAfter(this); if (cp>1) { cell.attr('colspan', cp); } } } if (!target) { target = $this; } else { html += $this.html(); $this.remove(); } } else if (accept) { if (i == 0) { length += parseInt($this.attr('colspan')||1); } html += $this.html(); $this.remove(); } }) html += _l!=html.length ? '<br />' : ''; }); target.removeAttr('colspan').removeAttr('rowspan').html(target.html()+html) if (length>1) { target.attr('colspan', length); } if (rl>1) { target.attr('rowspan', rl); } // sometimes when merge cells with different rowspans we get "lost" cells in rows // this add cells if needed this.rte.dom.fixTable($(cells[0]).parents('table').get(0)); } } this.update = function() { if (selectedCells()) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery); /** * @class button - split merged cell * * @param elRTE rte объект-редактор * @param String name название кнопки * @todo split not merged cell * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tbcellsplit = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { var n = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^(TD|TH)$/); if (n) { this.rte.history.add(); var colspan = parseInt(this.rte.dom.attr(n, 'colspan')); var rowspan = parseInt(this.rte.dom.attr(n, 'rowspan')); if (colspan>1 || rowspan>1) { var cnum = colspan-1; var rnum = rowspan-1; var tb = this.rte.dom.parent(n, /^TABLE$/); var tbm = this.rte.dom.tableMatrix(tb); // ячейки в текущем ряду if (cnum) { for (var i=0; i<cnum; i++) { $(this.rte.dom.create(n.nodeName)).html('&nbsp;').insertAfter(n); } } if (rnum) { var ndx = this.rte.dom.indexesOfCell(n, tbm) var rndx = ndx[0]; var cndx = ndx[1]; // ячейки в следущих рядах for (var r=rndx+1; r < rndx+rnum+1; r++) { var cell; if (!tbm[r][cndx].nodeName) { if (tbm[r][cndx-1].nodeName) { cell = tbm[r][cndx-1]; } else { for (var i=cndx-1; i>=0; i--) { if (tbm[r][i].nodeName) { cell =tbm[r][i]; break; } } } if (cell) { for (var i=0; i<= cnum; i++) { $(this.rte.dom.create(cell.nodeName)).html('&nbsp;').insertAfter(cell); } } } }; } $(n).removeAttr('colspan').removeAttr('rowspan'); this.rte.dom.fixTable(tb); } } this.rte.ui.update(true); } this.update = function() { var n = this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^(TD|TH)$/); if (n && (parseInt(this.rte.dom.attr(n, 'colspan'))>1 || parseInt(this.rte.dom.attr(n, 'rowspan'))>1)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery); /** * @class button - Insert new column in table(before or after current) * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tbcolbefore = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { var self = this; var cells = this.rte.dom.tableColumn(this.rte.selection.getNode(), false, true); if (cells.length) { this.rte.history.add(); $.each(cells, function() { var $this = $(this); var cp = parseInt($this.attr('colspan')||1) if (cp >1) { $this.attr('colspan', cp+1); } else { var c = $(self.rte.dom.create(this.nodeName)).html('&nbsp;'); if (self.name == 'tbcolbefore') { c.insertBefore(this); } else { c.insertAfter(this); } } }); this.rte.ui.update(); } } this.update = function() { if (this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^(TD|TH)$/)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } elRTE.prototype.ui.prototype.buttons.tbcolafter = elRTE.prototype.ui.prototype.buttons.tbcolbefore; })(jQuery); /** * @class button - remove table colunm * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tbcolrm = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { var n = this.rte.selection.getNode(); var c = this.rte.dom.selfOrParent(n, /^(TD|TH)$/); var prev = $(c).prev('td,th').get(0); var next = $(c).next('td,th').get(0); var tb = this.rte.dom.parent(n, /^TABLE$/); var cells = this.rte.dom.tableColumn(n, false, true); if (cells.length) { this.rte.history.add(); $.each(cells, function() { var $this = $(this); var cp = parseInt($this.attr('colspan')||1); if ( cp>1 ) { $this.attr('colspan', cp-1); } else { $this.remove(); } }); this.rte.dom.fixTable(tb); if (prev || next) { this.rte.selection.selectContents(prev ? prev : next).collapse(true); } this.rte.ui.update(true); } } this.update = function() { if (this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^(TD|TH)$/)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery); /** * @class меню - Новый ряд в таблице * * @param elRTE rte объект-редактор * @param String name название кнопки **/ elRTE.prototype.ui.prototype.buttons.tbrowbefore = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { var n = this.rte.selection.getNode(); var c = this.rte.dom.selfOrParent(n, /^(TD|TH)$/); var r = this.rte.dom.selfOrParent(c, /^TR$/); var mx = this.rte.dom.tableMatrix(this.rte.dom.selfOrParent(c, /^TABLE$/)); if (c && r && mx) { this.rte.history.add(); var before = this.name == 'tbrowbefore'; var ro = $(r).prevAll('tr').length; var cnt = 0; var mdf = []; function _find(x, y) { while (y>0) { y--; if (mx[y] && mx[y][x] && mx[y][x].nodeName) { return mx[y][x]; } } } for (var i=0; i<mx[ro].length; i++) { if (mx[ro][i] && mx[ro][i].nodeName) { var cell = $(mx[ro][i]); var colspan = parseInt(cell.attr('colspan')||1); if (parseInt(cell.attr('rowspan')||1) > 1) { if (before) { cnt += colspan; } else { mdf.push(cell); } } else { cnt += colspan; } } else if (mx[ro][i] == '-') { cell = _find(i, ro); cell && mdf.push($(cell)); } } var row = $(this.rte.dom.create('tr')); for (var i=0; i<cnt; i++) { row.append('<td>&nbsp;</td>'); } if (before) { row.insertBefore(r); } else { row.insertAfter(r); } $.each(mdf, function() { $(this).attr('rowspan', parseInt($(this).attr('rowspan')||1)+1); }); this.rte.ui.update(); } } this.update = function() { if (this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^TR$/)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } elRTE.prototype.ui.prototype.buttons.tbrowafter = elRTE.prototype.ui.prototype.buttons.tbrowbefore; /** * @class button - remove table row * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.tbrowrm = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); var self = this; this.command = function() { var n = this.rte.selection.getNode(), c = this.rte.dom.selfOrParent(n, /^(TD|TH)$/), r = this.rte.dom.selfOrParent(c, /^TR$/), tb = this.rte.dom.selfOrParent(c, /^TABLE$/), mx = this.rte.dom.tableMatrix(tb); if (c && r && mx.length) { this.rte.history.add(); if (mx.length==1) { $(tb).remove(); return this.rte.ui.update(); } var mdf = []; var ro = $(r).prevAll('tr').length; function _find(x, y) { while (y>0) { y--; if (mx[y] && mx[y][x] && mx[y][x].nodeName) { return mx[y][x]; } } } // move cell with rowspan>1 to next row function _move(cell, x) { y = ro+1; var sibling= null; if (mx[y]) { for (var _x=0; _x<x; _x++) { if (mx[y][_x] && mx[y][_x].nodeName) { sibling = mx[y][_x]; } }; cell = cell.remove(); if (sibling) { cell.insertAfter(sibling); } else { cell.prependTo($(r).next('tr').eq(0)); } } } function _cursorPos(column) { for (var i = 0; i<column.length; i++) { if (column[i] == c) { return i<column.length-1 ? column[i+1] : column[i-1]; } } } for (var i=0; i<mx[ro].length; i++) { var cell = null; var move = false; if (mx[ro][i] && mx[ro][i].nodeName) { cell = mx[ro][i]; move = true; } else if (mx[ro][i] == '-' && (cell = _find(i, ro))) { move = false; } if (cell) { cell = $(cell); var rowspan = parseInt(cell.attr('rowspan')||1); if (rowspan>1) { cell.attr('rowspan', rowspan-1); move && _move(cell, i, ro); } } }; var _c = _cursorPos(this.rte.dom.tableColumn(c)); if (_c) { this.rte.selection.selectContents(_c).collapse(true); } $(r).remove(); } this.rte.ui.update(); } this.update = function() { if (this.rte.dom.selfOrParent(this.rte.selection.getNode(), /^TR$/)) { this.domElem.removeClass('disabled'); } else { this.domElem.addClass('disabled'); } } } })(jQuery);/** * @class кнопка - отмена повтор действий * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.undo = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { if (this.name == 'undo' && this.rte.history.canBack()) { this.rte.history.back(); this.rte.ui.update(); } else if (this.name == 'redo' && this.rte.history.canFwd()) { this.rte.history.fwd(); this.rte.ui.update(); } } this.update = function() { this.domElem.toggleClass('disabled', this.name == 'undo' ? !this.rte.history.canBack() : !this.rte.history.canFwd()); } } elRTE.prototype.ui.prototype.buttons.redo = elRTE.prototype.ui.prototype.buttons.undo; })(jQuery);/** * @class button - remove link * * @param elRTE rte объект-редактор * @param String name название кнопки * * @author: Dmitry Levashov (dio) dio@std42.ru * @copyright: Studio 42, http://www.std42.ru **/ (function($) { elRTE.prototype.ui.prototype.buttons.unlink = function(rte, name) { this.constructor.prototype.constructor.call(this, rte, name); this.command = function() { var n = this.rte.selection.getNode(), l = this.rte.dom.selfOrParentLink(n); function isLink(n) { return n.nodeName == 'A' && n.href; } if (!l) { var sel = $.browser.msie ? this.rte.selection.selected() : this.rte.selection.selected({wrap : false}); if (sel.length) { for (var i=0; i < sel.length; i++) { if (isLink(sel[i])) { l = sel[i]; break; } }; if (!l) { l = this.rte.dom.parent(sel[0], isLink) || this.rte.dom.parent(sel[sel.length-1], isLink); } } } if (l) { this.rte.history.add(); this.rte.selection.select(l); this.rte.doc.execCommand('unlink', false, null); this.rte.ui.update(true); } } this.update = function() { var n = this.rte.selection.getNode(); if (this.rte.dom.selfOrParentLink(n)) { this.domElem.removeClass('disabled').addClass('active'); } else if (this.rte.dom.selectionHas(function(n) { return n.nodeName == 'A' && n.href; })) { this.domElem.removeClass('disabled').addClass('active'); } else { this.domElem.addClass('disabled').removeClass('active'); } } } })(jQuery);
JavaScript
(function($) { /** * @class File manager (main controller) * @author dio dio@std42.ru **/ elFinder = function(el, o) { var self = this, id; this.log = function(m) { window.console && window.console.log && window.console.log(m); } /** * Object. File manager configuration **/ this.options = $.extend({}, this.options, o||{}); if (!this.options.url) { alert('Invalid configuration! You have to set URL option.'); return; } /** * String. element id, create random if not set; **/ this.id = ''; if ((id = $(el).attr('id'))) { this.id = id; } else { // this.id = 'el-finder-'+Math.random().toString().substring(2); } /** * String. Version number; **/ this.version = '1.2'; /** * String. jQuery version; **/ this.jquery = $.fn.jquery.split('.').join(''); /** * Object. Current Working Dir info **/ this.cwd = {}; /** * Object. Current Dir Content. Files/folders info **/ this.cdc = {}; /** * Object. Buffer for copied files **/ this.buffer = {}; /** * Array. Selected files IDs **/ this.selected = []; /** * Array. Folder navigation history **/ this.history = []; /** * Boolean. Enable/disable actions **/ this.locked = false; /** * Number. Max z-index on page + 1, need for contextmenu and quicklook **/ this.zIndex = 2; /** * DOMElement. jQueryUI dialog **/ this.dialog = null; /** * DOMElement. For docked mode - place where fm is docked **/ this.anchor = this.options.docked ? $('<div/>').hide().insertBefore(el) : null; /** * Object. Some options get from server **/ this.params = { dotFiles : false, arc : '', uplMaxSize : '' }; this.vCookie = 'el-finder-view-'+this.id; this.pCookie = 'el-finder-places-'+this.id; this.lCookie = 'el-finder-last-'+this.id; /** * Object. View. After init we can accessel as this.view.win **/ this.view = new this.view(this, el); /** * Object. User Iterface. Controller for commands/buttons/contextmenu **/ this.ui = new this.ui(this); /** * Object. Set/update events **/ this.eventsManager = new this.eventsManager(this); /** * Object. Quick Look like in MacOS X :) **/ this.quickLook = new this.quickLook(this); /** * Set/get cookie value * * @param String name cookie name * @param String value cookie value, null to unset **/ this.cookie = function(name, value) { if (typeof value == 'undefined') { if (document.cookie && document.cookie != '') { var i, c = document.cookie.split(';'); name += '='; for (i=0; i<c.length; i++) { c[i] = $.trim(c[i]); if (c[i].substring(0, name.length) == name) { return decodeURIComponent(c[i].substring(name.length)); } } } return ''; } else { var d, o = $.extend({}, this.options.cookie); if (value===null) { value = ''; o.expires = -1; } if (typeof(o.expires) == 'number') { d = new Date(); d.setTime(d.getTime()+(o.expires * 24 * 60 * 60 * 1000)); o.expires = d; } document.cookie = name+'='+encodeURIComponent(value)+'; expires='+o.expires.toUTCString()+(o.path ? '; path='+o.path : '')+(o.domain ? '; domain='+o.domain : '')+(o.secure ? '; secure' : ''); } } /** * Set/unset this.locked flag * * @param Boolean state **/ this.lock = function(l) { this.view.spinner((this.locked = l||false)); this.eventsManager.lock = this.locked; } /** * Set/unset lock for keyboard shortcuts * * @param Boolean state **/ this.lockShortcuts = function(l) { this.eventsManager.lock = !!l; } /** * Set file manager view type (list|icons) * * @param String v view name **/ this.setView = function(v) { if (v == 'list' || v == 'icons') { this.options.view = v; this.cookie(this.vCookie, v); } } /** * make ajax request, show message on error, call callback on success * * @param Object. data for ajax request * @param Function * @param Object overrwrite some options */ this.ajax = function(data, callback, options) { var opts = { url : this.options.url, async : true, type : 'GET', data : data, dataType : 'json', cache : false, lock : true, force : false, silent : false } if (typeof(options) == 'object') { opts = $.extend({}, opts, options); } if (!opts.silent) { opts.error = self.view.fatal; } opts.success = function(data) { opts.lock && self.lock(); if (data) { data.debug && self.log(data.debug); if (data.error) { !opts.silent && self.view.error(data.error, data.errorData); if (!opts.force) { return; } } callback(data); delete data; } } opts.lock && this.lock(true); $.ajax(opts); } /** * Load generated thumbnails in background * **/ this.tmb = function() { this.ajax({cmd : 'tmb', current : self.cwd.hash}, function(data) { if (self.options.view == 'icons' && data.images && data.current == self.cwd.hash) { for (var i in data.images) { if (self.cdc[i]) { self.cdc[i].tmb = data.images[i]; $('div[key="'+i+'"]>p', self.view.cwd).css('background', ' url("'+data.images[i]+'") 0 0 no-repeat'); } } data.tmb && self.tmb(); } }, {lock : false, silent : true}); } /** * Return folders in places IDs * * @return Array **/ this.getPlaces = function() { var pl = [], p = this.cookie(this.pCookie); if (p.length) { if (p.indexOf(':')!=-1) { pl = p.split(':'); } else { pl.push(p); } } return pl; } /** * Add new folder to places * * @param String Folder ID * @return Boolean **/ this.addPlace = function(id) { var p = this.getPlaces(); if ($.inArray(id, p) == -1) { p.push(id); this.savePlaces(p); return true; } } /** * Remove folder from places * * @param String Folder ID * @return Boolean **/ this.removePlace = function(id) { var p = this.getPlaces(); if ($.inArray(id, p) != -1) { this.savePlaces($.map(p, function(o) { return o == id?null:o; })); return true; } } /** * Save new places data in cookie * * @param Array Folders IDs **/ this.savePlaces = function(p) { this.cookie(this.pCookie, p.join(':')); } /** * Update file manager content * * @param Object Data from server **/ this.reload = function(data) { var i; this.cwd = data.cwd; this.cdc = {}; for (i=0; i<data.cdc.length ; i++) { if (data.cdc[i].hash && data.cdc[i].name) { this.cdc[data.cdc[i].hash] = data.cdc[i]; this.cwd.size += data.cdc[i].size; } } if (data.tree) { this.view.renderNav(data.tree); this.eventsManager.updateNav(); } this.updateCwd(); /* tell connector to generate thumbnails */ if (data.tmb && !self.locked && self.options.view == 'icons') { self.tmb(); } /* have to select some files */ if (data.select && data.select.length) { var l = data.select.length; while (l--) { this.cdc[data.select[l]] && this.selectById(data.select[l]); } } this.lastDir(this.cwd.hash); if (this.options.autoReload>0) { this.iID && clearInterval(this.iID); this.iID = setInterval(function() { !self.locked && self.ui.exec('reload'); }, this.options.autoReload*60000); } } /** * Redraw current directory * */ this.updateCwd = function() { this.lockShortcuts(true); this.selected = []; this.view.renderCwd(); this.eventsManager.updateCwd(); this.view.tree.find('a[key="'+this.cwd.hash+'"]').trigger('select'); this.lockShortcuts(); } /** * Execute after files was dropped onto folder * * @param Object drop event * @param Object drag helper object * @param String target folder ID */ this.drop = function(e, ui, target) { if (ui.helper.find('[key="'+target+'"]').length) { return self.view.error('Unable to copy into itself'); } var ids = []; ui.helper.find('div:not(.noaccess):has(>label):not(:has(em[class="readonly"],em[class=""]))').each(function() { ids.push($(this).hide().attr('key')); }); if (!ui.helper.find('div:has(>label):visible').length) { ui.helper.hide(); } if (ids.length) { self.setBuffer(ids, e.shiftKey?0:1, target); if (self.buffer.files) { /* some strange jquery ui bug (in list view) */ setTimeout(function() {self.ui.exec('paste'); self.buffer = {}}, 300); } } else { $(this).removeClass('el-finder-droppable'); } } /** * Return selected files data * * @param Number if set, returns only element with this index or empty object * @return Array|Object */ this.getSelected = function(ndx) { var i, s = []; if (ndx>=0) { return this.cdc[this.selected[ndx]]||{}; } for (i=0; i<this.selected.length; i++) { this.cdc[this.selected[i]] && s.push(this.cdc[this.selected[i]]); } return s; } this.select = function(el, reset) { reset && $('.ui-selected', self.view.cwd).removeClass('ui-selected'); el.addClass('ui-selected'); self.updateSelect(); } this.selectById = function(id) { var el = $('[key="'+id+'"]', this.view.cwd); if (el.length) { this.select(el); this.checkSelectedPos(); } } this.unselect = function(el) { el.removeClass('ui-selected'); self.updateSelect(); } this.toggleSelect = function(el) { el.toggleClass('ui-selected'); this.updateSelect(); } this.selectAll = function() { $('[key]', self.view.cwd).addClass('ui-selected') self.updateSelect(); } this.unselectAll = function() { $('.ui-selected', self.view.cwd).removeClass('ui-selected'); self.updateSelect(); } this.updateSelect = function() { self.selected = []; $('.ui-selected', self.view.cwd).each(function() { self.selected.push($(this).attr('key')); }); self.view.selectedInfo(); self.ui.update(); self.quickLook.update(); } /** * Scroll selected element in visible position * * @param Boolean check last or first selected element? */ this.checkSelectedPos = function(last) { var s = self.view.cwd.find('.ui-selected:'+(last ? 'last' : 'first')).eq(0), p = s.position(), h = s.outerHeight(), ph = self.view.cwd.height(); if (p.top < 0) { self.view.cwd.scrollTop(p.top+self.view.cwd.scrollTop()-2); } else if (ph - p.top < h) { self.view.cwd.scrollTop(p.top+h-ph+self.view.cwd.scrollTop()); } } /** * Add files to clipboard buffer * * @param Array files IDs * @param Boolean copy or cut files? * @param String destination folder ID */ this.setBuffer = function(files, cut, dst) { var i, id, f; this.buffer = { src : this.cwd.hash, dst : dst, files : [], names : [], cut : cut||0 }; for (i=0; i<files.length; i++) { id = files[i]; f = this.cdc[id]; if (f && f.read && f.type != 'link') { this.buffer.files.push(f.hash); this.buffer.names.push(f.name); } } if (!this.buffer.files.length) { this.buffer = {}; } } /** * Return true if file name is acceptable * * @param String file/folder name * @return Boolean */ this.isValidName = function(n) { if (!this.cwd.dotFiles && n.indexOf('.') == 0) { return false; } return n.match(/^[^\\\/\<\>:]+$/); } /** * Return true if file with this name exists * * @param String file/folder name * @return Boolean */ this.fileExists = function(n) { for (var i in this.cdc) { if (this.cdc[i].name == n) { return i; } } return false; } /** * Return name for new file/folder * * @param String base name (i18n) * @param String extension for file * @return String */ this.uniqueName = function(n, ext) { n = self.i18n(n); var name = n, i = 0, ext = ext||''; if (!this.fileExists(name+ext)) { return name+ext; } while (i++<100) { if (!this.fileExists(name+i+ext)) { return name+i+ext; } } return name.replace('100', '')+Math.random()+ext; } /** * Get/set last opened dir * * @param String dir hash * @return String */ this.lastDir = function(dir) { if (this.options.rememberLastDir) { return dir ? this.cookie(this.lCookie, dir) : this.cookie(this.lCookie); } } /** * Resize file manager * * @param Number width * @param Number height */ function resize(w, h) { w && self.view.win.width(w); h && self.view.nav.add(self.view.cwd).height(h); } /** * Resize file manager in dialog window while it resize * */ function dialogResize() { resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32)) } this.time = function() { return new Date().getMilliseconds(); } /* here we init file manager */ this.setView(this.cookie(this.vCookie)); resize(self.options.width, self.options.height); /* dialog or docked mode */ if (this.options.dialog || this.options.docked) { this.options.dialog = $.extend({width : 570, dialogClass : '', minWidth : 480, minHeight: 330}, this.options.dialog || {}); this.options.dialog.open = function() { setTimeout(function() { $('<input type="text" value="f"/>').appendTo(self.view.win).focus().select().remove() }, 200) } this.options.dialog.dialogClass += 'el-finder-dialog'; this.options.dialog.resize = dialogResize; if (this.options.docked) { /* docked mode - create dialog and store size */ this.options.dialog.close = function() { self.dock(); }; this.view.win.data('size', {width : this.view.win.width(), height : this.view.nav.height()}); } else { this.options.dialog.close = function() { self.destroy(); } this.dialog = $('<div/>').append(this.view.win).dialog(this.options.dialog); } } this.ajax({ cmd : 'open', target : this.lastDir()||'', init : true, tree : true }, function(data) { if (data.cwd) { self.eventsManager.init(); self.reload(data); $.extend(self.params, data.params||{}); $('*', document.body).each(function() { var z = parseInt($(this).css('z-index')); if (z >= self.zIndex) { self.zIndex = z+1; } }); self.ui.init(data.disabled); } }, {force : true}); this.open = function() { this.dialog ? this.dialog.dialog('open') : this.view.win.show(); this.eventsManager.lock = false; } this.close = function() { this.quickLook.hide(); if (this.options.docked && this.view.win.attr('undocked')) { this.dock(); } else { this.dialog ? this.dialog.dialog('close') : this.view.win.hide(); } this.eventsManager.lock = true; } this.destroy = function() { this.eventsManager.lock = true; this.quickLook.hide(); this.quickLook.win.remove(); if (this.dialog) { this.dialog.dialog('destroy'); this.view.win.parent().remove(); } else { this.view.win.remove(); } this.ui.menu.remove(); } this.dock = function() { if (this.options.docked && this.view.win.attr('undocked')) { this.quickLook.hide(); var s =this.view.win.data('size'); this.view.win.insertAfter(this.anchor).removeAttr('undocked'); resize(s.width, s.height); this.dialog.dialog('destroy'); this.dialog = null; } } this.undock = function() { if (this.options.docked && !this.view.win.attr('undocked')) { this.quickLook.hide(); this.dialog = $('<div/>').append(this.view.win.css('width', '100%').attr('undocked', true).show()).dialog(this.options.dialog); dialogResize(); } } } /** * Translate message into selected language * * @param String message in english * @param String translated or original message */ elFinder.prototype.i18n = function(m) { return this.options.i18n[this.options.lang] && this.options.i18n[this.options.lang][m] ? this.options.i18n[this.options.lang][m] : m; } /** * Default config * */ elFinder.prototype.options = { /* connector url. Required! */ url : '', /* interface language */ lang : 'en', /* additional css class for filemanager container */ cssClass : '', /* characters number to wrap file name in icons view. set to 0 to disable wrap */ wrap : 14, /* Name for places/favorites (i18n), set to '' to disable places */ places : 'Places', /* show places before navigation? */ placesFirst : true, /* callback to get file url (for wswing editors) */ editorCallback : null, /* string to cut from file url begin before pass it to editorCallback. variants: '' - nothing to cut, 'root' - cut root url, 'http://...' - string if it exists in the beginig of url */ cutURL : '', /* close elfinder after editorCallback */ closeOnEditorCallback : true, /* i18 messages. not set manually! */ i18n : {}, /* fm view (icons|list) */ view : 'icons', /* width to overwrite css options */ width : '', /* height to overwrite css options. Attenion! this is heigt of navigation/cwd panels! not total fm height */ height : '', /* disable shortcuts exclude arrows/space */ disableShortcuts : false, /* open last visited dir after reload page or close and open browser */ rememberLastDir : true, /* cookie options */ cookie : { expires : 30, domain : '', path : '/', secure : false }, /* buttons on toolbar */ toolbar : [ ['back', 'reload'], ['select', 'open'], ['mkdir', 'mkfile', 'upload'], ['copy', 'paste', 'rm'], ['rename', 'edit'], ['info', 'quicklook', 'resize'], ['icons', 'list'], ['help'] ], /* contextmenu commands */ contextmenu : { 'cwd' : ['reload', 'delim', 'mkdir', 'mkfile', 'upload', 'delim', 'paste', 'delim', 'info'], 'file' : ['select', 'open', 'quicklook', 'delim', 'copy', 'cut', 'rm', 'delim', 'duplicate', 'rename', 'edit', 'resize', 'archive', 'extract', 'delim', 'info'], 'group' : ['select', 'copy', 'cut', 'rm', 'delim', 'archive', 'extract', 'delim', 'info'] }, /* jqueryUI dialog options */ dialog : null, /* docked mode */ docked : false, /* auto reload time (min) */ autoReload : 0, /* set to true if you need to select several files at once from editorCallback */ selectMultiple : false } $.fn.elfinder = function(o) { return this.each(function() { var cmd = typeof(o) == 'string' ? o : ''; if (!this.elfinder) { this.elfinder = new elFinder(this, typeof(o) == 'object' ? o : {}) } switch(cmd) { case 'close': case 'hide': this.elfinder.close(); break; case 'open': case 'show': this.elfinder.open(); break; case 'dock': this.elfinder.dock(); break; case 'undock': this.elfinder.undock(); break; case'destroy': this.elfinder.destroy(); break; } }) } })(jQuery); (function($) { elFinder.prototype.view = function(fm, el) { var self = this; this.fm = fm; /** * Object. Mimetypes to kinds mapping **/ this.kinds = { 'unknown' : 'Unknown', 'directory' : 'Folder', 'symlink' : 'Alias', 'symlink-broken' : 'Broken alias', 'application/x-empty' : 'Plain text', 'application/postscript' : 'Postscript document', 'application/octet-stream' : 'Application', 'application/vnd.ms-office' : 'Microsoft Office document', 'application/vnd.ms-word' : 'Microsoft Word document', 'application/vnd.ms-excel' : 'Microsoft Excel document', 'application/vnd.ms-powerpoint' : 'Microsoft Powerpoint presentation', 'application/pdf' : 'Portable Document Format (PDF)', 'application/vnd.oasis.opendocument.text' : 'Open Office document', 'application/x-shockwave-flash' : 'Flash application', 'application/xml' : 'XML document', 'application/x-bittorrent' : 'Bittorrent file', 'application/x-7z-compressed' : '7z archive', 'application/x-tar' : 'TAR archive', 'application/x-gzip' : 'GZIP archive', 'application/x-bzip2' : 'BZIP archive', 'application/zip' : 'ZIP archive', 'application/x-rar' : 'RAR archive', 'application/javascript' : 'Javascript application', 'text/plain' : 'Plain text', 'text/x-php' : 'PHP source', 'text/html' : 'HTML document', 'text/javascript' : 'Javascript source', 'text/css' : 'CSS style sheet', 'text/rtf' : 'Rich Text Format (RTF)', 'text/rtfd' : 'RTF with attachments (RTFD)', 'text/x-c' : 'C source', 'text/x-c++' : 'C++ source', 'text/x-shellscript' : 'Unix shell script', 'text/x-python' : 'Python source', 'text/x-java' : 'Java source', 'text/x-ruby' : 'Ruby source', 'text/x-perl' : 'Perl script', 'text/xml' : 'XML document', 'image/x-ms-bmp' : 'BMP image', 'image/jpeg' : 'JPEG image', 'image/gif' : 'GIF Image', 'image/png' : 'PNG image', 'image/x-targa' : 'TGA image', 'image/tiff' : 'TIFF image', 'image/vnd.adobe.photoshop' : 'Adobe Photoshop image', 'audio/mpeg' : 'MPEG audio', 'audio/midi' : 'MIDI audio', 'audio/ogg' : 'Ogg Vorbis audio', 'audio/mp4' : 'MP4 audio', 'audio/wav' : 'WAV audio', 'video/x-dv' : 'DV video', 'video/mp4' : 'MP4 video', 'video/mpeg' : 'MPEG video', 'video/x-msvideo' : 'AVI video', 'video/quicktime' : 'Quicktime video', 'video/x-ms-wmv' : 'WM video', 'video/x-flv' : 'Flash video', 'video/x-matroska' : 'Matroska video' } this.tlb = $('<ul />'); this.nav = $('<div class="el-finder-nav"/>').resizable({handles : 'e', autoHide : true, minWidth : 200, maxWidth: 500}); this.cwd = $('<div class="el-finder-cwd"/>').attr('unselectable', 'on'); this.spn = $('<div class="el-finder-spinner"/>'); this.err = $('<p class="el-finder-err"><strong/></p>').click(function() { $(this).hide(); }); this.nfo = $('<div class="el-finder-stat"/>'); this.pth = $('<div class="el-finder-path"/>'); this.sel = $('<div class="el-finder-sel"/>'); this.stb = $('<div class="el-finder-statusbar"/>') .append(this.pth) .append(this.nfo) .append(this.sel); this.wrz = $('<div class="el-finder-workzone" />') .append(this.nav) .append(this.cwd) .append(this.spn) .append(this.err) .append('<div style="clear:both" />'); this.win = $(el).empty().attr('id', this.fm.id).addClass('el-finder '+(fm.options.cssClass||'')) .append($('<div class="el-finder-toolbar" />').append(this.tlb)) .append(this.wrz) .append(this.stb); this.tree = $('<ul class="el-finder-tree"></ul>').appendTo(this.nav); this.plc = $('<ul class="el-finder-places"><li><a href="#" class="el-finder-places-root"><div/>'+this.fm.i18n(this.fm.options.places)+'</a><ul/></li></ul>').hide(); this.nav[this.fm.options.placesFirst ? 'prepend' : 'append'](this.plc); /* * Render ajax spinner */ this.spinner = function(show) { this.win.toggleClass('el-finder-disabled', show); this.spn.toggle(show); } /* * Display ajax error */ this.fatal = function(t) { self.error(t.status != '404' ? 'Invalid backend configuration' : 'Unable to connect to backend') } /* * Render error */ this.error = function(err, data) { this.fm.lock(); this.err.show().children('strong').html(this.fm.i18n(err)+'!'+this.formatErrorData(data)); setTimeout(function() { self.err.fadeOut('slow'); }, 4000); } /* * Render navigation panel with dirs tree */ this.renderNav = function(tree) { var d = tree.dirs.length ? traverse(tree.dirs) : '', li = '<li><a href="#" class="el-finder-tree-root" key="'+tree.hash+'"><div'+(d ? ' class="collapsed expanded"' : '')+'/>'+tree.name+'</a>'+d+'</li>'; this.tree.html(li); this.fm.options.places && this.renderPlaces(); function traverse(tree) { var i, hash, c, html = '<ul style="display:none">'; for (i=0; i < tree.length; i++) { if (!tree[i].name || !tree[i].hash) { continue; } c = ''; if (!tree[i].read && !tree[i].write) { c = 'noaccess'; } else if (!tree[i].read) { c = 'dropbox'; } else if (!tree[i].write) { c = 'readonly'; } html += '<li><a href="#" class="'+c+'" key="'+tree[i].hash+'"><div'+(tree[i].dirs.length ? ' class="collapsed"' : '')+'/>'+tree[i].name+'</a>'; if (tree[i].dirs.length) { html += traverse(tree[i].dirs); } html += '</li>'; } return html +'</ul>'; } } /* * Render places */ this.renderPlaces = function() { var i, c, pl = this.fm.getPlaces(), ul = this.plc.show().find('ul').empty().hide(); $('div:first', this.plc).removeClass('collapsed expanded'); if (pl.length) { pl.sort(function(a, b) { var _a = self.tree.find('a[key="'+a+'"]').text()||'', _b = self.tree.find('a[key="'+b+'"]').text()||''; return _a.localeCompare(_b); }); for (i=0; i < pl.length; i++) { if ((c = this.tree.find('a[key="'+pl[i]+'"]:not(.dropbox)').parent()) && c.length) { ul.append(c.clone().children('ul').remove().end().find('div').removeClass('collapsed expanded').end()); } else { this.fm.removePlace(pl[i]); } }; ul.children().length && $('div:first', this.plc).addClass('collapsed'); } } /* * Render current directory */ this.renderCwd = function() { this.cwd.empty(); var num = 0, size = 0, html = ''; for (var hash in this.fm.cdc) { num++; size += this.fm.cdc[hash].size; html += this.fm.options.view == 'icons' ? this.renderIcon(this.fm.cdc[hash]) : this.renderRow(this.fm.cdc[hash], num%2); } if (this.fm.options.view == 'icons') { this.cwd.append(html); } else { this.cwd.append('<table><tr><th colspan="2">'+this.fm.i18n('Name')+'</th><th>'+this.fm.i18n('Permissions')+'</th><th>'+this.fm.i18n('Modified')+'</th><th class="size">'+this.fm.i18n('Size')+'</th><th>'+this.fm.i18n('Kind')+'</th></tr>'+html+'</table>'); } this.pth.text(fm.cwd.rel); this.nfo.text(fm.i18n('items')+': '+num+', '+this.formatSize(size)); this.sel.empty(); } /* * Render one file as icon */ this.renderIcon = function(f) { var str = '<p'+(f.tmb ? ' style="'+"background:url('"+f.tmb+"') 0 0 no-repeat"+'"' : '')+'/><label>'+this.formatName(f.name)+'</label>'; if (f.link || f.mime == 'symlink-broken') { str += '<em/>'; } if (!f.read && !f.write) { str += '<em class="noaccess"/>'; } else if (f.read && !f.write) { str += '<em class="readonly"/>'; } else if (!f.read && f.write) { str += '<em class="'+(f.mime == 'directory' ? 'dropbox' :'noread')+'" />'; } return '<div class="'+this.mime2class(f.mime)+'" key="'+f.hash+'">'+str+'</div>'; } /* * Render one file as table row */ this.renderRow = function(f, odd) { var str = f.link || f.mime =='symlink-broken' ? '<em/>' : ''; if (!f.read && !f.write) { str += '<em class="noaccess"/>'; } else if (f.read && !f.write) { str += '<em class="readonly"/>'; } else if (!f.read && f.write) { str += '<em class="'+(f.mime == 'directory' ? 'dropbox' :'noread')+'" />'; } return '<tr key="'+f.hash+'" class="'+self.mime2class(f.mime)+(odd ? ' el-finder-row-odd' : '')+'"><td class="icon"><p>'+str+'</p></td><td>'+f.name+'</td><td>'+self.formatPermissions(f.read, f.write, f.rm)+'</td><td>'+self.formatDate(f.date)+'</td><td class="size">'+self.formatSize(f.size)+'</td><td>'+self.mime2kind(f.link ? 'symlink' : f.mime)+'</td></tr>'; } /* * Re-render file (after editing) */ this.updateFile = function(f) { var e = this.cwd.find('[key="'+f.hash+'"]'); e.replaceWith(e[0].nodeName == 'DIV' ? this.renderIcon(f) : this.renderRow(f)); } /* * Update info about selected files */ this.selectedInfo = function() { var i, s = 0, sel; if (self.fm.selected.length) { sel = this.fm.getSelected(); for (i=0; i<sel.length; i++) { s += sel[i].size; } } this.sel.text(i>0 ? this.fm.i18n('selected items')+': '+sel.length+', '+this.formatSize(s) : ''); } /* * Return wraped file name if needed */ this.formatName = function(n) { var w = self.fm.options.wrap; if (w>0) { if (n.length > w*2) { return n.substr(0, w)+"&shy;"+n.substr(w, w-5)+"&hellip;"+n.substr(n.length-3); } else if (n.length > w) { return n.substr(0, w)+"&shy;"+n.substr(w); } } return n; } /* * Return error message */ this.formatErrorData = function(data) { var i, err = '' if (typeof(data) == 'object') { err = '<br />'; for (i in data) { err += i+' '+self.fm.i18n(data[i])+'<br />'; } } return err; } /* * Convert mimetype into css class */ this.mime2class = function(mime) { return mime.replace('/' , ' ').replace(/\./g, '-'); } /* * Return localized date */ this.formatDate = function(d) { return d.replace(/([a-z]+)\s/i, function(a1, a2) { return self.fm.i18n(a2)+' '; }); } /* * Return formated file size */ this.formatSize = function(s) { var n = 1, u = 'bytes'; if (s > 1073741824) { n = 1073741824; u = 'Gb'; } else if (s > 1048576) { n = 1048576; u = 'Mb'; } else if (s > 1024) { n = 1024; u = 'Kb'; } return Math.round(s/n)+' '+u; } /* * Return localized string with file permissions */ this.formatPermissions = function(r, w, rm) { var p = []; r && p.push(self.fm.i18n('read')); w && p.push(self.fm.i18n('write')); rm && p.push(self.fm.i18n('remove')); return p.join('/'); } /* * Return kind of file */ this.mime2kind = function(mime) { return this.fm.i18n(this.kinds[mime]||'unknown'); } } })(jQuery); /** * @class elFinder user Interface. * @author dio dio@std42.ru **/ (function($) { elFinder.prototype.ui = function(fm) { var self = this; this.fm = fm; this.cmd = {}; this.buttons = {}; this.menu = $('<div class="el-finder-contextmenu" />').appendTo(document.body).hide(); this.dockButton = $('<div class="el-finder-dock-button" title="'+self.fm.i18n('Dock/undock filemanager window')+'" />'); this.exec = function(cmd, arg) { if (this.cmd[cmd]) { if (cmd != 'open' && !this.cmd[cmd].isAllowed()) { return this.fm.view.error('Command not allowed'); } if (!this.fm.locked) { this.fm.quickLook.hide(); $('.el-finder-info').remove(); this.cmd[cmd].exec(arg); this.update(); } } } this.cmdName = function(cmd) { if (this.cmd[cmd] && this.cmd[cmd].name) { return cmd == 'archive' && this.fm.params.archives.length == 1 ? this.fm.i18n('Create')+' '+this.fm.view.mime2kind(this.fm.params.archives[0]).toLowerCase() : this.fm.i18n(this.cmd[cmd].name); } return cmd; } this.isCmdAllowed = function(cmd) { return self.cmd[cmd] && self.cmd[cmd].isAllowed(); } this.execIfAllowed = function(cmd) { this.isCmdAllowed(cmd) && this.exec(cmd); } this.includeInCm = function(cmd, t) { return this.isCmdAllowed(cmd) && this.cmd[cmd].cm(t); } this.showMenu = function(e) { var t, win, size, id = ''; this.hideMenu(); if (!self.fm.selected.length) { t = 'cwd'; } else if (self.fm.selected.length == 1) { t = 'file'; } else { t = 'group'; } menu(t); win = $(window); size = { height : win.height(), width : win.width(), sT : win.scrollTop(), cW : this.menu.width(), cH : this.menu.height() }; this.menu.css({ left : ((e.clientX + size.cW) > size.width ? ( e.clientX - size.cW) : e.clientX), top : ((e.clientY + size.cH) > size.height && e.clientY > size.cH ? (e.clientY + size.sT - size.cH) : e.clientY + size.sT) }) .show() .find('div[name]') .hover( function() { var t = $(this), s = t.children('div'), w; t.addClass('hover'); if (s.length) { if (!s.attr('pos')) { w = t.outerWidth(); s.css($(window).width() - w - t.offset().left > s.width() ? 'left' : 'right', w-5).attr('pos', true); } s.show(); } }, function() { $(this).removeClass('hover').children('div').hide(); } ).click(function(e) { e.stopPropagation(); var t = $(this); if (!t.children('div').length) { self.hideMenu(); self.exec(t.attr('name'), t.attr('argc')); } }); function menu(t) { var i, j, a, html, l, src = self.fm.options.contextmenu[t]||[]; for (i=0; i < src.length; i++) { if (src[i] == 'delim') { self.menu.children().length && !self.menu.children(':last').hasClass('delim') && self.menu.append('<div class="delim" />'); } else if (self.fm.ui.includeInCm(src[i], t)) { a = self.cmd[src[i]].argc(); html = ''; if (a.length) { html = '<span/><div class="el-finder-contextmenu-sub" style="z-index:'+(parseInt(self.menu.css('z-index'))+1)+'">'; for (var j=0; j < a.length; j++) { html += '<div name="'+src[i]+'" argc="'+a[j].argc+'" class="'+a[j]['class']+'">'+a[j].text+'</div>'; }; html += '</div>'; } self.menu.append('<div class="'+src[i]+'" name="'+src[i]+'">'+html+self.cmdName(src[i])+'</div>'); } }; } } this.hideMenu = function() { this.menu.hide().empty(); } this.update = function() { for (var i in this.buttons) { this.buttons[i].toggleClass('disabled', !this.cmd[i].isAllowed()); } } this.init = function(disabled) { var i, j, n, c=false, zindex = 2, z, t = this.fm.options.toolbar; /* disable select command if there is no callback for it */ if (!this.fm.options.editorCallback) { disabled.push('select'); } /* disable archive command if no archivers enabled */ if (!this.fm.params.archives.length && $.inArray('archive', disabled) == -1) { disabled.push('archive'); } for (i in this.commands) { if ($.inArray(i, disabled) == -1) { this.commands[i].prototype = this.command.prototype; this.cmd[i] = new this.commands[i](this.fm); } } for (i=0; i<t.length; i++) { if (c) { this.fm.view.tlb.append('<li class="delim" />'); } c = false; for (j=0; j<t[i].length; j++) { n = t[i][j]; if (this.cmd[n]) { c = true; this.buttons[n] = $('<li class="'+n+'" title="'+this.cmdName(n)+'" name="'+n+'" />') .appendTo(this.fm.view.tlb) .click(function(e) { e.stopPropagation(); }) .bind('click', (function(ui){ return function() { !$(this).hasClass('disabled') && ui.exec($(this).attr('name')); } })(this) ).hover( function() { !$(this).hasClass('disabled') && $(this).addClass('el-finder-tb-hover')}, function() { $(this).removeClass('el-finder-tb-hover')} ); } } } this.update(); /* set z-index for context menu */ this.menu.css('z-index', this.fm.zIndex); if (this.fm.options.docked) { this.dockButton.hover( function() { $(this).addClass('el-finder-dock-button-hover')}, function() { $(this).removeClass('el-finder-dock-button-hover')} ).click(function() { self.fm.view.win.attr('undocked') ? self.fm.dock() : self.fm.undock(); $(this).trigger('mouseout'); }).prependTo(this.fm.view.tlb); } } } /** * @class elFinder user Interface Command. * @author dio dio@std42.ru **/ elFinder.prototype.ui.prototype.command = function(fm) { } /** * Return true if command can be applied now * @return Boolean **/ elFinder.prototype.ui.prototype.command.prototype.isAllowed = function() { return true; } /** * Return true if command can be included in contextmenu of required type * @param String contextmenu type (cwd|group|file) * @return Boolean **/ elFinder.prototype.ui.prototype.command.prototype.cm = function(t) { return false; } /** * Return not empty array if command required submenu in contextmenu * @return Array **/ elFinder.prototype.ui.prototype.command.prototype.argc = function(t) { return []; } elFinder.prototype.ui.prototype.commands = { /** * @class Go into previous folder * @param Object elFinder **/ back : function(fm) { var self = this; this.name = 'Back'; this.fm = fm; this.exec = function() { if (this.fm.history.length) { this.fm.ajax({ cmd : 'open', target : this.fm.history.pop() }, function(data) { self.fm.reload(data); }); } } this.isAllowed = function() { return this.fm.history.length } }, /** * @class Reload current directory and navigation panel * @param Object elFinder **/ reload : function(fm) { var self = this; this.name = 'Reload'; this.fm = fm; this.exec = function() { this.fm.ajax({ cmd : 'open', target : this.fm.cwd.hash, tree : true }, function(data) { self.fm.reload(data); }); } this.cm = function(t) { return t == 'cwd'; } }, /** * @class Open file/folder * @param Object elFinder **/ open : function(fm) { var self = this; this.name = 'Open'; this.fm = fm; /** * Open file/folder * @param String file/folder id (only from click on nav tree) **/ this.exec = function(dir) { var t = null; if (dir) { t = { hash : $(dir).attr('key'), mime : 'directory', read : !$(dir).hasClass('noaccess') && !$(dir).hasClass('dropbox') } } else { t = this.fm.getSelected(0); } if (!t.hash) { return; } if (!t.read) { return this.fm.view.error('Access denied'); } if (t.type == 'link' && !t.link) { return this.fm.view.error('Unable to open broken link'); } if (t.mime == 'directory') { openDir(t.link||t.hash); } else { openFile(t); } function openDir(id) { self.fm.history.push(self.fm.cwd.hash); self.fm.ajax({ cmd : 'open', target : id }, function(data) { self.fm.reload(data); }); } function openFile(f) { var s, ws = ''; if (f.dim) { s = f.dim.split('x'); ws = 'width='+(parseInt(s[0])+20)+',height='+(parseInt(s[1])+20)+','; } window.open(f.url||self.fm.options.url+'?cmd=open&current='+(f.parent||self.fm.cwd.hash)+'&target='+(f.link||f.hash), false, 'top=50,left=50,'+ws+'scrollbars=yes,resizable=yes'); } } this.isAllowed = function() { return this.fm.selected.length == 1 && this.fm.getSelected(0).read; } this.cm = function(t) { return t == 'file'; } }, /** * @class. Return file url * @param Object elFinder **/ select : function(fm) { this.name = 'Select file'; this.fm = fm; if (fm.options.selectMultiple) { this.exec = function() { var selected = $(fm.getSelected()).map(function() { return fm.options.cutURL == 'root' ? this.url.substr(fm.params.url.length) : this.url.replace(new RegExp('^('+fm.options.cutURL+')'), ''); }); fm.options.editorCallback(selected); if (fm.options.closeOnEditorCallback) { fm.dock(); fm.close(); } } } else { this.exec = function() { var f = this.fm.getSelected(0); if (!f.url) { return this.fm.view.error('File URL disabled by connector config'); } this.fm.options.editorCallback(this.fm.options.cutURL == 'root' ? f.url.substr(this.fm.params.url.length) : f.url.replace(new RegExp('^('+this.fm.options.cutURL+')'), '')); if (this.fm.options.closeOnEditorCallback) { this.fm.dock(); this.fm.close(); this.fm.destroy(); } } } this.isAllowed = function() { return ((this.fm.options.selectMultiple && this.fm.selected.length >= 1) || this.fm.selected.length == 1) && !/(symlink\-broken|directory)/.test(this.fm.getSelected(0).mime); } this.cm = function(t) { return t != 'cwd'; // return t == 'file'; } }, /** * @class. Open/close quickLook window * @param Object elFinder **/ quicklook : function(fm) { var self = this; this.name = 'Preview with Quick Look'; this.fm = fm; this.exec = function() { self.fm.quickLook.toggle(); } this.isAllowed = function() { return this.fm.selected.length == 1; } this.cm = function() { return true; } }, /** * @class Display files/folders info in dialog window * @param Object elFinder **/ info : function(fm) { var self = this; this.name = 'Get info'; this.fm = fm; /** * Open dialog windows for each selected file/folder or for current folder **/ this.exec = function() { var f, s, cnt = this.fm.selected.length, w = $(window).width(), h = $(window).height(); this.fm.lockShortcuts(true); if (!cnt) { /** nothing selected - show cwd info **/ info(self.fm.cwd); } else { /** show info for each selected obj **/ $.each(this.fm.getSelected(), function() { info(this); }); } function info(f) { var p = ['50%', '50%'], x, y, d, tb = '<table cellspacing="0"><tr><td>'+self.fm.i18n('Name')+'</td><td>'+f.name+'</td></tr><tr><td>'+self.fm.i18n('Kind')+'</td><td>'+self.fm.view.mime2kind(f.link ? 'symlink' : f.mime)+'</td></tr><tr><td>'+self.fm.i18n('Size')+'</td><td>'+self.fm.view.formatSize(f.size)+'</td></tr><tr><td>'+self.fm.i18n('Modified')+'</td><td>'+self.fm.view.formatDate(f.date)+'</td></tr><tr><td>'+self.fm.i18n('Permissions')+'</td><td>'+self.fm.view.formatPermissions(f.read, f.write, f.rm)+'</td></tr>'; if (f.link) { tb += '<tr><td>'+self.fm.i18n('Link to')+'</td><td>'+f.linkTo+'</td></tr>'; } if (f.dim) { tb += '<tr><td>'+self.fm.i18n('Dimensions')+'</td><td>'+f.dim+' px.</td></tr>'; } if (f.url) { tb += '<tr><td>'+self.fm.i18n('URL')+'</td><td><a href="'+f.url+'" target="_blank">'+f.url+'</a></td></tr>'; } if (cnt>1) { d = $('.el-finder-dialog-info:last'); if (!d.length) { x = Math.round(((w-350)/2)-(cnt*10)); y = Math.round(((h-300)/2)-(cnt*10)); p = [x>20?x:20, y>20?y:20]; } else { x = d.offset().left+10; y = d.offset().top+10; p = [x<w-350 ? x : 20, y<h-300 ? y : 20]; } } $('<div />').append(tb+'</table>').dialog({ dialogClass : 'el-finder-dialog el-finder-dialog-info', width : 390, position : p, title : self.fm.i18n(f.mime == 'directory' ? 'Folder info' : 'File info'), close : function() { if (--cnt <= 0) { self.fm.lockShortcuts(); } $(this).dialog('destroy'); }, buttons : { Ok : function() { $(this).dialog('close'); }} }); } } this.cm = function(t) { return true; } }, /** * @class Rename file/folder * @param Object elFinder **/ rename : function(fm) { var self = this; this.name = 'Rename'; this.fm = fm; this.exec = function() { var s = this.fm.getSelected(), el, c, input, f, n; if (s.length == 1) { f = s[0]; el = this.fm.view.cwd.find('[key="'+f.hash+'"]'); c = this.fm.options.view == 'icons' ? el.children('label') : el.find('td').eq(1); n = c.html(); input = $('<input type="text" />').val(f.name).appendTo(c.empty()) .bind('change blur', rename) .keydown(function(e) { e.stopPropagation(); if (e.keyCode == 27) { restore(); } else if (e.keyCode == 13) { if (f.name == input.val()) { restore(); } else { $(this).trigger('change'); } } }) .click(function(e) { e.stopPropagation(); }) .select() .focus(); this.fm.lockShortcuts(true); } function restore() { c.html(n); self.fm.lockShortcuts(); } function rename() { if (!self.fm.locked) { var err, name = input.val(); if (f.name == input.val()) { return restore(); } if (!self.fm.isValidName(name)) { err = 'Invalid name'; } else if (self.fm.fileExists(name)) { err = 'File or folder with the same name already exists'; } if (err) { self.fm.view.error(err); el.addClass('ui-selected'); self.fm.lockShortcuts(true); return input.select().focus(); } self.fm.ajax({cmd : 'rename', current : self.fm.cwd.hash, target : f.hash, name : name}, function(data) { if (data.error) { restore(); } else { f.mime == 'directory' && self.fm.removePlace(f.hash) && self.fm.addPlace(data.target); self.fm.reload(data); } }, { force : true }); } } } /** * Return true if only one file selected and has write perms and current dir has write perms * @return Boolean */ this.isAllowed = function() { return this.fm.cwd.write && this.fm.getSelected(0).write; } this.cm = function(t) { return t == 'file'; } }, /** * @class Copy file/folder to "clipboard" * @param Object elFinder **/ copy : function(fm) { this.name = 'Copy'; this.fm = fm; this.exec = function() { this.fm.setBuffer(this.fm.selected); } this.isAllowed = function() { if (this.fm.selected.length) { var s = this.fm.getSelected(), l = s.length; while (l--) { if (s[l].read) { return true; } } } return false; } this.cm = function(t) { return t != 'cwd'; } }, /** * @class Cut file/folder to "clipboard" * @param Object elFinder **/ cut : function(fm) { this.name = 'Cut'; this.fm = fm; this.exec = function() { this.fm.setBuffer(this.fm.selected, 1); } this.isAllowed = function() { if (this.fm.selected.length) { var s = this.fm.getSelected(), l = s.length; while (l--) { if (s[l].read && s[l].rm) { return true; } } } return false; } this.cm = function(t) { return t != 'cwd'; } }, /** * @class Paste file/folder from "clipboard" * @param Object elFinder **/ paste : function(fm) { var self = this; this.name = 'Paste'; this.fm = fm; this.exec = function() { var i, d, f, r, msg = ''; if (!this.fm.buffer.dst) { this.fm.buffer.dst = this.fm.cwd.hash; } d = this.fm.view.tree.find('[key="'+this.fm.buffer.dst+'"]'); if (!d.length || d.hasClass('noaccess') || d.hasClass('readonly')) { return this.fm.view.error('Access denied'); } if (this.fm.buffer.src == this.fm.buffer.dst) { return this.fm.view.error('Unable to copy into itself'); } var o = { cmd : 'paste', current : this.fm.cwd.hash, src : this.fm.buffer.src, dst : this.fm.buffer.dst, cut : this.fm.buffer.cut }; if (this.fm.jquery>132) { o.targets = this.fm.buffer.files; } else { o['targets[]'] = this.fm.buffer.files; } this.fm.ajax(o, function(data) { data.cdc && self.fm.reload(data); }, {force : true}); } this.isAllowed = function() { return this.fm.buffer.files; } this.cm = function(t) { return t == 'cwd'; } }, /** * @class Remove files/folders * @param Object elFinder **/ rm : function(fm) { var self = this; this.name = 'Remove'; this.fm = fm; this.exec = function() { var i, ids = [], s =this.fm.getSelected(); for (var i=0; i < s.length; i++) { if (!s[i].rm) { return this.fm.view.error(s[i].name+': '+this.fm.i18n('Access denied')); } ids.push(s[i].hash); }; if (ids.length) { this.fm.lockShortcuts(true); $('<div><div class="ui-state-error ui-corner-all"><span class="ui-icon ui-icon-alert"/><strong>'+this.fm.i18n('Are you sure you want to remove files?<br /> This cannot be undone!')+'</strong></div></div>') .dialog({ title : this.fm.i18n('Confirmation required'), dialogClass : 'el-finder-dialog', width : 350, close : function() { self.fm.lockShortcuts(); }, buttons : { Cancel : function() { $(this).dialog('close'); }, Ok : function() { $(this).dialog('close'); var o = { cmd : 'rm', current : self.fm.cwd.hash }; if (self.fm.jquery > 132) { o.targets = ids; } else { o['targets[]'] = ids; } self.fm.ajax(o, function(data) { data.tree && self.fm.reload(data); }, {force : true}); } } }); } } this.isAllowed = function(f) { if (this.fm.selected.length) { var s = this.fm.getSelected(), l = s.length; while (l--) { if (s[l].rm) { return true; } } } return false; } this.cm = function(t) { return t != 'cwd'; } }, /** * @class Create new folder * @param Object elFinder **/ mkdir : function(fm) { var self = this; this.name = 'New folder'; this.fm = fm; this.exec = function() { self.fm.unselectAll(); var n = this.fm.uniqueName('untitled folder'); input = $('<input type="text"/>').val(n); prev = this.fm.view.cwd.find('.directory:last'); f = {name : n, hash : '', mime :'directory', read : true, write : true, date : '', size : 0}, el = this.fm.options.view == 'list' ? $(this.fm.view.renderRow(f)).children('td').eq(1).empty().append(input).end().end() : $(this.fm.view.renderIcon(f)).children('label').empty().append(input).end() el.addClass('directory ui-selected'); if (prev.length) { el.insertAfter(prev); } else if (this.fm.options.view == 'list') { el.insertAfter(this.fm.view.cwd.find('tr').eq(0)) } else { el.prependTo(this.fm.view.cwd) } self.fm.checkSelectedPos(); input.select().focus() .click(function(e) { e.stopPropagation(); }) .bind('change blur', mkdir) .keydown(function(e) { e.stopPropagation(); if (e.keyCode == 27) { el.remove(); self.fm.lockShortcuts(); } else if (e.keyCode == 13) { mkdir(); } }); self.fm.lockShortcuts(true); function mkdir() { if (!self.fm.locked) { var err, name = input.val(); if (!self.fm.isValidName(name)) { err = 'Invalid name'; } else if (self.fm.fileExists(name)) { err = 'File or folder with the same name already exists'; } if (err) { self.fm.view.error(err); self.fm.lockShortcuts(true); el.addClass('ui-selected'); return input.select().focus(); } self.fm.ajax({cmd : 'mkdir', current : self.fm.cwd.hash, name : name}, function(data) { if (data.error) { el.addClass('ui-selected'); return input.select().focus(); } self.fm.reload(data); }, {force : true}); } } } this.isAllowed = function() { return this.fm.cwd.write; } this.cm = function(t) { return t == 'cwd'; } }, /** * @class Create new text file * @param Object elFinder **/ mkfile : function(fm) { var self = this; this.name = 'New text file'; this.fm = fm; this.exec = function() { self.fm.unselectAll(); var n = this.fm.uniqueName('untitled file', '.txt'), input = $('<input type="text"/>').val(n), f = {name : n, hash : '', mime :'text/plain', read : true, write : true, date : '', size : 0}, el = this.fm.options.view == 'list' ? $(this.fm.view.renderRow(f)).children('td').eq(1).empty().append(input).end().end() : $(this.fm.view.renderIcon(f)).children('label').empty().append(input).end(); el.addClass('text ui-selected').appendTo(this.fm.options.view == 'list' ? self.fm.view.cwd.children('table') : self.fm.view.cwd); input.select().focus() .bind('change blur', mkfile) .click(function(e) { e.stopPropagation(); }) .keydown(function(e) { e.stopPropagation(); if (e.keyCode == 27) { el.remove(); self.fm.lockShortcuts(); } else if (e.keyCode == 13) { mkfile(); } }); self.fm.lockShortcuts(true); function mkfile() { if (!self.fm.locked) { var err, name = input.val(); if (!self.fm.isValidName(name)) { err = 'Invalid name'; } else if (self.fm.fileExists(name)) { err = 'File or folder with the same name already exists'; } if (err) { self.fm.view.error(err); self.fm.lockShortcuts(true); el.addClass('ui-selected'); return input.select().focus(); } self.fm.ajax({cmd : 'mkfile', current : self.fm.cwd.hash, name : name}, function(data) { if (data.error) { el.addClass('ui-selected'); return input.select().focus(); } self.fm.reload(data); }, {force : true }); } } } this.isAllowed = function(f) { return this.fm.cwd.write; } this.cm = function(t) { return t == 'cwd'; } }, /** * @class Upload files * @param Object elFinder **/ upload : function(fm) { var self = this; this.name = 'Upload files'; this.fm = fm; this.exec = function() { var id = 'el-finder-io-'+(new Date().getTime()), e = $('<div class="ui-state-error ui-corner-all"><span class="ui-icon ui-icon-alert"/><div/></div>'), m = this.fm.params.uplMaxSize ? '<p>'+this.fm.i18n('Maximum allowed files size')+': '+this.fm.params.uplMaxSize+'</p>' : '', b = $('<p class="el-finder-add-field"><span class="ui-state-default ui-corner-all"><em class="ui-icon ui-icon-circle-plus"/></span>'+this.fm.i18n('Add field')+'</p>') .click(function() { $(this).before('<p><input type="file" name="upload[]"/></p>'); }), f = '<form method="post" enctype="multipart/form-data" action="'+self.fm.options.url+'" target="'+id+'"><input type="hidden" name="cmd" value="upload" /><input type="hidden" name="current" value="'+self.fm.cwd.hash+'" />', d = $('<div/>'), i = 3; while (i--) { f += '<p><input type="file" name="upload[]"/></p>'; } // Rails csrf meta tag (for XSS protection), see #256 var rails_csrf_token = $('meta[name=csrf-token]').attr('content'); var rails_csrf_param = $('meta[name=csrf-param]').attr('content'); if (rails_csrf_param != null && rails_csrf_token != null) { f += '<input name="'+rails_csrf_param+'" value="'+rails_csrf_token+'" type="hidden" />'; } f = $(f+'</form>'); d.append(f.append(e.hide()).prepend(m).append(b)).dialog({ dialogClass : 'el-finder-dialog', title : self.fm.i18n('Upload files'), modal : true, resizable : false, close : function() { self.fm.lockShortcuts(); }, buttons : { Cancel : function() { $(this).dialog('close'); }, Ok : function() { if (!$(':file[value]', f).length) { return error(self.fm.i18n('Select at least one file to upload')); } setTimeout(function() { self.fm.lock(); if ($.browser.safari) { $.ajax({ url : self.fm.options.url, data : {cmd : 'ping'}, error : submit, success : submit }); } else { submit(); } }); $(this).dialog('close'); } } }); self.fm.lockShortcuts(true); function error(err) { e.show().find('div').empty().text(err); } function submit() { var $io = $('<iframe name="'+id+'" name="'+id+'" src="about:blank"/>'), io = $io[0], cnt = 50, doc, html, data; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }) .appendTo('body').bind('load', function() { $io.unbind('load'); result(); }); self.fm.lock(true); f.submit(); function result() { try { doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; /* opera */ if (doc.body == null || doc.body.innerHTML == '') { if (--cnt) { return setTimeout(result, 100); } else { complite(); return self.fm.view.error('Unable to access iframe DOM after 50 tries'); } } /* get server response */ html = $(doc.body).html(); if (self.fm.jquery>=141) { data = $.parseJSON(html); } else if ( /^[\],:{}\s]*$/.test(html.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { /* get from jQuery 1.4 */ data = window.JSON && window.JSON.parse ? window.JSON.parse(html) : (new Function("return " + html))(); } else { data = { error : 'Unable to parse server response' }; } } catch(e) { data = { error : 'Unable to parse server response' }; } complite(); data.error && self.fm.view.error(data.error, data.errorData); data.cwd && self.fm.reload(data); data.tmb && self.fm.tmb(); } function complite() { self.fm.lock(); $io.remove(); } } } this.isAllowed = function() { return this.fm.cwd.write; } this.cm = function(t) { return t == 'cwd'; } }, /** * @class Make file/folder copy * @param Object elFinder **/ duplicate : function(fm) { var self = this; this.name = 'Duplicate'; this.fm = fm; this.exec = function() { this.fm.ajax({ cmd : 'duplicate', current : this.fm.cwd.hash, target : this.fm.selected[0] }, function(data) { self.fm.reload(data); }); } this.isAllowed = function() { return this.fm.cwd.write && this.fm.selected.length == 1 && this.fm.getSelected()[0].read; } this.cm = function(t) { return t == 'file'; } }, /** * @class Edit text file * @param Object elFinder **/ edit : function(fm) { var self = this; this.name = 'Edit text file'; this.fm = fm; this.exec = function() { var f = this.fm.getSelected(0); this.fm.lockShortcuts(true); this.fm.ajax({ cmd : 'read', current : this.fm.cwd.hash, target : f.hash }, function(data) { self.fm.lockShortcuts(true); var ta = $('<textarea/>').val(data.content||'').keydown(function(e) { e.stopPropagation(); if (e.keyCode == 9) { e.preventDefault(); if ($.browser.msie) { var r = document.selection.createRange(); r.text = "\t"+r.text; this.focus(); } else { var before = this.value.substr(0, this.selectionStart), after = this.value.substr(this.selectionEnd); this.value = before+"\t"+after; this.setSelectionRange(before.length+1, before.length+1); } } }); $('<div/>').append(ta) .dialog({ dialogClass : 'el-finder-dialog', title : self.fm.i18n(self.name), modal : true, width : 500, close : function() { self.fm.lockShortcuts(); }, buttons : { Cancel : function() { $(this).dialog('close'); }, Ok : function() { var c = ta.val(); $(this).dialog('close'); self.fm.ajax({ cmd : 'edit', current : self.fm.cwd.hash, target : f.hash, content : c }, function(data) { if (data.target) { self.fm.cdc[data.target.hash] = data.target; self.fm.view.updateFile(data.target); self.fm.selectById(data.target.hash); } }, {type : 'POST'}); } } }); }); } this.isAllowed = function() { if (self.fm.selected.length == 1) { var f = this.fm.getSelected()[0]; return f.write && f.read && (f.mime.indexOf('text') == 0 || f.mime == 'application/x-empty' || f.mime == 'application/xml'); } } this.cm = function(t) { return t == 'file'; } }, /** * @class Create archive * @param Object elFinder **/ archive : function(fm) { var self = this; this.name = 'Create archive'; this.fm = fm; this.exec = function(t) { var o = { cmd : 'archive', current : self.fm.cwd.hash, type : $.inArray(t, this.fm.params.archives) != -1 ? t : this.fm.params.archives[0], name : self.fm.i18n('Archive') }; if (this.fm.jquery>132) { o.targets = self.fm.selected; } else { o['targets[]'] = self.fm.selected; } this.fm.ajax(o, function(data) { self.fm.reload(data); }); } this.isAllowed = function() { if (this.fm.cwd.write && this.fm.selected.length) { var s = this.fm.getSelected(), l = s.length; while (l--) { if (s[l].read) { return true; } } } return false; } this.cm = function(t) { return t != 'cwd'; } this.argc = function() { var i, v = []; for (i=0; i < self.fm.params.archives.length; i++) { v.push({ 'class' : 'archive', 'argc' : self.fm.params.archives[i], 'text' : self.fm.view.mime2kind(self.fm.params.archives[i]) }); }; return v; } }, /** * @class Extract files from archive * @param Object elFinder **/ extract : function(fm) { var self = this; this.name = 'Uncompress archive'; this.fm = fm; this.exec = function() { this.fm.ajax({ cmd : 'extract', current : this.fm.cwd.hash, target : this.fm.getSelected(0).hash }, function(data) { self.fm.reload(data); }) } this.isAllowed = function() { var extract = this.fm.params.extract, cnt = extract && extract.length; return this.fm.cwd.write && this.fm.selected.length == 1 && this.fm.getSelected(0).read && cnt && $.inArray(this.fm.getSelected(0).mime, extract) != -1; } this.cm = function(t) { return t == 'file'; } }, /** * @class Resize image * @param Object elFinder **/ resize : function(fm) { var self = this; this.name = 'Resize image'; this.fm = fm; this.exec = function() { var s = this.fm.getSelected(); if (s[0] && s[0].write && s[0].dim) { var size = s[0].dim.split('x'), w = parseInt(size[0]), h = parseInt(size[1]), rel = w/h iw = $('<input type="text" size="9" value="'+w+'" name="width"/>'), ih = $('<input type="text" size="9" value="'+h+'" name="height"/>'), f = $('<form/>').append(iw).append(' x ').append(ih).append(' px'); iw.add(ih).bind('change', calc); self.fm.lockShortcuts(true); var d = $('<div/>').append($('<div/>').text(self.fm.i18n('Dimensions')+':')).append(f).dialog({ title : self.fm.i18n('Resize image'), dialogClass : 'el-finder-dialog', width : 230, modal : true, close : function() { self.fm.lockShortcuts(); }, buttons : { Cancel : function() { $(this).dialog('close'); }, Ok : function() { var _w = parseInt(iw.val()) || 0, _h = parseInt(ih.val()) || 0; if (_w>0 && _w != w && _h>0 && _h != h) { self.fm.ajax({ cmd : 'resize', current : self.fm.cwd.hash, target : s[0].hash, width : _w, height : _h }, function (data) { self.fm.reload(data); }); } $(this).dialog('close'); } } }); } function calc() { var _w = parseInt(iw.val()) || 0, _h = parseInt(ih.val()) || 0; if (_w<=0 || _h<=0) { _w = w; _h = h; } else if (this == iw.get(0)) { _h = parseInt(_w/rel); } else { _w = parseInt(_h*rel); } iw.val(_w); ih.val(_h); } } this.isAllowed = function() { return this.fm.selected.length == 1 && this.fm.cdc[this.fm.selected[0]].write && this.fm.cdc[this.fm.selected[0]].read && this.fm.cdc[this.fm.selected[0]].resize; } this.cm = function(t) { return t == 'file'; } }, /** * @class Switch elFinder into icon view * @param Object elFinder **/ icons : function(fm) { this.name = 'View as icons'; this.fm = fm; this.exec = function() { this.fm.view.win.addClass('el-finder-disabled'); this.fm.setView('icons'); this.fm.updateCwd(); this.fm.view.win.removeClass('el-finder-disabled'); $('div.image', this.fm.view.cwd).length && this.fm.tmb(); } this.isAllowed = function() { return this.fm.options.view != 'icons'; } this.cm = function(t) { return t == 'cwd'; } }, /** * @class Switch elFinder into list view * @param Object elFinder **/ list : function(fm) { this.name = 'View as list'; this.fm = fm; this.exec = function() { this.fm.view.win.addClass('el-finder-disabled'); this.fm.setView('list'); this.fm.updateCwd(); this.fm.view.win.removeClass('el-finder-disabled'); } this.isAllowed = function() { return this.fm.options.view != 'list'; } this.cm = function(t) { return t == 'cwd'; } }, help : function(fm) { this.name = 'Help'; this.fm = fm; this.exec = function() { var h, ht = this.fm.i18n('helpText'), a, s, tabs; h = '<div class="el-finder-logo"/><strong>'+this.fm.i18n('elFinder: Web file manager')+'</strong><br/>'+this.fm.i18n('Version')+': '+this.fm.version+'<br/>' +'jQuery/jQueryUI: '+$().jquery+'/'+$.ui.version+'<br clear="all"/>' +'<p><strong><a href="http://elrte.org/'+this.fm.options.lang+'/elfinder" target="_blank">'+this.fm.i18n('Donate to support project development')+'</a></strong></p>' + '<p><a href="http://elrte.org/redmine/projects/elfinder/wiki" target="_blank">'+this.fm.i18n('elFinder documentation')+'</a></p>'; h += '<p>'+(ht != 'helpText' ? ht : 'elFinder works similar to file manager on your computer. <br /> To make actions on files/folders use icons on top panel. If icon action it is not clear for you, hold mouse cursor over it to see the hint. <br /> Manipulations with existing files/folders can be done through the context menu (mouse right-click).<br/> To copy/delete a group of files/folders, select them using Shift/Alt(Command) + mouse left-click.')+'</p>'; h += '<p>' + '<strong>'+this.fm.i18n('elFinder support following shortcuts')+':</strong><ul>' + '<li><kbd>Ctrl+A</kbd> - '+this.fm.i18n('Select all files')+'</li>' + '<li><kbd>Ctrl+C/Ctrl+X/Ctrl+V</kbd> - '+this.fm.i18n('Copy/Cut/Paste files')+'</li>' + '<li><kbd>Enter</kbd> - '+this.fm.i18n('Open selected file/folder')+'</li>' + '<li><kbd>Space</kbd> - '+this.fm.i18n('Open/close QuickLook window')+'</li>' + '<li><kbd>Delete/Cmd+Backspace</kbd> - '+this.fm.i18n('Remove selected files')+'</li>' + '<li><kbd>Ctrl+I</kbd> - '+this.fm.i18n('Selected files or current directory info')+'</li>' + '<li><kbd>Ctrl+N</kbd> - '+this.fm.i18n('Create new directory')+'</li>' + '<li><kbd>Ctrl+U</kbd> - '+this.fm.i18n('Open upload files form')+'</li>' + '<li><kbd>Left arrow</kbd> - '+this.fm.i18n('Select previous file')+'</li>' + '<li><kbd>Right arrow </kbd> - '+this.fm.i18n('Select next file')+'</li>' + '<li><kbd>Ctrl+Right arrow</kbd> - '+this.fm.i18n('Open selected file/folder')+'</li>' + '<li><kbd>Ctrl+Left arrow</kbd> - '+this.fm.i18n('Return into previous folder')+'</li>' + '<li><kbd>Shift+arrows</kbd> - '+this.fm.i18n('Increase/decrease files selection')+'</li></ul>' + '</p><p>' + this.fm.i18n('Contacts us if you need help integrating elFinder in you products')+': dev@std42.ru</p>'; a = '<div class="el-finder-help-std"/>' +'<p>'+this.fm.i18n('Javascripts/PHP programming: Dmitry (dio) Levashov, dio@std42.ru')+'</p>' +'<p>'+this.fm.i18n('Python programming, techsupport: Troex Nevelin, troex@fury.scancode.ru')+'</p>' +'<p>'+this.fm.i18n('Design: Valentin Razumnih')+'</p>' +'<p>'+this.fm.i18n('Chezh localization')+': Roman Matěna, info@romanmatena.cz</p>' +'<p>'+this.fm.i18n('Chinese (traditional) localization')+': Tad, tad0616@gmail.com</p>' +'<p>'+this.fm.i18n('Dutch localization')+': Kurt Aerts, <a href="http://ilabsolutions.net/" target="_blank">http://ilabsolutions.net</a></p>' +'<p>'+this.fm.i18n('Greek localization')+': Panagiotis Skarvelis</p>' +'<p>'+this.fm.i18n('Hungarian localization')+': Viktor Tamas, tamas.viktor@totalstudio.hu</p>' +'<p>'+this.fm.i18n('Italian localization')+': Ugo Punzolo, sadraczerouno@gmail.com</p>' +'<p>'+this.fm.i18n('Latvian localization')+': Uldis Plotiņš, uldis.plotins@gmail.com</p>' +'<p>'+this.fm.i18n('Poland localization')+': Darek Wapiński, darek@wapinski.us</p>' +'<p>'+this.fm.i18n('Spanish localization')+': Alex (xand) Vavilin, xand@xand.es, <a href="http://xand.es" target="_blank">http://xand.es</a></p>' +'<p>'+this.fm.i18n('Icons')+': <a href="http://pixelmixer.ru/" target="_blank">pixelmixer</a>, <a href="http://www.famfamfam.com/lab/icons/silk/" target="_blank">Famfam silk icons</a>, <a href="http://www.fatcow.com/free-icons/" target="_blank">Fatcow icons</a>'+'</p>' +'<p>'+this.fm.i18n('Copyright: <a href="http://www.std42.ru" target="_blank">Studio 42 LTD</a>')+'</p>' +'<p>'+this.fm.i18n('License: BSD License')+'</p>' +'<p>'+this.fm.i18n('Web site: <a href="http://elrte.org/elfinder/" target="_blank">elrte.org/elfinder</a>')+'</p>'; s = '<div class="el-finder-logo"/><strong><a href="http://www.eldorado-cms.ru" target="_blank">ELDORADO.CMS</a></strong><br/>' +this.fm.i18n('Simple and usefull Content Management System') +'<hr/>' + this.fm.i18n('Support project development and we will place here info about you'); tabs = '<ul><li><a href="#el-finder-help-h">'+this.fm.i18n('Help')+'</a></li><li><a href="#el-finder-help-a">'+this.fm.i18n('Authors')+'</a><li><a href="#el-finder-help-sp">'+this.fm.i18n('Sponsors')+'</a></li></ul>' +'<div id="el-finder-help-h"><p>'+h+'</p></div>' +'<div id="el-finder-help-a"><p>'+a+'</p></div>' +'<div id="el-finder-help-sp"><p>'+s+'</p></div>'; var d = $('<div/>').html(tabs).dialog({ width : 617, title : this.fm.i18n('Help'), dialogClass : 'el-finder-dialog', modal : true, close : function() { d.tabs('destroy').dialog('destroy').remove() }, buttons : { Ok : function() { $(this).dialog('close'); } } }).tabs() } this.cm = function(t) { return t == 'cwd'; } } } })(jQuery); /** * @class Create quick look window (similar to MacOS X Quick Look) * @author dio dio@std42.ru **/ (function($) { elFinder.prototype.quickLook = function(fm, el) { var self = this; this.fm = fm; this._hash = ''; this.title = $('<strong/>'); this.ico = $('<p/>'); this.info = $('<label/>'); this.media = $('<div class="el-finder-ql-media"/>').hide() this.name = $('<span class="el-finder-ql-name"/>') this.kind = $('<span class="el-finder-ql-kind"/>') this.size = $('<span class="el-finder-ql-size"/>') this.date = $('<span class="el-finder-ql-date"/>') this.url = $('<a href="#"/>').hide().click(function(e) { e.preventDefault(); window.open($(this).attr('href')); self.hide(); }); this.add = $('<div/>') this.content = $('<div class="el-finder-ql-content"/>') this.win = $('<div class="el-finder-ql"/>').hide() .append($('<div class="el-finder-ql-drag-handle"/>').append($('<span class="ui-icon ui-icon-circle-close"/>').click(function() { self.hide(); })).append(this.title)) .append(this.ico) .append(this.media) .append(this.content.append(this.name).append(this.kind).append(this.size).append(this.date).append(this.url).append(this.add)) // .appendTo(this.fm.view.win) .appendTo('body') .draggable({handle : '.el-finder-ql-drag-handle'}) .resizable({ minWidth : 420, minHeight : 150, resize : function() { if (self.media.children().length) { var t = self.media.children(':first'); switch (t[0].nodeName) { case 'IMG': var w = t.width(), h = t.height(), _w = self.win.width(), _h = self.win.css('height') == 'auto' ? 350 : self.win.height()-self.content.height()-self.th, r = w>_w || h>_h ? Math.min(Math.min(_w, w)/w, Math.min(_h, h)/h) : Math.min(Math.max(_w, w)/w, Math.max(_h, h)/h); t.css({ width : Math.round(t.width()*r), height : Math.round(t.height()*r) }) break; case 'IFRAME': case 'EMBED': t.css('height', self.win.height()-self.content.height()-self.th); break; case 'OBJECT': t.children('embed').css('height', self.win.height()-self.content.height()-self.th); } } } }); this.th = parseInt(this.win.children(':first').css('height'))||18; /* All browsers do it, but some is shy to says about it. baka da ne! */ this.mimes = { 'image/jpeg' : 'jpg', 'image/gif' : 'gif', 'image/png' : 'png' }; for (var i=0; i<navigator.mimeTypes.length; i++) { var t = navigator.mimeTypes[i].type; if (t && t != '*') { this.mimes[t] = navigator.mimeTypes[i].suffixes; } } if (($.browser.safari && navigator.platform.indexOf('Mac') != -1) || $.browser.msie) { /* not booletproof, but better then nothing */ this.mimes['application/pdf'] = 'pdf'; } else { for (var n=0; n < navigator.plugins.length; n++) { for (var m=0; m < navigator.plugins[n].length; m++) { var e = navigator.plugins[n][m].description.toLowerCase(); if (e.substring(0, e.indexOf(" ")) == 'pdf') { this.mimes['application/pdf'] = 'pdf'; break; } } } } if (this.mimes['image/x-bmp']) { this.mimes['image/x-ms-bmp'] = 'bmp'; } if ($.browser.msie && !this.mimes['application/x-shockwave-flash']) { this.mimes['application/x-shockwave-flash'] = 'swf'; } // self.fm.log(this.mimes) /** * Open quickLook window **/ this.show = function() { if (this.win.is(':hidden') && self.fm.selected.length == 1) { update(); var id = self.fm.selected[0], el = self.fm.view.cwd.find('[key="'+id+'"]'), o = el.offset(); self.fm.lockShortcuts(true); this.win.css({ width : el.width()-20, height : el.height(), left : o.left, top : o.top, opacity : 0 }).show().animate({ width : 420, height : 150, opacity : 1, top : Math.round($(window).height()/5), left : $(window).width()/2-210 }, 450, function() { self.win.css({height: 'auto'}); self.fm.lockShortcuts(); }); } } /** * Close quickLook window **/ this.hide = function() { if (this.win.is(':visible')) { var o, el = self.fm.view.cwd.find('[key="'+this._hash+'"]'); if (el) { o = el.offset(); this.media.hide(200)//.empty() this.win.animate({ width : el.width()-20, height : el.height(), left : o.left, top : o.top, opacity : 0 }, 350, function() { self.fm.lockShortcuts(); reset(); self.win.hide().css('height', 'auto'); }); } else { this.win.fadeOut(200); reset(); self.fm.lockShortcuts(); } } } /** * Open/close quickLook window **/ this.toggle = function() { if (this.win.is(':visible')) { this.hide(); } else { this.show(); } } /** * Update quickLook window content if only one file selected, * otherwise close window **/ this.update = function() { if (this.fm.selected.length != 1) { this.hide(); } else if (this.win.is(':visible') && this.fm.selected[0] != this._hash) { update(); } } /** * Return height of this.media block * @return Number **/ this.mediaHeight = function() { return this.win.is(':animated') || this.win.css('height') == 'auto' ? 315 : this.win.height()-this.content.height()-this.th; } /** * Clean quickLook window DOM elements **/ function reset() { self.media.hide().empty(); self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex); self.title.empty(); self.ico.attr('style', '').show(); self.add.hide().empty(); self._hash = ''; } /** * Update quickLook window content **/ function update() { var f = self.fm.getSelected(0); reset(); self._hash = f.hash; self.title.text(f.name); self.win.addClass(self.fm.view.mime2class(f.mime)); self.name.text(f.name); self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime)); self.size.text(self.fm.view.formatSize(f.size)); self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date)); f.dim && self.add.append('<span>'+f.dim+' px</span>').show(); f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat'); if (f.url) { self.url.text(f.url).attr('href', f.url).show(); for (var i in self.plugins) { if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) { self.plugins[i].show(self, f); return; } } } else { self.url.hide(); } self.win.css({ width : '420px', height : 'auto' }); } } elFinder.prototype.quickLook.prototype.plugins = { image : new function() { this.test = function(mime, mimes) { return mime.match(/^image\//); } this.show = function(ql, f) { var url, t; if (ql.mimes[f.mime] && f.hash == ql._hash) { $('<img/>').hide().appendTo(ql.media.show()).attr('src', f.url+($.browser.msie || $.browser.opera ? '?'+Math.random() : '')).load(function() { t = $(this).unbind('load'); if (f.hash == ql._hash) { ql.win.is(':animated') ? setTimeout(function() { preview(t); }, 330) : preview(t); } }); } function preview(img) { var w = img.width(), h = img.height(), a = ql.win.is(':animated'), _w = a ? 420 : ql.win.width(), _h = a || ql.win.css('height') == 'auto' ? 315 : ql.win.height()-ql.content.height()-ql.th, r = w>_w || h>_h ? Math.min(Math.min(_w, w)/w, Math.min(_h, h)/h) : Math.min(Math.max(_w, w)/w, Math.max(_h, h)/h); ql.fm.lockShortcuts(true); ql.ico.hide(); img.css({ width : ql.ico.width(), height : ql.ico.height() }).show().animate({ width : Math.round(r*w), height : Math.round(r*h) }, 450, function() { ql.fm.lockShortcuts(); }); } } }, text : new function() { this.test = function(mime, mimes) { return (mime.indexOf('text') == 0 && mime.indexOf('rtf') == -1) || mime.match(/application\/(xml|javascript|json)/); } this.show = function(ql, f) { if (f.hash == ql._hash) { ql.ico.hide(); ql.media.append('<iframe src="'+f.url+'" style="height:'+ql.mediaHeight()+'px" />').show(); } } }, swf : new function() { this.test = function(mime, mimes) { return mime == 'application/x-shockwave-flash' && mimes[mime]; } this.show = function(ql, f) { if (f.hash == ql._hash) { ql.ico.hide(); // ql.media.append('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="quality" value="high" /><param name="movie" value="'+url+'" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+url+'" type="application/x-shockwave-flash" style="width:100%;height:'+ql.mediaHeight()+'px"></embed></object>') // .slideDown(400); var e = ql.media.append('<embed pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+f.url+'" style="width:100%;height:'+ql.mediaHeight()+'px" type="application/x-shockwave-flash" />'); if (ql.win.is(':animated')) { e.slideDown(450) } else { e.show() } } } }, audio : new function() { this.test = function(mime, mimes) { return mime.indexOf('audio') == 0 && mimes[mime]; } this.show = function(ql, f) { if (f.hash == ql._hash) { ql.ico.hide(); var h = ql.win.is(':animated') || ql.win.css('height') == 'auto' ? 100 : ql.win.height()-ql.content.height()-ql.th; ql.media.append('<embed src="'+f.url+'" style="width:100%;height:'+h+'px" />').show(); } } }, video : new function() { this.test = function(mime, mimes) { return mime.indexOf('video') == 0 && mimes[mime]; } this.show = function(ql, f) { if (f.hash == ql._hash) { ql.ico.hide(); ql.media.append('<embed src="'+f.url+'" style="width:100%;height:'+ql.mediaHeight()+'px" />').show(); } } }, pdf : new function() { this.test = function(mime, mimes) { return mime == 'application/pdf' && mimes[mime]; } this.show = function(ql, f) { if (f.hash == ql._hash) { ql.ico.hide(); ql.media.append('<embed src="'+f.url+'" style="width:100%;height:'+ql.mediaHeight()+'px" />').show(); } } } } })(jQuery); /** * @class Bind/update events * @author dio dio@std42.ru **/ (function($) { elFinder.prototype.eventsManager = function(fm, el) { var self = this; this.lock = false; this.fm = fm; this.ui = fm.ui; this.tree = fm.view.tree this.cwd = fm.view.cwd; this.pointer = ''; /** * Initial events binding * **/ this.init = function() { var self = this, ignore = false; self.lock = false; this.cwd .bind('click', function(e) { var t = $(e.target); if (t.hasClass('ui-selected')) { self.fm.unselectAll(); } else { if (!t.attr('key')) { t = t.parent('[key]'); } if (e.ctrlKey || e.metaKey) { self.fm.toggleSelect(t); } else { self.fm.select(t, true); } } }) .bind(window.opera?'click':'contextmenu', function(e) { if (window.opera && !e.ctrlKey) { return; } e.preventDefault(); e.stopPropagation(); var t = $(e.target); if ($.browser.mozilla) { ignore = true; } if (t.hasClass('el-finder-cwd')) { self.fm.unselectAll(); } else { self.fm.select(t.attr('key') ? t : t.parent('[key]')); } self.fm.quickLook.hide(); self.fm.ui.showMenu(e); }) .selectable({ filter : '[key]', delay : 300, stop : function() { self.fm.updateSelect(); self.fm.log('mouseup') } }); $(document).bind('click', function(e) { !ignore && self.fm.ui.hideMenu(); ignore = false $('input', self.cwd).trigger('change'); if (!$(e.target).is('input,textarea,select')) { $('input,textarea').blur(); } }); $('input,textarea').live('focus', function(e) { self.lock = true; }).live('blur', function(e) { self.lock = false; }); /* open parents dir in tree */ this.tree.bind('select', function(e) { self.tree.find('a').removeClass('selected'); $(e.target).addClass('selected').parents('li:has(ul)').children('ul').show().prev().children('div').addClass('expanded'); }); /* make places droppable */ if (this.fm.options.places) { this.fm.view.plc.click(function(e) { e.preventDefault(); var t = $(e.target), h = t.attr('key'), ul; if (h) { h != self.fm.cwd.hash && self.ui.exec('open', e.target) } else if (e.target.nodeName == 'A' || e.target.nodeName == 'DIV') { ul = self.fm.view.plc.find('ul'); if (ul.children().length) { ul.toggle(300); self.fm.view.plc.children('li').find('div').toggleClass('expanded'); } } }); this.fm.view.plc.droppable({ accept : '(div,tr).directory', tolerance : 'pointer', over : function() { $(this).addClass('el-finder-droppable'); }, out : function() { $(this).removeClass('el-finder-droppable'); }, drop : function(e, ui) { $(this).removeClass('el-finder-droppable'); var upd = false; /* accept only folders with read access */ ui.helper.children('.directory:not(.noaccess,.dropbox)').each(function() { if (self.fm.addPlace($(this).attr('key'))) { upd = true; $(this).hide(); } }); /* update places id's and view */ if (upd) { self.fm.view.renderPlaces(); self.updatePlaces(); self.fm.view.plc.children('li').children('div').trigger('click'); } /* hide helper if empty */ if (!ui.helper.children('div:visible').length) { ui.helper.hide(); } } }); } /* bind shortcuts */ $(document).bind($.browser.mozilla || $.browser.opera ? 'keypress' : 'keydown', function(e) { var meta = e.ctrlKey||e.metaKey; if (self.lock) { return; } switch(e.keyCode) { /* arrows left/up. with Ctrl - exec "back", w/o - move selection */ case 37: case 38: e.stopPropagation(); e.preventDefault(); if (e.keyCode == 37 && meta) { self.ui.execIfAllowed('back'); } else { moveSelection(false, !e.shiftKey); } break; /* arrows right/down. with Ctrl - exec "open", w/o - move selection */ case 39: case 40: e.stopPropagation(); e.preventDefault(); if (meta) { self.ui.execIfAllowed('open'); } else { moveSelection(true, !e.shiftKey); } break; } }); $(document).bind($.browser.opera ? 'keypress' : 'keydown', function(e) { if (self.lock) { return; } switch(e.keyCode) { /* Space - QuickLook */ case 32: e.preventDefault(); e.stopPropagation(); self.fm.quickLook.toggle(); break; /* Esc */ case 27: self.fm.quickLook.hide(); break; } }); if (!this.fm.options.disableShortcuts) { $(document).bind('keydown', function(e) { var meta = e.ctrlKey||e.metaKey; if (self.lock) { return; } switch (e.keyCode) { /* Meta+Backspace - delete */ case 8: if (meta && self.ui.isCmdAllowed('rm')) { e.preventDefault(); self.ui.exec('rm'); } break; /* Enter - exec "select" command if enabled, otherwise exec "open" */ case 13: if (self.ui.isCmdAllowed('select')) { return self.ui.exec('select'); } self.ui.execIfAllowed('open'); break; /* Delete */ case 46: self.ui.execIfAllowed('rm'); break; /* Ctrl+A */ case 65: if (meta) { e.preventDefault(); self.fm.selectAll(); } break; /* Ctrl+C */ case 67: meta && self.ui.execIfAllowed('copy'); break; /* Ctrl+I - get info */ case 73: if (meta) { e.preventDefault(); self.ui.exec('info'); } break; /* Ctrl+N - new folder */ case 78: if (meta) { e.preventDefault(); self.ui.execIfAllowed('mkdir'); } break; /* Ctrl+U - upload files */ case 85: if (meta) { e.preventDefault(); self.ui.execIfAllowed('upload'); } break; /* Ctrl+V */ case 86: meta && self.ui.execIfAllowed('paste'); break; /* Ctrl+X */ case 88: meta && self.ui.execIfAllowed('cut'); break; case 113: self.ui.execIfAllowed('rename'); break; } }); } } /** * Update navigation droppable/draggable * **/ this.updateNav = function() { $('a', this.tree).click(function(e) { e.preventDefault(); var t = $(this), c; if (e.target.nodeName == 'DIV' && $(e.target).hasClass('collapsed')) { $(e.target).toggleClass('expanded').parent().next('ul').toggle(300); } else if (t.attr('key') != self.fm.cwd.hash) { if (t.hasClass('noaccess') || t.hasClass('dropbox')) { self.fm.view.error('Access denied'); } else { self.ui.exec('open', t.trigger('select')[0]); } } else { c = t.children('.collapsed'); if (c.length) { c.toggleClass('expanded'); t.next('ul').toggle(300); } } }); $('a:not(.noaccess,.readonly)', this.tree).droppable({ tolerance : 'pointer', accept : 'div[key],tr[key]', over : function() { $(this).addClass('el-finder-droppable'); }, out : function() { $(this).removeClass('el-finder-droppable'); }, drop : function(e, ui) { $(this).removeClass('el-finder-droppable'); self.fm.drop(e, ui, $(this).attr('key')); } }); this.fm.options.places && this.updatePlaces(); } /** * Update places draggable * **/ this.updatePlaces = function() { this.fm.view.plc.children('li').find('li').draggable({ scroll : false, stop : function() { if (self.fm.removePlace($(this).children('a').attr('key'))) { $(this).remove(); if (!$('li', self.fm.view.plc.children('li')).length) { self.fm.view.plc.children('li').find('div').removeClass('collapsed expanded').end().children('ul').hide(); } } } }); } /** * Update folders droppable & files/folders draggable **/ this.updateCwd = function() { $('[key]', this.cwd) .bind('dblclick', function(e) { self.fm.select($(this), true); self.ui.exec(self.ui.isCmdAllowed('select') ? 'select' : 'open'); }) .draggable({ delay : 3, addClasses : false, appendTo : '.el-finder-cwd', revert : true, drag : function(e, ui) { ui.helper.toggleClass('el-finder-drag-copy', e.shiftKey||e.ctrlKey); }, helper : function() { var t = $(this), h = $('<div class="el-finder-drag-helper"/>'), c = 0; !t.hasClass('ui-selected') && self.fm.select(t, true); self.cwd.find('.ui-selected').each(function(i) { var el = self.fm.options.view == 'icons' ? $(this).clone().removeClass('ui-selected') : $(self.fm.view.renderIcon(self.fm.cdc[$(this).attr('key')])) if (c++ == 0 || c%12 == 0) { el.css('margin-left', 0); } h.append(el); }); return h.css('width', (c<=12 ? 85+(c-1)*29 : 387)+'px'); } }) .filter('.directory') .droppable({ tolerance : 'pointer', accept : 'div[key],tr[key]', over : function() { $(this).addClass('el-finder-droppable'); }, out : function() { $(this).removeClass('el-finder-droppable'); }, drop : function(e, ui) { $(this).removeClass('el-finder-droppable'); self.fm.drop(e, ui, $(this).attr('key')); } }); if ($.browser.msie) { $('*', this.cwd).attr('unselectable', 'on') .filter('[key]') .bind('dragstart', function() { self.cwd.selectable('disable').removeClass('ui-state-disabled ui-selectable-disabled'); }) .bind('dragstop', function() { self.cwd.selectable('enable'); }); } } /** * Move selection in current dir * * @param Boolean move forward? * @param Boolean clear current selection? **/ function moveSelection(forward, reset) { var p, _p, cur; if (!$('[key]', self.cwd).length) { return; } if (self.fm.selected.length == 0) { p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd); self.fm.select(p); } else if (reset) { p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd); _p = p[forward ? 'next' : 'prev']('[key]'); if (_p.length) { p = _p; } self.fm.select(p, true); } else { if (self.pointer) { cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd); } if (!cur || !cur.length) { cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd); } p = cur[forward ? 'next' : 'prev']('[key]'); if (!p.length) { p = cur; } else { if (!p.hasClass('ui-selected')) { self.fm.select(p); } else { if (!cur.hasClass('ui-selected')) { self.fm.unselect(p); } else { _p = cur[forward ? 'prev' : 'next']('[key]') if (!_p.length || !_p.hasClass('ui-selected')) { self.fm.unselect(cur); } else { while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) { p = _p; } self.fm.select(p); } } } } } self.pointer = p.attr('key'); self.fm.checkSelectedPos(forward); } } })(jQuery);
JavaScript
$().ready(function() { elRTE.prototype.options.pasteOnlyText = false; //elRTE.prototype.options.pasteOnlyText = true; elRTE.prototype.options.panels.myCopyPaste = [ //'copy', //'cut', //'paste', 'pastetext', //'pasteformattext', 'removeformat', //'docstructure' ]; elRTE.prototype.options.panels.myStyle = [ 'bold', 'italic', 'underline', 'strikethrough', //'subscript', //'superscript' ]; elRTE.prototype.options.panels.myAligment = [ 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull' ]; elRTE.prototype.options.panels.myFullScreen = [ 'fullscreen' ]; elRTE.prototype.options.panels.myFormat = [ 'formatblock', //'fontsize', //'fontname' ]; elRTE.prototype.options.panels.myLinks = [ 'link', 'unlink', //'anchor' ]; elRTE.prototype.options.panels.myElements = [ //'horizontalrule', //'blockquote', //'div', //'stopfloat', 'css', 'nbsp', //'smiley', //'pagebreak' ]; elRTE.prototype.options.panels.web2pyPanel = [ 'bold', 'italic', 'underline', 'forecolor', 'justifyleft', 'justifyright', 'justifycenter', 'justifyfull', 'formatblock', 'insertorderedlist', 'insertunorderedlist', 'link', 'image', 'flash' ]; elRTE.prototype.options.toolbars.wysiwygAdmin = [ //'save', 'myCopyPaste', 'undoredo', //'elfinder', 'myStyle', 'myAligment', //'direction', 'colors', 'myFormat', //'indent', 'lists', 'myLinks', 'myElements', 'images', 'myFullScreen', 'tables', ]; var opts = { lang : 'ru', // set your language styleWithCSS : false, height : 400, toolbar : 'wysiwygAdmin', cssfiles : [W_ABSPATH + 'content/css/plugins/jquery.wysiwyg_in.css'], fmOpen : function(callback) { $('<div id=\"myelfinder\" />').elfinder({ url : W_AJAX + 'wysiwyg/connector/', lang : 'ru', dialog : { width : 900, modal : true, title : 'Files' }, // открываем в диалоговом окне closeOnEditorCallback : true, // закрываем после выбора файла editorCallback : callback // передаем callback файловому менеджеру }) } }; // create editor $('.wysiwygAdmin').elrte(opts); });
JavaScript
// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support // (c) 2008-2009 Angus Turnbull http://www.twinhelix.com // This is licensed under the GNU LGPL, version 2.1 or later. // For details, see: http://creativecommons.org/licenses/LGPL/2.1/ var IEPNGFix = window.IEPNGFix || {}; IEPNGFix.tileBG = function(elm, pngSrc, ready) { // Params: A reference to a DOM element, the PNG src file pathname, and a // hidden "ready-to-run" passed when called back after image preloading. var data = this.data[elm.uniqueID], elmW = Math.max(elm.clientWidth, elm.scrollWidth), elmH = Math.max(elm.clientHeight, elm.scrollHeight), bgX = elm.currentStyle.backgroundPositionX, bgY = elm.currentStyle.backgroundPositionY, bgR = elm.currentStyle.backgroundRepeat; // Cache of DIVs created per element, and image preloader/data. if (!data.tiles) { data.tiles = { elm: elm, src: '', cache: [], img: new Image(), old: {} }; } var tiles = data.tiles, pngW = tiles.img.width, pngH = tiles.img.height; if (pngSrc) { if (!ready && pngSrc != tiles.src) { // New image? Preload it with a callback to detect dimensions. tiles.img.onload = function() { this.onload = null; IEPNGFix.tileBG(elm, pngSrc, 1); }; return tiles.img.src = pngSrc; } } else { // No image? if (tiles.src) ready = 1; pngW = pngH = 0; } tiles.src = pngSrc; if (!ready && elmW == tiles.old.w && elmH == tiles.old.h && bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) { return; } // Convert English and percentage positions to pixels. var pos = { top: '0%', left: '0%', center: '50%', bottom: '100%', right: '100%' }, x, y, pc; x = pos[bgX] || bgX; y = pos[bgY] || bgY; if (pc = x.match(/(\d+)%/)) { x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100)); } if (pc = y.match(/(\d+)%/)) { y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100)); } x = parseInt(x); y = parseInt(y); // Handle backgroundRepeat. var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR], repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR]; if (repeatX) { x %= pngW; if (x > 0) x -= pngW; } if (repeatY) { y %= pngH; if (y > 0) y -= pngH; } // Go! this.hook.enabled = 0; if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) { elm.style.position = 'relative'; } var count = 0, xPos, maxX = repeatX ? elmW : x + 0.1, yPos, maxY = repeatY ? elmH : y + 0.1, d, s, isNew; if (pngW && pngH) { for (xPos = x; xPos < maxX; xPos += pngW) { for (yPos = y; yPos < maxY; yPos += pngH) { isNew = 0; if (!tiles.cache[count]) { tiles.cache[count] = document.createElement('div'); isNew = 1; } var clipR = Math.max(0, xPos + pngW > elmW ? elmW - xPos : pngW), clipB = Math.max(0, yPos + pngH > elmH ? elmH - yPos : pngH); d = tiles.cache[count]; s = d.style; s.behavior = 'none'; s.left = (xPos - parseInt(elm.currentStyle.paddingLeft)) + 'px'; s.top = yPos + 'px'; s.width = clipR + 'px'; s.height = clipB + 'px'; s.clip = 'rect(' + (yPos < 0 ? 0 - yPos : 0) + 'px,' + clipR + 'px,' + clipB + 'px,' + (xPos < 0 ? 0 - xPos : 0) + 'px)'; s.display = 'block'; if (isNew) { s.position = 'absolute'; s.zIndex = -999; if (elm.firstChild) { elm.insertBefore(d, elm.firstChild); } else { elm.appendChild(d); } } this.fix(d, pngSrc, 0); count++; } } } while (count < tiles.cache.length) { this.fix(tiles.cache[count], '', 0); tiles.cache[count++].style.display = 'none'; } this.hook.enabled = 1; // Cache so updates are infrequent. tiles.old = { w: elmW, h: elmH, x: bgX, y: bgY, r: bgR }; }; IEPNGFix.update = function() { // Update all PNG backgrounds. for (var i in IEPNGFix.data) { var t = IEPNGFix.data[i].tiles; if (t && t.elm && t.src) { IEPNGFix.tileBG(t.elm, t.src); } } }; IEPNGFix.update.timer = 0; if (window.attachEvent && !window.opera) { window.attachEvent('onresize', function() { clearTimeout(IEPNGFix.update.timer); IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100); }); }
JavaScript
W_ABSPATH = '/wp/'; W_FULLPATH = 'http://localhost/wp/'; //W_ABSPATH = '/'; W_ADMIN = W_ABSPATH + 'cms/'; CUR_ABS_PATH = W_ABSPATH; W_AJAX = W_ABSPATH + 'ajax/'; W_IMAGES = W_ABSPATH + 'content/images/'; W_BLOCKS = W_ABSPATH + 'content/blocks/'; W_CSS = W_ABSPATH + 'content/css/'; W_JS = W_ABSPATH + 'content/js/'; W_SWF = W_ABSPATH + 'content/swf/'; W_TMPL = W_ABSPATH + 'content/js/templates/';
JavaScript
/* 织梦科技 “会员中心表格相关” 动作 2008.10.14 10:48 for Fangyu12@gmail.com Last modified 2008.10.14 17:30 Copyright (c) 2008, dedecms All rights reserved. */ $(document).ready(function(){ //表格奇偶行不同样式 $(".list tbody tr:even").addClass("row0");//偶行 $(".list tbody tr:odd").addClass("row1");//奇行 $(".submit tbody tr:even").addClass("row0");//偶行 $(".submit tbody tr:odd").addClass("row1");//奇行 $(".friend:odd").addClass("row1"); //书签 $("#linkList .flink:odd").addClass("row1"); //点击单元格时该行高亮 $(".list tbody tr td").click(function(){$(this).parent("tr").toggleClass("click");$(this).parent("tr").toggleClass("hover"); }); $(".list tbody tr td").hover(function(){$(this).parent("tr").addClass("hover"); },function(){$(this).parent("tr").removeClass("hover"); }); //checked 全选&反选&单选 $("#checkedClick").click(function(){ $(".list tbody [type='checkbox']").each(function(){ if($(this).attr("checked")){ $(this).removeAttr("checked"); $(".list tbody tr").removeClass("click"); } else{ $(this).attr("checked",'true'); $(".list tbody tr").addClass("click"); } }) }); //checked 全选&反选&单选 $("#checkedClick").click(function(){ $("form [type='checkbox']").each(function(){ if($(this).attr("checked")){ $(this).removeAttr("checked"); } else{ $(this).attr("checked",'true'); } }) }); //项目-收藏 未完带,续头脑混乱ing 注:方域 $(".favorite #allDeploy").click(function(){$(".itemBody").toggleClass("invisible");}); $(".favorite .itemHead").click(function(){$(this).next(".itemBody").toggleClass("invisible");}); //项目-好友friend $(".friend .itemHead").click(function(){$(this).next(".itemBody").toggleClass("invisible");}); //项目-搜索好友friend $(".search .itemHead").click(function(){$(this).next(".itemBody").toggleClass("invisible");}); //项目-探访visit $("#allDeploy").click(function(){$(".itemBody").toggleClass("invisible");}); $(".visit .itemHead").click(function(){$(this).next(".itemBody").toggleClass("invisible");}); //项目-详细资料info $(".info .itemHead").click(function(){ $(this).next(".itemBody").toggleClass("invisible"); $(this).children(".icon16").toggleClass("titHide"); $(this).children(".icon16").toggleClass("titShow")}); //服务购买 /*$(".card").load( function() {$(this).addClass("invisible")}); $(".level").load( function() {$(this).addClass("invisible")}); $(".rechargeable").load( function() {$(this).addClass("invisible")}); $("#buy").click(function(){$(".rechargeable").addClass("invisible");$(".card").removeClass("invisible");$(".level").removeClass("invisible");}); $("#rechargeable").click(function(){$(".rechargeable").removeClass("invisible");$(".card").addClass("invisible");$(".level").addClass("invisible");}); $(".buyCard").click(function(){$(".card").removeClass("invisible");$(".level").addClass("invisible");}); $(".buyLevel").click(function(){$(".card").addClass("invisible");$(".level").removeClass("invisible");});*/ });
JavaScript
$(document).ready(function(){ //表格奇偶行不同样式 $(".list tbody tr:even").addClass("row0");//偶行 $(".list tbody tr:odd").addClass("row1");//奇行 $(".submit tbody tr:even").addClass("row0");//偶行 $(".submit tbody tr:odd").addClass("row1");//奇行 //修正IE6下hover Bug if ( $.browser.msie ){ if($.browser.version == '6.0'){ $("#menuBody li").hover( function(){ //进行判断,是否存在 //先设置所有.act为隐藏 $(".act").each(function(){this.style.visibility='hidden'}); if($(this).find(".act").length != 0) { $(this).children(".act").css("visibility","visible"); } else { $(".act").css("visibility","hidden"); } } ) } } })
JavaScript
<!-- var cal; var isFocus=false; //是否为焦点 //以上为 寒羽枫 2006-06-25 添加的变量 //Download:http://www.codefans.net //选择日期 → 由 寒羽枫 2006-06-25 添加 function SelectDate(obj,strFormat) { var date = new Date(); var by = date.getFullYear()-50; //最小值 → 50 年前 var ey = date.getFullYear()+50; //最大值 → 50 年后 //cal = new Calendar(by, ey,1,strFormat); //初始化英文版,0 为中文版 cal = (cal==null) ? new Calendar(by, ey, 0) : cal; //不用每次都初始化 2006-12-03 修正 cal.dateFormatStyle = strFormat; cal.show(obj); } /**//**//**//** * 返回日期 * @param d the delimiter * @param p the pattern of your date 2006-06-25 由 寒羽枫 修改为根据用户指定的 style 来确定; */ //String.prototype.toDate = function(x, p) { String.prototype.toDate = function(style) { /**//**//**//* if(x == null) x = "-"; if(p == null) p = "ymd"; var a = this.split(x); var y = parseInt(a[p.indexOf("y")]); //remember to change this next century ;) if(y.toString().length <= 2) y += 2000; if(isNaN(y)) y = new Date().getFullYear(); var m = parseInt(a[p.indexOf("m")]) - 1; var d = parseInt(a[p.indexOf("d")]); if(isNaN(d)) d = 1; return new Date(y, m, d); */ var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年 var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月 var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日 if(isNaN(y)) y = new Date().getFullYear(); if(isNaN(m)) m = new Date().getMonth(); if(isNaN(d)) d = new Date().getDate(); var dt ; eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')"); return dt; } /**//**//**//** * 格式化日期 * @param d the delimiter * @param p the pattern of your date * @author meizz */ Date.prototype.format = function(style) { var o = { "M+" : this.getMonth() + 1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "w+" : "日一二三四五六".charAt(this.getDay()), //week "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(style)) { style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for(var k in o){ if(new RegExp("("+ k +")").test(style)){ style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return style; }; /**//**//**//** * 日历类 * @param beginYear 1990 * @param endYear 2010 * @param lang 0(中文)|1(英语) 可自由扩充 * @param dateFormatStyle "yyyy-MM-dd"; * @version 2006-04-01 * @author KimSoft (jinqinghua [at] gmail.com) * @update */ function Calendar(beginYear, endYear, lang, dateFormatStyle) { this.beginYear = 1990; this.endYear = 2010; this.lang = 0; //0(中文) | 1(英文) this.dateFormatStyle = "yyyy-MM-dd"; if (beginYear != null && endYear != null){ this.beginYear = beginYear; this.endYear = endYear; } if (lang != null){ this.lang = lang } if (dateFormatStyle != null){ this.dateFormatStyle = dateFormatStyle } this.dateControl = null; this.panel = this.getElementById("calendarPanel"); this.container = this.getElementById("ContainerPanel"); this.form = null; this.date = new Date(); this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.colors = { "cur_word" : "#FFFFFF", //当日日期文字颜色 "cur_bg" : "#00FF00", //当日日期单元格背影色 "sel_bg" : "#FFCCCC", //已被选择的日期单元格背影色 2006-12-03 寒羽枫添加 "sun_word" : "#FF0000", //星期天文字颜色 "sat_word" : "#0000FF", //星期六文字颜色 "td_word_light" : "#333333", //单元格文字颜色 "td_word_dark" : "#CCCCCC", //单元格文字暗色 "td_bg_out" : "#EFEFEF", //单元格背影色 "td_bg_over" : "#FFCC00", //单元格背影色 "tr_word" : "#FFFFFF", //日历头文字颜色 "tr_bg" : "#666666", //日历头背影色 "input_border" : "#CCCCCC", //input控件的边框颜色 "input_bg" : "#EFEFEF" //input控件的背影色 } this.draw(); this.bindYear(); this.bindMonth(); this.changeSelect(); this.bindData(); } /**//**//**//** * 日历类属性(语言包,可自由扩展) */ Calendar.language = { "year" : [[""], [""]], "months" : [["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"], ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"] ], "weeks" : [["日","一","二","三","四","五","六"], ["SUN","MON","TUR","WED","THU","FRI","SAT"] ], "clear" : [["清空"], ["CLS"]], "today" : [["今天"], ["TODAY"]], "close" : [["关闭"], ["CLOSE"]] } Calendar.prototype.draw = function() { calendar = this; var mvAry = []; //mvAry[mvAry.length] = ' <form name="calendarForm" style="margin: 0px;">'; //因 <form> 不能嵌套, 2006-12-01 由寒羽枫改用 Div mvAry[mvAry.length] = ' <div name="calendarForm" style="margin: 0px;">'; mvAry[mvAry.length] = ' <table width="100%" border="0" cellpadding="0" cellspacing="1">'; mvAry[mvAry.length] = ' <tr>'; mvAry[mvAry.length] = ' <th align="left" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="prevMonth" type="button" id="prevMonth" value="&lt;" /></th>'; mvAry[mvAry.length] = ' <th align="center" width="98%" nowrap="nowrap"><select name="calendarYear" id="calendarYear" style="font-size:12px;"></select><select name="calendarMonth" id="calendarMonth" style="font-size:12px;"></select></th>'; mvAry[mvAry.length] = ' <th align="right" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="nextMonth" type="button" id="nextMonth" value="&gt;" /></th>'; mvAry[mvAry.length] = ' </tr>'; mvAry[mvAry.length] = ' </table>'; mvAry[mvAry.length] = ' <table id="calendarTable" width="100%" style="border:0px solid #CCCCCC;background-color:#FFFFFF" border="0" cellpadding="3" cellspacing="1">'; mvAry[mvAry.length] = ' <tr>'; for(var i = 0; i < 7; i++) { mvAry[mvAry.length] = ' <th style="font-weight:normal;background-color:' + calendar.colors["tr_bg"] + ';color:' + calendar.colors["tr_word"] + ';">' + Calendar.language["weeks"][this.lang][i] + '</th>'; } mvAry[mvAry.length] = ' </tr>'; for(var i = 0; i < 6;i++){ mvAry[mvAry.length] = ' <tr align="center">'; for(var j = 0; j < 7; j++) { if (j == 0){ mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sun_word"] + ';"></td>'; } else if(j == 6) { mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sat_word"] + ';"></td>'; } else { mvAry[mvAry.length] = ' <td style="cursor:default;"></td>'; } } mvAry[mvAry.length] = ' </tr>'; } mvAry[mvAry.length] = ' <tr style="background-color:' + calendar.colors["input_bg"] + ';">'; mvAry[mvAry.length] = ' <th colspan="2"><input name="calendarClear" type="button" id="calendarClear" value="' + Calendar.language["clear"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' <th colspan="3"><input name="calendarToday" type="button" id="calendarToday" value="' + Calendar.language["today"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' <th colspan="2"><input name="calendarClose" type="button" id="calendarClose" value="' + Calendar.language["close"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' </tr>'; mvAry[mvAry.length] = ' </table>'; //mvAry[mvAry.length] = ' </from>'; mvAry[mvAry.length] = ' </div>'; this.panel.innerHTML = mvAry.join(""); /**//******** 以下代码由寒羽枫 2006-12-01 添加 **********/ var obj = this.getElementById("prevMonth"); obj.onclick = function () {calendar.goPrevMonth(calendar);} obj.onblur = function () {calendar.onblur();} this.prevMonth= obj; obj = this.getElementById("nextMonth"); obj.onclick = function () {calendar.goNextMonth(calendar);} obj.onblur = function () {calendar.onblur();} this.nextMonth= obj; obj = this.getElementById("calendarClear"); obj.onclick = function () {calendar.dateControl.value = "";calendar.hide();} this.calendarClear = obj; obj = this.getElementById("calendarClose"); obj.onclick = function () {calendar.hide();} this.calendarClose = obj; obj = this.getElementById("calendarYear"); obj.onchange = function () {calendar.update(calendar);} obj.onblur = function () {calendar.onblur();} this.calendarYear = obj; obj = this.getElementById("calendarMonth"); with(obj) { onchange = function () {calendar.update(calendar);} onblur = function () {calendar.onblur();} }this.calendarMonth = obj; obj = this.getElementById("calendarToday"); obj.onclick = function () { var today = new Date(); calendar.date = today; calendar.year = today.getFullYear(); calendar.month = today.getMonth(); calendar.changeSelect(); calendar.bindData(); calendar.dateControl.value = today.format(calendar.dateFormatStyle); calendar.hide(); } this.calendarToday = obj; /**//******** 以上代码由寒羽枫 2006-12-01 添加 **********/ /**//* //this.form = document.forms["calendarForm"]; this.form.prevMonth.onclick = function () {calendar.goPrevMonth(this);} this.form.nextMonth.onclick = function () {calendar.goNextMonth(this);} this.form.prevMonth.onblur = function () {calendar.onblur();} this.form.nextMonth.onblur = function () {calendar.onblur();} this.form.calendarClear.onclick = function () {calendar.dateControl.value = "";calendar.hide();} this.form.calendarClose.onclick = function () {calendar.hide();} this.form.calendarYear.onchange = function () {calendar.update(this);} this.form.calendarMonth.onchange = function () {calendar.update(this);} this.form.calendarYear.onblur = function () {calendar.onblur();} this.form.calendarMonth.onblur = function () {calendar.onblur();} this.form.calendarToday.onclick = function () { var today = new Date(); calendar.date = today; calendar.year = today.getFullYear(); calendar.month = today.getMonth(); calendar.changeSelect(); calendar.bindData(); calendar.dateControl.value = today.format(calendar.dateFormatStyle); calendar.hide(); } */ } //年份下拉框绑定数据 Calendar.prototype.bindYear = function() { //var cy = this.form.calendarYear; var cy = this.calendarYear;//2006-12-01 由寒羽枫修改 cy.length = 0; for (var i = this.beginYear; i <= this.endYear; i++){ cy.options[cy.length] = new Option(i + Calendar.language["year"][this.lang], i); } } //月份下拉框绑定数据 Calendar.prototype.bindMonth = function() { //var cm = this.form.calendarMonth; var cm = this.calendarMonth;//2006-12-01 由寒羽枫修改 cm.length = 0; for (var i = 0; i < 12; i++){ cm.options[cm.length] = new Option(Calendar.language["months"][this.lang][i], i); } } //向前一月 Calendar.prototype.goPrevMonth = function(e){ if (this.year == this.beginYear && this.month == 0){return;} this.month--; if (this.month == -1) { this.year--; this.month = 11; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //向后一月 Calendar.prototype.goNextMonth = function(e){ if (this.year == this.endYear && this.month == 11){return;} this.month++; if (this.month == 12) { this.year++; this.month = 0; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //改变SELECT选中状态 Calendar.prototype.changeSelect = function() { //var cy = this.form.calendarYear; //var cm = this.form.calendarMonth; var cy = this.calendarYear;//2006-12-01 由寒羽枫修改 var cm = this.calendarMonth; for (var i= 0; i < cy.length; i++){ if (cy.options[i].value == this.date.getFullYear()){ cy[i].selected = true; break; } } for (var i= 0; i < cm.length; i++){ if (cm.options[i].value == this.date.getMonth()){ cm[i].selected = true; break; } } } //更新年、月 Calendar.prototype.update = function (e){ //this.year = e.form.calendarYear.options[e.form.calendarYear.selectedIndex].value; //this.month = e.form.calendarMonth.options[e.form.calendarMonth.selectedIndex].value; this.year = e.calendarYear.options[e.calendarYear.selectedIndex].value;//2006-12-01 由寒羽枫修改 this.month = e.calendarMonth.options[e.calendarMonth.selectedIndex].value; this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //绑定数据到月视图 Calendar.prototype.bindData = function () { var calendar = this; var dateArray = this.getMonthViewArray(this.date.getYear(), this.date.getMonth()); var tds = this.getElementById("calendarTable").getElementsByTagName("td"); for(var i = 0; i < tds.length; i++) { //tds[i].style.color = calendar.colors["td_word_light"]; tds[i].style.backgroundColor = calendar.colors["td_bg_out"]; tds[i].onclick = function () {return;} tds[i].onmouseover = function () {return;} tds[i].onmouseout = function () {return;} if (i > dateArray.length - 1) break; tds[i].innerHTML = dateArray[i]; if (dateArray[i] != "&nbsp;"){ tds[i].onclick = function () { if (calendar.dateControl != null){ calendar.dateControl.value = new Date(calendar.date.getFullYear(), calendar.date.getMonth(), this.innerHTML).format(calendar.dateFormatStyle); } calendar.hide(); } tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["td_bg_out"]; } if (new Date().format(calendar.dateFormatStyle) == new Date(calendar.date.getFullYear(), calendar.date.getMonth(), dateArray[i]).format(calendar.dateFormatStyle)) { //tds[i].style.color = calendar.colors["cur_word"]; tds[i].style.backgroundColor = calendar.colors["cur_bg"]; tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["cur_bg"]; } //continue; //若不想当天单元格的背景被下面的覆盖,请取消注释 → 2006-12-03 寒羽枫添加 }//end if //设置已被选择的日期单元格背影色 2006-12-03 寒羽枫添加 if (calendar.dateControl != null && calendar.dateControl.value == new Date(calendar.date.getFullYear(), calendar.date.getMonth(), dateArray[i]).format(calendar.dateFormatStyle)) { tds[i].style.backgroundColor = calendar.colors["sel_bg"]; tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["sel_bg"]; } } } } } //根据年、月得到月视图数据(数组形式) Calendar.prototype.getMonthViewArray = function (y, m) { var mvArray = []; var dayOfFirstDay = new Date(y, m, 1).getDay(); var daysOfMonth = new Date(y, m + 1, 0).getDate(); for (var i = 0; i < 42; i++) { mvArray[i] = "&nbsp;"; } for (var i = 0; i < daysOfMonth; i++){ mvArray[i + dayOfFirstDay] = i + 1; } return mvArray; } //扩展 document.getElementById(id) 多浏览器兼容性 from meizz tree source Calendar.prototype.getElementById = function(id){ if (typeof(id) != "string" || id == "") return null; if (document.getElementById) return document.getElementById(id); if (document.all) return document.all(id); try {return eval(id);} catch(e){ return null;} } //扩展 object.getElementsByTagName(tagName) Calendar.prototype.getElementsByTagName = function(object, tagName){ if (document.getElementsByTagName) return document.getElementsByTagName(tagName); if (document.all) return document.all.tags(tagName); } //取得HTML控件绝对位置 Calendar.prototype.getAbsPoint = function (e){ var x = e.offsetLeft; var y = e.offsetTop; while(e = e.offsetParent){ x += e.offsetLeft; y += e.offsetTop; } return {"x": x, "y": y}; } //显示日历 Calendar.prototype.show = function (dateObj, popControl) { if (dateObj == null){ throw new Error("arguments[0] is necessary") } this.dateControl = dateObj; //if (dateObj.value.length > 0){ //this.date = new Date(dateObj.value.toDate()); //this.date = new Date(dateObj.value.toDate(this.dateFormatStyle));//由寒羽枫修改,带入用户指定的 style this.date = (dateObj.value.length > 0) ? new Date(dateObj.value.toDate(this.dateFormatStyle)) : new Date() ;//2006-12-03 寒羽枫添加 → 若为空则显示当前月份 this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.changeSelect(); this.bindData(); //} if (popControl == null){ popControl = dateObj; } var xy = this.getAbsPoint(popControl); this.panel.style.left = xy.x -25 + "px"; this.panel.style.top = (xy.y + dateObj.offsetHeight) + "px"; //由寒羽枫 2006-06-25 修改 → 把 visibility 变为 display,并添加失去焦点的事件 //this.setDisplayStyle("select", "hidden"); //this.panel.style.visibility = "visible"; //this.container.style.visibility = "visible"; this.panel.style.display = ""; this.container.style.display = ""; dateObj.onblur = function(){calendar.onblur();} this.container.onmouseover = function(){isFocus=true;} this.container.onmouseout = function(){isFocus=false;} } //隐藏日历 Calendar.prototype.hide = function() { //this.setDisplayStyle("select", "visible"); //this.panel.style.visibility = "hidden"; //this.container.style.visibility = "hidden"; this.panel.style.display = "none"; this.container.style.display = "none"; isFocus=false; } //焦点转移时隐藏日历 → 由寒羽枫 2006-06-25 添加 Calendar.prototype.onblur = function() { if(!isFocus){this.hide();} } //以下由寒羽枫 2006-06-25 修改 → 用<iframe> 遮住 IE 的下拉框 /**//**//**//* //设置控件显示或隐藏 Calendar.prototype.setDisplayStyle = function(tagName, style) { var tags = this.getElementsByTagName(null, tagName) for(var i = 0; i < tags.length; i++) { if (tagName.toLowerCase() == "select" && (tags[i].name == "calendarYear" || tags[i].name == "calendarMonth")){ continue; } //tags[i].style.visibility = style; tags[i].style.display = style; } } */ //document.write('<div id="ContainerPanel" style="visibility:hidden"><div id="calendarPanel" style="position: absolute;visibility: hidden;z-index: 9999;'); document.write('<div id="ContainerPanel" style="display:none"><div id="calendarPanel" style="position: absolute;display: none;z-index: 9999;'); document.write('background-color: #FFFFFF;border: 1px solid #CCCCCC;width:175px;font-size:12px;"></div>'); if(document.all) { document.write('<iframe style="position:absolute;z-index:2000;width:expression(this.previousSibling.offsetWidth);'); document.write('height:expression(this.previousSibling.offsetHeight);'); document.write('left:expression(this.previousSibling.offsetLeft);top:expression(this.previousSibling.offsetTop);'); document.write('display:expression(this.previousSibling.style.display);" scrolling="no" frameborder="no"></iframe>'); } document.write('</div>'); //-->
JavaScript
<!-- $(document).ready(function() { //用户类型 if($('.usermtype2').attr("checked")==true) $('#uwname').text('公司名称:'); $('.usermtype').click(function() { $('#uwname').text('真实姓名:'); }); $('.usermtype2').click(function() { $('#uwname').text('公司名称:'); }); //checkSubmit $('#regUser').submit(function () { if(!$('#agree').get(0).checked) { alert("你必须同意注册协议!"); return false; } if($('#txtUsername').val()==""){ $('#txtUsername').focus(); alert("用户名不能为空!"); return false; } if($('#txtPassword').val()=="") { $('#txtPassword').focus(); alert("登陆密码不能为空!"); return false; } if($('#userpwdok').val()!=$('#txtPassword').val()) { $('#userpwdok').focus(); alert("两次密码不一致!"); return false; } if($('#uname').val()=="") { $('#uname').focus(); alert("用户真实姓名不能为空!"); return false; } if($('#vdcode').val()=="") { $('#vdcode').focus(); alert("验证码不能为空!"); return false; } }) //AJAX changChickValue $("#txtUsername").change( function() { $.ajax({type: reMethod,url: "index_do.php", data: "dopost=checkuser&fmdo=user&cktype=1&uid="+$("#txtUsername").val(), dataType: 'html', success: function(result){$("#_userid").html(result);}}); }); /* $("#uname").change( function() { $.ajax({type: reMethod,url: "index_do.php", data: "dopost=checkuser&fmdo=user&cktype=0&uid="+$("#uname").val(), dataType: 'html', success: function(result){$("#_uname").html(result);}}); }); */ $("#email").change( function() { var sEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; if(!sEmail.exec($("#email").val())) { $('#_email').html("<font color='red'><b>×Email格式不正确</b></font>"); $('#email').focus(); }else{ $.ajax({type: reMethod,url: "index_do.php", data: "dopost=checkmail&fmdo=user&email="+$("#email").val(), dataType: 'html', success: function(result){$("#_email").html(result);}}); } }); $('#txtPassword').change( function(){ if($('#txtPassword').val().length < pwdmin) { $('#_userpwdok').html("<font color='red'><b>×密码不能小于"+pwdmin+"位</b></font>"); } else if($('#userpwdok').val()!=$('txtPassword').val()) { $('#_userpwdok').html("<font color='red'><b>×两次输入密码不一致</b></font>"); } else if($('#userpwdok').val().length < pwdmin) { $('#_userpwdok').html("<font color='red'><b>×密码不能小于"+pwdmin+"位</b></font>"); } else { $('#_userpwdok').html("<font color='#4E7504'><b>√填写正确</b></font>"); } }); $('#userpwdok').change( function(){ if($('#txtPassword').val().length < pwdmin) { $('#_userpwdok').html("<font color='red'><b>×密码不能小于"+pwdmin+"位</b></font>"); } else if($('#userpwdok').val()=='') { $('#_userpwdok').html("<b>请填写确认密码</b>"); } else if($('#userpwdok').val()!=$('#txtPassword').val()) { $('#_userpwdok').html("<font color='red'><b>×两次输入密码不一致</b></font>"); } else { $('#_userpwdok').html("<font color='#4E7504'><b>√填写正确</b></font>"); } }); $("a[href*='#vdcode'],#vdimgck").bind("click", function(){ $("#vdimgck").attr("src","../include/vdimgck.php?tag="+Math.random()); return false; }); }); -->
JavaScript
function checkSubmit() { if(document.addcontent.title.value==""){ alert("名称不能为空!"); document.addcontent.title.focus(); return false; } if(document.addcontent.tags.value==0){ alert("Tag标签不能为空!"); return false; } if(document.addcontent.description.value==0){ alert("文章摘要不能为空!"); return false; } if(document.addcontent.litpic.value==0){ alert("缩略图不能为空!"); return false; } if(document.addcontent.typeid.value==0){ alert("隶属栏目必须选择!"); return false; } if(document.addcontent.typeid.options && document.addcontent.typeid.options[document.addcontent.typeid.selectedIndex].className!='option3') { alert("隶属栏目必须选择白色背景的项目!"); return false; } if(document.addcontent.vdcode.value==""){ document.addcontent.vdcode.focus(); alert("验证码不能为空!"); return false; } }
JavaScript
$(document).ready(function(){ //表格奇偶行不同样式 $(".list tbody tr:even").addClass("row0");//偶行 $(".list tbody tr:odd").addClass("row1");//奇行 $(".submit tbody tr:even").addClass("row0");//偶行 $(".submit tbody tr:odd").addClass("row1");//奇行 //修正IE6下hover Bug if ( $.browser.msie ){ if($.browser.version == '6.0'){ $("#menuBody li").hover( function(){ //进行判断,是否存在 //先设置所有.act为隐藏 $(".act").each(function(){this.style.visibility='hidden'}); if($(this).find(".act").length != 0) { $(this).children(".act").css("visibility","visible"); } else { $(".act").css("visibility","hidden"); } } ) } } })
JavaScript
$(function(){ //文本框Style $(".text").mouseover(function(){ $(this).addClass("text_o"); }).mouseout(function(){ $(this).removeClass("text_o"); }).focus(function(){ $(this).addClass("text_s"); }).blur(function(){ $(this).removeClass("text_s"); }); $(".intxt").mouseover(function(){ $(this).addClass("text_o"); }).mouseout(function(){ $(this).removeClass("text_o"); }).focus(function(){ $(this).addClass("text_s"); }).blur(function(){ $(this).removeClass("text_s"); }); })
JavaScript
//显示表情 function showFace() { if($('#share_textarea').val() == '来,说点啥吧...'){ $('#share_textarea').val(''); } //采用普通样式 //$('#mood_msg_menu').css('display', 'block'); var leftpos = $(".share02").position().left; //获取位置并且决定表情框弹出位置 $('#mood_msg_menu').css('left', leftpos+'px'); $('#mood_msg_menu').show('normal'); //$('#mood_add'). if($('#mood_face_bg')) {$('#mood_face_bg').remove();} var modDiv = '<div id="mood_face_bg" style="position: absolute; top: 0px; left: 0px; width: 100%; height: 788px; z-index: 10000; opacity: 0;" onclick="hideFace()"/>' $('#baseParent').append(modDiv); } //隐藏表情 function hideFace() { //alert($('#share_textarea').val()); if($('#share_textarea').val() == ''){ $('#share_textarea').val('来,说点啥吧...'); } $('#mood_msg_menu').css('display', 'none'); if($('#mood_face_bg')) {$('#mood_face_bg').remove();} } //增加表情 function addFace(faceid) { //通过faceid解析为表情代码添加到编辑框 var facecode; facecode = '[face:' + faceid + ']'; $('#share_textarea').val($('#share_textarea').val() + facecode); }
JavaScript
<!-- function $Nav(){ if(window.navigator.userAgent.indexOf("MSIE")>=1) return 'IE'; else if(window.navigator.userAgent.indexOf("Firefox")>=1) return 'FF'; else return "OT"; } function $Obj(objname){ return document.getElementById(objname); } function ShowColor(){ if(document.all){ var posLeft = window.event.clientY-100; var posTop = window.event.clientX-400; } else{ var posLeft = 100; var posTop = 100; } var fcolor=showModalDialog("img/color.htm?ok",false,"dialogWidth:106px;dialogHeight:110px;status:0;dialogTop:"+posTop+";dialogLeft:"+posLeft); if(fcolor!=null && fcolor!="undefined") document.form1.color.value = fcolor; } function ShowHide(objname){ var obj = $Obj(objname); if(obj.style.display == "block" || obj.style.display == ""){ obj.style.display = "none"; } else{ obj.style.display = "block"; } } function ShowObj(objname){ var obj = $Obj(objname); obj.style.display = "block"; } function HideObj(objname){ var obj = $Obj(objname); obj.style.display = "none"; } function ShowItem1(){ ShowObj('head1'); ShowObj('needset'); HideObj('head2'); HideObj('adset'); } function ShowItem2(){ ShowObj('head2'); ShowObj('adset'); HideObj('head1'); HideObj('needset'); } function SeePic(img,f){ if ( f.value != "" ) { img.src = f.value; } } function SeePicNew(imgdid,f) { if(f.value=='') return ; var newPreview = document.getElementById(imgdid); var filepath = 'file:///'+f.value.replace(/\\/g,"/").replace(/\:/,"|"); var image = new Image(); var ImgD = new Image(); ImgD.src = filepath; image.src = ImgD.src; FitWidth = 150; FitHeight = 100; if(image.width>0 && image.height>0) { if(image.width/image.height>= FitWidth/FitHeight) { if(image.width>FitWidth) { ImgD.width=FitWidth; ImgD.height=(image.height*FitWidth)/image.width; } else { ImgD.width=image.width; ImgD.height=image.height; } } else { if(image.height>FitHeight) { ImgD.height=FitHeight; ImgD.width=(image.width*FitHeight)/image.height; } else { ImgD.width=image.width; ImgD.height=image.height; } } } newPreview.style.width = ImgD.width+"px"; newPreview.style.height = ImgD.height+"px"; if(window.navigator.userAgent.indexOf("MSIE") < 1) { newPreview.style.background = "url('"+ImgD.src+"') no-repeat"; } else { newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ImgD.src+"',sizingMethod='scale')"; } ImgD = image = null; //newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = f.value; } function SelectFlash(){ if($Nav()=='IE'){ var posLeft = window.event.clientX-300; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } window.open("uploads_select.php?mediatype=2&f=form1.flashurl", "popUpFlashWin", "scrollbars=yes,resizable=yes,statebar=no,width=500,height=350,left="+posLeft+", top="+posTop); } function SelectMedia(fname){ if($Nav()=='IE'){ var posLeft = window.event.clientX-200; var posTop = window.event.clientY; } else{ var posLeft = 100;var posTop = 100; } window.open("uploads_select.php?mediatype=3&f="+fname, "popUpFlashWin", "scrollbars=yes,resizable=yes,statebar=no,width=500,height=350,left="+posLeft+", top="+posTop); } function SelectSoft(fname){ if($Nav()=='IE'){ var posLeft = window.event.clientX-200; var posTop = window.event.clientY-50; } else{ var posLeft = 100; var posTop = 100; } window.open("uploads_select.php?mediatype=4&f="+fname, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=400,left="+posLeft+", top="+posTop); } function SelectImage(fname,stype){ if($Nav()=='IE'){ var posLeft = window.event.clientX-100; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } if(!fname) fname = 'form1.picname'; if(!stype) stype = ''; window.open("uploads_select.php?mediatype=1&f="+fname+"&imgstick="+stype, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=400,left="+posLeft+", top="+posTop); } function SelectImageN(fname,stype,vname){ if($Nav()=='IE'){ var posLeft = window.event.clientX-100; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } if(!fname) fname = 'form1.picname'; if(!stype) stype = ''; window.open("uploads_select.php?mediatype=1&f="+fname+"&imgstick="+stype+"&v="+vname, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=400,left="+posLeft+", top="+posTop); } function SelectKeywords(f){ if($Nav()=='IE'){ var posLeft = window.event.clientX-350; var posTop = window.event.clientY-200; } else{ var posLeft = 100; var posTop = 100; } window.open("article_keywords_select.php?f="+f, "popUpkwWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=450,left="+posLeft+", top="+posTop); } function InitPage(){ var selsource = $Obj('selsource'); var selwriter = $Obj('selwriter'); if(selsource){ selsource.onmousedown=function(e){ SelectSource(e); } } if(selwriter){ selwriter.onmousedown=function(e){ SelectWriter(e); } } } function OpenMyWin(surl){ window.open(surl, "popUpMyWin", "scrollbars=yes,resizable=yes,statebar=no,width=500,height=350,left=200, top=100"); } function PutSource(str){ var osource = $Obj('source'); if(osource) osource.value = str; } function PutWriter(str){ var owriter = $Obj('writer'); if(owriter) owriter.value = str; } function SelectSource(e){ LoadNewDiv(e,'article_select_sw.php?t=source&k=8','_mysource'); } function SelectWriter(e){ LoadNewDiv(e,'article_select_sw.php?t=writer&k=8','_mywriter'); } function LoadNewDiv(e,surl,oname){ if($Nav()=='IE'){ var posLeft = window.event.clientX-20; var posTop = window.event.clientY-20; } else{ var posLeft = e.pageX-20; var posTop = e.pageY-20; } var newobj = $Obj(oname); if(!newobj){ newobj = document.createElement("DIV"); newobj.id = oname; newobj.style.position='absolute'; newobj.className = "dlg"; newobj.style.top = posTop; newobj.style.left = posLeft; document.body.appendChild(newobj); } else{ newobj.style.display = "block"; } if(newobj.innerHTML.length<10){ var myajax = new DedeAjax(newobj); myajax.SendGet(surl); } } function ShowUrlTr(){ var jumpTest = $Obj('isjump'); var jtr = $Obj('redirecturltr'); if(jumpTest.checked) jtr.style.display = "block"; else jtr.style.display = "none"; } function ShowUrlTrEdit(){ ShowUrlTr(); var jumpTest = $Obj('isjump'); var rurl = $Obj('redirecturl'); if(!jumpTest.checked) rurl.value=""; } function CkRemote(ckname,fname){ var ckBox = $Obj(ckname); var fileBox = $Obj(fname); if(ckBox.checked){ fileBox.style.display = 'none'; }else{ fileBox.style.display = 'block'; } } -->
JavaScript
<!-- function inputAutoClear(ipt) { ipt.onfocus=function() {if(this.value==this.defaultValue){this.value='';}}; ipt.onblur=function() {if(this.value==''){this.value=this.defaultValue;}}; ipt.onfocus(); } //-->
JavaScript
<!-- function checkSubmit() { if(document.form1.title.value=='') { alert("图集标题不能为空!"); document.form1.title.focus(); return false; } if(document.form1.typeid.value==0) { alert("隶属栏目必须选择!"); return false; } if(document.form1.typeid.options[document.form1.typeid.selectedIndex].className!='option3') { alert("隶属栏目必须选择白色背景的项目!"); return false; } document.form1.imagebody.value = $Obj('copyhtml').innerHTML; $Obj('postloader').style.display = 'block'; } function CheckSelTable(nnum){ var cbox = $Obj('isokcheck'+nnum); var seltb = $Obj('seltb'+nnum); if(!cbox.checked) seltb.style.display = 'none'; else seltb.style.display = 'block'; } var startNum = 1; function MakeUpload(mnum) { var endNum = 0; var upfield = document.getElementById("uploadfield"); var pnumObj = document.getElementById("picnum"); var fhtml = ""; var dsel = " checked='checked' "; var dplay = "display:none"; if(mnum==0) endNum = startNum + Number(pnumObj.value); else endNum = mnum; if(endNum>120) endNum = 120; //$Obj('handfield').style.display = 'block'; for(startNum;startNum < endNum;startNum++) { if(startNum==1){ dsel = " checked='checked' "; dplay = "block"; }else { dsel = " "; dplay = "display:none"; } fhtml = ''; fhtml += "<table width='100%'><tr><td><input type='checkbox' name='isokcheck"+startNum+"' id='isokcheck"+startNum+"' value='1' class='np' "+dsel+" onClick='CheckSelTable("+startNum+")' />显示图片 "+startNum+" 的上传框</td></tr></table>"; fhtml += "<table width='610' border=\"0\" id=\"seltb"+startNum+"\" cellpadding=\"1\" cellspacing=\"1\" bgcolor=\"#E8F5D6\" style=\"margin-bottom:6px;margin-left:10px;"+dplay+"\"><tobdy>"; fhtml += "<tr bgcolor=\"#F7F7F7\">\r\n"; fhtml += "<td height=\"25\" colspan=\"2\"> <strong>图片"+startNum+":</strong></td>"; fhtml += "</tr>"; fhtml += "<tr bgcolor=\"#FFFFFF\"> "; fhtml += "<td width=\"510\" height=\"25\">  本地上传: "; fhtml += "<input type=\"file\" name='imgfile"+startNum+"' style=\"width:200px\" class=\"intxt\" onChange=\"SeePicNew('divpicview"+startNum+"',this);\" /> <nobr>可填远程网址</nobr></td>"; fhtml += "<td width=\"100\" rowspan=\"2\" align=\"center\"><div id='divpicview"+startNum+"' class='divpre'></div></td>"; fhtml += "</tr>"; fhtml += "<tr bgcolor=\"#FFFFFF\"> "; fhtml += "<td height=\"56\" valign=\"top\"> 图片简介: "; fhtml += "<textarea name='imgmsg"+startNum+"' style=\"height:46px;width:330px\"></textarea></td>"; fhtml += "</tr></tobdy></table>\r\n"; upfield.innerHTML += fhtml; } } function TestGet() { LoadTestDiv(); } var vcc = 0; function LoadTestDiv() { var posLeft = 100; var posTop = 100; var newobj = $Obj('_myhtml'); $Obj('imagebody').value = $Obj('copyhtml').innerHTML; var dfstr = '粘贴到这里...'; if($Obj('imagebody').value.length <= dfstr.length) { alert('你还没有粘贴任何东西都编辑框哦!'); return; } if(!newobj){ newobj = document.createElement("DIV"); newobj.id = '_myhtml'; newobj.style.position='absolute'; newobj.className = "dlg2"; newobj.style.top = posTop; newobj.style.left = posLeft; document.body.appendChild(newobj); } else{ newobj.style.display = "block"; } var myajax = new DedeAjax(newobj,false,true,'-','-','...'); var v = $Obj('imagebody').value; vcc++; //utf8 myajax.AddKeyUtf8('myhtml',v); myajax.AddKeyUtf8('vcc',vcc); myajax.SendPost2('album_testhtml.php'); //gbk //myajax.SendGet2("album_testhtml.php?vcc="+vcc+"&myhtml="+v); DedeXHTTP = null; } function checkMuList(psid,cmid) { if($Obj('pagestyle3').checked) { $Obj('spagelist').style.display = 'none'; } else if($Obj('pagestyle1').checked) { $Obj('spagelist').style.display = 'block'; } else { $Obj('spagelist').style.display = 'none'; } } //图集,显示与隐藏zip文件选项 function ShowZipField(formitem,zipid,upid) { if(formitem.checked){ $Obj(zipid).style.display = 'block'; $Obj(upid).style.display = 'none'; //$Obj('handfield').style.display = 'none'; $Obj('formhtml').checked = false; $Obj('copyhtml').innerHTML = ''; }else { $Obj(zipid).style.display = 'none'; //$Obj('handfield').style.display = 'block'; } } //图集,显示与隐藏Html编辑框 function ShowHtmlField(formitem,htmlid,upid) { if($Nav()!="IE"){ alert("该方法不适用于非IE浏览器!"); return ; } if(formitem.checked){ $Obj(htmlid).style.display = 'block'; //$Obj(upid).style.display = 'none'; //$Obj('handfield').style.display = 'none'; //$Obj('formzip').checked = false; }else { $Obj(htmlid).style.display = 'none'; //$Obj('handfield').style.display = 'block'; $Obj('copyhtml').innerHTML = ''; } } -->
JavaScript
//创建多组对话框 function createDialog(options) { options = $.extend({title: "对话框"}, options || {}); var dialog = new Boxy("<div><p>这是一个对话框 <a href='#nogo' onclick='Boxy.get(this).hide(); return false'>单击我!</a></p></div>", options); return false; }
JavaScript
/****************************************************************************************** * 检查密码强度 ******************************************************************************************/ checkPasswordLevel = function(strPassword) { var result = 0; if ( strPassword.length == 0) result += 0; else if ( strPassword.length<8 && strPassword.length >0 ) result += 5; else if (strPassword.length>10) result += 25; else result += 10; //check letter var bHave = false; var bAll = false; var capital = strPassword.match(/[A-Z]{1}/);//找大写字母 var small = strPassword.match(/[a-z]{1}/);//找小写字母 if ( capital == null && small == null ) { result += 0; //没有字母 bHave = false; } else if ( capital != null && small != null ) { result += 20; bAll = true; } else { result += 10; bAll = true; } //alert("检查字母:"+result); //检查数字 var bDigi = false; var digitalLen = 0; for ( var i=0; i<strPassword.length; i++) { if ( strPassword.charAt(i) <= '9' && strPassword.charAt(i) >= '0' ) { bDigi = true; digitalLen += 1; //alert(strPassword[i]); } } if ( digitalLen==0 )//没有数字 { result += 0; bDigi = false; } else if (digitalLen>2)//2个数字以上 { result += 20 ; bDigi = true; } else { result += 10; bDigi = true; } //alert("数字个数:" + digitalLen); //alert("检查数字:"+result); //检查非单词字符 var bOther = false; var otherLen = 0; for (var i=0; i<strPassword.length; i++) { if ( (strPassword.charAt(i)>='0' && strPassword.charAt(i)<='9') || (strPassword.charAt(i)>='A' && strPassword.charAt(i)<='Z') || (strPassword.charAt(i)>='a' && strPassword.charAt(i)<='z')) continue; otherLen += 1; bOther = true; } if ( otherLen == 0 )//没有非单词字符 { result += 0; bOther = false; } else if ( otherLen >1)//1个以上非单词字符 { result +=25 ; bOther = true; } else { result +=10; bOther = true; } //alert("检查非单词:"+result); //检查额外奖励 if ( bAll && bDigi && bOther) result += 5; else if (bHave && bDigi && bOther) result += 3; else if (bHave && bDigi ) result += 2; //alert("检查额外奖励:"+result); var level = ""; //根据分数来算密码强度的等级 if ( result >=80 ) level = "rank r7"; else if ( result>=70) level = "rank r6"; else if ( result>=60) level = "rank r5"; else if ( result>=50) level = "rank r4"; else if ( result>=40) level = "rank r3"; else if ( result>20) level = "rank r2"; else if ( result>0) level = "rank r1"; else level = "rank r0"; // alert("return:"+level); return level.toString(); } /****************************************************************************************** * 设置密码强度样式 ******************************************************************************************/ setPasswordLevel = function(passwordObj, levelObj) { var level = "rank r0"; level = checkPasswordLevel(passwordObj.value); levelObj.className = level; //alert("level"+level); }
JavaScript
/** * Boxy 0.1.4 - Facebook-style dialog, with frills * * (c) 2008 Jason Frame * Licensed under the MIT License (LICENSE) */ /* * jQuery plugin * * Options: * message: confirmation message for form submit hook (default: "Please confirm:") * * Any other options - e.g. 'clone' - will be passed onto the boxy constructor (or * Boxy.load for AJAX operations) */ jQuery.fn.boxy = function(options) { options = options || {}; return this.each(function() { var node = this.nodeName.toLowerCase(), self = this; if (node == 'a') { jQuery(this).click(function() { var active = Boxy.linkedTo(this), href = this.getAttribute('href'), localOptions = jQuery.extend({actuator: this, title: this.title}, options); if (active) { active.show(); } else if (href.indexOf('#') >= 0) { var content = jQuery(href.substr(href.indexOf('#'))), newContent = content.clone(true); content.remove(); localOptions.unloadOnHide = false; new Boxy(newContent, localOptions); } else { // fall back to AJAX; could do with a same-origin check if (!localOptions.cache) localOptions.unloadOnHide = true; Boxy.load(this.href, localOptions); } return false; }); } else if (node == 'form') { jQuery(this).bind('submit.boxy', function() { Boxy.confirm(options.message || '请确认:', function() { jQuery(self).unbind('submit.boxy').submit(); }); return false; }); } }); }; // // Boxy Class function Boxy(element, options) { this.boxy = jQuery(Boxy.WRAPPER); jQuery.data(this.boxy[0], 'boxy', this); this.visible = false; this.options = jQuery.extend({}, Boxy.DEFAULTS, options || {}); if (this.options.modal) { this.options = jQuery.extend(this.options, {center: true, draggable: false}); } // options.actuator == DOM element that opened this boxy // association will be automatically deleted when this boxy is remove()d if (this.options.actuator) { jQuery.data(this.options.actuator, 'active.boxy', this); } this.setContent(element || "<div></div>"); this._setupTitleBar(); this.boxy.css('display', 'none').appendTo(document.body); this.toTop(); if (this.options.fixed) { if (jQuery.browser.msie && jQuery.browser.version < 7) { this.options.fixed = false; // IE6 doesn't support fixed positioning } else { this.boxy.addClass('fixed'); } } if (this.options.center && Boxy._u(this.options.x, this.options.y)) { this.center(); } else { this.moveTo( Boxy._u(this.options.x) ? this.options.x : Boxy.DEFAULT_X, Boxy._u(this.options.y) ? this.options.y : Boxy.DEFAULT_Y ); } if (this.options.show) this.show(); }; Boxy.EF = function() {}; jQuery.extend(Boxy, { WRAPPER: "<table cellspacing='0' cellpadding='0' border='0' class='boxy-wrapper'>" + "<tr><td class='top-left'></td><td class='top'></td><td class='top-right'></td></tr>" + "<tr><td class='left'></td><td class='boxy-inner'></td><td class='right'></td></tr>" + "<tr><td class='bottom-left'></td><td class='bottom'></td><td class='bottom-right'></td></tr>" + "</table>", DEFAULTS: { title: null, // titlebar text. titlebar will not be visible if not set. closeable: true, // display close link in titlebar? draggable: true, // can this dialog be dragged? clone: false, // clone content prior to insertion into dialog? actuator: null, // element which opened this dialog center: true, // center dialog in viewport? show: true, // show dialog immediately? modal: false, // make dialog modal? fixed: true, // use fixed positioning, if supported? absolute positioning used otherwise closeText: '[关闭]', // text to use for default close link unloadOnHide: false, // should this dialog be removed from the DOM after being hidden? clickToFront: false, // bring dialog to foreground on any click (not just titlebar)? behaviours: Boxy.EF, // function used to apply behaviours to all content embedded in dialog. afterDrop: Boxy.EF, // callback fired after dialog is dropped. executes in context of Boxy instance. afterShow: Boxy.EF, // callback fired after dialog becomes visible. executes in context of Boxy instance. afterHide: Boxy.EF, // callback fired after dialog is hidden. executed in context of Boxy instance. beforeUnload: Boxy.EF // callback fired after dialog is unloaded. executed in context of Boxy instance. }, DEFAULT_X: 50, DEFAULT_Y: 50, zIndex: 1337, dragConfigured: false, // only set up one drag handler for all boxys resizeConfigured: false, dragging: null, // load a URL and display in boxy // url - url to load // options keys (any not listed below are passed to boxy constructor) // type: HTTP method, default: GET // cache: cache retrieved content? default: false // filter: jQuery selector used to filter remote content load: function(url, options) { options = options || {}; var ajax = { url: url, type: 'GET', dataType: 'html', cache: false, success: function(html) { html = jQuery(html); if (options.filter) html = jQuery(options.filter, html); new Boxy(html, options); } }; jQuery.each(['type', 'cache'], function() { if (this in options) { ajax[this] = options[this]; delete options[this]; } }); jQuery.ajax(ajax); }, // allows you to get a handle to the containing boxy instance of any element // e.g. <a href='#' onclick='alert(Boxy.get(this));'>inspect!</a>. // this returns the actual instance of the boxy 'class', not just a DOM element. // Boxy.get(this).hide() would be valid, for instance. get: function(ele) { var p = jQuery(ele).parents('.boxy-wrapper'); return p.length ? jQuery.data(p[0], 'boxy') : null; }, // returns the boxy instance which has been linked to a given element via the // 'actuator' constructor option. linkedTo: function(ele) { return jQuery.data(ele, 'active.boxy'); }, // displays an alert box with a given message, calling optional callback // after dismissal. alert: function(message, callback, options) { return Boxy.ask(message, ['OK'], callback, options); }, // displays an alert box with a given message, calling after callback iff // user selects OK. confirm: function(message, after, options) { return Boxy.ask(message, ['OK', 'Cancel'], function(response) { if (response == 'OK') after(); }, options); }, // asks a question with multiple responses presented as buttons // selected item is returned to a callback method. // answers may be either an array or a hash. if it's an array, the // the callback will received the selected value. if it's a hash, // you'll get the corresponding key. ask: function(question, answers, callback, options) { options = jQuery.extend({modal: true, closeable: false}, options || {}, {show: true, unloadOnHide: true}); var body = jQuery('<div></div>').append(jQuery('<div class="question"></div>').html(question)); // ick var map = {}, answerStrings = []; if (answers instanceof Array) { for (var i = 0; i < answers.length; i++) { map[answers[i]] = answers[i]; answerStrings.push(answers[i]); } } else { for (var k in answers) { map[answers[k]] = k; answerStrings.push(answers[k]); } } var buttons = jQuery('<form class="answers"></form>'); buttons.html(jQuery.map(answerStrings, function(v) { return "<input type='button' value='" + v + "' />"; }).join(' ')); jQuery('input[type=button]', buttons).click(function() { var clicked = this; Boxy.get(this).hide(function() { if (callback) callback(map[clicked.value]); }); }); body.append(buttons); new Boxy(body, options); }, // returns true if a modal boxy is visible, false otherwise isModalVisible: function() { return jQuery('.boxy-modal-blackout').length > 0; }, _u: function() { for (var i = 0; i < arguments.length; i++) if (typeof arguments[i] != 'undefined') return false; return true; }, _handleResize: function(evt) { var d = jQuery(document); jQuery('.boxy-modal-blackout').css('display', 'none').css({ width: d.width(), height: d.height() }).css('display', 'block'); }, _handleDrag: function(evt) { var d; if (d = Boxy.dragging) { d[0].boxy.css({left: evt.pageX - d[1], top: evt.pageY - d[2]}); } }, _nextZ: function() { return Boxy.zIndex++; }, _viewport: function() { var d = document.documentElement, b = document.body, w = window; return jQuery.extend( jQuery.browser.msie ? { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop } : { left: w.pageXOffset, top: w.pageYOffset }, !Boxy._u(w.innerWidth) ? { width: w.innerWidth, height: w.innerHeight } : (!Boxy._u(d) && !Boxy._u(d.clientWidth) && d.clientWidth != 0 ? { width: d.clientWidth, height: d.clientHeight } : { width: b.clientWidth, height: b.clientHeight }) ); } }); Boxy.prototype = { // Returns the size of this boxy instance without displaying it. // Do not use this method if boxy is already visible, use getSize() instead. estimateSize: function() { this.boxy.css({visibility: 'hidden', display: 'block'}); var dims = this.getSize(); this.boxy.css('display', 'none').css('visibility', 'visible'); return dims; }, // Returns the dimensions of the entire boxy dialog as [width,height] getSize: function() { return [this.boxy.width(), this.boxy.height()]; }, // Returns the dimensions of the content region as [width,height] getContentSize: function() { var c = this.getContent(); return [c.width(), c.height()]; }, // Returns the position of this dialog as [x,y] getPosition: function() { var b = this.boxy[0]; return [b.offsetLeft, b.offsetTop]; }, // Returns the center point of this dialog as [x,y] getCenter: function() { var p = this.getPosition(); var s = this.getSize(); return [Math.floor(p[0] + s[0] / 2), Math.floor(p[1] + s[1] / 2)]; }, // Returns a jQuery object wrapping the inner boxy region. // Not much reason to use this, you're probably more interested in getContent() getInner: function() { return jQuery('.boxy-inner', this.boxy); }, // Returns a jQuery object wrapping the boxy content region. // This is the user-editable content area (i.e. excludes titlebar) getContent: function() { return jQuery('.boxy-content', this.boxy); }, // Replace dialog content setContent: function(newContent) { newContent = jQuery(newContent).css({display: 'block'}).addClass('boxy-content'); if (this.options.clone) newContent = newContent.clone(true); this.getContent().remove(); this.getInner().append(newContent); this._setupDefaultBehaviours(newContent); this.options.behaviours.call(this, newContent); return this; }, // Move this dialog to some position, funnily enough moveTo: function(x, y) { this.moveToX(x).moveToY(y); return this; }, // Move this dialog (x-coord only) moveToX: function(x) { if (typeof x == 'number') this.boxy.css({left: x}); else this.centerX(); return this; }, // Move this dialog (y-coord only) moveToY: function(y) { if (typeof y == 'number') this.boxy.css({top: y}); else this.centerY(); return this; }, // Move this dialog so that it is centered at (x,y) centerAt: function(x, y) { var s = this[this.visible ? 'getSize' : 'estimateSize'](); if (typeof x == 'number') this.moveToX(x - s[0] / 2); if (typeof y == 'number') this.moveToY(y - s[1] / 2); return this; }, centerAtX: function(x) { return this.centerAt(x, null); }, centerAtY: function(y) { return this.centerAt(null, y); }, // Center this dialog in the viewport // axis is optional, can be 'x', 'y'. center: function(axis) { var v = Boxy._viewport(); var o = this.options.fixed ? [0, 0] : [v.left, v.top]; if (!axis || axis == 'x') this.centerAt(o[0] + v.width / 2, null); if (!axis || axis == 'y') this.centerAt(null, o[1] + v.height / 2); return this; }, // Center this dialog in the viewport (x-coord only) centerX: function() { return this.center('x'); }, // Center this dialog in the viewport (y-coord only) centerY: function() { return this.center('y'); }, // Resize the content region to a specific size resize: function(width, height, after) { if (!this.visible) return; var bounds = this._getBoundsForResize(width, height); this.boxy.css({left: bounds[0], top: bounds[1]}); this.getContent().css({width: bounds[2], height: bounds[3]}); if (after) after(this); return this; }, // Tween the content region to a specific size tween: function(width, height, after) { if (!this.visible) return; var bounds = this._getBoundsForResize(width, height); var self = this; this.boxy.stop().animate({left: bounds[0], top: bounds[1]}); this.getContent().stop().animate({width: bounds[2], height: bounds[3]}, function() { if (after) after(self); }); return this; }, // Returns true if this dialog is visible, false otherwise isVisible: function() { return this.visible; }, // Make this boxy instance visible show: function() { if (this.visible) return; if (this.options.modal) { var self = this; if (!Boxy.resizeConfigured) { Boxy.resizeConfigured = true; jQuery(window).resize(function() { Boxy._handleResize(); }); } this.modalBlackout = jQuery('<div class="boxy-modal-blackout"></div>') .css({zIndex: Boxy._nextZ(), opacity: 0.7, width: jQuery(document).width(), height: jQuery(document).height()}) .appendTo(document.body); this.toTop(); if (this.options.closeable) { jQuery(document.body).bind('keypress.boxy', function(evt) { var key = evt.which || evt.keyCode; if (key == 27) { self.hide(); jQuery(document.body).unbind('keypress.boxy'); } }); } } this.boxy.stop().css({opacity: 1}).show(); this.visible = true; this._fire('afterShow'); return this; }, // Hide this boxy instance hide: function(after) { if (!this.visible) return; var self = this; if (this.options.modal) { jQuery(document.body).unbind('keypress.boxy'); this.modalBlackout.animate({opacity: 0}, function() { jQuery(this).remove(); }); } this.boxy.stop().animate({opacity: 0}, 300, function() { self.boxy.css({display: 'none'}); self.visible = false; self._fire('afterHide'); if (after) after(self); if (self.options.unloadOnHide) self.unload(); }); return this; }, toggle: function() { this[this.visible ? 'hide' : 'show'](); return this; }, hideAndUnload: function(after) { this.options.unloadOnHide = true; this.hide(after); return this; }, unload: function() { this._fire('beforeUnload'); this.boxy.remove(); if (this.options.actuator) { jQuery.data(this.options.actuator, 'active.boxy', false); } }, // Move this dialog box above all other boxy instances toTop: function() { this.boxy.css({zIndex: Boxy._nextZ()}); return this; }, // Returns the title of this dialog getTitle: function() { return jQuery('> .title-bar h2', this.getInner()).html(); }, // Sets the title of this dialog setTitle: function(t) { jQuery('> .title-bar h2', this.getInner()).html(t); return this; }, // // Don't touch these privates _getBoundsForResize: function(width, height) { var csize = this.getContentSize(); var delta = [width - csize[0], height - csize[1]]; var p = this.getPosition(); return [Math.max(p[0] - delta[0] / 2, 0), Math.max(p[1] - delta[1] / 2, 0), width, height]; }, _setupTitleBar: function() { if (this.options.title) { var self = this; var tb = jQuery("<div class='title-bar'></div>").html("<h2>" + this.options.title + "</h2>"); if (this.options.closeable) { tb.append(jQuery("<a href='#' class='close'></a>").html(this.options.closeText)); } if (this.options.draggable) { tb[0].onselectstart = function() { return false; } tb[0].unselectable = 'on'; tb[0].style.MozUserSelect = 'none'; if (!Boxy.dragConfigured) { jQuery(document).mousemove(Boxy._handleDrag); Boxy.dragConfigured = true; } tb.mousedown(function(evt) { self.toTop(); Boxy.dragging = [self, evt.pageX - self.boxy[0].offsetLeft, evt.pageY - self.boxy[0].offsetTop]; jQuery(this).addClass('dragging'); }).mouseup(function() { jQuery(this).removeClass('dragging'); Boxy.dragging = null; self._fire('afterDrop'); }); } this.getInner().prepend(tb); this._setupDefaultBehaviours(tb); } }, _setupDefaultBehaviours: function(root) { var self = this; if (this.options.clickToFront) { root.click(function() { self.toTop(); }); } jQuery('.close', root).click(function() { self.hide(); return false; }).mousedown(function(evt) { evt.stopPropagation(); }); }, _fire: function(event) { this.options[event].call(this); } };
JavaScript
<!-- function changeAuthCode() { var num = new Date().getTime(); var rand = Math.round(Math.random() * 10000); num = num + rand; var leftpos = $("#vdcode").position().left; var toppos = $("#vdcode").position().top - 42; $('#ver_code').css('left', leftpos+'px'); $('#ver_code').css('top', toppos+'px'); $('#ver_code').css('visibility','visible'); if ($("#vdimgck")[0]) { $("#vdimgck")[0].src = "../include/vdimgck.php?tag=" + num; } return false; } function hideVc() { $('#ver_code').css('visibility','hidden'); } $(document).ready(function(){ $("#vdcode").focus(function(){ var leftpos = $("#vdcode").position().left; var toppos = $("#vdcode").position().top - 42; $('#ver_code').css('left', leftpos+'px'); $('#ver_code').css('top', toppos+'px'); $('#ver_code').css('visibility','visible'); }); $("input[type='password']").click(function(){ hideVc() }); $("#txtUsername").click(function(){ hideVc() }); $("input[type='radio']").focus(function(){ hideVc() }); }) -->
JavaScript
<!-- em_infotypes=new Array(); em_infotypes[500]='商品'; em_infotypes[501]='出售'; em_infotypes[502]='求购'; em_infotypes[503]='交换'; em_infotypes[504]='合作'; em_infotypes[1000]='租房'; em_infotypes[1001]='出租'; em_infotypes[1002]='求租'; em_infotypes[1003]='合租'; em_infotypes[1500]='交友'; em_infotypes[1501]='找帅哥'; em_infotypes[1502]='找美女'; em_infotypes[1503]='纯友谊'; em_infotypes[1504]='玩伴'; em_infotypes[2000]='招聘'; em_infotypes[2500]='求职'; em_infotypes[3000]='票务'; em_infotypes[3500]='服务'; em_infotypes[4000]='培训'; -->
JavaScript
<!-- em_nativeplaces=new Array(); em_nativeplaces[500]='广州市'; em_nativeplaces[501]='天河区'; em_nativeplaces[502]='越秀区'; em_nativeplaces[503]='海珠区'; em_nativeplaces[1000]='中山市'; em_nativeplaces[1001]='石岐区'; em_nativeplaces[1002]='西区'; em_nativeplaces[1003]='东区'; em_nativeplaces[1004]='小榄镇'; -->
JavaScript
<!-- em_vocations=new Array(); em_vocations[500]='互联网'; em_vocations[501]='网站制作'; em_vocations[502]='虚心'; em_vocations[503]='cms制作'; em_vocations[1000]='机械'; em_vocations[1001]='农业机械'; em_vocations[1002]='机床'; em_vocations[1003]='纺织设备和器材'; em_vocations[1004]='风机/排风设备'; -->
JavaScript
//网站换肤 $(function(){ var cookie_skin = $.cookie("MyCssSkin"); switchSkin(cookie_skin); addEvent(); }); function switchSkin(skinName){ $("#"+skinName).addClass("selected") //当前<li>元素选中 .siblings().removeClass("selected"); //去掉其他同辈<li>元素的选中 $("#cssfile").attr("href","/templets/default/style/"+ skinName +".css"); //设置不同皮肤 $.cookie( "MyCssSkin",skinName, {path: '/', expires: 10 }); } function addEvent(){ var $li =$("#dedecms_skins li"); $li.click(function(){ switchSkin(this.id ); }); var cookie_skin = $.cookie("MyCssSkin"); if (cookie_skin) { switchSkin(cookie_skin); } }
JavaScript
(function () { $.fn.infiniteCarousel = function () { function repeat(str, n) { return new Array( n + 1 ).join(str); } return this.each(function () { // magic! var $wrapper = $('> div', this).css('overflow', 'hidden'), $slider = $wrapper.find('> ul').width(9999), $items = $slider.find('> li'), $single = $items.filter(':first') singleWidth = $single.outerWidth(), visible = Math.ceil($wrapper.innerWidth() / singleWidth), currentPage = 1, pages = Math.ceil($items.length / visible); /* TASKS */ // 1. pad the pages with empty element if required if ($items.length % visible != 0) { // pad $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible))); $items = $slider.find('> li'); } // 2. create the carousel padding on left and right (cloned) $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned')); $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned')); $items = $slider.find('> li'); // 3. reset scroll $wrapper.scrollLeft(singleWidth * visible); // 4. paging function function gotoPage(page) { var dir = page < currentPage ? -1 : 1, n = Math.abs(currentPage - page), left = singleWidth * dir * visible * n; $wrapper.filter(':not(:animated)').animate({ scrollLeft : '+=' + left }, 500, function () { // if page == last page - then reset position if (page > pages) { $wrapper.scrollLeft(singleWidth * visible); page = 1; } else if (page == 0) { page = pages; $wrapper.scrollLeft(singleWidth * visible * pages); } currentPage = page; }); } // 5. insert the back and forward link $wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>'); // 6. bind the back and forward links $('a.back', this).click(function () { gotoPage(currentPage - 1); return false; }); $('a.forward', this).click(function () { gotoPage(currentPage + 1); return false; }); $(this).bind('goto', function (event, page) { gotoPage(page); }); // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL $(this).bind('next', function () { gotoPage(currentPage + 1); }); }); }; })(jQuery); $(document).ready(function () { // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL var autoscrolling = true; $('.infiniteCarousel').infiniteCarousel().mouseover(function () { autoscrolling = false; }).mouseout(function () { autoscrolling = true; }); setInterval(function () { if (autoscrolling) { $('.infiniteCarousel').trigger('next'); } }, 5000); });
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // CAUTION: Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/** * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget. * @requires jQuery v1.2 or above * * http://gmarwaha.com/jquery/jcarousellite/ * * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 1.0.1 * Note: Requires jquery 1.2 or above from version 1.0.1 */ /** * Creates a carousel-style navigation widget for images/any-content from a simple HTML markup. * * The HTML markup that is used to build the carousel can be as simple as... * * <div class="carousel"> * <ul> * <li><img src="image/1.jpg" alt="1"></li> * <li><img src="image/2.jpg" alt="2"></li> * <li><img src="image/3.jpg" alt="3"></li> * </ul> * </div> * * As you can see, this snippet is nothing but a simple div containing an unordered list of images. * You don't need any special "class" attribute, or a special "css" file for this plugin. * I am using a class attribute just for the sake of explanation here. * * To navigate the elements of the carousel, you need some kind of navigation buttons. * For example, you will need a "previous" button to go backward, and a "next" button to go forward. * This need not be part of the carousel "div" itself. It can be any element in your page. * Lets assume that the following elements in your document can be used as next, and prev buttons... * * <button class="prev">&lt;&lt;</button> * <button class="next">&gt;&gt;</button> * * Now, all you need to do is call the carousel component on the div element that represents it, and pass in the * navigation buttons as options. * * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev" * }); * * That's it, you would have now converted your raw div, into a magnificient carousel. * * There are quite a few other options that you can use to customize it though. * Each will be explained with an example below. * * @param an options object - You can specify all the options shown below as an options object param. * * @option btnPrev, btnNext : string - no defaults * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev" * }); * @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward. * * @option btnGo - array - no defaults * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * btnGo: [".0", ".1", ".2"] * }); * @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on * the item number within the carousel, you can use this option. Just supply an array of selectors for each element * in the carousel. The index of the array represents the index of the element. What i mean is, if the * first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel * will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed * interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding * any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin. * The best part is that, the tab will "slide" based on the provided effect. :-) * * @option mouseWheel : boolean - default is false * @example * $(".carousel").jCarouselLite({ * mouseWheel: true * }); * @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons. * To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon. * Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel * using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation * as well. They complement each other. To use both together, just supply the options required for both as shown below. * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * mouseWheel: true * }); * * @option auto : number - default is null, meaning autoscroll is disabled by default * @example * $(".carousel").jCarouselLite({ * auto: 800, * speed: 500 * }); * @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option. * The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling. * Specify this value and magically your carousel will start auto scrolling. * * @option speed : number - 200 is default * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * speed: 800 * }); * @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with * different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect. * * @option easing : string - no easing effects by default. * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * easing: "bounceout" * }); * @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified, * the carousel will slide based on the provided easing effect. * * @option vertical : boolean - default is false * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * vertical: true * }); * @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and * prev buttons will slide the items vertically as well. The default is false, which means that the carousel will * display horizontally. The next and prev items will slide the items from left-right in this case. * * @option circular : boolean - default is true * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * circular: false * }); * @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last * element, you will automatically slide to the first element and vice versa. If you set circular to false, then * if you click on the "next" button after you reach the last element, you will stay in the last element itself * and similarly for "previous" button and first element. * * @option visible : number - default is 3 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * visible: 4 * }); * @desc This specifies the number of items visible at all times within the carousel. The default is 3. * You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the * last item half visible. This gives you the effect of showing the user that there are more images to the right. * * @option start : number - default is 0 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * start: 2 * }); * @desc You can specify from which item the carousel should start. Remember, the first item in the carousel * has a start of 0, and so on. * * @option scrool : number - default is 1 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * scroll: 2 * }); * @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By * default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll * 2 items when you click the next or previous buttons. * * @option beforeStart, afterEnd : function - callbacks * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * beforeStart: function(a) { * alert("Before animation starts:" + a); * }, * afterEnd: function(a) { * alert("After animation ends:" + a); * } * }); * @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can * register these 2 callbacks. The functions will be passed an argument that represents an array of elements that * are visible at the time of callback. * * * @cat Plugins/Image Gallery * @author Ganeshji Marwaha/ganeshread@gmail.com */ (function($) { // Compliant with jquery.noConflict() $.fn.jCarouselLite = function(o) { o = $.extend({ btnPrev: '.next', btnNext: '.prev', btnGo: null, mouseWheel: false, auto: null, speed: 200, easing: null, vertical: false, circular: true, visible: 4, start: 0, scroll: 1, beforeStart: null, afterEnd: null }, o || {}); return this.each(function() { // Returns the element collection. Chainable. var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible; if(o.circular) { ul.prepend(tLi.slice(tl-v-1+1).clone()) .append(tLi.slice(0,v).clone()); o.start += v; } var li = $("li", ul), itemLength = li.size(), curr = o.start; div.css("visibility", "visible"); li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"}); var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) var divSize = liSize * v; // size of entire div(total length for just the visible items) li.css({width: li.width(), height: li.height()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images if(o.btnPrev) $(o.btnPrev).click(function() { return go(curr-o.scroll); }); if(o.btnNext) $(o.btnNext).click(function() { return go(curr+o.scroll); }); if(o.btnGo) $.each(o.btnGo, function(i, val) { $(val).click(function() { return go(o.circular ? o.visible+i : i); }); }); if(o.mouseWheel && div.mousewheel) div.mousewheel(function(e, d) { return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); }); if(o.auto) setInterval(function() { go(curr+o.scroll); }, o.auto+o.speed); function vis() { return li.slice(curr).slice(0,v); }; function go(to) { if(!running) { if(o.beforeStart) o.beforeStart.call(this, vis()); if(o.circular) { // If circular we are in first or last, then goto the other end if(to<=o.start-v-1) { // If first, then goto last ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; } else if(to>=itemLength-v+1) { // If last, then goto first ul.css(animCss, -( (v) * liSize ) + "px" ); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. curr = to==itemLength-v+1 ? v+1 : v+o.scroll; } else curr = to; } else { // If non-circular and to points to first or last, we just return. if(to<0 || to>itemLength-v) return; else curr = to; } // If neither overrides it, the curr will still be "to" and we can proceed. running = true; ul.animate( animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, function() { if(o.afterEnd) o.afterEnd.call(this, vis()); running = false; } ); // Disable buttons when the carousel reaches the last/first, and enable when not if(!o.circular) { $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $( (curr-o.scroll<0 && o.btnPrev) || (curr+o.scroll > itemLength-v && o.btnNext) || [] ).addClass("disabled"); } } return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery);
JavaScript
//高清图集 //UI&UE Dept. mengjia //090708 var sina = { $ : function(objName){if(document.getElementById){return eval('document.getElementById("'+objName+'")')}else{return eval('document.all.'+objName)}}, isIE : navigator.appVersion.indexOf("MSIE")!=-1?true:false, //Event addEvent : function(obj,eventType,func){if(obj.attachEvent){obj.attachEvent("on" + eventType,func);}else{obj.addEventListener(eventType,func,false)}}, delEvent : function(obj,eventType,func){ if(obj.detachEvent){obj.detachEvent("on" + eventType,func)}else{obj.removeEventListener(eventType,func,false)} }, //Cookie readCookie : function(l){var i="",I=l+"=";if(document.cookie.length>0){var offset=document.cookie.indexOf(I);if(offset!=-1){offset+=I.length;var end=document.cookie.indexOf(";",offset);if(end==-1)end=document.cookie.length;i=document.cookie.substring(offset,end)}};return i}, writeCookie : function(O,o,l,I){var i="",c="";if(l!=null){i=new Date((new Date).getTime()+l*3600000);i="; expires="+i.toGMTString()};if(I!=null){c=";domain="+I};document.cookie=O+"="+escape(o)+i+c}, //Style readStyle:function(i,I){if(i.style[I]){return i.style[I]}else if(i.currentStyle){return i.currentStyle[I]}else if(document.defaultView&&document.defaultView.getComputedStyle){var l=document.defaultView.getComputedStyle(i,null);return l.getPropertyValue(I)}else{return null}}, absPosition : function(obj,parentObj){ //位置 var left = 0; var top = 0; var tempObj = obj; try{ do{ left += tempObj.offsetLeft; top += tempObj.offsetTop; tempObj = tempObj.offsetParent; }while(tempObj.id!=document.body && tempObj.id!=document.documentElement && tempObj != parentObj && tempObj!= null); }catch(e){}; return {left:left,top:top}; }, _getJsData : function(url,callback){ var _script = document.createElement("script"); _script.type = "text/javascript"; _script.language = "javascript"; _script[_script.onreadystatechange === null ? "onreadystatechange" : "onload"] = function(){ if(this.onreadystatechange){ if(this.readyState != "complete" && this.readyState != "loaded") {return;} }; if(callback){callback()}; setTimeout(function(){_script.parentNode.removeChild(_script)},1000); }; _script.src = url; document.getElementsByTagName("head")[0].appendChild(_script); } }; sina.Step = function(){ this.stepIndex = 0; //当前步数 this.classBase = 'step_'; //class规则 this.limit = 3; //步总数 this.stepTime = 20; //步时长 this.element = null; //html对象 this._timeObj = null; //setInterval对象 this._type = '+'; //步方向 }; sina.Step.prototype.action = function(type){ if(!this.element){return}; var tempThis = this; if(type=='+'){ this._type = '+'; }else{ this._type = '-'; }; clearInterval(this._timeObj); this._timeObj = setInterval(function(){tempThis.nextStep()},this.stepTime); }; sina.Step.prototype.nextStep = function(){ if(this._type == '+'){ this.stepIndex ++; }else{ this.stepIndex --; }; if(this.stepIndex <= 0){ clearInterval(this._timeObj); this.stepIndex = 0; if(this._type == '-'){ if(this.onfirst){this.onfirst()}; }; }; if(this.stepIndex >= this.limit){ clearInterval(this._timeObj); this.stepIndex = this.limit; if(this._type == '+'){ if(this.onlast){this.onlast()}; }; }; this.element.className = this.classBase + this.stepIndex; if(this.onstep){this.onstep()}; }; var epidiascope = { picTitleId : "d_picTit", picMemoId : "d_picIntro", picTimeId : 'd_picTime', picListId : "efpPicListCont", BigPicId : "d_BigPic", picArrLeftId : "efpLeftArea", picArrRightId : "efpRightArea", playButtonId : "ecbPlay", statusId : "ecpPlayStatus", mainBoxId : "efpBigPic", PVUrl_a : null, PVUrl_m : null, repetition : false, //循环播放 prefetch : false, //预读图片 autoPlay : true, //自动播放 mode : 'player', //模式 player|list autoPlayTimeObj : null, timeSpeed : 5, maxWidth : 958, filmstrips : [], prefetchImg : [], commNum : [], selectedIndex : -1, previousPicList : {}, nextPicList : {}, add : function(s){ this.filmstrips.push(s); if(this.prefetch){ //预载图片 var tempImg = new Image(); tempImg.src = s.src; this.prefetchImg.push(tempImg); }; }, init : function(){ var tempThis = this; var tempWidth = 0; if(this.filmstrips.length * 110 < sina.$(this.picListId).offsetWidth){ tempWidth = Math.round(sina.$(this.picListId).offsetWidth / 2 - this.filmstrips.length * 110/2); }; var commKey = ""; var tempHTML = '<div style="width:32760px;padding-left:' + tempWidth + 'px;">',i; for(i=0;i<this.filmstrips.length;i++){ //子列表 tempHTML += '<div class="pic" id="slide_' + i + '"><table cellspacing="0"><tr><td class="picCont"><table cellspacing="0"><tr><td class="pb_01"></td><td class="pb_02"></td><td class="pb_03"></td></tr><tr><td class="pb_04"></td><td><a href="javascript:epidiascope.select(' + i + ');" onclick="this.blur();"><img src="' + this.filmstrips[i].lowsrc_s + '" alt="' + this.filmstrips[i].title + '" onload="DrawImage(this);" oncontextmenu="event.returnValue=false;return false;" /></a></td><td class="pb_05"></td></tr><tr><td class="pb_06"></td><td class="pb_07"></td><td class="pb_08"></td></tr></table></td></tr></table></div>'; //评论数据 var commId = this.filmstrips[i].comment.match(/channel\=(.*?)\&newsid\=(.*?)(\&|$)/); this.filmstrips[i].commNum = 0; this.filmstrips[i].commId = ""; if(commId){ commId = commId[1] + ":" + commId[2] + ":0"; this.filmstrips[i].commId = commId; if(commKey!=''){commKey+=','}; commKey += commId; }; }; /*window.counter_callback = function(){ tempThis.readCommNum(); };*/ //sina._getJsData('http://counter.sina.com.cn/querylist?format=js&entry=g_clist&id=0&key='+commKey,function(){tempThis.readCommNum()}); sina.$(this.picListId).innerHTML = tempHTML + "</div>"; // sina.$(this.picArrLeftId).onclick = function(){epidiascope.previous();epidiascope.stop();}; sina.$(this.picArrRightId).onclick = function(){epidiascope.next();epidiascope.stop();}; //按钮 this.buttonNext = new epidiascope.Button('ecbNext'); //下一页 this.buttonPre = new epidiascope.Button('ecbPre'); //上一页 this.buttonPlay = new epidiascope.Button('ecbPlay'); //播放暂停 //this.buttonCommTop = new epidiascope.Button('ecbComm'); //评论 this.buttonMode = new epidiascope.Button('ecbMode'); //模式切换 this.buttonFullScreen = new epidiascope.Button('ecbFullScreen'); //全屏 this.buttonSpeed = new epidiascope.Button('ecbSpeed'); //速度 this.buttonModeReturn = new epidiascope.Button('ecbModeReturn'); //模式切换 this.buttonPre.element.onclick = function(){epidiascope.previous();epidiascope.stop();}; this.buttonNext.element.onclick = function(){epidiascope.next();epidiascope.stop();}; this.buttonMode.element.onclick = function(){epidiascope.setMode('list');}; this.buttonModeReturn.element.onclick = function(){epidiascope.setMode('player');}; // this.BigImgBox = sina.$(this.BigPicId); //禁止右键 this.BigImgBox.oncontextmenu = function(e){ e = e?e:event; e.returnValue=false; return false; }; this._imgLoad = function(){ if(epidiascope.maxWidth == 0 ){return}; if(this.width > epidiascope.maxWidth){ this.width = epidiascope.maxWidth; //this.height = Math.round(epidiascope.maxWidth * this.height / this.width); }; if(this.width < 958){ sina.$('d_BigPic').style.paddingTop = "15px"; this.style.border = "1px solid #000"; }else{ sina.$('d_BigPic').style.paddingTop = "0px"; this.style.border = "none"; this.style.borderBottom = "1px solid #e5e6e6"; }; //隐藏loading图片 clearTimeout(tempThis._hideBgTimeObj); sina.$('d_BigPic').className = ''; }; this.createImg(this.filmstrips[0].src); var page; var imgId = window.location.search.match(/img=(\d+)/i); if(imgId){ imgId = imgId[1]; page = 0; for(var i = 0, len = this.filmstrips.length; i<len; i++){ if(this.filmstrips[i]['id'] == imgId){ page = i; break; } } }else{ page = window.location.hash.match(/p=(\d+)/i); if(page){ page = page[1] - 1; if(page<0 || page >= this.filmstrips.length){ page = 0; }; }else{ page = 0; }; } this.select(page); if(!sina.isIE){ this.BigImgBox.style.position = 'relative'; this.BigImgBox.style.overflow = "hidden"; }else{ clearInterval(this._ieButHeiTimeObj); this._ieButHeiTimeObj = setInterval(function(){tempThis.setPicButtonHeight()},300); }; //设置下一图集 var nextPics = sina.$('efpNextGroup').getElementsByTagName('a'); sina.$('nextPicsBut').href = nextPics[0].href; if(this.autoPlay){this.play()}else{this.stop()}; this.listInit(); if(this.onstart){this.onstart()}; }, readTry : 0, readCommNum : function(){ var tempThis = this; try{ for(var i=0;i<g_clist.length;i++){ for(var j=0;j<this.filmstrips.length;j++){ if(this.filmstrips[j].commId == g_clist[i][0]){ this.filmstrips[j].commNum = g_clist[i][1]; break; }; }; }; //sina.$('commAObjNum').innerHTML = this.filmstrips[this.selectedIndex].commNum; }catch(e){ this.readTry ++; if(this.readTry<10){ setTimeout(function(){tempThis.readCommNum()},1000); }; return; }; }, createImg : function(src){ if(this.ImgObj1){ this.BigImgBox.removeChild(this.ImgObj1); }; this.ImgObj1 = document.createElement("img"); this.ImgObj1.onmousedown = function(){return false}; this.ImgObj1.galleryImg = false; this.ImgObj1.onload = this._imgLoad; if(src){ this.ImgObj1.src = src; }; this.BigImgBox.appendChild(this.ImgObj1); }, select : function(num,type){ var tempThis = this; if(this.endSelect.status == 1){ this.endSelect.close(); }; if(num == this.selectedIndex){return}; var i; if(num >= this.filmstrips.length || num < 0){return}; sina.$(this.picTitleId).innerHTML = this.filmstrips[num].title; sina.$(this.picMemoId).innerHTML = this.filmstrips[num].text; sina.$(this.picTimeId).innerHTML = this.filmstrips[num].date; //隐藏loading图片1s钟 sina.$('d_BigPic').className = ''; clearTimeout(this._hideBgTimeObj); this._hideBgTimeObj = setTimeout("sina.$('d_BigPic').className='loading'",500); this.createImg(); this.ImgObj1.style.opacity = 0; if(this._timeOut){ for(i=0;i<this._timeOut.length;i++){ clearTimeout(this._timeOut[i]); }; }; this._timeOut = []; if(sina.isIE){ this.ImgObj1.src = 'http://i0.sinaimg.cn/dy/deco/2008/0331/yocc080331img/news_mj_005.gif'; this.ImgObj1.filters[0].Apply(); this.ImgObj1.src = this.filmstrips[num].src; this.ImgObj1.filters[0].Play(); }else{ this.ImgObj1.src = this.filmstrips[num].src; for(i = 0;i <= 3;i ++){ this._timeOut[i] = setTimeout("epidiascope.ImgObj1.style.opacity = " + i * 0.3,i * 100); }; this._timeOut[i] = setTimeout("epidiascope.ImgObj1.style.opacity = 1;",4 * 100); }; if(sina.$("slide_" + this.selectedIndex)){sina.$("slide_" + this.selectedIndex).className = "pic"}; sina.$("slide_" + num).className = "picOn"; this.selectedIndex = num; this.picList.foucsTo(num + 1); //滚动 sina.$("total").innerHTML = '(<span class="cC00">'+(num + 1) + "</span>/" + this.filmstrips.length + ')'; if(this.autoPlay){this.play()}; this.PVCount(type); //PV统计 //预载下一张 if(!this.prefetch && num < this.filmstrips.length - 1){ //未预载全部图片 this.reLoad = new Image(); this.reLoad.src = this.filmstrips[num + 1].src; }; //评论 //if(this.filmstrips[num].comment != ''){ //sina.$('commAObj').href = this.filmstrips[num].comment; //sina.$('commAObj').target = '_blank'; //}else{ //sina.$('commAObj').href = 'javascript:void(0)'; //sina.$('commAObj').target = '_self'; //}; //sina.$('commAObjNum').innerHTML = this.filmstrips[num].commNum; }, setPicButtonHeight : function(){ sina.$(this.picArrLeftId).style.height = sina.$(this.picArrRightId).style.height = sina.$(this.picArrLeftId).parentNode.offsetHeight + 'px'; }, PVCount : function(type){ if(type=="auto"){ if(this.PVUrl_a == null){return;}; }else{ if(this.PVUrl_m == null){return;}; }; if(!this.firstPage){ //第一次不请求PV this.firstPage = true; return; }; //移除iframe if(this.PVFrame){ this.PVFrame.parentNode.removeChild(this.PVFrame); }; //create new iframe this.PVFrame = document.createElement("iframe"); //style="height:0px;width:1px;overflow:hidden;" this.PVFrame.style.height = "0px"; this.PVFrame.style.width = "1px"; this.PVFrame.style.overflow = "hidden"; this.PVFrame.frameBorder = 0; sina.$(this.mainBoxId).appendChild(this.PVFrame); this.PVFrame.src = (type=="auto"?this.PVUrl_a:this.PVUrl_m) + "?r=" + Math.random(); //set page if(type!="auto"){this.setPageInfo(this.selectedIndex)}; }, setPageInfo : function(num){ window.location.hash = "p="+Math.round(num+1); }, next : function(type){ var tempNum = this.selectedIndex + 1; if(tempNum >= this.filmstrips.length){ if(this.repetition){ //循环播放 tempNum = 0; }else{ this.endSelect.open(); //选择 return; }; }; //自动播放,判断下张图片是否载入 if(type=="auto"){ var testImg = new Image(); testImg.src = this.filmstrips[tempNum].src; if(!testImg.complete){ return; }; }; this.select(tempNum,type); }, previous : function(){ var tempNum = this.selectedIndex - 1; if(tempNum < 0){ //循环播放 if(this.repetition){ tempNum = this.filmstrips.length - 1 }else{ return; }; }; this.select(tempNum); }, play : function(){ clearInterval(this.autoPlayTimeObj); this.autoPlayTimeObj = setInterval("epidiascope.next('auto')",this.timeSpeed*1000); sina.$(this.playButtonId).onclick = function(){epidiascope.stop()}; sina.$(this.statusId).className = "stop"; sina.$(this.statusId).title = "暂停"; this.autoPlay = true; }, stop : function(){ clearInterval(this.autoPlayTimeObj); sina.$(this.playButtonId).onclick = function(){epidiascope.play();epidiascope.next('auto');}; sina.$(this.statusId).className = "play"; sina.$(this.statusId).title = "播放"; this.autoPlay = false; }, rePlay : function(){ //重新播放 if(this.endSelect.status == 1){this.endSelect.close()}; this.autoPlay = true; this.select(0); }, clickComment : function(){ //评论 var thisFilmstrip = this.filmstrips[this.selectedIndex]; if(thisFilmstrip.comment){window.open(thisFilmstrip.comment)}; }, downloadPic : function(){ //下载图片 var thisFilmstrip = this.filmstrips[this.selectedIndex]; }, setMode : function(mode){ //切换模式 this.speedBar.close(); this.commTop.close(); if(this.endSelect.status == 1){ this.endSelect.close(); }; if(mode == 'list'){ this.buttonSpeed.hide(); this.buttonFullScreen.hide(); this.buttonPlay.hide(); this.buttonNext.hide(); this.buttonPre.hide(); sina.$('ecbLine').style.visibility = 'hidden'; this.buttonMode.element.style.display = 'none'; this.buttonModeReturn.element.style.display = 'block'; this.buttonModeReturn.rePosi(); this.stop(); this.mode = 'list'; this.listSelect(this.selectedIndex); //alert(this.selectedIndex); sina.$('eFramePic').style.display = 'none'; sina.$('ePicList').style.display = 'block'; this.listView(); }else{ window.scroll(0,0); this.buttonSpeed.show(); this.buttonFullScreen.show(); this.buttonPlay.show(); this.buttonNext.show(); this.buttonPre.show(); sina.$('ecbLine').style.visibility = 'visible'; this.buttonMode.element.className = ''; this.buttonMode.element.style.display = 'block'; this.buttonModeReturn.element.style.display = 'none'; this.mode = 'player'; sina.$('eFramePic').style.display = 'block'; sina.$('ePicList').style.display = 'none'; //this.select(this.listSelectedIndex); }; }, switchMode : function(){ if(this.mode == 'list'){ this.setMode('player'); }else{ this.setMode('list'); }; }, listData : null, listFrameId : 'ePicList', listSelectedIndex : null, listSelect : function(num){ if(num<0 || num >= this.listData.length){return}; if(this.listSelectedIndex !== null){ this.listData[this.listSelectedIndex].className = 'picBox'; }; this.listSelectedIndex = num; this.listData[this.listSelectedIndex].className = 'picBox selected'; }, listInit : function(){ var tempThis = this; this.listData = []; for(var i=0;i<this.filmstrips.length;i++){ var tempObj = document.createElement('div'); this.listData.push(tempObj); sina.$(this.listFrameId).appendChild(tempObj); tempObj.className = 'picBox'; tempObj.innerHTML = '<table cellspacing="0"><tr><td><img src="' + this.filmstrips[i].lowsrc_b + '" alt="" width="210" height="158"/></td></tr></table>'; //tempObj.innerHTML = '<table cellspacing="0"><tr><td><img src="' + this.filmstrips[i].lowsrc_b + '" alt="1111" width="220" height="166"/></td></tr></table><h3>' + this.filmstrips[i].title + '</h3><p class="time">' + this.filmstrips[i].date + '</p>'; tempObj.num = i; tempObj.onmousemove = function(){ tempThis.listSelect(this.num); }; tempObj.onclick = function(){ tempThis.select(tempThis.listSelectedIndex); tempThis.setMode('player'); }; }; }, listRowSize : 6, //每行个数 listView : function(){ var element = this.listData[this.listSelectedIndex]; var bodyHeight = document.documentElement.clientHeight==0?document.body.clientHeight:document.documentElement.clientHeight; var scrollTop = document.documentElement.scrollTop==0?document.body.scrollTop:document.documentElement.scrollTop; var posi = sina.absPosition(element,document.documentElement); if((posi.top + (element.offsetHeight * 0.3)) < scrollTop || (posi.top + (element.offsetHeight * 0.7)) > scrollTop + bodyHeight){ window.scroll(0,posi.top - Math.round((bodyHeight - element.offsetHeight)/2)); }; }, listMoveUp : function(){ var newNum = this.listSelectedIndex - this.listRowSize; if(newNum<0){ return; }; this.listSelect(newNum); this.listView(); }, listMoveDown : function(){ var newNum = this.listSelectedIndex + this.listRowSize; if(newNum>=this.listData.length){ nweNum = this.listData.length - 1; }; this.listSelect(newNum); this.listView(); }, listMoveLeft : function(){ var newNum = this.listSelectedIndex - 1; if(newNum<0){ return; }; this.listSelect(newNum); this.listView(); }, listMoveRight : function(){ var newNum = this.listSelectedIndex + 1; if(newNum>=this.listData.length){ return; }; this.listSelect(newNum); this.listView(); }, postComm : function(content,pos){ //提交评论 if(content == ''){ alert('请输入评论内容!'); return; }; var connInfo = this.filmstrips[this.selectedIndex].commId; if(connInfo){ connInfo = connInfo.match(/(.*?)\:(.*?)\:/); var Cmsg = {}; Cmsg.m_channel = connInfo[1]; Cmsg.m_newsid = connInfo[2]; Cmsg.m_content = content; cmnt_post(Cmsg); }; if(pos == 'bottom'){ this.commBottom.close(); }else{ this.commTop.close(); }; } }; epidiascope.speedBar = { //速度条 boxId : "SpeedBox", //容器id contId : "SpeedCont", //内容id slideId : "SpeedSlide", //滑区id slideButtonId : "SpeedNonius", //滑块id infoId : "ecbSpeedInfo", //信息id grades : 10, //等级数 grade : 5, //等级 _slideHeight : 112, //滑区高度 _slideButtonHeight : 9, //滑块高度 _baseTop : 4, //top基数 _marginTop : 0, _mouseDisparity : 0, _showStep : 0, _showType : 'close', _showTimeObj : null, init : function(){ var tempThis = this; this._marginTop = Math.round(this._slideHeight/this.grades * (this.grade - 1)); sina.$(this.slideButtonId).style.top = this._marginTop + this._baseTop + "px"; sina.$(this.infoId).innerHTML = this.grade + "秒"; //动画效果 this.step = new sina.Step(); this.step.element = sina.$(this.contId); this.step.limit = 6; this.step.stepTime = 20; this.step.classBase = 'speedStep_'; this.step.onfirst = function(){ epidiascope.buttonSpeed.setStatus('ok'); sina.$(epidiascope.speedBar.boxId).style.display = 'none'; }; sina.$(this.slideId).onselectstart = function(){return false}; sina.$(this.slideButtonId).onmousedown = function(e){tempThis.mouseDown(e);return false}; sina.$(this.slideId).onmousedown = function(e){tempThis.slideClick(e);return false}; epidiascope.buttonSpeed.element.onmousedown = function(){tempThis.show();return false;}; epidiascope.buttonSpeed.element.onselectstart = function(){return false}; }, show : function(){ if(this._showType == 'close'){ this.open(); }else{ this.close(); }; }, open : function(){ var tempThis = this; this._showType = 'open'; var tempMouseDown = document.onmousedown; var mousedown = function(e){ e = window.event?event:e; if(e.stopPropagation){ //阻止冒泡 e.stopPropagation(); }else{ window.event.cancelBubble = true; }; var eventObj = e.target?e.target:e.srcElement; while(eventObj != sina.$(tempThis.boxId) && eventObj != epidiascope.buttonSpeed.element){ if(eventObj.parentNode){ eventObj = eventObj.parentNode; }else{ break; }; }; if(eventObj == sina.$(tempThis.boxId) || eventObj == epidiascope.buttonSpeed.element){ return; }else{ tempThis.close(); }; sina.delEvent(document,'mousedown',mousedown); }; sina.addEvent(document,'mousedown',mousedown); epidiascope.buttonSpeed.setStatus('down'); sina.$(this.boxId).style.display = 'block'; this.step.action('+'); }, close : function(){ var tempThis = this; this._showType = 'close'; epidiascope.buttonSpeed.setStatus('ok'); this.step.action('-'); }, slideClick : function(e){ e = window.event?event:e; var Y = e.layerY?e.layerY:e.offsetY; if(!Y){return}; this._marginTop = Y - Math.round(this._slideButtonHeight/2); if(this._marginTop<0){this._marginTop=0}; this.grade = Math.round(this._marginTop/(this._slideHeight/this.grades) + 1); sina.$(this.slideButtonId).style.top = this._marginTop + this._baseTop + "px"; sina.$(this.infoId).innerHTML = this.grade + "秒"; if(this.onend){this.onend()}; }, setGrade : function(num){ this.grade = num; this._marginTop = Math.round(this._slideHeight/this.grades * (this.grade - 1)); sina.$(this.slideButtonId).style.top = this._marginTop + this._baseTop + "px"; sina.$(this.infoId).innerHTML = this.grade + "秒"; sina.writeCookie("eSp",this.grade,720); }, mouseDown : function(e){ var tempThis = this; e = window.event?window.event:e; this._mouseDisparity = (e.pageY?e.pageY:e.clientY) - this._marginTop; document.onmousemove = function(e){tempThis.mouseOver(e)}; document.onmouseup = function(){tempThis.mouseEnd()}; }, mouseOver : function(e){ e = window.event?window.event:e; this._marginTop = (e.pageY?e.pageY:e.clientY) - this._mouseDisparity; if(this._marginTop > (this._slideHeight - this._slideButtonHeight)){this._marginTop = this._slideHeight - this._slideButtonHeight}; if(this._marginTop < 0){this._marginTop = 0;}; sina.$(this.slideButtonId).style.top = this._marginTop + this._baseTop + "px"; this.grade = Math.round(this._marginTop/(this._slideHeight/this.grades) + 1); if(this.onmover){this.onmover()}; }, mouseEnd : function(){ if(this.onend){this.onend()}; document.onmousemove = null; document.onmouseup = null; }, onmover : function(){ sina.$(this.infoId).innerHTML = this.grade + "秒"; }, onend : function(){ sina.writeCookie("eSp",this.grade,720); epidiascope.timeSpeed = this.grade; if(epidiascope.autoPlay){epidiascope.play()}; } }; epidiascope.commTop = { _showType : 'close', boxId : 'CommFormTopBox', contId : 'CommFormTopCont', playStatus : null, init : function(){ var tempThis = this; //动画效果 this.step = new sina.Step(); this.step.element = sina.$(this.contId); this.step.limit = 6; this.step.stepTime = 20; this.step.classBase = 'commTopStep_'; this.step.onfirst = function(){ //epidiascope.buttonCommTop.setStatus('ok'); sina.$(epidiascope.commTop.boxId).style.display = 'none'; }; //关闭 //sina.$('cftClose').onclick = function(){ //epidiascope.commTop.close(); //}; //epidiascope.buttonCommTop.element.onmousedown = function(){tempThis.show();return false;}; //epidiascope.buttonCommTop.element.onselectstart = function(){return false}; }, show : function(){ if(this._showType == 'close'){ this.open(); }else{ this.close(); }; }, open : function(){ this.playStatus = epidiascope.autoPlay; epidiascope.stop(); var tempThis = this; this._showType = 'open'; var mousedown = function(e){ e = window.event?event:e; if(e.stopPropagation){ //阻止冒泡 e.stopPropagation(); }else{ window.event.cancelBubble = true; }; var eventObj = e.target?e.target:e.srcElement; while(eventObj != sina.$(tempThis.boxId)){ if(eventObj.parentNode){ eventObj = eventObj.parentNode; }else{ break; }; }; if(eventObj == sina.$(tempThis.boxId)){ return; }else{ tempThis.close(); }; sina.delEvent(document,'mousedown',mousedown); }; sina.addEvent(document,'mousedown',mousedown); //epidiascope.buttonCommTop.setStatus('down'); sina.$(this.boxId).style.display = 'block'; this.step.action('+'); }, close : function(){ epidiascope.autoPlay = this.playStatus; if(epidiascope.autoPlay){epidiascope.play()}; var tempThis = this; this._showType = 'close'; //epidiascope.buttonCommTop.setStatus('ok'); this.step.action('-'); } }; epidiascope.commBottom = { _showType : 'close', boxId : 'CommFormBottomBox', contId : 'CommFormBottomCont', playStatus : null, init : function(){ var tempThis = this; //动画效果 this.step = new sina.Step(); this.step.element = sina.$(this.contId); this.step.limit = 6; this.step.stepTime = 20; this.step.classBase = 'commBottomStep_'; this.step.onfirst = function(){ sina.$(epidiascope.commBottom.boxId).style.display = 'none'; }; //关闭 //sina.$('cfbClose').onclick = function(){ //epidiascope.commBottom.close(); //}; //sina.$('buttonCommBottom').onmousedown = function(){tempThis.show();return false;}; }, show : function(){ if(this._showType == 'close'){ this.open(); }else{ this.close(); }; }, open : function(){ this.playStatus = epidiascope.autoPlay; epidiascope.stop(); var tempThis = this; this._showType = 'open'; var mousedown = function(e){ e = window.event?event:e; if(e.stopPropagation){ //阻止冒泡 e.stopPropagation(); }else{ window.event.cancelBubble = true; }; var eventObj = e.target?e.target:e.srcElement; while(eventObj != sina.$(tempThis.boxId) && eventObj != sina.$('buttonCommBottom')){ if(eventObj.parentNode){ eventObj = eventObj.parentNode; }else{ break; }; }; if(eventObj == sina.$(tempThis.boxId) || eventObj == sina.$('buttonCommBottom')){ return; }else{ tempThis.close(); }; sina.delEvent(document,'mousedown',mousedown); }; sina.addEvent(document,'mousedown',mousedown); sina.$(this.boxId).style.display = 'block'; this.step.action('+'); }, close : function(){ epidiascope.autoPlay = this.playStatus; if(epidiascope.autoPlay){epidiascope.play()}; var tempThis = this; this._showType = 'close'; this.step.action('-'); } }; epidiascope.picList = { //列表滚动 leftArrId : "efpListLeftArr", rightArrId : "efpListRightArr", picListId : "efpPicListCont", timeoutObj : null, pageWidth : 110, totalWidth : 0, offsetWidth : 0, lock : false, init : function(){ sina.$(this.rightArrId).onmousedown = function(){epidiascope.picList.leftMouseDown()}; sina.$(this.rightArrId).onmouseout = function(){epidiascope.picList.leftEnd("out");this.className='';}; sina.$(this.rightArrId).onmouseup = function(){epidiascope.picList.leftEnd("up")}; sina.$(this.leftArrId).onmousedown = function(){epidiascope.picList.rightMouseDown()}; sina.$(this.leftArrId).onmouseout = function(){epidiascope.picList.rightEnd("out");this.className='';}; sina.$(this.leftArrId).onmouseup = function(){epidiascope.picList.rightEnd("up")}; this.totalWidth = epidiascope.filmstrips.length * this.pageWidth; this.offsetWidth = sina.$(this.picListId).offsetWidth; }, leftMouseDown : function(){ if(this.lock){return}; this.lock = true; this.timeoutObj = setInterval("epidiascope.picList.moveLeft()",10); }, rightMouseDown : function(){ if(this.lock){return}; this.lock = true; this.timeoutObj = setInterval("epidiascope.picList.moveRight()",10); }, moveLeft : function(){ if(sina.$(this.picListId).scrollLeft + 10 > this.totalWidth - this.offsetWidth){ sina.$(this.picListId).scrollLeft = this.totalWidth - this.offsetWidth; this.leftEnd(); }else{ sina.$(this.picListId).scrollLeft += 10; }; }, moveRight : function(){ sina.$(this.picListId).scrollLeft -= 10; if(sina.$(this.picListId).scrollLeft == 0){this.rightEnd()}; }, leftEnd : function(type){ if(type=="out"){if(!this.lock){return}}; clearInterval(this.timeoutObj); this.lock = false; this.move(30); }, rightEnd : function(type){ if(type=="out"){if(!this.lock){return}}; clearInterval(this.timeoutObj); this.lock = false; this.move(-30); }, foucsTo : function(num){ if(this.lock){return}; this.lock = true; var _moveWidth = Math.round(num * this.pageWidth - this.offsetWidth / 2) - 33; _moveWidth -= sina.$(this.picListId).scrollLeft; if(sina.$(this.picListId).scrollLeft + _moveWidth < 0){ _moveWidth = - sina.$(this.picListId).scrollLeft; }; if(sina.$(this.picListId).scrollLeft + _moveWidth >= this.totalWidth - this.offsetWidth){ _moveWidth = this.totalWidth - this.offsetWidth - sina.$(this.picListId).scrollLeft; }; this.move(_moveWidth); }, move : function(num){ var thisMove = num/4; if(Math.abs(thisMove)<1 && thisMove!=0){ thisMove = (thisMove>=0?1:-1)*1; }else{ thisMove = Math.round(thisMove); }; var temp = sina.$(this.picListId).scrollLeft + thisMove; if(temp <= 0){sina.$(this.picListId).scrollLeft = 0;this.lock = false;return;} if(temp >= this.totalWidth - this.offsetWidth){sina.$(this.picListId).scrollLeft = this.totalWidth - this.offsetWidth;this.lock = false;return;} sina.$(this.picListId).scrollLeft += thisMove; num -= thisMove; if(Math.abs(num) <= 1){this.lock = false;return;}else{ setTimeout("epidiascope.picList.move(" + num + ")",10) } } }; //键盘控制 epidiascope.keyboard = { _timeObj : null, init : function(){ var tempThis = this; sina.addEvent(document,'keydown',function(e){tempThis.keyDown(e)}); this.step = new sina.Step(); this.step.element = sina.$('efpClew'); this.step.limit = 5; this.step.stepTime = 30; this.step.classBase = 'efpClewStep_'; if(!this.closeObj){ this.closeObj = document.createElement('span'); this.closeObj.style.display = 'block'; this.closeObj.id = 'efpClewClose'; sina.$('efpClew').appendChild(this.closeObj); this.closeObj.onclick = function(){tempThis.clewClose()}; }; //提示次数 this.clewNum = parseInt(sina.readCookie('eCn')); if(isNaN(this.clewNum)){this.clewNum = 0}; if(this.clewNum<5){ //this.clewNum ++; //sina.writeCookie('eCn',this.clewNum,24*7); this.clewOpen(); }; }, clewClose : function(){ this.step.action('-'); sina.writeCookie('eCn',6,24*7); }, clewOpen : function(){ this.step.action('+'); }, keyDown : function(e){ e = window.event?event:e; var obj = e.target?e.target:e.srcElement; if(obj.tagName == 'INPUT' || obj.tagName == 'SELECT' || obj.tagName == 'TEXTAREA'){ if(e.stopPropagation){ //阻止冒泡 e.stopPropagation(); }else{ window.event.cancelBubble = true; }; return; }; var stopKey = false; //是否阻止按键 if(epidiascope.mode == 'list'){ //列表模式 if(e.keyCode == 40){ epidiascope.listMoveDown(); stopKey = true; }; if(e.keyCode == 37){ epidiascope.listMoveLeft(); stopKey = true; }; if(e.keyCode == 38){ epidiascope.listMoveUp(); stopKey = true; }; if(e.keyCode == 39){ epidiascope.listMoveRight(); stopKey = true; }; if(e.keyCode == 13){ epidiascope.setMode('player'); epidiascope.select(epidiascope.listSelectedIndex); stopKey = true; }; }else{ //默认模式 if(e.keyCode == 39){ epidiascope.next(); stopKey = true; this.clewClose(); }; if(e.keyCode == 37){ epidiascope.previous(); stopKey = true; this.clewClose(); }; }; if(e.keyCode == 9){ epidiascope.switchMode(); stopKey = true; }; if(stopKey === true){ if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue=false; }; }; } }; //结束选择 epidiascope.endSelect = { endSelectId : "endSelect", closeId : "endSelClose", rePlayButId : "rePlayBut", status : 0, //1:open 0:close open : function(){ this.status = 1; sina.$(this.endSelectId).style.display = "block"; sina.$(this.endSelectId).style.left = Math.round((sina.$(epidiascope.mainBoxId).offsetWidth - sina.$(this.endSelectId).offsetWidth)/2) + "px"; sina.$(this.endSelectId).style.top = Math.round((sina.$(epidiascope.mainBoxId).offsetHeight - sina.$(this.endSelectId).offsetHeight)/2) + "px"; epidiascope.stop(); sina.$(epidiascope.playButtonId).onclick = function(){epidiascope.rePlay()}; sina.$(this.closeId).onclick = function(){epidiascope.endSelect.close()}; sina.$(this.rePlayButId).onclick = function(){epidiascope.rePlay()}; }, close : function(){ this.status = 0; //sina.$(epidiascope.playButtonId).onclick = function(){epidiascope.play()}; sina.$(this.endSelectId).style.display = "none"; } }; epidiascope.onstart = function(){ try{document.execCommand('BackgroundImageCache', false, true);}catch(e){}; //速度条 epidiascope.speedBar.grade = parseInt(sina.readCookie("eSp")); if(isNaN(epidiascope.speedBar.grade)){epidiascope.speedBar.grade = 5}; epidiascope.speedBar.init(); epidiascope.speedBar.onend(); //顶部评论 epidiascope.commTop.init(); //底部评论 epidiascope.commBottom.init(); //图片列表滚动 epidiascope.picList.init(); //按键控制 epidiascope.keyboard.init(); }; //按钮构造函数 epidiascope.Button = function(id){ this.status = 'ok'; this.id = id; this.init(); }; epidiascope.Button.prototype.init = function(){ if(!sina.$(this.id)){return}; var tempThis = this; this.element = sina.$(this.id); this.classNameNum = ''; if(this.element.offsetWidth == 43){ this.classNameNum = '1'; }; this.mouseStatus = 'out'; this.bgDiv = document.createElement('div'); this.bgDiv.className = 'buttonBg' + this.classNameNum; this.element.parentNode.style.position = 'relative'; this.element.style.position = 'relative'; this.element.style.zIndex = '5'; this.element.parentNode.appendChild(this.bgDiv); this.bgDiv.style.top = this.element.offsetTop - 6 + 'px'; this.bgDiv.style.left = this.element.offsetLeft - 6 + 'px'; //动画效果 this.step = new sina.Step(); this.step.element = this.bgDiv; this.step.limit = 3; this.step.stepTime = 30; this.step.classBase = 'buttonBg' + this.classNameNum + ' bBg' + this.classNameNum + 'S_'; sina.addEvent(this.element,'mouseover',function(){tempThis.mouseover()}); sina.addEvent(this.element,'mouseout',function(){tempThis.mouseout()}); sina.addEvent(this.element,'mousedown',function(){tempThis.mousedown()}); sina.addEvent(this.element,'mouseup',function(){tempThis.mouseup()}); }; epidiascope.Button.prototype.rePosi = function(){ this.bgDiv.style.top = this.element.offsetTop - 6 + 'px'; this.bgDiv.style.left = this.element.offsetLeft - 6 + 'px'; }; epidiascope.Button.prototype.mouseover = function(){ this.mouseStatus = 'in'; if(this.status != 'down'){ this.element.className = "hover"; this.step.action('+'); }; }; epidiascope.Button.prototype.mouseout = function(){ this.mouseStatus = 'out'; if(this.status != 'down'){ this.element.className = ""; this.step.action('-'); }; }; epidiascope.Button.prototype.mouseup = function(){ if(this.status == 'down'){return;} this.element.className = "hover"; }; epidiascope.Button.prototype.mousedown = function(){ if(this.status == 'down'){return;} this.element.className = "active"; }; epidiascope.Button.prototype.setStatus = function(status){ switch(status){ case 'ok': this.status = 'ok'; this.element.className = ""; if(this.mouseStatus == 'in'){ this.step.action('+'); }else{ this.step.action('-'); }; break; case 'down': this.status = 'down'; this.step.action('-'); this.element.className = "active"; break; }; }; epidiascope.Button.prototype.hide = function(){ this.element.style.visibility = 'hidden'; this.bgDiv.style.visibility = 'hidden'; }; epidiascope.Button.prototype.show = function(){ this.element.style.visibility = 'visible'; this.bgDiv.style.visibility = 'visible'; }; // ------------------------------------------------------------------------------------- function DrawImage(ImgD,iwidth,iheight){ var image=new Image(); if(!iwidth)iwidth = 90; if(!iheight)iheight = 90; //定义允许高度,当宽度大于这个值时等比例缩小 image.src=ImgD.src; if(image.width>0 && image.height>0){ var flag=true; if(image.width/image.height>= iwidth/iheight){ if(image.width>iwidth){ ImgD.width=iwidth; ImgD.height=(image.height*iwidth)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } }else{ if(image.height>iheight){ ImgD.height=iheight; ImgD.width=(image.width*iheight)/image.height; }else{ ImgD.width=image.width; ImgD.height=image.height; } } } }; //模拟Select mengjia 2008.12.30 function DivSelect(O,l,I){var C=this;C.id=O;C.divId=l;C.divClassName=I;C.selectObj=sina.$(C.id);if(!C.selectObj){return};var o=C;C.status="close";C.parentObj=C.selectObj.parentNode;while(sina.readStyle(C.parentObj,"display")!="block"){if(C.parentObj.parentNode){C.parentObj=C.parentObj.parentNode}else{break}};C.parentObj.style.position="relative";C.selectObjWidth=C.selectObj.offsetWidth;C.selectObjHeight=C.selectObj.offsetHeight;C.selectPosition=sina.absPosition(C.selectObj,C.parentObj);C.selectObj.style.visibility="hidden";C.divObj=document.createElement("div");C.divObj.id=C.divId;if(C.divClassName){C.divObj.className=C.divClassName};C.parentObj.appendChild(C.divObj);C.divObj.style.width=C.selectObjWidth+"px";C.divObj.style.position="absolute";C.divObj.style.left=C.selectPosition.left+"px";C.divObj.style.top=C.selectPosition.top+"px";C.divObj.onclick=function(){o.click()};C.divObj_count=document.createElement("div");C.divObj.appendChild(C.divObj_count);C.divObj_count.className="ds_cont";C.divObj_title=document.createElement("div");C.divObj_count.appendChild(C.divObj_title);C.divObj_title.className="ds_title";C.divObj_button=document.createElement("div");C.divObj_count.appendChild(C.divObj_button);C.divObj_button.className="ds_button";C.divObj_list=document.createElement("div");C.divObj.appendChild(C.divObj_list);C.divObj_list.className="ds_list";C.divObj_list.style.display="none";C.divObj_listCont=document.createElement("div");C.divObj_list.appendChild(C.divObj_listCont);C.divObj_listCont.className="dsl_cont";C.list=[];var i;for(var c=0;c<C.selectObj.options.length;c++){i=document.createElement("p");C.list.push(i);C.divObj_listCont.appendChild(i);i.innerHTML=C.selectObj.options[c].innerHTML;if(C.selectObj.selectedIndex==c){C.divObj_title.innerHTML=i.innerHTML};i.onmouseover=function(){this.className="selected"};i.onmouseout=function(){this.className=""};i.onclick=function(){o.select(this.innerHTML)}};C.select=function(i){var l=this;for(var I=0;I<l.selectObj.options.length;I++){if(l.selectObj.options[I].innerHTML==i){l.selectObj.selectedIndex=I;if(l.selectObj.onchange){l.selectObj.onchange()};l.divObj_title.innerHTML=i;break}}};C.clickClose=function(I){var i=I.target?I.target:event.srcElement;do{if(i==o.divObj){return};if(i.tagName=="BODY"){break};i=i.parentNode}while(i.parentNode);o.close()};C.open=function(){var i=this;i.divObj_list.style.display="block";i.status="open";sina.addEvent(document,"click",i.clickClose)};C.close=function(){var i=this;i.divObj_list.style.display="none";i.status="close";sina.delEvent(document,"click",i.clickClose)};C.click=function(){var i=this;if(i.status=="open"){i.close()}else{i.open()}}};
JavaScript
function myGod(id,w,n){ var box=document.getElementById(id),can=true,w=w||3500,fq=fq||10,n=n==-1?-1:1; box.innerHTML+=box.innerHTML; box.onmouseover=function(){can=false}; box.onmouseout=function(){can=true}; var max=parseInt(box.scrollHeight/2); new function (){ var stop=box.scrollTop%34==0&&!can; if(!stop){ var set=n>0?[max,0]:[0,max]; box.scrollTop==set[0]?box.scrollTop=set[1]:box.scrollTop+=n; }; setTimeout(arguments.callee,box.scrollTop%34?fq:w); }; }; $(document).ready(function(){ var list_featured_pos = $('#list-featured-post .post').length; if(list_featured_pos == 0){ $('.mod-list-featured-post').hide(); }; $('#user-box-body').load('/index.html .mod-teacher .mod-box-body'); $('#rankingListAll').load('/index.html #rankingList'); $('#art_body img').click(function(){ window.open($(this).attr('src')) }); $("#rankingList li").mouseover(function(){ $('#rankingList li').removeClass('show'); $(this).addClass('show'); }); $("#navi .submenu,#navi .on").hover(function(){ $(this).find('.submenu-box').show(); },function(){ $(this).find('.submenu-box').hide(); }); $('.mod-category li:odd').css({ "border-right": "0", "width": "89px" }); $('#mod-tab').each(function(){ $(this).find('.mod-tab-menu li').eq(0).addClass('on'); $(this).find('.mod-tab-col').hide().eq(0).show(); var _this = $(this); $(_this).find('.home-post-ad-box').css('top',$(this).find('.post-in-ad').eq(0).position().top+15) $(this).find('.mod-tab-menu li').click(function(){ var _num = $(this).index(); _this.find('.mod-tab-menu li').removeClass('on').eq(_num).addClass('on'); _this.find('.mod-tab-col').hide().eq(_num).show(); $(_this).find('.home-post-ad-box').css('top',$(_this).find('.post-in-ad').eq($(this).index()).position().top+15) return false; }); }); $("#featured").scrollable(1,2); myGod('announcement',3500); }); $.fn.extend({ scrollable:function(list,row,_item){ var _item = 0; var _itemList = $(this).find('.featured-post').length; var _itemWidth = $(this).find('.featured-post').width()+52; var _page = Math.ceil(_itemList/row)-1; var _pageWidth = row*_itemWidth; var _pageBox = $(this).find('.featured-list-box'); var _thisBox = $(this); var _autoPlayTime = 8000; _thisBox.after('<span class="button next">&nbsp;</span><span class="button prev">&nbsp;</span>') _pageBox.css('width',''+_itemWidth*_itemList+'px'); $('.featured .prev').click(function(){ if(_item == 0){ return false; }else{ playPage(_item--); }; }); $('.featured .next').click(function(){ if(_item == _page){ playPage(_item=0); }else{ playPage(_item++); }; }); function playPage(){ _pageBox.animate( { left: '-'+_pageWidth*_item+'px' }, 800 ); _thisBox.find(".navi span").removeClass('on').eq(_item).addClass('on'); if(_item == 0){_thisBox.find('.prev img').addClass('on');}else{_thisBox.find('.prev img').removeClass('on');}; if(_item == _page){_thisBox.find('.next img').addClass('on');}else{_thisBox.find('.next img').removeClass('on');}; }; playPage(); function autoPlayPage(){ if(_item == _page){ playPage(_item=0); }else{ playPage(_item++); } }; if(!_page==0){ int=setInterval(autoPlayPage,_autoPlayTime); }; /* $("#smooth_sliderc_page span").click(function(){ clearInterval(int); }); */ $(this).hover(function(){ clearInterval(int); },function(){ int=setInterval(autoPlayPage,_autoPlayTime); }); } });
JavaScript
//网站换肤 $(function(){ var cookie_skin = $.cookie("MyCssSkin"); switchSkin(cookie_skin); addEvent(); }); function switchSkin(skinName){ $("#"+skinName).addClass("selected") //当前<li>元素选中 .siblings().removeClass("selected"); //去掉其他同辈<li>元素的选中 $("#cssfile").attr("href","/templets/default/style/"+ skinName +".css"); //设置不同皮肤 $.cookie( "MyCssSkin",skinName, {path: '/', expires: 10 }); } function addEvent(){ var $li =$("#dedecms_skins li"); $li.click(function(){ switchSkin(this.id ); }); var cookie_skin = $.cookie("MyCssSkin"); if (cookie_skin) { switchSkin(cookie_skin); } }
JavaScript
function CheckLogin(){ var taget_obj = document.getElementById('_ajax_feedback'); myajax = new DedeAjax(taget_obj,false,false,'','',''); myajax.SendGet2("/member/ajax_feedback.php"); DedeXHTTP = null; }
JavaScript
(function () { $.fn.infiniteCarousel = function () { function repeat(str, n) { return new Array( n + 1 ).join(str); } return this.each(function () { // magic! var $wrapper = $('> div', this).css('overflow', 'hidden'), $slider = $wrapper.find('> ul').width(9999), $items = $slider.find('> li'), $single = $items.filter(':first') singleWidth = $single.outerWidth(), visible = Math.ceil($wrapper.innerWidth() / singleWidth), currentPage = 1, pages = Math.ceil($items.length / visible); /* TASKS */ // 1. pad the pages with empty element if required if ($items.length % visible != 0) { // pad $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible))); $items = $slider.find('> li'); } // 2. create the carousel padding on left and right (cloned) $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned')); $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned')); $items = $slider.find('> li'); // 3. reset scroll $wrapper.scrollLeft(singleWidth * visible); // 4. paging function function gotoPage(page) { var dir = page < currentPage ? -1 : 1, n = Math.abs(currentPage - page), left = singleWidth * dir * visible * n; $wrapper.filter(':not(:animated)').animate({ scrollLeft : '+=' + left }, 500, function () { // if page == last page - then reset position if (page > pages) { $wrapper.scrollLeft(singleWidth * visible); page = 1; } else if (page == 0) { page = pages; $wrapper.scrollLeft(singleWidth * visible * pages); } currentPage = page; }); } // 5. insert the back and forward link $wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>'); // 6. bind the back and forward links $('a.back', this).click(function () { gotoPage(currentPage - 1); return false; }); $('a.forward', this).click(function () { gotoPage(currentPage + 1); return false; }); $(this).bind('goto', function (event, page) { gotoPage(page); }); // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL $(this).bind('next', function () { gotoPage(currentPage + 1); }); }); }; })(jQuery); $(document).ready(function () { // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL var autoscrolling = true; $('.infiniteCarousel').infiniteCarousel().mouseover(function () { autoscrolling = false; }).mouseout(function () { autoscrolling = true; }); setInterval(function () { if (autoscrolling) { $('.infiniteCarousel').trigger('next'); } }, 5000); });
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // CAUTION: Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/** * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget. * @requires jQuery v1.2 or above * * http://gmarwaha.com/jquery/jcarousellite/ * * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 1.0.1 * Note: Requires jquery 1.2 or above from version 1.0.1 */ /** * Creates a carousel-style navigation widget for images/any-content from a simple HTML markup. * * The HTML markup that is used to build the carousel can be as simple as... * * <div class="carousel"> * <ul> * <li><img src="image/1.jpg" alt="1"></li> * <li><img src="image/2.jpg" alt="2"></li> * <li><img src="image/3.jpg" alt="3"></li> * </ul> * </div> * * As you can see, this snippet is nothing but a simple div containing an unordered list of images. * You don't need any special "class" attribute, or a special "css" file for this plugin. * I am using a class attribute just for the sake of explanation here. * * To navigate the elements of the carousel, you need some kind of navigation buttons. * For example, you will need a "previous" button to go backward, and a "next" button to go forward. * This need not be part of the carousel "div" itself. It can be any element in your page. * Lets assume that the following elements in your document can be used as next, and prev buttons... * * <button class="prev">&lt;&lt;</button> * <button class="next">&gt;&gt;</button> * * Now, all you need to do is call the carousel component on the div element that represents it, and pass in the * navigation buttons as options. * * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev" * }); * * That's it, you would have now converted your raw div, into a magnificient carousel. * * There are quite a few other options that you can use to customize it though. * Each will be explained with an example below. * * @param an options object - You can specify all the options shown below as an options object param. * * @option btnPrev, btnNext : string - no defaults * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev" * }); * @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward. * * @option btnGo - array - no defaults * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * btnGo: [".0", ".1", ".2"] * }); * @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on * the item number within the carousel, you can use this option. Just supply an array of selectors for each element * in the carousel. The index of the array represents the index of the element. What i mean is, if the * first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel * will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed * interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding * any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin. * The best part is that, the tab will "slide" based on the provided effect. :-) * * @option mouseWheel : boolean - default is false * @example * $(".carousel").jCarouselLite({ * mouseWheel: true * }); * @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons. * To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon. * Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel * using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation * as well. They complement each other. To use both together, just supply the options required for both as shown below. * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * mouseWheel: true * }); * * @option auto : number - default is null, meaning autoscroll is disabled by default * @example * $(".carousel").jCarouselLite({ * auto: 800, * speed: 500 * }); * @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option. * The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling. * Specify this value and magically your carousel will start auto scrolling. * * @option speed : number - 200 is default * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * speed: 800 * }); * @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with * different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect. * * @option easing : string - no easing effects by default. * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * easing: "bounceout" * }); * @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified, * the carousel will slide based on the provided easing effect. * * @option vertical : boolean - default is false * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * vertical: true * }); * @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and * prev buttons will slide the items vertically as well. The default is false, which means that the carousel will * display horizontally. The next and prev items will slide the items from left-right in this case. * * @option circular : boolean - default is true * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * circular: false * }); * @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last * element, you will automatically slide to the first element and vice versa. If you set circular to false, then * if you click on the "next" button after you reach the last element, you will stay in the last element itself * and similarly for "previous" button and first element. * * @option visible : number - default is 3 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * visible: 4 * }); * @desc This specifies the number of items visible at all times within the carousel. The default is 3. * You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the * last item half visible. This gives you the effect of showing the user that there are more images to the right. * * @option start : number - default is 0 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * start: 2 * }); * @desc You can specify from which item the carousel should start. Remember, the first item in the carousel * has a start of 0, and so on. * * @option scrool : number - default is 1 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * scroll: 2 * }); * @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By * default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll * 2 items when you click the next or previous buttons. * * @option beforeStart, afterEnd : function - callbacks * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * beforeStart: function(a) { * alert("Before animation starts:" + a); * }, * afterEnd: function(a) { * alert("After animation ends:" + a); * } * }); * @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can * register these 2 callbacks. The functions will be passed an argument that represents an array of elements that * are visible at the time of callback. * * * @cat Plugins/Image Gallery * @author Ganeshji Marwaha/ganeshread@gmail.com */ (function($) { // Compliant with jquery.noConflict() $.fn.jCarouselLite = function(o) { o = $.extend({ btnPrev: '.next', btnNext: '.prev', btnGo: null, mouseWheel: false, auto: null, speed: 200, easing: null, vertical: false, circular: true, visible: 4, start: 0, scroll: 1, beforeStart: null, afterEnd: null }, o || {}); return this.each(function() { // Returns the element collection. Chainable. var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible; if(o.circular) { ul.prepend(tLi.slice(tl-v-1+1).clone()) .append(tLi.slice(0,v).clone()); o.start += v; } var li = $("li", ul), itemLength = li.size(), curr = o.start; div.css("visibility", "visible"); li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"}); var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) var divSize = liSize * v; // size of entire div(total length for just the visible items) li.css({width: li.width(), height: li.height()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images if(o.btnPrev) $(o.btnPrev).click(function() { return go(curr-o.scroll); }); if(o.btnNext) $(o.btnNext).click(function() { return go(curr+o.scroll); }); if(o.btnGo) $.each(o.btnGo, function(i, val) { $(val).click(function() { return go(o.circular ? o.visible+i : i); }); }); if(o.mouseWheel && div.mousewheel) div.mousewheel(function(e, d) { return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); }); if(o.auto) setInterval(function() { go(curr+o.scroll); }, o.auto+o.speed); function vis() { return li.slice(curr).slice(0,v); }; function go(to) { if(!running) { if(o.beforeStart) o.beforeStart.call(this, vis()); if(o.circular) { // If circular we are in first or last, then goto the other end if(to<=o.start-v-1) { // If first, then goto last ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; } else if(to>=itemLength-v+1) { // If last, then goto first ul.css(animCss, -( (v) * liSize ) + "px" ); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. curr = to==itemLength-v+1 ? v+1 : v+o.scroll; } else curr = to; } else { // If non-circular and to points to first or last, we just return. if(to<0 || to>itemLength-v) return; else curr = to; } // If neither overrides it, the curr will still be "to" and we can proceed. running = true; ul.animate( animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, function() { if(o.afterEnd) o.afterEnd.call(this, vis()); running = false; } ); // Disable buttons when the carousel reaches the last/first, and enable when not if(!o.circular) { $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $( (curr-o.scroll<0 && o.btnPrev) || (curr+o.scroll > itemLength-v && o.btnNext) || [] ).addClass("disabled"); } } return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery);
JavaScript
/* * jQuery UI @VERSION * * Copyright (c) 2008 Paul Bakaus (ui.jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ ;(function($) { $.ui = { plugin: { add: function(module, option, set) { var proto = $.ui[module].prototype; for(var i in set) { proto.plugins[i] = proto.plugins[i] || []; proto.plugins[i].push([option, set[i]]); } }, call: function(instance, name, args) { var set = instance.plugins[name]; if(!set) { return; } for (var i = 0; i < set.length; i++) { if (instance.options[set[i][0]]) { set[i][1].apply(instance.element, args); } } } }, cssCache: {}, css: function(name) { if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; } var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body'); //if (!$.browser.safari) //tmp.appendTo('body'); //Opera and Safari set width and height to 0px instead of auto //Safari returns rgba(0,0,0,0) when bgcolor is not set $.ui.cssCache[name] = !!( (!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || !(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor'))) ); try { $('body').get(0).removeChild(tmp.get(0)); } catch(e){} return $.ui.cssCache[name]; }, disableSelection: function(el) { $(el).attr('unselectable', 'on').css('MozUserSelect', 'none'); }, enableSelection: function(el) { $(el).attr('unselectable', 'off').css('MozUserSelect', ''); }, hasScroll: function(e, a) { var scroll = /top/.test(a||"top") ? 'scrollTop' : 'scrollLeft', has = false; if (e[scroll] > 0) return true; e[scroll] = 1; has = e[scroll] > 0 ? true : false; e[scroll] = 0; return has; } }; /** jQuery core modifications and additions **/ var _remove = $.fn.remove; $.fn.remove = function() { $("*", this).add(this).triggerHandler("remove"); return _remove.apply(this, arguments ); }; // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code // created by Scott González and J?rn Zaefferer function getter(namespace, plugin, method) { var methods = $[namespace][plugin].getter || []; methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods); return ($.inArray(method, methods) != -1); } $.widget = function(name, prototype) { var namespace = name.split(".")[0]; name = name.split(".")[1]; // create plugin method $.fn[name] = function(options) { var isMethodCall = (typeof options == 'string'), args = Array.prototype.slice.call(arguments, 1); if (isMethodCall && getter(namespace, name, options)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } return this.each(function() { var instance = $.data(this, name); if (isMethodCall && instance && $.isFunction(instance[options])) { instance[options].apply(instance, args); } else if (!isMethodCall) { $.data(this, name, new $[namespace][name](this, options)); } }); }; // create widget constructor $[namespace][name] = function(element, options) { var self = this; this.widgetName = name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, options); this.element = $(element) .bind('setData.' + name, function(e, key, value) { return self.setData(key, value); }) .bind('getData.' + name, function(e, key) { return self.getData(key); }) .bind('remove', function() { return self.destroy(); }); this.init(); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); }; $.widget.prototype = { init: function() {}, destroy: function() { this.element.removeData(this.widgetName); }, getData: function(key) { return this.options[key]; }, setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.element[value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled'); } }, enable: function() { this.setData('disabled', false); }, disable: function() { this.setData('disabled', true); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { mouseInit: function() { var self = this; this.element.bind('mousedown.'+this.widgetName, function(e) { return self.mouseDown(e); }); // Prevent text selection in IE if ($.browser.msie) { this._mouseUnselectable = this.element.attr('unselectable'); this.element.attr('unselectable', 'on'); } this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse mouseDestroy: function() { this.element.unbind('.'+this.widgetName); // Restore text selection in IE ($.browser.msie && this.element.attr('unselectable', this._mouseUnselectable)); }, mouseDown: function(e) { // we may have missed mouseup (out of window) (this._mouseStarted && this.mouseUp(e)); this._mouseDownEvent = e; var self = this, btnIsLeft = (e.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this.mouseCapture(e)) { return true; } this._mouseDelayMet = !this.options.delay; if (!this._mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self._mouseDelayMet = true; }, this.options.delay); } if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) { this._mouseStarted = (this.mouseStart(e) !== false); if (!this._mouseStarted) { e.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(e) { return self.mouseMove(e); }; this._mouseUpDelegate = function(e) { return self.mouseUp(e); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); return false; }, mouseMove: function(e) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !e.button) { return this.mouseUp(e); } if (this._mouseStarted) { this.mouseDrag(e); return false; } if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) { this._mouseStarted = (this.mouseStart(this._mouseDownEvent, e) !== false); (this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e)); } return !this._mouseStarted; }, mouseUp: function(e) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this.mouseStop(e); } return false; }, mouseDistanceMet: function(e) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - e.pageX), Math.abs(this._mouseDownEvent.pageY - e.pageY) ) >= this.options.distance ); }, mouseDelayMet: function(e) { return this._mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin mouseStart: function(e) {}, mouseDrag: function(e) {}, mouseStop: function(e) {}, mouseCapture: function(e) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(jQuery);
JavaScript
/* * jQuery UI Resizable * * Copyright (c) 2008 Paul Bakaus * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Resizables * * Depends: * ui.core.js */ (function($) { $.widget("ui.resizable", $.extend({}, $.ui.mouse, { init: function() { var self = this, o = this.options; var elpos = this.element.css('position'); this.originalElement = this.element; // simulate .ui-resizable { position: relative; } this.element.addClass("ui-resizable").css({ position: /static/.test(elpos) ? 'relative' : elpos }); $.extend(o, { _aspectRatio: !!(o.aspectRatio), helper: o.helper || o.ghost || o.animate ? o.helper || 'proxy' : null, knobHandles: o.knobHandles === true ? 'ui-resizable-knob-handle' : o.knobHandles }); //Default Theme var aBorder = '1px solid #DEDEDE'; o.defaultTheme = { 'ui-resizable': { display: 'block' }, 'ui-resizable-handle': { position: 'absolute', background: '#F2F2F2', fontSize: '0.1px' }, 'ui-resizable-n': { cursor: 'n-resize', height: '4px', left: '0px', right: '0px', borderTop: aBorder }, 'ui-resizable-s': { cursor: 's-resize', height: '4px', left: '0px', right: '0px', borderBottom: aBorder }, 'ui-resizable-e': { cursor: 'e-resize', width: '4px', top: '0px', bottom: '0px', borderRight: aBorder }, 'ui-resizable-w': { cursor: 'w-resize', width: '4px', top: '0px', bottom: '0px', borderLeft: aBorder }, 'ui-resizable-se': { cursor: 'se-resize', width: '4px', height: '4px', borderRight: aBorder, borderBottom: aBorder }, 'ui-resizable-sw': { cursor: 'sw-resize', width: '4px', height: '4px', borderBottom: aBorder, borderLeft: aBorder }, 'ui-resizable-ne': { cursor: 'ne-resize', width: '4px', height: '4px', borderRight: aBorder, borderTop: aBorder }, 'ui-resizable-nw': { cursor: 'nw-resize', width: '4px', height: '4px', borderLeft: aBorder, borderTop: aBorder } }; o.knobTheme = { 'ui-resizable-handle': { background: '#F2F2F2', border: '1px solid #808080', height: '8px', width: '8px' }, 'ui-resizable-n': { cursor: 'n-resize', top: '0px', left: '45%' }, 'ui-resizable-s': { cursor: 's-resize', bottom: '0px', left: '45%' }, 'ui-resizable-e': { cursor: 'e-resize', right: '0px', top: '45%' }, 'ui-resizable-w': { cursor: 'w-resize', left: '0px', top: '45%' }, 'ui-resizable-se': { cursor: 'se-resize', right: '0px', bottom: '0px' }, 'ui-resizable-sw': { cursor: 'sw-resize', left: '0px', bottom: '0px' }, 'ui-resizable-nw': { cursor: 'nw-resize', left: '0px', top: '0px' }, 'ui-resizable-ne': { cursor: 'ne-resize', right: '0px', top: '0px' } }; o._nodeName = this.element[0].nodeName; //Wrap the element if it cannot hold child nodes if(o._nodeName.match(/canvas|textarea|input|select|button|img/i)) { var el = this.element; //Opera fixing relative position if (/relative/.test(el.css('position')) && $.browser.opera) el.css({ position: 'relative', top: 'auto', left: 'auto' }); //Create a wrapper element and set the wrapper to the new current internal element el.wrap( $('<div class="ui-wrapper" style="overflow: hidden;"></div>').css( { position: el.css('position'), width: el.outerWidth(), height: el.outerHeight(), top: el.css('top'), left: el.css('left') }) ); var oel = this.element; this.element = this.element.parent(); // store instance on wrapper this.element.data('resizable', this); //Move margins to the wrapper this.element.css({ marginLeft: oel.css("marginLeft"), marginTop: oel.css("marginTop"), marginRight: oel.css("marginRight"), marginBottom: oel.css("marginBottom") }); oel.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); //Prevent Safari textarea resize if ($.browser.safari && o.preventDefault) oel.css('resize', 'none'); o.proportionallyResize = oel.css({ position: 'static', zoom: 1, display: 'block' }); // avoid IE jump this.element.css({ margin: oel.css('margin') }); // fix handlers offset this._proportionallyResize(); } if(!o.handles) o.handles = !$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' }; if(o.handles.constructor == String) { o.zIndex = o.zIndex || 1000; if(o.handles == 'all') o.handles = 'n,e,s,w,se,sw,ne,nw'; var n = o.handles.split(","); o.handles = {}; // insertions are applied when don't have theme loaded var insertionsDefault = { handle: 'position: absolute; display: none; overflow:hidden;', n: 'top: 0pt; width:100%;', e: 'right: 0pt; height:100%;', s: 'bottom: 0pt; width:100%;', w: 'left: 0pt; height:100%;', se: 'bottom: 0pt; right: 0px;', sw: 'bottom: 0pt; left: 0px;', ne: 'top: 0pt; right: 0px;', nw: 'top: 0pt; left: 0px;' }; for(var i = 0; i < n.length; i++) { var handle = $.trim(n[i]), dt = o.defaultTheme, hname = 'ui-resizable-'+handle, loadDefault = !$.ui.css(hname) && !o.knobHandles, userKnobClass = $.ui.css('ui-resizable-knob-handle'), allDefTheme = $.extend(dt[hname], dt['ui-resizable-handle']), allKnobTheme = $.extend(o.knobTheme[hname], !userKnobClass ? o.knobTheme['ui-resizable-handle'] : {}); // increase zIndex of sw, se, ne, nw axis var applyZIndex = /sw|se|ne|nw/.test(handle) ? { zIndex: ++o.zIndex } : {}; var defCss = (loadDefault ? insertionsDefault[handle] : ''), axis = $(['<div class="ui-resizable-handle ', hname, '" style="', defCss, insertionsDefault.handle, '"></div>'].join('')).css( applyZIndex ); o.handles[handle] = '.ui-resizable-'+handle; this.element.append( //Theme detection, if not loaded, load o.defaultTheme axis.css( loadDefault ? allDefTheme : {} ) // Load the knobHandle css, fix width, height, top, left... .css( o.knobHandles ? allKnobTheme : {} ).addClass(o.knobHandles ? 'ui-resizable-knob-handle' : '').addClass(o.knobHandles) ); } if (o.knobHandles) this.element.addClass('ui-resizable-knob').css( !$.ui.css('ui-resizable-knob') ? { /*border: '1px #fff dashed'*/ } : {} ); } this._renderAxis = function(target) { target = target || this.element; for(var i in o.handles) { if(o.handles[i].constructor == String) o.handles[i] = $(o.handles[i], this.element).show(); if (o.transparent) o.handles[i].css({opacity:0}); //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.element.is('.ui-wrapper') && o._nodeName.match(/textarea|input|select|button/i)) { var axis = $(o.handles[i], this.element), padWrapper = 0; //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... var padPos = [ 'padding', /ne|nw|n/.test(i) ? 'Top' : /se|sw|s/.test(i) ? 'Bottom' : /^e$/.test(i) ? 'Right' : 'Left' ].join(""); if (!o.transparent) target.css(padPos, padWrapper); this._proportionallyResize(); } if(!$(o.handles[i]).length) continue; } }; this._renderAxis(this.element); o._handles = $('.ui-resizable-handle', self.element); if (o.disableSelection) o._handles.each(function(i, e) { $.ui.disableSelection(e); }); //Matching axis name o._handles.mouseover(function() { if (!o.resizing) { if (this.className) var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); //Axis, default = se self.axis = o.axis = axis && axis[1] ? axis[1] : 'se'; } }); //If we want to auto hide the elements if (o.autoHide) { o._handles.hide(); $(self.element).addClass("ui-resizable-autohide").hover(function() { $(this).removeClass("ui-resizable-autohide"); o._handles.show(); }, function(){ if (!o.resizing) { $(this).addClass("ui-resizable-autohide"); o._handles.hide(); } }); } this.mouseInit(); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, options: this.options, originalSize: this.originalSize, originalPosition: this.originalPosition }; }, propagate: function(n,e) { $.ui.plugin.call(this, n, [e, this.ui()]); if (n != "resize") this.element.triggerHandler(["resize", n].join(""), [e, this.ui()], this.options[n]); }, destroy: function() { var el = this.element, wrapped = el.children(".ui-resizable").get(0); this.mouseDestroy(); var _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled") .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); }; _destroy(el); if (el.is('.ui-wrapper') && wrapped) { el.parent().append( $(wrapped).css({ position: el.css('position'), width: el.outerWidth(), height: el.outerHeight(), top: el.css('top'), left: el.css('left') }) ).end().remove(); _destroy(wrapped); } }, mouseStart: function(e) { if(this.options.disabled) return false; var handle = false; for(var i in this.options.handles) { if($(this.options.handles[i])[0] == e.target) handle = true; } if (!handle) return false; var o = this.options, iniPos = this.element.position(), el = this.element, num = function(v) { return parseInt(v, 10) || 0; }, ie6 = $.browser.msie && $.browser.version < 7; o.resizing = true; o.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; // bugfix #1749 if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { // sOffset decides if document scrollOffset will be added to the top/left of the resizable element var sOffset = $.browser.msie && !o.containment && (/absolute/).test(el.css('position')) && !(/relative/).test(el.parent().css('position')); var dscrollt = sOffset ? o.documentScroll.top : 0, dscrolll = sOffset ? o.documentScroll.left : 0; el.css({ position: 'absolute', top: (iniPos.top + dscrollt), left: (iniPos.left + dscrolll) }); } //Opera fixing relative position if ($.browser.opera && /relative/.test(el.css('position'))) el.css({ position: 'relative', top: 'auto', left: 'auto' }); this._renderProxy(); var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); if (o.containment) { curleft += $(o.containment).scrollLeft()||0; curtop += $(o.containment).scrollTop()||0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: e.pageX, top: e.pageY }; //Aspect Ratio o.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.height / this.originalSize.width)||1); if (o.preserveCursor) $('body').css('cursor', this.axis + '-resize'); this.propagate("start", e); return true; }, mouseDrag: function(e) { //Increase performance, avoid regex var el = this.helper, o = this.options, props = {}, self = this, smp = this.originalMousePosition, a = this.axis; var dx = (e.pageX-smp.left)||0, dy = (e.pageY-smp.top)||0; var trigger = this._change[a]; if (!trigger) return false; // Calculate the attrs that will be change var data = trigger.apply(this, [e, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; if (o._aspectRatio || e.shiftKey) data = this._updateRatio(data, e); data = this._respectSize(data, e); // plugins callbacks need to be called first this.propagate("resize", e); el.css({ top: this.position.top + "px", left: this.position.left + "px", width: this.size.width + "px", height: this.size.height + "px" }); if (!o.helper && o.proportionallyResize) this._proportionallyResize(); this._updateCache(data); // calling the user callback at the end this.element.triggerHandler("resize", [e, this.ui()], this.options["resize"]); return false; }, mouseStop: function(e) { this.options.resizing = false; var o = this.options, num = function(v) { return parseInt(v, 10) || 0; }, self = this; if(o.helper) { var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName), soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, soffsetw = ista ? 0 : self.sizeDiff.width; var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; if (!o.animate) this.element.css($.extend(s, { top: top, left: left })); if (o.helper && !o.animate) this._proportionallyResize(); } if (o.preserveCursor) $('body').css('cursor', 'auto'); this.propagate("stop", e); if (o.helper) this.helper.remove(); return false; }, _updateCache: function(data) { var o = this.options; this.offset = this.helper.offset(); if (data.left) this.position.left = data.left; if (data.top) this.position.top = data.top; if (data.height) this.size.height = data.height; if (data.width) this.size.width = data.width; }, _updateRatio: function(data, e) { var o = this.options, cpos = this.position, csize = this.size, a = this.axis; if (data.height) data.width = (csize.height / o.aspectRatio); else if (data.width) data.height = (csize.width * o.aspectRatio); if (a == 'sw') { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a == 'nw') { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function(data, e) { var el = this.helper, o = this.options, pRatio = o._aspectRatio || e.shiftKey, a = this.axis, ismaxw = data.width && o.maxWidth && o.maxWidth < data.width, ismaxh = data.height && o.maxHeight && o.maxHeight < data.height, isminw = data.width && o.minWidth && o.minWidth > data.width, isminh = data.height && o.minHeight && o.minHeight > data.height; if (isminw) data.width = o.minWidth; if (isminh) data.height = o.minHeight; if (ismaxw) data.width = o.maxWidth; if (ismaxh) data.height = o.maxHeight; var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw && cw) data.left = dw - o.minWidth; if (ismaxw && cw) data.left = dw - o.maxWidth; if (isminh && ch) data.top = dh - o.minHeight; if (ismaxh && ch) data.top = dh - o.maxHeight; // fixing jump error on top/left - bug #2330 var isNotwh = !data.width && !data.height; if (isNotwh && !data.left && data.top) data.top = null; else if (isNotwh && !data.top && data.left) data.left = null; return data; }, _proportionallyResize: function() { var o = this.options; if (!o.proportionallyResize) return; var prel = o.proportionallyResize, el = this.helper || this.element; if (!o.borderDif) { var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; o.borderDif = $.map(b, function(v, i) { var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; return border + padding; }); } prel.css({ height: (el.height() - o.borderDif[0] - o.borderDif[2]) + "px", width: (el.width() - o.borderDif[1] - o.borderDif[3]) + "px" }); }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(o.helper) { this.helper = this.helper || $('<div style="overflow:hidden;"></div>'); // fix ie6 offset var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), pxyoffset = ( ie6 ? 2 : -1 ); this.helper.addClass(o.helper).css({ width: el.outerWidth() + pxyoffset, height: el.outerHeight() + pxyoffset, position: 'absolute', left: this.elementOffset.left - ie6offset +'px', top: this.elementOffset.top - ie6offset +'px', zIndex: ++o.zIndex }); this.helper.appendTo("body"); if (o.disableSelection) $.ui.disableSelection(this.helper.get(0)); } else { this.helper = el; } }, _change: { e: function(e, dx, dy) { return { width: this.originalSize.width + dx }; }, w: function(e, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(e, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(e, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(e, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [e, dx, dy])); }, sw: function(e, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [e, dx, dy])); }, ne: function(e, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [e, dx, dy])); }, nw: function(e, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [e, dx, dy])); } } })); $.extend($.ui.resizable, { defaults: { cancel: ":input", distance: 1, delay: 0, preventDefault: true, transparent: false, minWidth: 10, minHeight: 10, aspectRatio: false, disableSelection: true, preserveCursor: true, autoHide: false, knobHandles: false } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "containment", { start: function(e, ui) { var o = ui.options, self = $(this).data("resizable"), el = self.element; var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; if (!ce) return; self.containerElement = $(ce); if (/document/.test(oc) || oc == document) { self.containerOffset = { left: 0, top: 0 }; self.containerPosition = { left: 0, top: 0 }; self.parentData = { element: $(document), left: 0, top: 0, width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight }; } // i'm a node, so compute top, left, right, bottom else{ self.containerOffset = $(ce).offset(); self.containerPosition = $(ce).position(); self.containerSize = { height: $(ce).innerHeight(), width: $(ce).innerWidth() }; var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width, width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); self.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function(e, ui) { var o = ui.options, self = $(this).data("resizable"), ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, pRatio = o._aspectRatio || e.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; if (ce[0] != document && /static/.test(ce.css('position'))) cop = self.containerPosition; if (cp.left < (o.helper ? co.left : cop.left)) { self.size.width = self.size.width + (o.helper ? (self.position.left - co.left) : (self.position.left - cop.left)); if (pRatio) self.size.height = self.size.width * o.aspectRatio; self.position.left = o.helper ? co.left : cop.left; } if (cp.top < (o.helper ? co.top : 0)) { self.size.height = self.size.height + (o.helper ? (self.position.top - co.top) : self.position.top); if (pRatio) self.size.width = self.size.height / o.aspectRatio; self.position.top = o.helper ? co.top : 0; } var woset = (o.helper ? self.offset.left - co.left : (self.position.left - cop.left)) + self.sizeDiff.width, hoset = (o.helper ? self.offset.top - co.top : self.position.top) + self.sizeDiff.height; if (woset + self.size.width >= self.parentData.width) { self.size.width = self.parentData.width - woset; if (pRatio) self.size.height = self.size.width * o.aspectRatio; } if (hoset + self.size.height >= self.parentData.height) { self.size.height = self.parentData.height - hoset; if (pRatio) self.size.width = self.size.height / o.aspectRatio; } }, stop: function(e, ui){ var o = ui.options, self = $(this).data("resizable"), cp = self.position, co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; var helper = $(self.helper), ho = helper.offset(), w = helper.innerWidth(), h = helper.innerHeight(); if (o.helper && !o.animate && /relative/.test(ce.css('position'))) $(this).css({ left: (ho.left - co.left), top: (ho.top - co.top), width: w, height: h }); if (o.helper && !o.animate && /static/.test(ce.css('position'))) $(this).css({ left: cop.left + (ho.left - co.left), top: cop.top + (ho.top - co.top), width: w, height: h }); } }); $.ui.plugin.add("resizable", "grid", { resize: function(e, ui) { var o = ui.options, self = $(this).data("resizable"), cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || e.shiftKey; o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); if (/^(se|s|e)$/.test(a)) { self.size.width = os.width + ox; self.size.height = os.height + oy; } else if (/^(ne)$/.test(a)) { self.size.width = os.width + ox; self.size.height = os.height + oy; self.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { self.size.width = os.width + ox; self.size.height = os.height + oy; self.position.left = op.left - ox; } else { self.size.width = os.width + ox; self.size.height = os.height + oy; self.position.top = op.top - oy; self.position.left = op.left - ox; } } }); $.ui.plugin.add("resizable", "animate", { stop: function(e, ui) { var o = ui.options, self = $(this).data("resizable"); var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName), soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, soffsetw = ista ? 0 : self.sizeDiff.width; var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; self.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration || "slow", easing: o.animateEasing || "swing", step: function() { var data = { width: parseInt(self.element.css('width'), 10), height: parseInt(self.element.css('height'), 10), top: parseInt(self.element.css('top'), 10), left: parseInt(self.element.css('left'), 10) }; if (pr) pr.css({ width: data.width, height: data.height }); // propagating resize, and updating values for each animation step self._updateCache(data); self.propagate("animate", e); } } ); } }); $.ui.plugin.add("resizable", "ghost", { start: function(e, ui) { var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize, cs = self.size; if (!pr) self.ghost = self.element.clone(); else self.ghost = pr.clone(); self.ghost.css( { opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 } ) .addClass('ui-resizable-ghost').addClass(typeof o.ghost == 'string' ? o.ghost : ''); self.ghost.appendTo(self.helper); }, resize: function(e, ui){ var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize; if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); }, stop: function(e, ui){ var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize; if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); } }); $.ui.plugin.add("resizable", "alsoResize", { start: function(e, ui) { var o = ui.options, self = $(this).data("resizable"), _store = function(exp) { $(exp).each(function() { $(this).data("resizable-alsoresize", { width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10), left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10) }); }); }; if (typeof(o.alsoResize) == 'object') { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function(e, ui){ var o = ui.options, self = $(this).data("resizable"), os = self.originalSize, op = self.originalPosition; var delta = { height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 }, _alsoResize = function(exp, c) { $(exp).each(function() { var start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left']; $.each(css || ['width', 'height', 'top', 'left'], function(i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) style[prop] = sum || null; }); $(this).css(style); }); }; if (typeof(o.alsoResize) == 'object') { $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function(e, ui){ $(this).removeData("resizable-alsoresize-start"); } }); })(jQuery);
JavaScript
/* * jQuery UI Draggable * * Copyright (c) 2008 Paul Bakaus * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Draggables * * Depends: * ui.core.js */ (function($) { $.widget("ui.draggable", $.extend({}, $.ui.mouse, { init: function() { //Initialize needed constants var o = this.options; //Position the node if (o.helper == 'original' && !(/(relative|absolute|fixed)/).test(this.element.css('position'))) this.element.css('position', 'relative'); this.element.addClass('ui-draggable'); (o.disabled && this.element.addClass('ui-draggable-disabled')); this.mouseInit(); }, mouseStart: function(e) { var o = this.options; if (this.helper || o.disabled || $(e.target).is('.ui-resizable-handle')) return false; var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false; $(this.options.handle, this.element).find("*").andSelf().each(function() { if(this == e.target) handle = true; }); if (!handle) return false; if($.ui.ddmanager) $.ui.ddmanager.current = this; //Create and append the visible helper this.helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [e])) : (o.helper == 'clone' ? this.element.clone() : this.element); if(!this.helper.parents('body').length) this.helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)); if(this.helper[0] != this.element[0] && !(/(fixed|absolute)/).test(this.helper.css("position"))) this.helper.css("position", "absolute"); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ this.margins = { //Cache the margins left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0) }; this.cssPosition = this.helper.css("position"); //Store the helper's css position this.offset = this.element.offset(); //The element's absolute position on the page this.offset = { //Substract the margins from the element's absolute offset top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; this.offset.click = { //Where the click happened, relative to the element left: e.pageX - this.offset.left, top: e.pageY - this.offset.top }; this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); //Get the offsetParent and cache its position if(this.offsetParent[0] == document.body && $.browser.mozilla) po = { top: 0, left: 0 }; //Ugly FF3 fix this.offset.parent = { //Store its position plus border top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; var p = this.element.position(); //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helpers this.offset.relative = this.cssPosition == "relative" ? { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.offsetParent[0].scrollTop, left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.offsetParent[0].scrollLeft } : { top: 0, left: 0 }; this.originalPosition = this.generatePosition(e); //Generate the original position this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };//Cache the helper size if(o.cursorAt) { if(o.cursorAt.left != undefined) this.offset.click.left = o.cursorAt.left + this.margins.left; if(o.cursorAt.right != undefined) this.offset.click.left = this.helperProportions.width - o.cursorAt.right + this.margins.left; if(o.cursorAt.top != undefined) this.offset.click.top = o.cursorAt.top + this.margins.top; if(o.cursorAt.bottom != undefined) this.offset.click.top = this.helperProportions.height - o.cursorAt.bottom + this.margins.top; } /* * - Position constraining - * Here we prepare position constraining like grid and containment. */ if(o.containment) { if(o.containment == 'parent') o.containment = this.helper[0].parentNode; if(o.containment == 'document' || o.containment == 'window') this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment == 'document' ? document : window).width() - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0), ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0) ]; if(!(/^(document|window|parent)$/).test(o.containment)) { var ce = $(o.containment)[0]; var co = $(o.containment).offset(); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top, co.left+Math.max(ce.scrollWidth,ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0), co.top+Math.max(ce.scrollHeight,ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0) ]; } } //Call plugins and callbacks this.propagate("start", e); this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };//Recache the helper size if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, e); this.helper.addClass("ui-draggable-dragging"); this.mouseDrag(e); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, convertPositionTo: function(d, pos) { if(!pos) pos = this.position; var mod = d == "absolute" ? 1 : -1; return { top: ( pos.top // the calculated relative position + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border) - (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : this.offsetParent[0].scrollTop) * mod // The offsetParent's scroll position, not if the element is fixed + (this.cssPosition == "fixed" ? $(document).scrollTop() : 0) * mod + this.margins.top * mod //Add the margin (you don't want the margin counting in intersection methods) ), left: ( pos.left // the calculated relative position + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border) - (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : this.offsetParent[0].scrollLeft) * mod // The offsetParent's scroll position, not if the element is fixed + (this.cssPosition == "fixed" ? $(document).scrollLeft() : 0) * mod + this.margins.left * mod //Add the margin (you don't want the margin counting in intersection methods) ) }; }, generatePosition: function(e) { var o = this.options; var position = { top: ( e.pageY // The absolute mouse position - this.offset.click.top // Click offset (relative to the element) - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top // The offsetParent's offset without borders (offset + border) + (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : this.offsetParent[0].scrollTop) // The offsetParent's scroll position, not if the element is fixed - (this.cssPosition == "fixed" ? $(document).scrollTop() : 0) ), left: ( e.pageX // The absolute mouse position - this.offset.click.left // Click offset (relative to the element) - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left // The offsetParent's offset without borders (offset + border) + (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : this.offsetParent[0].scrollLeft) // The offsetParent's scroll position, not if the element is fixed - (this.cssPosition == "fixed" ? $(document).scrollLeft() : 0) ) }; if(!this.originalPosition) return position; //If we are not dragging yet, we won't check for options /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.containment) { if(position.left < this.containment[0]) position.left = this.containment[0]; if(position.top < this.containment[1]) position.top = this.containment[1]; if(position.left > this.containment[2]) position.left = this.containment[2]; if(position.top > this.containment[3]) position.top = this.containment[3]; } if(o.grid) { var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1]; position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0]; position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } return position; }, mouseDrag: function(e) { //Compute the helpers position this.position = this.generatePosition(e); this.positionAbs = this.convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned this.position = this.propagate("drag", e) || this.position; if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px'; if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px'; if($.ui.ddmanager) $.ui.ddmanager.drag(this, e); return false; }, mouseStop: function(e) { //If we are using droppables, inform the manager about the drop var dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) var dropped = $.ui.ddmanager.drop(this, e); if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true) { var self = this; $(this.helper).animate(this.originalPosition, parseInt(this.options.revert, 10) || 500, function() { self.propagate("stop", e); self.clear(); }); } else { this.propagate("stop", e); this.clear(); } return false; }, clear: function() { this.helper.removeClass("ui-draggable-dragging"); if(this.options.helper != 'original' && !this.cancelHelperRemoval) this.helper.remove(); //if($.ui.ddmanager) $.ui.ddmanager.current = null; this.helper = null; this.cancelHelperRemoval = false; }, // From now on bulk stuff - mainly helpers plugins: {}, uiHash: function(e) { return { helper: this.helper, position: this.position, absolutePosition: this.positionAbs, options: this.options }; }, propagate: function(n,e) { $.ui.plugin.call(this, n, [e, this.uiHash()]); if(n == "drag") this.positionAbs = this.convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [e, this.uiHash()], this.options[n]); }, destroy: function() { if(!this.element.data('draggable')) return; this.element.removeData("draggable").unbind(".draggable").removeClass('ui-draggable'); this.mouseDestroy(); } })); $.extend($.ui.draggable, { defaults: { appendTo: "parent", axis: false, cancel: ":input", delay: 0, distance: 1, helper: "original" } }); $.ui.plugin.add("draggable", "cursor", { start: function(e, ui) { var t = $('body'); if (t.css("cursor")) ui.options._cursor = t.css("cursor"); t.css("cursor", ui.options.cursor); }, stop: function(e, ui) { if (ui.options._cursor) $('body').css("cursor", ui.options._cursor); } }); $.ui.plugin.add("draggable", "zIndex", { start: function(e, ui) { var t = $(ui.helper); if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex"); t.css('zIndex', ui.options.zIndex); }, stop: function(e, ui) { if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex); } }); $.ui.plugin.add("draggable", "opacity", { start: function(e, ui) { var t = $(ui.helper); if(t.css("opacity")) ui.options._opacity = t.css("opacity"); t.css('opacity', ui.options.opacity); }, stop: function(e, ui) { if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity); } }); $.ui.plugin.add("draggable", "iframeFix", { start: function(e, ui) { $(ui.options.iframeFix === true ? "iframe" : ui.options.iframeFix).each(function() { $('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>') .css({ width: this.offsetWidth+"px", height: this.offsetHeight+"px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); }, stop: function(e, ui) { $("div.DragDropIframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers } }); $.ui.plugin.add("draggable", "scroll", { start: function(e, ui) { var o = ui.options; var i = $(this).data("draggable"); o.scrollSensitivity = o.scrollSensitivity || 20; o.scrollSpeed = o.scrollSpeed || 20; i.overflowY = function(el) { do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode); return $(document); }(this); i.overflowX = function(el) { do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode); return $(document); }(this); if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') i.overflowYOffset = i.overflowY.offset(); if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') i.overflowXOffset = i.overflowX.offset(); }, drag: function(e, ui) { var o = ui.options; var i = $(this).data("draggable"); if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') { if((i.overflowYOffset.top + i.overflowY[0].offsetHeight) - e.pageY < o.scrollSensitivity) i.overflowY[0].scrollTop = i.overflowY[0].scrollTop + o.scrollSpeed; if(e.pageY - i.overflowYOffset.top < o.scrollSensitivity) i.overflowY[0].scrollTop = i.overflowY[0].scrollTop - o.scrollSpeed; } else { if(e.pageY - $(document).scrollTop() < o.scrollSensitivity) $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); if($(window).height() - (e.pageY - $(document).scrollTop()) < o.scrollSensitivity) $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') { if((i.overflowXOffset.left + i.overflowX[0].offsetWidth) - e.pageX < o.scrollSensitivity) i.overflowX[0].scrollLeft = i.overflowX[0].scrollLeft + o.scrollSpeed; if(e.pageX - i.overflowXOffset.left < o.scrollSensitivity) i.overflowX[0].scrollLeft = i.overflowX[0].scrollLeft - o.scrollSpeed; } else { if(e.pageX - $(document).scrollLeft() < o.scrollSensitivity) $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); if($(window).width() - (e.pageX - $(document).scrollLeft()) < o.scrollSensitivity) $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } }); $.ui.plugin.add("draggable", "snap", { start: function(e, ui) { var inst = $(this).data("draggable"); inst.snapElements = []; $(ui.options.snap === true ? '.ui-draggable' : ui.options.snap).each(function() { var $t = $(this); var $o = $t.offset(); if(this != inst.element[0]) inst.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); }); }, drag: function(e, ui) { var inst = $(this).data("draggable"); var d = ui.options.snapTolerance || 20; var x1 = ui.absolutePosition.left, x2 = x1 + inst.helperProportions.width, y1 = ui.absolutePosition.top, y2 = y1 + inst.helperProportions.height; for (var i = inst.snapElements.length - 1; i >= 0; i--){ var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width, t = inst.snapElements[i].top, b = t + inst.snapElements[i].height; //Yes, I know, this is insane ;) if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) continue; if(ui.options.snapMode != 'inner') { var ts = Math.abs(t - y2) <= 20; var bs = Math.abs(b - y1) <= 20; var ls = Math.abs(l - x2) <= 20; var rs = Math.abs(r - x1) <= 20; if(ts) ui.position.top = inst.convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top; if(bs) ui.position.top = inst.convertPositionTo("relative", { top: b, left: 0 }).top; if(ls) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left; if(rs) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: r }).left; } if(ui.options.snapMode != 'outer') { var ts = Math.abs(t - y1) <= 20; var bs = Math.abs(b - y2) <= 20; var ls = Math.abs(l - x1) <= 20; var rs = Math.abs(r - x2) <= 20; if(ts) ui.position.top = inst.convertPositionTo("relative", { top: t, left: 0 }).top; if(bs) ui.position.top = inst.convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top; if(ls) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: l }).left; if(rs) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left; } }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function(e,ui) { var inst = $(this).data("draggable"); inst.sortables = []; $(ui.options.connectToSortable).each(function() { if($.data(this, 'sortable')) { var sortable = $.data(this, 'sortable'); inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshItems(); //Do a one-time refresh at start to refresh the containerCache sortable.propagate("activate", e, inst); } }); }, stop: function(e,ui) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var inst = $(this).data("draggable"); $.each(inst.sortables, function() { if(this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) if(this.shouldRevert) this.instance.options.revert = true; //revert here this.instance.mouseStop(e); //Also propagate receive event, since the sortable is actually receiving a element this.instance.element.triggerHandler("sortreceive", [e, $.extend(this.instance.ui(), { sender: inst.element })], this.instance.options["receive"]); this.instance.options.helper = this.instance.options._helper; } else { this.instance.propagate("deactivate", e, inst); } }); }, drag: function(e,ui) { var inst = $(this).data("draggable"), self = this; var checkPos = function(o) { var l = o.left, r = l + o.width, t = o.top, b = t + o.height; return (l < (this.positionAbs.left + this.offset.click.left) && (this.positionAbs.left + this.offset.click.left) < r && t < (this.positionAbs.top + this.offset.click.top) && (this.positionAbs.top + this.offset.click.top) < b); }; $.each(inst.sortables, function(i) { if(checkPos.call(inst, this.instance.containerCache)) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if(!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; e.target = this.instance.currentItem[0]; this.instance.mouseCapture(e, true); this.instance.mouseStart(e, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst.propagate("toSortable", e); } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if(this.instance.currentItem) this.instance.mouseDrag(e); } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if(this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; this.instance.options.revert = false; //No revert here this.instance.mouseStop(e, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if(this.instance.placeholder) this.instance.placeholder.remove(); inst.propagate("fromSortable", e); } }; }); } }); $.ui.plugin.add("draggable", "stack", { start: function(e,ui) { var group = $.makeArray($(ui.options.stack.group)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || ui.options.stack.min) - (parseInt($(b).css("zIndex"),10) || ui.options.stack.min); }); $(group).each(function(i) { this.style.zIndex = ui.options.stack.min + i; }); this[0].style.zIndex = ui.options.stack.min + group.length; } }); })(jQuery);
JavaScript
var cssdropdown={ disappeardelay: 250, disablemenuclick: false, enableswipe: 1, enableiframeshim: 1, dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0, getposOffset:function(what, offsettype){ var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop; var parentEl=what.offsetParent; while (parentEl!=null){ totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop; parentEl=parentEl.offsetParent; } return totaloffset; }, swipeeffect:function(){ if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){ this.bottomclip+=10+(this.bottomclip/10) this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)" } else return this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10) }, showhide:function(obj, e){ if (this.ie || this.firefox) this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px" if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){ if (this.enableswipe==1){ if (typeof this.swipetimer!="undefined") clearTimeout(this.swipetimer) obj.clip="rect(0 auto 0 0)" this.bottomclip=0 this.swipeeffect() } obj.visibility="visible" } else if (e.type=="click") obj.visibility="hidden" }, iecompattest:function(){ return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body }, clearbrowseredge:function(obj, whichedge){ var edgeoffset=0 if (whichedge=="rightedge"){ var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15 this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure) edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth } else{ var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18 this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge } } return edgeoffset }, dropit:function(obj, e, dropmenuID){ if (this.dropmenuobj!=null) this.dropmenuobj.style.visibility="hidden" this.clearhidemenu() if (this.ie||this.firefox){ obj.onmouseout=function(){cssdropdown.delayhidemenu()} obj.onclick=function(){return !cssdropdown.disablemenuclick} this.dropmenuobj=document.getElementById(dropmenuID) if(!this.dropmenuobj) return; this.dropmenuobj.onmouseover=function(){cssdropdown.clearhidemenu()} this.dropmenuobj.onmouseout=function(e){cssdropdown.dynamichide(e)} this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()} this.showhide(this.dropmenuobj.style, e) this.dropmenuobj.x=this.getposOffset(obj, "left") this.dropmenuobj.y=this.getposOffset(obj, "top") this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px" this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px" this.positionshim() } }, positionshim:function(){ if (this.enableiframeshim && typeof this.shimobject!="undefined"){ if (this.dropmenuobj.style.visibility=="visible"){ this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px" this.shimobject.style.height=this.dropmenuobj.offsetHeight+"px" this.shimobject.style.left=this.dropmenuobj.style.left this.shimobject.style.top=this.dropmenuobj.style.top } this.shimobject.style.display=(this.dropmenuobj.style.visibility=="visible")? "block" : "none" } }, hideshim:function(){ if (this.enableiframeshim && typeof this.shimobject!="undefined") this.shimobject.style.display='none' }, contains_firefox:function(a, b) { while (b.parentNode) if ((b = b.parentNode) == a) return true; return false; }, dynamichide:function(e){ var evtobj=window.event? window.event : e if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement)) this.delayhidemenu() else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget)) this.delayhidemenu() }, delayhidemenu:function(){ this.delayhide=setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'; cssdropdown.hideshim()",this.disappeardelay) }, clearhidemenu:function(){ if (this.delayhide!="undefined") clearTimeout(this.delayhide) }, startchrome:function(){ for (var ids=0; ids<arguments.length; ids++){ var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a") for (var i=0; i<menuitems.length; i++){ if (menuitems[i].getAttribute("rel")){ var relvalue=menuitems[i].getAttribute("rel") menuitems[i].onmouseover=function(e){ var event=typeof e!="undefined"? e : window.event cssdropdown.dropit(this,event,this.getAttribute("rel")) } } } } if (window.createPopup && !window.XmlHttpRequest){ document.write('<IFRAME id="iframeshim" src="" style="display: none; left: 0; top: 0; z-index: 90; position: absolute; filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)" frameBorder="0" scrolling="no"></IFRAME>') this.shimobject=document.getElementById("iframeshim") } } }
JavaScript
/** * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com * * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ * * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * */ /* ******************* */ /* Constructor & Init */ /* ******************* */ var SWFUpload; if (SWFUpload == undefined) { SWFUpload = function (settings) { this.initSWFUpload(settings); }; } SWFUpload.prototype.initSWFUpload = function (settings) { try { this.customSettings = {}; // A container where developers can place their own settings associated with this instance. this.settings = settings; this.eventQueue = []; this.movieName = "SWFUpload_" + SWFUpload.movieCount++; this.movieElement = null; // Setup global control tracking SWFUpload.instances[this.movieName] = this; // Load the settings. Load the Flash movie. this.initSettings(); this.loadFlash(); this.displayDebugInfo(); } catch (ex) { delete SWFUpload.instances[this.movieName]; throw ex; } }; /* *************** */ /* Static Members */ /* *************** */ SWFUpload.instances = {}; SWFUpload.movieCount = 0; SWFUpload.version = "2.2.0 2009-03-25"; SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED : -100, FILE_EXCEEDS_SIZE_LIMIT : -110, ZERO_BYTE_FILE : -120, INVALID_FILETYPE : -130 }; SWFUpload.UPLOAD_ERROR = { HTTP_ERROR : -200, MISSING_UPLOAD_URL : -210, IO_ERROR : -220, SECURITY_ERROR : -230, UPLOAD_LIMIT_EXCEEDED : -240, UPLOAD_FAILED : -250, SPECIFIED_FILE_ID_NOT_FOUND : -260, FILE_VALIDATION_FAILED : -270, FILE_CANCELLED : -280, UPLOAD_STOPPED : -290 }; SWFUpload.FILE_STATUS = { QUEUED : -1, IN_PROGRESS : -2, ERROR : -3, COMPLETE : -4, CANCELLED : -5 }; SWFUpload.BUTTON_ACTION = { SELECT_FILE : -100, SELECT_FILES : -110, START_UPLOAD : -120 }; SWFUpload.CURSOR = { ARROW : -1, HAND : -2 }; SWFUpload.WINDOW_MODE = { WINDOW : "window", TRANSPARENT : "transparent", OPAQUE : "opaque" }; // Private: takes a URL, determines if it is relative and converts to an absolute URL // using the current site. Only processes the URL if it can, otherwise returns the URL untouched SWFUpload.completeURL = function(url) { if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) { return url; } var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : ""); var indexSlash = window.location.pathname.lastIndexOf("/"); if (indexSlash <= 0) { path = "/"; } else { path = window.location.pathname.substr(0, indexSlash) + "/"; } return /*currentURL +*/ path + url; }; /* ******************** */ /* Instance Members */ /* ******************** */ // Private: initSettings ensures that all the // settings are set, getting a default value if one was not assigned. SWFUpload.prototype.initSettings = function () { this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // Upload backend settings this.ensureDefault("upload_url", ""); this.ensureDefault("preserve_relative_urls", false); this.ensureDefault("file_post_name", "Filedata"); this.ensureDefault("post_params", {}); this.ensureDefault("use_query_string", false); this.ensureDefault("requeue_on_error", false); this.ensureDefault("http_success", []); this.ensureDefault("assume_success_timeout", 0); // File Settings this.ensureDefault("file_types", "*.*"); this.ensureDefault("file_types_description", "All Files"); this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited" this.ensureDefault("file_upload_limit", 0); this.ensureDefault("file_queue_limit", 0); // Flash Settings this.ensureDefault("flash_url", "swfupload.swf"); this.ensureDefault("prevent_swf_caching", true); // Button Settings this.ensureDefault("button_image_url", ""); this.ensureDefault("button_width", 1); this.ensureDefault("button_height", 1); this.ensureDefault("button_text", ""); this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensureDefault("button_text_top_padding", 0); this.ensureDefault("button_text_left_padding", 0); this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES); this.ensureDefault("button_disabled", false); this.ensureDefault("button_placeholder_id", ""); this.ensureDefault("button_placeholder", null); this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW); this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW); // Debug Settings this.ensureDefault("debug", false); this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API // Event Handlers this.settings.return_upload_start_handler = this.returnUploadStart; this.ensureDefault("swfupload_loaded_handler", null); this.ensureDefault("file_dialog_start_handler", null); this.ensureDefault("file_queued_handler", null); this.ensureDefault("file_queue_error_handler", null); this.ensureDefault("file_dialog_complete_handler", null); this.ensureDefault("upload_start_handler", null); this.ensureDefault("upload_progress_handler", null); this.ensureDefault("upload_error_handler", null); this.ensureDefault("upload_success_handler", null); this.ensureDefault("upload_complete_handler", null); this.ensureDefault("debug_handler", this.debugMessage); this.ensureDefault("custom_settings", {}); // Other settings this.customSettings = this.settings.custom_settings; // Update the flash url if needed if (!!this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime(); } if (!this.settings.preserve_relative_urls) { //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url); this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url); } delete this.ensureDefault; }; // Private: loadFlash replaces the button_placeholder element with the flash movie. SWFUpload.prototype.loadFlash = function () { var targetElement, tempParent; // Make sure an element with the ID we are going to use doesn't already exist if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added"; } // Get the element where we will be placing the flash movie targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder; if (targetElement == undefined) { throw "Could not find the placeholder element: " + this.settings.button_placeholder_id; } // Append the container and load the flash tempParent = document.createElement("div"); tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers) targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement); // Fix IE Flash/Form bug if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement(); } }; // Private: getFlashHTML generates the object tag needed to embed the flash in to the document SWFUpload.prototype.getFlashHTML = function () { // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">', '<param name="wmode" value="', this.settings.button_window_mode, '" />', '<param name="movie" value="', this.settings.flash_url, '" />', '<param name="quality" value="high" />', '<param name="menu" value="false" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + this.getFlashVars() + '" />', '</object>'].join(""); }; // Private: getFlashVars builds the parameter string that will be passed // to flash in the flashvars param. SWFUpload.prototype.getFlashVars = function () { // Build a string from the post param object var paramString = this.buildParamString(); var httpSuccessString = this.settings.http_success.join(","); // Build the parameter string return ["movieName=", encodeURIComponent(this.movieName), "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url), "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string), "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&amp;httpSuccess=", encodeURIComponent(httpSuccessString), "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout), "&amp;params=", encodeURIComponent(paramString), "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name), "&amp;fileTypes=", encodeURIComponent(this.settings.file_types), "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width), "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height), "&amp;buttonText=", encodeURIComponent(this.settings.button_text), "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&amp;buttonAction=", encodeURIComponent(this.settings.button_action), "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor) ].join(""); }; // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload // The element is cached after the first lookup SWFUpload.prototype.getMovieElement = function () { if (this.movieElement == undefined) { this.movieElement = document.getElementById(this.movieName); } if (this.movieElement === null) { throw "Could not find Flash element"; } return this.movieElement; }; // Private: buildParamString takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&amp;name=value" SWFUpload.prototype.buildParamString = function () { var postParams = this.settings.post_params; var paramStringPairs = []; if (typeof(postParams) === "object") { for (var name in postParams) { if (postParams.hasOwnProperty(name)) { paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString())); } } } return paramStringPairs.join("&amp;"); }; // Public: Used to remove a SWFUpload instance from the page. This method strives to remove // all references to the SWF, and other objects so memory is properly freed. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state. // Credits: Major improvements provided by steffen SWFUpload.prototype.destroy = function () { try { // Make sure Flash is done before we try to remove it this.cancelUpload(null, false); // Remove the SWFUpload DOM nodes var movieElement = null; movieElement = this.getMovieElement(); if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround) for (var i in movieElement) { try { if (typeof(movieElement[i]) === "function") { movieElement[i] = null; } } catch (ex1) {} } // Remove the Movie Element from the page try { movieElement.parentNode.removeChild(movieElement); } catch (ex) {} } // Remove IE form fix reference window[this.movieName] = null; // Destroy other references SWFUpload.instances[this.movieName] = null; delete SWFUpload.instances[this.movieName]; this.movieElement = null; this.settings = null; this.customSettings = null; this.eventQueue = null; this.movieName = null; return true; } catch (ex2) { return false; } }; // Public: displayDebugInfo prints out settings and configuration // information about this SWFUpload instance. // This function (and any references to it) can be deleted when placing // SWFUpload in production. SWFUpload.prototype.displayDebugInfo = function () { this.debug( [ "---SWFUpload Instance Info---\n", "Version: ", SWFUpload.version, "\n", "Movie Name: ", this.movieName, "\n", "Settings:\n", "\t", "upload_url: ", this.settings.upload_url, "\n", "\t", "flash_url: ", this.settings.flash_url, "\n", "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n", "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n", "\t", "http_success: ", this.settings.http_success.join(", "), "\n", "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n", "\t", "file_post_name: ", this.settings.file_post_name, "\n", "\t", "post_params: ", this.settings.post_params.toString(), "\n", "\t", "file_types: ", this.settings.file_types, "\n", "\t", "file_types_description: ", this.settings.file_types_description, "\n", "\t", "file_size_limit: ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n", "\t", "debug: ", this.settings.debug.toString(), "\n", "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n", "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n", "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n", "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n", "\t", "button_width: ", this.settings.button_width.toString(), "\n", "\t", "button_height: ", this.settings.button_height.toString(), "\n", "\t", "button_text: ", this.settings.button_text.toString(), "\n", "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n", "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n", "\t", "button_action: ", this.settings.button_action.toString(), "\n", "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n", "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n", "Event Handlers:\n", "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n", "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n", "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n", "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n", "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n", "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n", "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n", "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n", "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n" ].join("") ); }; /* Note: addSetting and getSetting are no longer used by SWFUpload but are included the maintain v2 API compatibility */ // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used. SWFUpload.prototype.addSetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found. SWFUpload.prototype.getSetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // Private: callFlash handles function calls made to the Flash element. // Calls are made with a setTimeout for some functions to work around // bugs in the ExternalInterface library. SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; // Flash's method if calling ExternalInterface methods (code adapted from MooTools). try { returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>'); returnValue = eval(returnString); } catch (ex) { throw "Call to " + functionName + " failed"; } // Unescape file post param values if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue); } return returnValue; }; /* ***************************** -- Flash control methods -- Your UI should use these to operate SWFUpload ***************************** */ // WARNING: this function does not work in Flash Player 10 // Public: selectFile causes a File Selection Dialog window to appear. This // dialog only allows 1 file to be selected. SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile"); }; // WARNING: this function does not work in Flash Player 10 // Public: selectFiles causes a File Selection Dialog window to appear/ This // dialog allows the user to select any number of files // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around // for this bug. SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles"); }; // Public: startUpload starts uploading the first file in the queue unless // the optional parameter 'fileID' specifies the ID SWFUpload.prototype.startUpload = function (fileID) { this.callFlash("StartUpload", [fileID]); }; // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) { if (triggerErrorEvent !== false) { triggerErrorEvent = true; } this.callFlash("CancelUpload", [fileID, triggerErrorEvent]); }; // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue. // If nothing is currently uploading then nothing happens. SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload"); }; /* ************************ * Settings methods * These methods change the SWFUpload settings. * SWFUpload settings should not be changed directly on the settings object * since many of the settings need to be passed to Flash in order to take * effect. * *********************** */ // Public: getStats gets the file statistics object. SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats"); }; // Public: setStats changes the SWFUpload statistics. You shouldn't need to // change the statistics but you can. Changing the statistics does not // affect SWFUpload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. SWFUpload.prototype.setStats = function (statsObject) { this.callFlash("SetStats", [statsObject]); }; // Public: getFile retrieves a File object by ID or Index. If the file is // not found then 'null' is returned. SWFUpload.prototype.getFile = function (fileID) { if (typeof(fileID) === "number") { return this.callFlash("GetFileByIndex", [fileID]); } else { return this.callFlash("GetFile", [fileID]); } }; // Public: addFileParam sets a name/value pair that will be posted with the // file specified by the Files ID. If the name already exists then the // exiting value will be overwritten. SWFUpload.prototype.addFileParam = function (fileID, name, value) { return this.callFlash("AddFileParam", [fileID, name, value]); }; // Public: removeFileParam removes a previously set (by addFileParam) name/value // pair from the specified file. SWFUpload.prototype.removeFileParam = function (fileID, name) { this.callFlash("RemoveFileParam", [fileID, name]); }; // Public: setUploadUrl changes the upload_url setting. SWFUpload.prototype.setUploadURL = function (url) { this.settings.upload_url = url.toString(); this.callFlash("SetUploadURL", [url]); }; // Public: setPostParams changes the post_params setting SWFUpload.prototype.setPostParams = function (paramsObject) { this.settings.post_params = paramsObject; this.callFlash("SetPostParams", [paramsObject]); }; // Public: addPostParam adds post name/value pair. Each name can have only one value. SWFUpload.prototype.addPostParam = function (name, value) { this.settings.post_params[name] = value; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: removePostParam deletes post name/value pair. SWFUpload.prototype.removePostParam = function (name) { delete this.settings.post_params[name]; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: setFileTypes changes the file_types setting and the file_types_description setting SWFUpload.prototype.setFileTypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callFlash("SetFileTypes", [types, description]); }; // Public: setFileSizeLimit changes the file_size_limit setting SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) { this.settings.file_size_limit = fileSizeLimit; this.callFlash("SetFileSizeLimit", [fileSizeLimit]); }; // Public: setFileUploadLimit changes the file_upload_limit setting SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) { this.settings.file_upload_limit = fileUploadLimit; this.callFlash("SetFileUploadLimit", [fileUploadLimit]); }; // Public: setFileQueueLimit changes the file_queue_limit setting SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) { this.settings.file_queue_limit = fileQueueLimit; this.callFlash("SetFileQueueLimit", [fileQueueLimit]); }; // Public: setFilePostName changes the file_post_name setting SWFUpload.prototype.setFilePostName = function (filePostName) { this.settings.file_post_name = filePostName; this.callFlash("SetFilePostName", [filePostName]); }; // Public: setUseQueryString changes the use_query_string setting SWFUpload.prototype.setUseQueryString = function (useQueryString) { this.settings.use_query_string = useQueryString; this.callFlash("SetUseQueryString", [useQueryString]); }; // Public: setRequeueOnError changes the requeue_on_error setting SWFUpload.prototype.setRequeueOnError = function (requeueOnError) { this.settings.requeue_on_error = requeueOnError; this.callFlash("SetRequeueOnError", [requeueOnError]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) { if (typeof http_status_codes === "string") { http_status_codes = http_status_codes.replace(" ", "").split(","); } this.settings.http_success = http_status_codes; this.callFlash("SetHTTPSuccess", [http_status_codes]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) { this.settings.assume_success_timeout = timeout_seconds; this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]); }; // Public: setDebugEnabled changes the debug_enabled setting SWFUpload.prototype.setDebugEnabled = function (debugEnabled) { this.settings.debug_enabled = debugEnabled; this.callFlash("SetDebugEnabled", [debugEnabled]); }; // Public: setButtonImageURL loads a button image sprite SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) { if (buttonImageURL == undefined) { buttonImageURL = ""; } this.settings.button_image_url = buttonImageURL; this.callFlash("SetButtonImageURL", [buttonImageURL]); }; // Public: setButtonDimensions resizes the Flash Movie and button SWFUpload.prototype.setButtonDimensions = function (width, height) { this.settings.button_width = width; this.settings.button_height = height; var movie = this.getMovieElement(); if (movie != undefined) { movie.style.width = width + "px"; movie.style.height = height + "px"; } this.callFlash("SetButtonDimensions", [width, height]); }; // Public: setButtonText Changes the text overlaid on the button SWFUpload.prototype.setButtonText = function (html) { this.settings.button_text = html; this.callFlash("SetButtonText", [html]); }; // Public: setButtonTextPadding changes the top and left padding of the text overlay SWFUpload.prototype.setButtonTextPadding = function (left, top) { this.settings.button_text_top_padding = top; this.settings.button_text_left_padding = left; this.callFlash("SetButtonTextPadding", [left, top]); }; // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button SWFUpload.prototype.setButtonTextStyle = function (css) { this.settings.button_text_style = css; this.callFlash("SetButtonTextStyle", [css]); }; // Public: setButtonDisabled disables/enables the button SWFUpload.prototype.setButtonDisabled = function (isDisabled) { this.settings.button_disabled = isDisabled; this.callFlash("SetButtonDisabled", [isDisabled]); }; // Public: setButtonAction sets the action that occurs when the button is clicked SWFUpload.prototype.setButtonAction = function (buttonAction) { this.settings.button_action = buttonAction; this.callFlash("SetButtonAction", [buttonAction]); }; // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button SWFUpload.prototype.setButtonCursor = function (cursor) { this.settings.button_cursor = cursor; this.callFlash("SetButtonCursor", [cursor]); }; /* ******************************* Flash Event Interfaces These functions are used by Flash to trigger the various events. All these functions a Private. Because the ExternalInterface library is buggy the event calls are added to a queue and the queue then executed by a setTimeout. This ensures that events are executed in a determinate order and that the ExternalInterface bugs are avoided. ******************************* */ SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) { // Warning: Don't call this.debug inside here or you'll create an infinite loop if (argumentArray == undefined) { argumentArray = []; } else if (!(argumentArray instanceof Array)) { argumentArray = [argumentArray]; } var self = this; if (typeof this.settings[handlerName] === "function") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler " + handlerName + " is unknown or is not a function"; } }; // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout // we must queue them in order to garentee that they are executed in order. SWFUpload.prototype.executeNextEvent = function () { // Warning: Don't call this.debug inside here or you'll create an infinite loop var f = this.eventQueue ? this.eventQueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }; // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have // properties that contain characters that are not valid for JavaScript identifiers. To work around this // the Flash Component escapes the parameter names and we must unescape again before passing them along. SWFUpload.prototype.unescapeFilePostParams = function (file) { var reg = /[$]([0-9a-f]{4})/i; var unescapedPost = {}; var uk; if (file != undefined) { for (var k in file.post) { if (file.post.hasOwnProperty(k)) { uk = k; var match; while ((match = reg.exec(uk)) !== null) { uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16))); } unescapedPost[uk] = file.post[k]; } } file.post = unescapedPost; } return file; }; // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working) SWFUpload.prototype.testExternalInterface = function () { try { return this.callFlash("TestExternalInterface"); } catch (ex) { return false; } }; // Private: This event is called by Flash when it has finished loading. Don't modify this. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded. SWFUpload.prototype.flashReady = function () { // Check that the movie element is loaded correctly with its ExternalInterface methods defined var movieElement = this.getMovieElement(); if (!movieElement) { this.debug("Flash called back ready but the flash movie can't be found."); return; } this.cleanUp(movieElement); this.queueEvent("swfupload_loaded_handler"); }; // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE. // This function is called by Flash each time the ExternalInterface functions are created. SWFUpload.prototype.cleanUp = function (movieElement) { // Pro-actively unhook all the Flash functions try { if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)"); for (var key in movieElement) { try { if (typeof(movieElement[key]) === "function") { movieElement[key] = null; } } catch (ex) { } } } } catch (ex1) { } // Fix Flashes own cleanup code so if the SWFMovie was removed from the page // it doesn't display errors. window["__flash__removeCallback"] = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashEx) { } }; }; /* This is a chance to do something before the browse window opens */ SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler"); }; /* Called when a file is successfully added to the queue. */ SWFUpload.prototype.fileQueued = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queued_handler", file); }; /* Handle errors that occur when an attempt to queue a file fails. */ SWFUpload.prototype.fileQueueError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queue_error_handler", [file, errorCode, message]); }; /* Called after the file dialog has closed and the selected files have been queued. You could call startUpload here if you want the queued files to begin uploading immediately. */ SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) { this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]); }; SWFUpload.prototype.uploadStart = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("return_upload_start_handler", file); }; SWFUpload.prototype.returnUploadStart = function (file) { var returnValue; if (typeof this.settings.upload_start_handler === "function") { file = this.unescapeFilePostParams(file); returnValue = this.settings.upload_start_handler.call(this, file); } else if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function"; } // Convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. if (returnValue === undefined) { returnValue = true; } returnValue = !!returnValue; this.callFlash("ReturnUploadStart", [returnValue]); }; SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]); }; SWFUpload.prototype.uploadError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_error_handler", [file, errorCode, message]); }; SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_success_handler", [file, serverData, responseReceived]); }; SWFUpload.prototype.uploadComplete = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_complete_handler", file); }; /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the internal debug console. You can override this event and have messages written where you want. */ SWFUpload.prototype.debug = function (message) { this.queueEvent("debug_handler", message); }; /* ********************************** Debug Console The debug console is a self contained, in page location for debug message to be sent. The Debug Console adds itself to the body if necessary. The console is automatically scrolled as messages appear. If you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // Private: debugMessage is the default debug_handler. If you want to print debug messages // call the debug() function. When overriding the function your own function should // check to see if the debug setting is true before outputting debug information. SWFUpload.prototype.debugMessage = function (message) { if (this.settings.debug) { var exceptionMessage, exceptionValues = []; // Check for an exception object and print it nicely if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") { for (var key in message) { if (message.hasOwnProperty(key)) { exceptionValues.push(key + ": " + message[key]); } } exceptionMessage = exceptionValues.join("\n") || ""; exceptionValues = exceptionMessage.split("\n"); exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: "); SWFUpload.Console.writeLine(exceptionMessage); } else { SWFUpload.Console.writeLine(message); } } }; SWFUpload.Console = {}; SWFUpload.Console.writeLine = function (message) { var console, documentForm; try { console = document.getElementById("SWFUpload_Console"); if (!console) { documentForm = document.createElement("form"); document.getElementsByTagName("body")[0].appendChild(documentForm); console = document.createElement("textarea"); console.id = "SWFUpload_Console"; console.style.fontFamily = "monospace"; console.setAttribute("wrap", "off"); console.wrap = "off"; console.style.overflow = "auto"; console.style.width = "700px"; console.style.height = "350px"; console.style.margin = "5px"; documentForm.appendChild(console); } console.value += message + "\n"; console.scrollTop = console.scrollHeight - console.clientHeight; } catch (ex) { alert("Exception: " + ex.name + " Message: " + ex.message); } };
JavaScript
/* Cookie Plug-in This plug in automatically gets all the cookies for this site and adds them to the post_params. Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params. The cookies will override any other post params with the same name. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.prototype.initSettings = function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point }; }(SWFUpload.prototype.initSettings); // refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True SWFUpload.prototype.refreshCookies = function (sendToFlash) { if (sendToFlash === undefined) { sendToFlash = true; } sendToFlash = !!sendToFlash; // Get the post_params object var postParams = this.settings.post_params; // Get the cookies var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value; for (i = 0; i < caLength; i++) { c = cookieArray[i]; // Left Trim spaces while (c.charAt(0) === " ") { c = c.substring(1, c.length); } eqIndex = c.indexOf("="); if (eqIndex > 0) { name = c.substring(0, eqIndex); value = c.substring(eqIndex + 1); postParams[name] = value; } } if (sendToFlash) { this.setPostParams(postParams); } }; }
JavaScript
/* Queue Plug-in Features: *Adds a cancelQueue() method for cancelling the entire queue. *All queued files are uploaded when startUpload() is called. *If false is returned from uploadComplete then the queue upload is stopped. If false is not returned (strict comparison) then the queue upload is continued. *Adds a QueueComplete event that is fired when all the queued files have finished uploading. Set the event handler with the queue_complete_handler setting. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.queue = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.queueSettings = {}; this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler; this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler; this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler; this.settings.queue_complete_handler = this.settings.queue_complete_handler || null; }; })(SWFUpload.prototype.initSettings); SWFUpload.prototype.startUpload = function (fileID) { this.queueSettings.queue_cancelled_flag = false; this.callFlash("StartUpload", [fileID]); }; SWFUpload.prototype.cancelQueue = function () { this.queueSettings.queue_cancelled_flag = true; this.stopUpload(); var stats = this.getStats(); while (stats.files_queued > 0) { this.cancelUpload(); stats = this.getStats(); } }; SWFUpload.queue.uploadStartHandler = function (file) { var returnValue; if (typeof(this.queueSettings.user_upload_start_handler) === "function") { returnValue = this.queueSettings.user_upload_start_handler.call(this, file); } // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value. returnValue = (returnValue === false) ? false : true; this.queueSettings.queue_cancelled_flag = !returnValue; return returnValue; }; SWFUpload.queue.uploadCompleteHandler = function (file) { var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler; var continueUpload; if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) { this.queueSettings.queue_upload_count++; } if (typeof(user_upload_complete_handler) === "function") { continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true; } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) { // If the file was stopped and re-queued don't restart the upload continueUpload = false; } else { continueUpload = true; } if (continueUpload) { var stats = this.getStats(); if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) { this.startUpload(); } else if (this.queueSettings.queue_cancelled_flag === false) { this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]); this.queueSettings.queue_upload_count = 0; } else { this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; } } }; }
JavaScript
/* Speed Plug-in Features: *Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc. - currentSpeed -- String indicating the upload speed, bytes per second - averageSpeed -- Overall average upload speed, bytes per second - movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second - timeRemaining -- Estimated remaining upload time in seconds - timeElapsed -- Number of seconds passed for this upload - percentUploaded -- Percentage of the file uploaded (0 to 100) - sizeUploaded -- Formatted size uploaded so far, bytes *Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed. *Adds several Formatting functions for formatting that values provided on the file object. - SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps) - SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S) - SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B ) - SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %) - SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean) - Formats a number using the division array to determine how to apply the labels in the Label Array - factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed) or as several numbers labeled with units (time) */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.speed = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // List used to keep the speed stats for the files we are tracking this.fileSpeedStats = {}; this.speedSettings = {}; this.ensureDefault("moving_average_history_size", "10"); this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler; this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler; this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler; this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler; this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler; this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler; this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler; this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler; this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler; this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler; this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler; this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler; this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler; delete this.ensureDefault; }; })(SWFUpload.prototype.initSettings); SWFUpload.speed.fileQueuedHandler = function (file) { if (typeof this.speedSettings.user_file_queued_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queued_handler.call(this, file); } }; SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) { if (typeof this.speedSettings.user_file_queue_error_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadStartHandler = function (file) { if (typeof this.speedSettings.user_upload_start_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_start_handler.call(this, file); } }; SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_error_handler === "function") { return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) { this.updateTracking(file, bytesComplete); file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_progress_handler === "function") { return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal); } }; SWFUpload.speed.uploadSuccessHandler = function (file, serverData) { if (typeof this.speedSettings.user_upload_success_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_success_handler.call(this, file, serverData); } }; SWFUpload.speed.uploadCompleteHandler = function (file) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_complete_handler === "function") { return this.speedSettings.user_upload_complete_handler.call(this, file); } }; // Private: extends the file object with the speed plugin values SWFUpload.speed.extendFile = function (file, trackingList) { var tracking; if (trackingList) { tracking = trackingList[file.id]; } if (tracking) { file.currentSpeed = tracking.currentSpeed; file.averageSpeed = tracking.averageSpeed; file.movingAverageSpeed = tracking.movingAverageSpeed; file.timeRemaining = tracking.timeRemaining; file.timeElapsed = tracking.timeElapsed; file.percentUploaded = tracking.percentUploaded; file.sizeUploaded = tracking.bytesUploaded; } else { file.currentSpeed = 0; file.averageSpeed = 0; file.movingAverageSpeed = 0; file.timeRemaining = 0; file.timeElapsed = 0; file.percentUploaded = 0; file.sizeUploaded = 0; } return file; }; // Private: Updates the speed tracking object, or creates it if necessary SWFUpload.prototype.updateTracking = function (file, bytesUploaded) { var tracking = this.fileSpeedStats[file.id]; if (!tracking) { this.fileSpeedStats[file.id] = tracking = {}; } // Sanity check inputs bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0; if (bytesUploaded < 0) { bytesUploaded = 0; } if (bytesUploaded > file.size) { bytesUploaded = file.size; } var tickTime = (new Date()).getTime(); if (!tracking.startTime) { tracking.startTime = (new Date()).getTime(); tracking.lastTime = tracking.startTime; tracking.currentSpeed = 0; tracking.averageSpeed = 0; tracking.movingAverageSpeed = 0; tracking.movingAverageHistory = []; tracking.timeRemaining = 0; tracking.timeElapsed = 0; tracking.percentUploaded = bytesUploaded / file.size; tracking.bytesUploaded = bytesUploaded; } else if (tracking.startTime > tickTime) { this.debug("When backwards in time"); } else { // Get time and deltas var now = (new Date()).getTime(); var lastTime = tracking.lastTime; var deltaTime = now - lastTime; var deltaBytes = bytesUploaded - tracking.bytesUploaded; if (deltaBytes === 0 || deltaTime === 0) { return tracking; } // Update tracking object tracking.lastTime = now; tracking.bytesUploaded = bytesUploaded; // Calculate speeds tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000); tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000); // Calculate moving average tracking.movingAverageHistory.push(tracking.currentSpeed); if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) { tracking.movingAverageHistory.shift(); } tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory); // Update times tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed; tracking.timeElapsed = (now - tracking.startTime) / 1000; // Update percent tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100); } return tracking; }; SWFUpload.speed.removeTracking = function (file, trackingList) { try { trackingList[file.id] = null; delete trackingList[file.id]; } catch (ex) { } }; SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) { var i, unit, unitDivisor, unitLabel; if (baseNumber === 0) { return "0 " + unitLabels[unitLabels.length - 1]; } if (singleFractional) { unit = baseNumber; unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : ""; for (i = 0; i < unitDivisors.length; i++) { if (baseNumber >= unitDivisors[i]) { unit = (baseNumber / unitDivisors[i]).toFixed(2); unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : ""; break; } } return unit + unitLabel; } else { var formattedStrings = []; var remainder = baseNumber; for (i = 0; i < unitDivisors.length; i++) { unitDivisor = unitDivisors[i]; unitLabel = unitLabels.length > i ? " " + unitLabels[i] : ""; unit = remainder / unitDivisor; if (i < unitDivisors.length -1) { unit = Math.floor(unit); } else { unit = unit.toFixed(2); } if (unit > 0) { remainder = remainder % unitDivisor; formattedStrings.push(unit + unitLabel); } } return formattedStrings.join(" "); } }; SWFUpload.speed.formatBPS = function (baseNumber) { var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"]; return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true); }; SWFUpload.speed.formatTime = function (baseNumber) { var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"]; return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false); }; SWFUpload.speed.formatBytes = function (baseNumber) { var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"]; return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true); }; SWFUpload.speed.formatPercent = function (baseNumber) { return baseNumber.toFixed(2) + " %"; }; SWFUpload.speed.calculateMovingAverage = function (history) { var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0; var i; var mSum = 0, mCount = 0; size = history.length; // Check for sufficient data if (size >= 8) { // Clone the array and Calculate sum of the values for (i = 0; i < size; i++) { vals[i] = history[i]; sum += vals[i]; } mean = sum / size; // Calculate variance for the set for (i = 0; i < size; i++) { varianceTemp += Math.pow((vals[i] - mean), 2); } variance = varianceTemp / size; standardDev = Math.sqrt(variance); //Standardize the Data for (i = 0; i < size; i++) { vals[i] = (vals[i] - mean) / standardDev; } // Calculate the average excluding outliers var deviationRange = 2.0; for (i = 0; i < size; i++) { if (vals[i] <= deviationRange && vals[i] >= -deviationRange) { mCount++; mSum += history[i]; } } } else { // Calculate the average (not enough data points to remove outliers) mCount = size; for (i = 0; i < size; i++) { mSum += history[i]; } } return mSum / mCount; }; }
JavaScript
<!-- //选择地区的二级分类(非通用调用) function selNext(oj, v) { var newobj = oj.options; var selv = parseInt(v); var maxv = parseInt(v) + 500; while(newobj.length > 0) { oj.remove(0); } clear(oj); if(selv==0) { aOption = document.createElement('OPTION'); aOption.text = '具体地区'; aOption.value = '0'; oj.options.add(aOption); return; } else { aOption = document.createElement('OPTION'); aOption.text = '具体地区'; aOption.value = '0'; oj.options.add(aOption); } var str = ''; for(i=selv+1; i < maxv; i++) { if(!em_nativeplaces[i]) continue; aOption = document.createElement('OPTION'); aOption.text = em_nativeplaces[i]; aOption.value = i; oj.options.add(aOption); } } //子类改变事件 function ChangeSon() { var emname = this.name.replace('_son', ''); var topSelObj = document.getElementById(emname+'_top'); if(this.options[this.selectedIndex].value==0) { document.getElementById('hidden_'+emname).value = topSelObj.options[topSelObj.selectedIndex].value; } else { document.getElementById('hidden_'+emname).value = this.options[this.selectedIndex].value; } } //顶级类改变事件 function selNextSon() { var emname = this.name.replace('_top', ''); if( document.getElementById(emname+'_son') ) { var oj = document.getElementById(emname + '_son'); } else { var oj = document.createElement('select'); oj.name = emname + '_son'; oj.id = emname + '_son'; oj.onchange = ChangeSon; } var v = this.options[this.selectedIndex].value; document.getElementById('hidden_'+emname).value = v; var newobj = oj.options; var selarr = eval('em_'+emname+'s'); var selv = parseInt(v); var maxv = parseInt(v) + 500; while(newobj && newobj.length > 0) oj.remove(0); clear(oj); if(selv==0) { aOption = document.createElement('OPTION'); aOption.text = '请选择..'; aOption.value = '0'; oj.options.add(aOption); return; } else { aOption = document.createElement('OPTION'); aOption.text = '请选择..'; aOption.value = '0'; oj.options.add(aOption); } var str = ''; for(i=selv+1; i < maxv; i++) { if(!selarr[i]) continue; aOption = document.createElement('OPTION'); aOption.text = selarr[i]; aOption.value = i; oj.options.add(aOption); } document.getElementById('span_'+emname+'_son').appendChild(oj); } //生成任意的两级选择框 function MakeTopSelect(emname, selvalue) { var selectFormHtml = ''; var aOption = null; var selObj = document.createElement("select"); selObj.name = emname + '_top'; selObj.id = emname + '_top'; selObj.onchange = selNextSon; var selarr = eval('em_'+emname+'s'); var topvalue = 0; var sonvalue = 0; aOption = document.createElement('OPTION'); aOption.text = '请选择..'; aOption.value = 0; selObj.options.add(aOption); if(selvalue%500 == 0 ) { topvalue = selvalue; } else { sonvalue = selvalue; topvalue = selvalue - (selvalue%500); } for(i=500; i<=selarr.length; i += 500) { if(!selarr[i]) continue; aOption = document.createElement('OPTION'); if(i == topvalue) { aOption = document.createElement('OPTION'); aOption.text = selarr[i]; aOption.value = i; selObj.options.add(aOption); aOption.selected = true; } else { aOption = document.createElement('OPTION'); aOption.text = selarr[i]; aOption.value = i; selObj.options.add(aOption); } } document.getElementById('span_'+emname).appendChild(selObj); //如果子类存在值,创建子类 //if(sonvalue > 0 || topvalue > 0) { selObj = document.createElement("select"); selObj.name = emname + '_son'; selObj.id = emname + '_son'; selObj.onchange = ChangeSon; aOption = document.createElement('OPTION'); aOption.text = '请选择..'; aOption.value = 0; selObj.options.add(aOption); //当大类有值输出子类 if(topvalue > 0) { var selv = topvalue; var maxv = parseInt(topvalue) + 500; for(i=selv+1; i < maxv; i++) { if(!selarr[i]) continue; aOption = document.createElement('OPTION'); if(i == sonvalue) { aOption = document.createElement('OPTION'); aOption.text = selarr[i]; aOption.value = i; selObj.options.add(aOption); aOption.selected = true; } else { aOption = document.createElement('OPTION'); aOption.text = selarr[i]; aOption.value = i; selObj.options.add(aOption); } } } document.getElementById('span_'+emname+'_son').appendChild(selObj); } //清除旧对象 function clear(o) { l=o.length; for (i = 0; i< l; i++){ o.options[1]=null; } } -->
JavaScript
/*Copyright Mihai Bazon, 2002, 2003|http://dynarch.com/mishoo/ */ Calendar = function (mondayFirst, dateStr, onSelected, onClose) { // member variables this.activeDiv = null; this.currentDateEl = null; this.getDateStatus = 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.mondayFirst = mondayFirst; this.dateStr = dateStr; this.ar_days = null; this.showsTime = false; this.time24 = true; // 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) ); /// 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 = Calendar.getAbsolutePos(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }; Calendar.isRelated = function (el, evt) { var related = evt.relatedTarget; if (!related) { var type = evt.type; if (type == "mouseover") { related = evt.fromElement; } else if (type == "mouseout") { related = evt.toElement; } } while (related) { if (related == el) { return true; } related = related.parentNode; } return false; }; Calendar.removeClass = function(el, className) { if (!(el && el.className)) { return; } var cls = el.className.split(" "); var ar = new Array(); for (var i = cls.length; i > 0;) { if (cls[--i] != className) { ar[ar.length] = cls[i]; } } el.className = ar.join(" "); }; Calendar.addClass = function(el, className) { Calendar.removeClass(el, className); el.className += " " + className; }; Calendar.getElement = function(ev) { if (Calendar.is_ie) { return window.event.srcElement; } else { return ev.currentTarget; } }; Calendar.getTargetElement = function(ev) { if (Calendar.is_ie) { return window.event.srcElement; } else { return ev.target; } }; 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 s.left = (cd.offsetLeft + cd.offsetWidth - mc.offsetWidth) + "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.firstChild.data = Y; yr.year = Y; yr.style.display = "block"; show = true; } else { yr.style.display = "none"; } yr = yr.nextSibling; Y += fwd ? 2 : -2; } if (show) { var s = yc.style; s.display = "block"; if (cd.navtype < 0) s.left = cd.offsetLeft + "px"; else s.left = (cd.offsetLeft + cd.offsetWidth - yc.offsetWidth) + "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 in range)) i = range.length - 1; } else if (!(++i in range)) i = 0; var newval = range[i]; el.firstChild.data = 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, "mouseover", stopEvent); 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.firstChild.data; addClass(el, "hilite active"); addEvent(document, "mouseover", tableMouseOver); addEvent(document, "mousemove", tableMouseOver); 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) == "_") { var date = null; with (el.calendar.date) { date = new Date(getFullYear(), getMonth(), el.caldate); } el.ttip = date.print(el.calendar.ttDateFormat) + el.ttip.substr(1); } el.calendar.tooltips.firstChild.data = 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"); } el.calendar.tooltips.firstChild.data = _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") { Calendar.removeClass(cal.currentDateEl, "selected"); Calendar.addClass(el, "selected"); closing = (cal.currentDateEl == el); if (!closing) { cal.currentDateEl = el; } cal.date.setDate(el.caldate); date = cal.date; newdate = true; // a date was clicked cal.dateClicked = true; } else { if (el.navtype == 200) { Calendar.removeClass(el, "hilite"); cal.callCloseHandler(); return; } date = (el.navtype == 0) ? new Date() : new Date(cal.date); // 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 <mishoo@infoiasi.ro> 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.setMondayFirst(!cal.mondayFirst); return; case 50: var range = el._range; var current = el.firstChild.data; for (var i = range.length; --i >= 0;) if (range[i] == current) break; if (ev && ev.shiftKey) { if (!(--i in range)) i = range.length - 1; } else if (!(++i in range)) i = 0; var newval = range[i]; el.firstChild.data = 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())) { // remember, "date" was previously set to new // Date() if TODAY was clicked; thus, it // contains today date. return false; } break; } if (!date.equalsTo(cal.date)) { cal.setDate(date); newdate = true; } } if (newdate) { cal.callHandler(); } if (closing) { Calendar.removeClass(el, "hilite"); 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; if (text.substr(0, 1) != "&") { cell.appendChild(document.createTextNode(text)); } else { // FIXME: dirty hack for entities cell.innerHTML = text; } 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("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"]; } row = Calendar.createElement("tr", thead); row.className = "headrow"; this._nav_py = hh("&#x00ab;", 1, -2); this._nav_py.ttip = Calendar._TT["PREV_YEAR"]; this._nav_pm = hh("&#x2039;", 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("&#x203a;", 1, 1); this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"]; this._nav_ny = hh("&#x00bb;", 1, 2); this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"]; // day names row = Calendar.createElement("tr", thead); row.className = "daynames"; if (this.weekNumbers) { cell = Calendar.createElement("td", row); cell.className = "name wn"; cell.appendChild(document.createTextNode(Calendar._TT["WK"])); } for (var i = 7; i > 0; --i) { cell = Calendar.createElement("td", row); cell.appendChild(document.createTextNode("")); 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); cell.appendChild(document.createTextNode("")); } for (var j = 7; j > 0; --j) { cell = Calendar.createElement("td", row); cell.appendChild(document.createTextNode("")); 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 = "&nbsp;"; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = this.weekNumbers ? 4 : 3; (function(){ function makeTimePart(className, init, range_start, range_end) { var part = Calendar.createElement("span", cell); part.className = className; part.appendChild(document.createTextNode(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.appendChild(document.createTextNode(":")); span.className = "colon"; var M = makeTimePart("minute", mins, 0, 59); var AP = null; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; if (t12) AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]); else cell.innerHTML = "&nbsp;"; cal.onSetTime = function() { var hrs = this.date.getHours(); var mins = this.date.getMinutes(); var pm = (hrs > 12); if (pm && t12) hrs -= 12; H.firstChild.data = (hrs < 10) ? ("0" + hrs) : hrs; M.firstChild.data = (mins < 10) ? ("0" + mins) : mins; if (t12) AP.firstChild.data = pm ? "pm" : "am"; }; cal.onUpdateTime = function() { var date = this.date; var h = parseInt(H.firstChild.data, 10); if (t12) { if (/pm/i.test(AP.firstChild.data) && h < 12) h += 12; else if (/am/i.test(AP.firstChild.data) && h == 12) h = 0; } var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); date.setHours(h); date.setMinutes(parseInt(M.firstChild.data, 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.appendChild(document.createTextNode(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"; yr.appendChild(document.createTextNode("")); div.appendChild(yr); } this._init(this.mondayFirst, this.date); parent.appendChild(this.element); }; /** keyboard navigation, only for popup calendars */ Calendar._keyEvent = function(ev) { if (!window.calendar) { return false; } (Calendar.is_ie) && (ev = window.event); var cal = window.calendar; var act = (Calendar.is_ie || ev.type == "keypress"); if (ev.ctrlKey) { switch (ev.keyCode) { 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 (ev.keyCode) { case 32: // KEY space (now) Calendar.cellClick(cal._nav_now); break; case 27: // KEY esc act && cal.hide(); break; case 37: // KEY left case 38: // KEY up case 39: // KEY right case 40: // KEY down if (act) { var date = cal.date.getDate() - 1; var el = cal.currentDateEl; var ne = null; var prev = (ev.keyCode == 37) || (ev.keyCode == 38); switch (ev.keyCode) { case 37: // KEY left (--date >= 0) && (ne = cal.ar_days[date]); break; case 38: // KEY up date -= 7; (date >= 0) && (ne = cal.ar_days[date]); break; case 39: // KEY right (++date < cal.ar_days.length) && (ne = cal.ar_days[date]); break; case 40: // KEY down date += 7; (date < cal.ar_days.length) && (ne = cal.ar_days[date]); break; } if (!ne) { if (prev) { Calendar.cellClick(cal._nav_pm); } else { Calendar.cellClick(cal._nav_nm); } date = (prev) ? cal.date.getMonthDays() : 1; el = cal.currentDateEl; ne = cal.ar_days[date - 1]; } Calendar.removeClass(el, "selected"); Calendar.addClass(ne, "selected"); cal.date.setDate(ne.caldate); cal.callHandler(); cal.currentDateEl = ne; } break; case 13: // KEY enter if (act) { cal.callHandler(); cal.hide(); } break; default: return false; } return Calendar.stopEvent(ev); }; /** *(RE)Initializes the calendar to the given date and style (if mondayFirst is *true it makes Monday the first day of week, otherwise the weeks start on *Sunday. */ Calendar.prototype._init = function (mondayFirst, date) { var today = new Date(); 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.mondayFirst = mondayFirst; this.date = new Date(date); var month = date.getMonth(); var mday = date.getDate(); var no_days = date.getMonthDays(); date.setDate(1); var wday = date.getDay(); var MON = mondayFirst ? 1 : 0; var SAT = mondayFirst ? 5 : 6; var SUN = mondayFirst ? 6 : 0; if (mondayFirst) { wday = (wday > 0) ? (wday - 1) : 6; } var iday = 1; var row = this.tbody.firstChild; var MN = Calendar._SMN[month]; var hasToday = ((today.getFullYear() == year) && (today.getMonth() == month)); var todayDate = today.getDate(); var week_number = date.getWeekNumber(); var ar_days = new Array(); for (var i = 0; i < 6; ++i) { if (iday > no_days) { row.className = "emptyrow"; row = row.nextSibling; continue; } var cell = row.firstChild; if (this.weekNumbers) { cell.className = "day wn"; cell.firstChild.data = week_number; cell = cell.nextSibling; } ++week_number; row.className = "daysrow"; for (var j = 0; j < 7; ++j) { cell.className = "day"; if ((!i && j < wday) || iday > no_days) { // cell.className = "emptycell"; cell.innerHTML = "&nbsp;"; cell.disabled = true; cell = cell.nextSibling; continue; } cell.disabled = false; cell.firstChild.data = iday; if (typeof this.getDateStatus == "function") { date.setDate(iday); var status = this.getDateStatus(date, year, month, iday); if (status === true) { cell.className += " disabled"; cell.disabled = true; } else { if (/disabled/i.test(status)) cell.disabled = true; cell.className += " " + status; } } if (!cell.disabled) { ar_days[ar_days.length] = cell; cell.caldate = iday; cell.ttip = "_"; if (iday == mday) { cell.className += " selected"; this.currentDateEl = cell; } if (hasToday && (iday == todayDate)) { cell.className += " today"; cell.ttip += Calendar._TT["PART_TODAY"]; } if (wday == SAT || wday == SUN) { cell.className += " weekend"; } } ++iday; ((++wday) ^ 7) || (wday = 0); cell = cell.nextSibling; } row = row.nextSibling; } this.ar_days = ar_days; this.title.firstChild.data = Calendar._MN[month] + ", " + year; this.onSetTime(); // PROFILE // this.tooltips.firstChild.data = "Generated in " + ((new Date()) - today) + " ms"; }; /** *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.mondayFirst, 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.mondayFirst, this.date); }; /** Modifies the "mondayFirst" parameter (EU/US style). */ Calendar.prototype.setMondayFirst = function (mondayFirst) { this._init(mondayFirst, 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.calendar = 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) { if (!window.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.calendar.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.calendar = 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; } 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 "r": p.x += el.offsetWidth - w; break; case "l": break; // already there } 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) { var y = 0; var m = -1; var d = 0; var a = str.split(/\W+/); if (!fmt) { fmt = this.dateFormat; } var b = []; fmt.replace(/(%.)/g, function(str, par) { return b[b.length] = par; }); var i = 0, j = 0; var hr = 0; var min = 0; for (i = 0; i < a.length; ++i) { if (b[i] == "%a" || b[i] == "%A") { continue; } if (b[i] == "%d" || b[i] == "%e") { d = parseInt(a[i], 10); } if (b[i] == "%m") { m = parseInt(a[i], 10) - 1; } if (b[i] == "%Y" || b[i] == "%y") { y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); } if (b[i] == "%b" || b[i] == "%B") { for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; } } } else if (/%[HIkl]/.test(b[i])) { hr = parseInt(a[i], 10); } else if (/%[pP]/.test(b[i])) { if (/pm/i.test(a[i]) && hr < 12) hr += 12; } else if (b[i] == "%M") { min = parseInt(a[i], 10); } } if (y != 0 && m != -1 && d != 0) { this.setDate(new Date(y, m, d, hr, min, 0)); return; } 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) { var today = new Date(); y = today.getFullYear(); } if (m != -1 && d != 0) { this.setDate(new Date(y, m, d, hr, min, 0)); } }; Calendar.prototype.hideShowCovered = function () { var self = this; Calendar.continuation_for_the_fucking_khtml_browser = function() { 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 = self.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 (self.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"; } } } }; if (Calendar.is_khtml) setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10); else Calendar.continuation_for_the_fucking_khtml_browser(); }; /** Internal function; it displays the bar with the names of the weekday. */ Calendar.prototype._displayWeekdays = function () { var MON = this.mondayFirst ? 0 : 1; var SUN = this.mondayFirst ? 6 : 0; var SAT = this.mondayFirst ? 5 : 6; var cell = this.firstdayname; for (var i = 0; i < 7; ++i) { cell.className = "day name"; if (!i) { cell.ttip = this.mondayFirst ? Calendar._TT["SUN_FIRST"] : Calendar._TT["MON_FIRST"]; cell.navtype = 100; cell.calendar = this; Calendar._add_evs(cell); } if (i == SUN || i == SAT) { Calendar.addClass(cell, "weekend"); } cell.firstChild.data = Calendar._SDN[i + 1 - MON]; 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, "mouseover", stopEvent); 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; /** 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, 1, 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 now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 1, 0, 0, 0); var time = now - then; var day = then.getDay(); // 0 means Sunday if (day == 0) day = 7; (day > 4) && (day -= 4) || (day += 3); return Math.round(((time / Date.DAY) + day) / 7); }; /** Checks dates equality (ignores time) */ 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())); }; /** 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 = Date._msh_formatRegexp; if (typeof re == "undefined") { var tmp = ""; for (var i in s) tmp += tmp ? ("|" + i) : i; Date._msh_formatRegexp = re = new RegExp("(" + tmp + ")", 'g'); } return str.replace(re, function(match, par) { return s[par]; }); }; // END: DATE OBJECT PATCHES // global object that remembers the calendar window.calendar = null; var oldLink = null; // code to change the active stylesheet function setActiveStyleSheet(link, title) { var i, a, main; for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) { a.disabled = true; if(a.getAttribute("title") == title) a.disabled = false; } } if (oldLink) oldLink.style.fontWeight = 'normal'; oldLink = link; link.style.fontWeight = 'bold'; return false; } // This function gets called when the end-user clicks on some date. function selected(cal, date) { cal.sel.value = date; // just update the date in the input field. if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3")) // if we add this call we close the calendar on single-click. // just to exemplify both cases, we are using this only for the 1st // and the 3rd field, while 2nd and 4th will still require double-click. cal.callCloseHandler(); } // And this gets called when the end-user clicks on the _selected_ date, // or clicks on the "Close" button.It just hides the calendar without // destroying it. function closeHandler(cal) { cal.hide();// hide the calendar cal.destroy(); calendar = null; } // This function shows the calendar under the element having the given id. // It takes care of catching "mousedown" signals on document and hiding the // calendar if the click was outside. function showCalendar(id, format, showsTime) { var el = document.getElementById(id); if (calendar != null) { // we already have some calendar created calendar.hide(); // so we hide it first. } else { // first-time call, create the calendar. var cal = new Calendar(true, null, selected, closeHandler); // uncomment the following line to hide the week numbers // cal.weekNumbers = false; if (typeof showsTime == "string") { cal.showsTime = true; cal.time24 = (showsTime == "24"); } calendar = cal;// remember it in the global var cal.setRange(1900, 2070);// min/max year allowed. cal.create(); } calendar.setDateFormat(format);// set the specified date format calendar.parseDate(el.value);// try to parse the text in field calendar.sel = el; // inform it what input field we use // the reference element that we pass to showAtElement is the button that // triggers the calendar.In this example we align the calendar bottom-right // to the button. calendar.showAtElement(el.nextSibling, "Br");// show the calendar return false; } var MINUTE = 60 * 1000; var HOUR = 60 * MINUTE; var DAY = 24 * HOUR; var WEEK = 7 * DAY; function isDisabled(date) { var today = new Date(); return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10; } function flatSelected(cal, date) { var el = document.getElementById("preview"); el.innerHTML = date; } function showFlatCalendar() { var parent = document.getElementById("display"); // construct a calendar giving only the "selected" handler. var cal = new Calendar(true, null, flatSelected); // hide week numbers cal.weekNumbers = false; // We want some dates to be disabled; see function isDisabled above cal.setDisabledHandler(isDisabled); cal.setDateFormat("%A, %B %e"); // this call must be the last as it might use data initialized above; if // we specify a parent, as opposite to the "showCalendar" function above, // then we create a flat calendar -- not popup.Hidden, though, but... cal.create(parent); // ... we can show it here. cal.show(); }
JavaScript
// ** I18N // Calendar EN language // Author: Mihai Bazon, <mishoo@infoiasi.ro> // 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 = 6; // short day name length Calendar._SMN_len = 9; // 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-2003\n" + // don't translate this this ;-) "For latest version visit: http://dynarch.com/mishoo/calendar.epl\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"] = "上一年"; 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-)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";
JavaScript
<!-- //xmlhttp和xmldom对象 var DedeXHTTP = null; var DedeXDOM = null; var DedeContainer = null; var DedeShowError = false; var DedeShowWait = false; var DedeErrCon = ""; var DedeErrDisplay = "下载数据失败"; var DedeWaitDisplay = "正在下载数据..."; //获取指定ID的元素 function $DE(id) { return document.getElementById(id); } //gcontainer 是保存下载完成的内容的容器 //mShowError 是否提示错误信息 //DedeShowWait 是否提示等待信息 //mErrCon 服务器返回什么字符串视为错误 //mErrDisplay 发生错误时显示的信息 //mWaitDisplay 等待时提示信息 //默认调用 DedeAjax('divid',false,false,'','','') function DedeAjax(gcontainer,mShowError,mShowWait,mErrCon,mErrDisplay,mWaitDisplay) { DedeContainer = gcontainer; DedeShowError = mShowError; DedeShowWait = mShowWait; if(mErrCon!="") DedeErrCon = mErrCon; if(mErrDisplay!="") DedeErrDisplay = mErrDisplay; if(mErrDisplay=="x") DedeErrDisplay = ""; if(mWaitDisplay!="") DedeWaitDisplay = mWaitDisplay; //post或get发送数据的键值对 this.keys = Array(); this.values = Array(); this.keyCount = -1; this.sendlang = 'gb2312'; //请求头类型 this.rtype = 'text'; //初始化xmlhttp //IE6、IE5 if(window.ActiveXObject) { try { DedeXHTTP = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { } if (DedeXHTTP == null) try { DedeXHTTP = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { } } else { DedeXHTTP = new XMLHttpRequest(); } //增加一个POST或GET键值对 this.AddKeyN = function(skey,svalue) { if(this.sendlang=='utf-8') this.AddKeyUtf8(skey, svalue); else this.AddKey(skey, svalue); }; this.AddKey = function(skey,svalue) { this.keyCount++; this.keys[this.keyCount] = skey; svalue = svalue+''; if(svalue != '') svalue = svalue.replace(/\+/g,'$#$'); this.values[this.keyCount] = escape(svalue); }; //增加一个POST或GET键值对 this.AddKeyUtf8 = function(skey,svalue) { this.keyCount++; this.keys[this.keyCount] = skey; svalue = svalue+''; if(svalue != '') svalue = svalue.replace(/\+/g,'$#$'); this.values[this.keyCount] = encodeURI(svalue); }; //增加一个Http请求头键值对 this.AddHead = function(skey,svalue) { this.rkeyCount++; this.rkeys[this.rkeyCount] = skey; this.rvalues[this.rkeyCount] = svalue; }; //清除当前对象的哈希表参数 this.ClearSet = function() { this.keyCount = -1; this.keys = Array(); this.values = Array(); this.rkeyCount = -1; this.rkeys = Array(); this.rvalues = Array(); }; DedeXHTTP.onreadystatechange = function() { //在IE6中不管阻断或异步模式都会执行这个事件的 if(DedeXHTTP.readyState == 4){ if(DedeXHTTP.status == 200) { if(DedeXHTTP.responseText!=DedeErrCon) { DedeContainer.innerHTML = DedeXHTTP.responseText; } else { if(DedeShowError) DedeContainer.innerHTML = DedeErrDisplay; } DedeXHTTP = null; } else { if(DedeShowError) DedeContainer.innerHTML = DedeErrDisplay; } } else { if(DedeShowWait) DedeContainer.innerHTML = DedeWaitDisplay; } }; //检测阻断模式的状态 this.BarrageStat = function() { if(DedeXHTTP==null) return; if(typeof(DedeXHTTP.status)!=undefined && DedeXHTTP.status == 200) { if(DedeXHTTP.responseText!=DedeErrCon) { DedeContainer.innerHTML = DedeXHTTP.responseText; } else { if(DedeShowError) DedeContainer.innerHTML = DedeErrDisplay; } } }; //发送http请求头 this.SendHead = function() { //发送用户自行设定的请求头 if(this.rkeyCount!=-1) { for(var i = 0;i<=this.rkeyCount;i++) { DedeXHTTP.setRequestHeader(this.rkeys[i],this.rvalues[i]); } }  if(this.rtype=='binary'){  DedeXHTTP.setRequestHeader("Content-Type","multipart/form-data"); }else{ DedeXHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } }; //用Post方式发送数据 this.SendPost = function(purl) { var pdata = ""; var i=0; this.state = 0; DedeXHTTP.open("POST", purl, true); this.SendHead(); //post数据 if(this.keyCount!=-1) { for(;i<=this.keyCount;i++) { if(pdata=="") pdata = this.keys[i]+'='+this.values[i]; else pdata += "&"+this.keys[i]+'='+this.values[i]; } } DedeXHTTP.send(pdata); }; //用GET方式发送数据 this.SendGet = function(purl) { var gkey = ""; var i=0; this.state = 0; //get参数 if(this.keyCount!=-1) { for(;i<=this.keyCount;i++) { if(gkey=="") gkey = this.keys[i]+'='+this.values[i]; else gkey += "&"+this.keys[i]+'='+this.values[i]; } if(purl.indexOf('?')==-1) purl = purl + '?' + gkey; else purl = purl + '&' + gkey; } DedeXHTTP.open("GET", purl, true); this.SendHead(); DedeXHTTP.send(null); }; //用GET方式发送数据,阻塞模式 this.SendGet2 = function(purl) { var gkey = ""; var i=0; this.state = 0; //get参数 if(this.keyCount!=-1) { for(;i<=this.keyCount;i++) { if(gkey=="") gkey = this.keys[i]+'='+this.values[i]; else gkey += "&"+this.keys[i]+'='+this.values[i]; } if(purl.indexOf('?')==-1) purl = purl + '?' + gkey; else purl = purl + '&' + gkey; } DedeXHTTP.open("GET", purl, false); this.SendHead(); DedeXHTTP.send(null); //firefox中直接检测XHTTP状态 this.BarrageStat(); }; //用Post方式发送数据 this.SendPost2 = function(purl) { var pdata = ""; var i=0; this.state = 0; DedeXHTTP.open("POST", purl, false); this.SendHead(); //post数据 if(this.keyCount!=-1) { for(;i<=this.keyCount;i++) { if(pdata=="") pdata = this.keys[i]+'='+this.values[i]; else pdata += "&"+this.keys[i]+'='+this.values[i]; } } DedeXHTTP.send(pdata); //firefox中直接检测XHTTP状态 this.BarrageStat(); }; } // End Class DedeAjax //初始化xmldom function InitXDom() { if(DedeXDOM!=null) return; var obj = null; // Gecko、Mozilla、Firefox if (typeof(DOMParser) != "undefined") { var parser = new DOMParser(); obj = parser.parseFromString(xmlText, "text/xml"); } // IE else { try { obj = new ActiveXObject("MSXML2.DOMDocument");} catch (e) { } if (obj == null) try { obj = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) { } } DedeXDOM = obj; }; //读写cookie函数 function GetCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=") if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";",c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start,c_end)); } } return null } function SetCookie(c_name,value,expiredays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie = c_name + "=" +escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()); //使设置的有效时间正确。增加toGMTString() } -->
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == */ (function() { // IE6 doens't handle absolute positioning properly (it is always in quirks // mode). This function fixes the sizes and positions of many elements that // compose the skin (this is skin specific). var fixSizes = window.DoResizeFixes = function() { var fckDlg = window.document.body ; for ( var i = 0 ; i < fckDlg.childNodes.length ; i++ ) { var child = fckDlg.childNodes[i] ; switch ( child.className ) { case 'contents' : child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 ) ; // -left -right child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 ) ; // -bottom -top break ; case 'blocker' : case 'cover' : child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 + 4 ) ; // -left -right + 4 child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 + 4 ) ; // -bottom -top + 4 break ; case 'tr' : child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ; break ; case 'tc' : child.style.width = Math.max( 0, fckDlg.clientWidth - 16 - 16 ) ; break ; case 'ml' : child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ; break ; case 'mr' : child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ; child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ; break ; case 'bl' : child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ; break ; case 'br' : child.style.left = Math.max( 0, fckDlg.clientWidth - 30 ) ; child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ; break ; case 'bc' : child.style.width = Math.max( 0, fckDlg.clientWidth - 30 - 30 ) ; child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ; break ; } } } var closeButtonOver = function() { this.style.backgroundPosition = '-16px -687px' ; } ; var closeButtonOut = function() { this.style.backgroundPosition = '-16px -651px' ; } ; var fixCloseButton = function() { var closeButton = document.getElementById ( 'closeButton' ) ; closeButton.onmouseover = closeButtonOver ; closeButton.onmouseout = closeButtonOut ; } var onLoad = function() { fixSizes() ; fixCloseButton() ; window.attachEvent( 'onresize', fixSizes ) ; window.detachEvent( 'onload', onLoad ) ; } window.attachEvent( 'onload', onLoad ) ; })() ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Compatibility code for Adobe AIR. */ if ( FCKBrowserInfo.IsAIR ) { var FCKAdobeAIR = (function() { /* * ### Private functions. */ var getDocumentHead = function( doc ) { var head ; var heads = doc.getElementsByTagName( 'head' ) ; if( heads && heads[0] ) head = heads[0] ; else { head = doc.createElement( 'head' ) ; doc.documentElement.insertBefore( head, doc.documentElement.firstChild ) ; } return head ; } ; /* * ### Public interface. */ return { FCKeditorAPI_Evaluate : function( parentWindow, script ) { // TODO : This one doesn't work always. The parent window will // point to an anonymous function in this window. If this // window is destroyied the parent window will be pointing to // an invalid reference. // Evaluate the script in this window. eval( script ) ; // Point the FCKeditorAPI property of the parent window to the // local reference. parentWindow.FCKeditorAPI = window.FCKeditorAPI ; }, EditingArea_Start : function( doc, html ) { // Get the HTML for the <head>. var headInnerHtml = html.match( /<head>([\s\S]*)<\/head>/i )[1] ; if ( headInnerHtml && headInnerHtml.length > 0 ) { // Inject the <head> HTML inside a <div>. // Do that before getDocumentHead because WebKit moves // <link css> elements to the <head> at this point. var div = doc.createElement( 'div' ) ; div.innerHTML = headInnerHtml ; // Move the <div> nodes to <head>. FCKDomTools.MoveChildren( div, getDocumentHead( doc ) ) ; } doc.body.innerHTML = html.match( /<body>([\s\S]*)<\/body>/i )[1] ; //prevent clicking on hyperlinks and navigating away doc.addEventListener('click', function( ev ) { ev.preventDefault() ; ev.stopPropagation() ; }, true ) ; }, Panel_Contructor : function( doc, baseLocation ) { var head = getDocumentHead( doc ) ; // Set the <base> href. head.appendChild( doc.createElement('base') ).href = baseLocation ; doc.body.style.margin = '0px' ; doc.body.style.padding = '0px' ; }, ToolbarSet_GetOutElement : function( win, outMatch ) { var toolbarTarget = win.parent ; var targetWindowParts = outMatch[1].split( '.' ) ; while ( targetWindowParts.length > 0 ) { var part = targetWindowParts.shift() ; if ( part.length > 0 ) toolbarTarget = toolbarTarget[ part ] ; } toolbarTarget = toolbarTarget.document.getElementById( outMatch[2] ) ; }, ToolbarSet_InitOutFrame : function( doc ) { var head = getDocumentHead( doc ) ; head.appendChild( doc.createElement('base') ).href = window.document.location ; var targetWindow = doc.defaultView; targetWindow.adjust = function() { targetWindow.frameElement.height = doc.body.scrollHeight; } ; targetWindow.onresize = targetWindow.adjust ; targetWindow.setTimeout( targetWindow.adjust, 0 ) ; doc.body.style.overflow = 'hidden'; doc.body.innerHTML = document.getElementById( 'xToolbarSpace' ).innerHTML ; } } ; })(); /* * ### Overrides */ ( function() { // Save references for override reuse. var _Original_FCKPanel_Window_OnFocus = FCKPanel_Window_OnFocus ; var _Original_FCKPanel_Window_OnBlur = FCKPanel_Window_OnBlur ; var _Original_FCK_StartEditor = FCK.StartEditor ; FCKPanel_Window_OnFocus = function( e, panel ) { // Call the original implementation. _Original_FCKPanel_Window_OnFocus.call( this, e, panel ) ; if ( panel._focusTimer ) clearTimeout( panel._focusTimer ) ; } FCKPanel_Window_OnBlur = function( e, panel ) { // Delay the execution of the original function. panel._focusTimer = FCKTools.SetTimeout( _Original_FCKPanel_Window_OnBlur, 100, this, [ e, panel ] ) ; } FCK.StartEditor = function() { // Force pointing to the CSS files instead of using the inline CSS cached styles. window.FCK_InternalCSS = FCKConfig.FullBasePath + 'css/fck_internal.css' ; _Original_FCK_StartEditor.apply( this, arguments ) ; } })(); }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Contains the DTD mapping for XHTML 1.0 Transitional. * This file was automatically generated from the file: xhtml10-transitional.dtd */ FCK.DTD = (function() { var X = FCKTools.Merge ; var A,L,J,M,N,O,D,H,P,K,Q,F,G,C,B,E,I ; A = {isindex:1, fieldset:1} ; B = {input:1, button:1, select:1, textarea:1, label:1} ; C = X({a:1}, B) ; D = X({iframe:1}, C) ; E = {hr:1, ul:1, menu:1, div:1, blockquote:1, noscript:1, table:1, center:1, address:1, dir:1, pre:1, h5:1, dl:1, h4:1, noframes:1, h6:1, ol:1, h1:1, h3:1, h2:1} ; F = {ins:1, del:1, script:1} ; G = X({b:1, acronym:1, bdo:1, 'var':1, '#':1, abbr:1, code:1, br:1, i:1, cite:1, kbd:1, u:1, strike:1, s:1, tt:1, strong:1, q:1, samp:1, em:1, dfn:1, span:1}, F) ; H = X({sub:1, img:1, object:1, sup:1, basefont:1, map:1, applet:1, font:1, big:1, small:1}, G) ; I = X({p:1}, H) ; J = X({iframe:1}, H, B) ; K = {img:1, noscript:1, br:1, kbd:1, center:1, button:1, basefont:1, h5:1, h4:1, samp:1, h6:1, ol:1, h1:1, h3:1, h2:1, form:1, font:1, '#':1, select:1, menu:1, ins:1, abbr:1, label:1, code:1, table:1, script:1, cite:1, input:1, iframe:1, strong:1, textarea:1, noframes:1, big:1, small:1, span:1, hr:1, sub:1, bdo:1, 'var':1, div:1, object:1, sup:1, strike:1, dir:1, map:1, dl:1, applet:1, del:1, isindex:1, fieldset:1, ul:1, b:1, acronym:1, a:1, blockquote:1, i:1, u:1, s:1, tt:1, address:1, q:1, pre:1, p:1, em:1, dfn:1} ; L = X({a:1}, J) ; M = {tr:1} ; N = {'#':1} ; O = X({param:1}, K) ; P = X({form:1}, A, D, E, I) ; Q = {li:1} ; return { col: {}, tr: {td:1, th:1}, img: {}, colgroup: {col:1}, noscript: P, td: P, br: {}, th: P, center: P, kbd: L, button: X(I, E), basefont: {}, h5: L, h4: L, samp: L, h6: L, ol: Q, h1: L, h3: L, option: N, h2: L, form: X(A, D, E, I), select: {optgroup:1, option:1}, font: J, // Changed from L to J (see (1)) ins: P, menu: Q, abbr: L, label: L, table: {thead:1, col:1, tbody:1, tr:1, colgroup:1, caption:1, tfoot:1}, code: L, script: N, tfoot: M, cite: L, li: P, input: {}, iframe: P, strong: J, // Changed from L to J (see (1)) textarea: N, noframes: P, big: J, // Changed from L to J (see (1)) small: J, // Changed from L to J (see (1)) span: J, // Changed from L to J (see (1)) hr: {}, dt: L, sub: J, // Changed from L to J (see (1)) optgroup: {option:1}, param: {}, bdo: L, 'var': J, // Changed from L to J (see (1)) div: P, object: O, sup: J, // Changed from L to J (see (1)) dd: P, strike: J, // Changed from L to J (see (1)) area: {}, dir: Q, map: X({area:1, form:1, p:1}, A, F, E), applet: O, dl: {dt:1, dd:1}, del: P, isindex: {}, fieldset: X({legend:1}, K), thead: M, ul: Q, acronym: L, b: J, // Changed from L to J (see (1)) a: J, blockquote: P, caption: L, i: J, // Changed from L to J (see (1)) u: J, // Changed from L to J (see (1)) tbody: M, s: L, address: X(D, I), tt: J, // Changed from L to J (see (1)) legend: L, q: L, pre: X(G, C), p: L, em: J, // Changed from L to J (see (1)) dfn: L } ; })() ; /* Notes: (1) According to the DTD, many elements, like <b> accept <a> elements inside of them. But, to produce better output results, we have manually changed the map to avoid breaking the links on pieces, having "<b>this is a </b><a><b>link</b> test</a>", instead of "<b>this is a <a>link</a></b><a> test</a>". */
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Chinese Simplified language file. */ var FCKLang = { // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "ltr", // Toolbar Items and Context Menu Preview : "预览", Cut : "剪切", Copy : "复制", Paste : "粘贴", PasteText : "粘贴为无格式文本", PasteWord : "从 MS Word 粘贴", RemoveFormat : "清除格式", InsertLinkLbl : "超链接", InsertLink : "插入/编辑超链接", RemoveLink : "取消超链接", Anchor : "插入/编辑锚点链接", AnchorDelete : "清除锚点链接", InsertImageLbl : "图象", InsertImage : "插入/编辑图象", InsertFlashLbl : "Flash", InsertFlash : "插入/编辑 Flash", InsertMyCode : "插入我定义的HTML", InsertMedia : "多媒体", InsertAddon : "附件", InsertDedePage : "分页符", InsertQuote : "引用", InsertBr : "段内换行符", InsertTableLbl : "表格", InsertTable : "插入/编辑表格", InsertLineLbl : "水平线", InsertLine : "插入水平线", InsertSmileyLbl : "表情符", InsertSmiley : "插入表情图标", About : "关于 FCKeditor", Bold : "加粗", Italic : "倾斜", Underline : "下划线", StrikeThrough : "删除线", LeftJustify : "左对齐", CenterJustify : "居中对齐", RightJustify : "右对齐", BlockJustify : "两端对齐", DecreaseIndent : "减少缩进量", IncreaseIndent : "增加缩进量", Blockquote : "引用文字", Undo : "撤消", Redo : "重做", NumberedListLbl : "编号列表", NumberedList : "插入/删除编号列表", BulletedListLbl : "项目列表", BulletedList : "插入/删除项目列表", ShowDetails : "显示详细资料", Style : "样式", FontFormat : "格式", Font : "字体", FontSize : "大小", TextColor : "文本颜色", BGColor : "背景颜色", Source : "源代码", InsertCodes : "插入代码", FontFormats : "普通;已编排格式;地址;标题 1;标题 2;标题 3;标题 4;标题 5;标题 6;段落(DIV)", // Alerts and Messages ProcessingXHTML : "正在处理 XHTML,请稍等...", Done : "完成", PasteWordConfirm : "您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?", NotCompatiblePaste : "该命令需要 Internet Explorer 5.5 或更高版本的支持,是否按常规粘贴进行?", UnknownToolbarItem : "未知工具栏项目 \"%1\"", UnknownCommand : "未知命令名称 \"%1\"", NotImplemented : "命令无法执行", UnknownToolbarSet : "工具栏设置 \"%1\" 不存在", NoActiveX : "浏览器安全设置限制了本编辑器的某些功能。您必须启用安全设置中的“运行 ActiveX 控件和插件”,否则将出现某些错误并缺少功能。", DialogBlocked : "无法打开对话框窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。", // Dialogs DlgBtnOK : "确定", DlgBtnCancel : "取消", DlgBtnClose : "关闭", DlgAdvancedTag : "高级", DlgOpOther : "<其它>", DlgInfoTab : "信息", DlgAlertUrl : "请插入 URL", // General Dialogs Labels DlgGenNotSet : "<没有设置>", // Image Dialog DlgImgTitle : "图象属性", DlgImgInfoTab : "图象", DlgImgURL : "源文件", DlgImgAlt : "替换文本", DlgImgWidth : "宽度", DlgImgHeight : "高度", DlgImgBorder : "边框大小", DlgImgHSpace : "水平间距", DlgImgVSpace : "垂直间距", DlgImgAlign : "对齐方式", DlgImgAlignLeft : "左对齐", DlgImgAlignAbsBottom: "绝对底边", DlgImgAlignAbsMiddle: "绝对居中", DlgImgAlignBaseline : "基线", DlgImgAlignBottom : "底边", DlgImgAlignMiddle : "居中", DlgImgAlignRight : "右对齐", DlgImgAlignTextTop : "文本上方", DlgImgAlignTop : "顶端", DlgImgAlertUrl : "请输入图象地址", // Flash Dialog DlgFlashTitle : "Flash 属性", DlgFlashChkPlay : "自动播放", DlgFlashChkLoop : "循环", DlgFlashChkMenu : "启用Flash菜单", DlgFlashScale : "缩放", DlgFlashScaleAll : "全部显示", DlgFlashScaleNoBorder : "无边框", DlgFlashScaleFit : "严格匹配", // Code Dialog DlgCodesTitle : "插入代码", DlgCodesLanguage : "语言", DlgCodesContent : "内容", // Link Dialog DlgLnkWindowTitle : "超链接", DlgMyCodeTitle : "插入我定义的HTML", DlgLnkTarget : "目标", DlgLnkTargetBlank : "新窗口 (_blank)", DlgLnkTargetParent : "父窗口 (_parent)", DlgLnkTargetSelf : "本窗口 (_self)", DlgLnkTargetTop : "整页 (_top)", DlnLnkMsgNoUrl : "请输入超链接地址", DlnLnkMsgNoEMail : "请输入电子邮件地址", DlnLnkMsgNoAnchor : "请选择一个锚点", DlnLnkMsgInvPopName : "弹出窗口名称必须以字母开头,并且不能含有空格。", // Color Dialog DlgColorTitle : "选择颜色", // Smiley Dialog DlgSmileyTitle : "插入表情图标", // Table Dialog DlgTableTitle : "表格属性", DlgTableRows : "行数", DlgTableColumns : "列数", DlgTableBorder : "边框", DlgTableAlign : "对齐", DlgTableAlignNotSet : "<没有设置>", DlgTableAlignLeft : "左对齐", DlgTableAlignCenter : "居中", DlgTableAlignRight : "右对齐", DlgTableWidth : "宽度", DlgTableWidthPx : "像素", DlgTableWidthPc : "百分比", DlgTableHeight : "高度", DlgTableCellSpace : "间距", DlgTableCellPad : "边距", DlgTableCaption : "标题", DlgTableSummary : "摘要", // Paste Operations / Dialog PasteErrorCut : "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成。", PasteErrorCopy : "您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl+C)来完成。", PasteAsText : "粘贴为无格式文本", PasteFromWord : "从 MS Word 粘贴", DlgPasteMsg2 : "请使用键盘快捷键(<STRONG>Ctrl+V</STRONG>)把内容粘贴到下面的方框里,再按 <STRONG>确定</STRONG>。", DlgPasteSec : "因为你的浏览器的安全设置原因,本编辑器不能直接访问你的剪贴板内容,你需要在本窗口重新粘贴一次。", DlgPasteIgnoreFont : "忽略 Font 标签", DlgPasteRemoveStyles : "清理 CSS 样式", // Color Picker ColorAutomatic : "自动", // Anchor Dialog DlgAnchorTitle : "命名锚点", DlgAnchorName : "锚点名称", DlgAnchorErrorName : "请输入锚点名称", // About Dialog DlgAboutAboutTab : "关于", DlgAboutInfo : "要获得更多信息请访问 " };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Chinese Simplified language file. */ var FCKLang = { // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "ltr", // Toolbar Items and Context Menu Preview : "预览", Cut : "剪切", Copy : "复制", Paste : "粘贴", PasteText : "粘贴为无格式文本", PasteWord : "从 MS Word 粘贴", RemoveFormat : "清除格式", InsertLinkLbl : "超链接", InsertLink : "插入/编辑超链接", RemoveLink : "取消超链接", Anchor : "插入/编辑锚点链接", AnchorDelete : "清除锚点链接", InsertImageLbl : "图象", InsertImage : "插入/编辑图象", InsertFlashLbl : "Flash", InsertFlash : "插入/编辑 Flash", InsertMyCode : "插入我定义的HTML", InsertMedia : "多媒体", InsertAddon : "附件", InsertDedePage : "分页符", InsertQuote : "引用", InsertBr : "段内换行符", InsertTableLbl : "表格", InsertTable : "插入/编辑表格", InsertLineLbl : "水平线", InsertLine : "插入水平线", InsertSmileyLbl : "表情符", InsertSmiley : "插入表情图标", About : "关于 FCKeditor", Bold : "加粗", Italic : "倾斜", Underline : "下划线", StrikeThrough : "删除线", LeftJustify : "左对齐", CenterJustify : "居中对齐", RightJustify : "右对齐", BlockJustify : "两端对齐", DecreaseIndent : "减少缩进量", IncreaseIndent : "增加缩进量", Blockquote : "引用文字", Undo : "撤消", Redo : "重做", NumberedListLbl : "编号列表", NumberedList : "插入/删除编号列表", BulletedListLbl : "项目列表", BulletedList : "插入/删除项目列表", ShowDetails : "显示详细资料", Style : "样式", FontFormat : "格式", Font : "字体", FontSize : "大小", TextColor : "文本颜色", BGColor : "背景颜色", Source : "源代码", InsertCodes : "插入代码", FontFormats : "普通;已编排格式;地址;标题 1;标题 2;标题 3;标题 4;标题 5;标题 6;段落(DIV)", // Alerts and Messages ProcessingXHTML : "正在处理 XHTML,请稍等...", Done : "完成", PasteWordConfirm : "您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?", NotCompatiblePaste : "该命令需要 Internet Explorer 5.5 或更高版本的支持,是否按常规粘贴进行?", UnknownToolbarItem : "未知工具栏项目 \"%1\"", UnknownCommand : "未知命令名称 \"%1\"", NotImplemented : "命令无法执行", UnknownToolbarSet : "工具栏设置 \"%1\" 不存在", NoActiveX : "浏览器安全设置限制了本编辑器的某些功能。您必须启用安全设置中的“运行 ActiveX 控件和插件”,否则将出现某些错误并缺少功能。", DialogBlocked : "无法打开对话框窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。", // Dialogs DlgBtnOK : "确定", DlgBtnCancel : "取消", DlgBtnClose : "关闭", DlgAdvancedTag : "高级", DlgOpOther : "<其它>", DlgInfoTab : "信息", DlgAlertUrl : "请插入 URL", // General Dialogs Labels DlgGenNotSet : "<没有设置>", // Image Dialog DlgImgTitle : "图象属性", DlgImgInfoTab : "图象", DlgImgURL : "源文件", DlgImgAlt : "替换文本", DlgImgWidth : "宽度", DlgImgHeight : "高度", DlgImgBorder : "边框大小", DlgImgHSpace : "水平间距", DlgImgVSpace : "垂直间距", DlgImgAlign : "对齐方式", DlgImgAlignLeft : "左对齐", DlgImgAlignAbsBottom: "绝对底边", DlgImgAlignAbsMiddle: "绝对居中", DlgImgAlignBaseline : "基线", DlgImgAlignBottom : "底边", DlgImgAlignMiddle : "居中", DlgImgAlignRight : "右对齐", DlgImgAlignTextTop : "文本上方", DlgImgAlignTop : "顶端", DlgImgAlertUrl : "请输入图象地址", // Flash Dialog DlgFlashTitle : "Flash 属性", DlgFlashChkPlay : "自动播放", DlgFlashChkLoop : "循环", DlgFlashChkMenu : "启用Flash菜单", DlgFlashScale : "缩放", DlgFlashScaleAll : "全部显示", DlgFlashScaleNoBorder : "无边框", DlgFlashScaleFit : "严格匹配", // Code Dialog DlgCodesTitle : "插入代码", DlgCodesLanguage : "语言", DlgCodesContent : "内容", // Link Dialog DlgLnkWindowTitle : "超链接", DlgMyCodeTitle : "插入我定义的HTML", DlgLnkTarget : "目标", DlgLnkTargetBlank : "新窗口 (_blank)", DlgLnkTargetParent : "父窗口 (_parent)", DlgLnkTargetSelf : "本窗口 (_self)", DlgLnkTargetTop : "整页 (_top)", DlnLnkMsgNoUrl : "请输入超链接地址", DlnLnkMsgNoEMail : "请输入电子邮件地址", DlnLnkMsgNoAnchor : "请选择一个锚点", DlnLnkMsgInvPopName : "弹出窗口名称必须以字母开头,并且不能含有空格。", // Color Dialog DlgColorTitle : "选择颜色", // Smiley Dialog DlgSmileyTitle : "插入表情图标", // Table Dialog DlgTableTitle : "表格属性", DlgTableRows : "行数", DlgTableColumns : "列数", DlgTableBorder : "边框", DlgTableAlign : "对齐", DlgTableAlignNotSet : "<没有设置>", DlgTableAlignLeft : "左对齐", DlgTableAlignCenter : "居中", DlgTableAlignRight : "右对齐", DlgTableWidth : "宽度", DlgTableWidthPx : "像素", DlgTableWidthPc : "百分比", DlgTableHeight : "高度", DlgTableCellSpace : "间距", DlgTableCellPad : "边距", DlgTableCaption : "标题", DlgTableSummary : "摘要", // Paste Operations / Dialog PasteErrorCut : "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成。", PasteErrorCopy : "您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl+C)来完成。", PasteAsText : "粘贴为无格式文本", PasteFromWord : "从 MS Word 粘贴", DlgPasteMsg2 : "请使用键盘快捷键(<STRONG>Ctrl+V</STRONG>)把内容粘贴到下面的方框里,再按 <STRONG>确定</STRONG>。", DlgPasteSec : "因为你的浏览器的安全设置原因,本编辑器不能直接访问你的剪贴板内容,你需要在本窗口重新粘贴一次。", DlgPasteIgnoreFont : "忽略 Font 标签", DlgPasteRemoveStyles : "清理 CSS 样式", // Color Picker ColorAutomatic : "自动", // Anchor Dialog DlgAnchorTitle : "命名锚点", DlgAnchorName : "锚点名称", DlgAnchorErrorName : "请输入锚点名称", // About Dialog DlgAboutAboutTab : "关于", DlgAboutInfo : "要获得更多信息请访问 " };
JavaScript
var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKRegexLib = oEditor.FCKRegexLib ; var FCKTools = oEditor.FCKTools ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { dialog.SetAutoSize( true ) ; } //#### Initialization Code // oLink: The actual selected link in the editor. var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ; if ( oLink ) FCK.Selection.SelectNode( oLink ) ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Load the selected link information (if any). LoadSelection() ; // Set the default target (from configuration). SetDefaultTarget() ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( !oLink ) return ; // Get the actual Link href. var sHRef = oLink.getAttribute( '_fcksavedurl' ) ; if ( sHRef == null ) sHRef = oLink.getAttribute( 'href' , 2 ) || '' ; GetE('txtUrl').value = sHRef ; // Get the target. var sTarget = oLink.target ; if ( sTarget && sTarget.length > 0 ) { sTarget = sTarget.toLowerCase() ; GetE('cmbTarget').value = sTarget ; } } //#### The OK button was hit. function Ok() { var sUri, sInnerHtml ; oEditor.FCKUndo.SaveUndoStep() ; sUri = GetE('txtUrl').value ; if ( sUri.length == 0 ) { alert( FCKLang.DlnLnkMsgNoUrl ) ; return false ; } // If no link is selected, create a new one (it may result in more than one link creation - #220). var aLinks = oLink ? [ oLink ] : oEditor.FCK.CreateLink( sUri, true ) ; // If no selection, no links are created, so use the uri as the link text (by dom, 2006-05-26) var aHasSelection = ( aLinks.length > 0 ) ; if ( !aHasSelection ) { sInnerHtml = sUri; /* //这里被过滤掉前面的协议类型了,还是保留的好 by angel var oLinkPathRegEx = new RegExp("//?([^?\"']+)([?].*)?$") ; var asLinkPath = oLinkPathRegEx.exec( sUri ) ; if (asLinkPath != null) sInnerHtml = asLinkPath[1]; // use matched path */ // Create a new (empty) anchor. aLinks = [ oEditor.FCK.InsertElement( 'a' ) ] ; } for ( var i = 0 ; i < aLinks.length ; i++ ) { oLink = aLinks[i] ; if ( aHasSelection ) sInnerHtml = oLink.innerHTML ; // Save the innerHTML (IE changes it if it is like an URL). oLink.href = sUri ; SetAttribute( oLink, '_fcksavedurl', sUri ) ; oLink.innerHTML = sInnerHtml ; // Set (or restore) the innerHTML // Target SetAttribute( oLink, 'target', GetE('cmbTarget').value ) ; } // Select the (first) link. oEditor.FCKSelection.SelectNode( aLinks[0] ); return true ; } function SetUrl( url ) { document.getElementById('txtUrl').value = url ; } function SetDefaultTarget() { var target = FCKConfig.DefaultLinkTarget || '' ; if ( oLink || target.length == 0 ) return ; GetE('cmbTarget').value = target ; }
JavaScript
var oEditor = window.parent.InnerDialogLoaded() ; var FCK = oEditor.FCK ; window.onload = function() { oEditor.FCKLanguageManager.TranslatePage(document) ; window.parent.SetOkButton( true ) ; } function Ok() { var sLan = GetE('codeLan').value; var sTxt = GetE('codeTxt').value; if( sTxt.length> 0) { var oCode = FCK.CreateElement('PRE'); var registered = new Object(); for(var brush in dp.sh.Brushes) { var aliases = dp.sh.Brushes[brush].Aliases; if(aliases == null) continue; for(var i=0;i<aliases.length;i++) registered[aliases[i]] = brush; }; var ht = new dp.sh.Brushes[registered[sLan]](); ht.Highlight(sTxt); oCode.innerHTML = ht.div.innerHTML; } else { oEditor.FCKUndo.SaveUndoStep() ; } return true ; } var dp = { sh : { Utils : {}, RegexLib: {}, Brushes : {} } }; dp.SyntaxHighlighter = dp.sh; dp.sh.RegexLib = { MultiLineCComments : new RegExp('/\\*[\\s\\S]*?\\*/', 'gm'), SingleLineCComments : new RegExp('//.*$', 'gm'), SingleLinePerlComments : new RegExp('#.*$', 'gm'), DoubleQuotedString : new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'), SingleQuotedString : new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'", 'g') }; dp.sh.Match = function(value, index, css) { this.value = value; this.index = index; this.length = value.length; this.css = css; } dp.sh.Highlighter = function() { this.tabsToSpaces = true; this.wrapColumn = 80; } dp.sh.Highlighter.SortCallback=function(m1,m2){if(m1.index<m2.index)return-1;else if(m1.index>m2.index)return 1;else{if(m1.length<m2.length)return-1;else if(m1.length>m2.length)return 1;}return 0;} dp.sh.Highlighter.prototype.CreateElement = function(name) { var result = document.createElement(name); result.highlighter = this; return result; } dp.sh.Highlighter.prototype.GetMatches = function(regex, css) { var index = 0; var match = null; while((match = regex.exec(this.code)) != null) this.matches[this.matches.length] = new dp.sh.Match(match[0], match.index, css); } dp.sh.Highlighter.prototype.AddBit = function(str, css) { if(str == null || str.length == 0) return; var span = this.CreateElement('SPAN'); str = str.replace(/&/g, '&amp;'); str = str.replace(/ /g, '&nbsp;'); str = str.replace(/</g, '&lt;'); // str = str.replace(/&lt;/g, '<'); // str = str.replace(/>/g, '&gt;'); // str = str.replace(/\n/gm, '&nbsp;<br>'); str = str.replace(/\n/gm, '<br>'); var lastWasBlank = false; if (str.indexOf(' ') > -1) { for (var i = 0; i < str.length; i++) { var isBlank = str[i] == ' '; if (lastWasBlank && isBlank) { // For each 2 consecutive blank spaces, replace it by one blank space and one &nbsp; str = str.substring(0, i) + "&nbsp;" + str.substring(i + 1); lastWasBlank = false; } else { lastWasBlank = isBlank; } } // Safari appears to get confused if the last char is a regular white space if (str[str.length - 1] == ' ') { str = str.substring(0, str.length - 1) + "&nbsp;" } } if(css != null) { if((/br/gi).test(str)) { //var lines = str.split('&nbsp;<br>'); var lines = str.split('<br>'); for(var i = 0; i < lines.length; i++) { span = this.CreateElement('SPAN'); span.className = css; span.innerHTML = lines[i]; this.div.appendChild(span); if(i + 1 < lines.length) this.div.appendChild(this.CreateElement('BR')); } } else { span.className = css; span.innerHTML = str; this.div.appendChild(span); } } else { span.innerHTML = str; this.div.appendChild(span); } } dp.sh.Highlighter.prototype.IsInside = function(match) { if(match == null || match.length == 0) return false; for(var i = 0; i < this.matches.length; i++) { var c = this.matches[i]; if(c == null) continue; if((match.index > c.index) && (match.index < c.index + c.length)) return true; } return false; } dp.sh.Highlighter.prototype.ProcessRegexList = function() { for(var i = 0; i < this.regexList.length; i++) this.GetMatches(this.regexList[i].regex, this.regexList[i].css); } dp.sh.Highlighter.prototype.ProcessSmartTabs = function(code) { var lines = code.split('\n'); var result = ''; var tabSize = 4; var tab = '\t'; function InsertSpaces(line, pos, count) { var left = line.substr(0, pos); var right = line.substr(pos + 1, line.length); var spaces = ''; for(var i = 0; i < count; i++) spaces += ' '; return left + spaces + right; } function ProcessLine(line, tabSize) { if(line.indexOf(tab) == -1) return line; var pos = 0; while((pos = line.indexOf(tab)) != -1) { var spaces = tabSize - pos % tabSize; line = InsertSpaces(line, pos, spaces); } return line; } for(var i = 0; i < lines.length; i++) result += ProcessLine(lines[i], tabSize) + '\n'; return result; } dp.sh.Highlighter.prototype.SwitchToList = function() { var html = this.div.innerHTML.replace(/<(br)\/?>/gi, '\n'); var lines = html.split('\n'); for(var i = 0, lineIndex = 1; i < lines.length - 1; i++, lineIndex++) { var li = this.CreateElement('LI'); var span = this.CreateElement('SPAN'); li.className = (i % 2 == 0) ? 'alt' : ''; span.innerHTML = lines[i] + '&nbsp;'; li.appendChild(span); this.ol.appendChild(li); } this.div.innerHTML = ''; } dp.sh.Highlighter.prototype.Highlight = function(code) { function Trim(str) { return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1'); } function Chop(str) { return str.replace(/\n*$/, '').replace(/^\n*/, ''); } function Unindent(str) { var lines = str.split('\n'); var indents = new Array(); var regex = new RegExp('^\\s*', 'g'); var min = 1000; for(var i = 0; i < lines.length && min > 0; i++) { if(Trim(lines[i]).length == 0) continue; var matches = regex.exec(lines[i]); if(matches != null && matches.length > 0) min = Math.min(matches[0].length, min); } if(min > 0) for(var i = 0; i < lines.length; i++) lines[i] = lines[i].substr(min); return lines.join('\n'); } function Copy(string, pos1, pos2) { return string.substr(pos1, pos2 - pos1); } var pos = 0; if(code == null) code = ''; this.originalCode = code; this.code = Chop(Unindent(code)); this.div = this.CreateElement('DIV'); this.ol = this.CreateElement('OL'); this.matches = new Array(); this.div.className = 'dp-highlighter'; this.div.highlighter = this; if(this.CssClass != null) this.ol.className = this.CssClass; if(this.tabsToSpaces == true) this.code = this.ProcessSmartTabs(this.code); this.ProcessRegexList(); if(this.matches.length == 0) { this.AddBit(this.code, null); this.SwitchToList(); this.div.appendChild(this.ol); return; } this.matches = this.matches.sort(dp.sh.Highlighter.SortCallback); for(var i = 0; i < this.matches.length; i++) if(this.IsInside(this.matches[i])) this.matches[i] = null; for(var i = 0; i < this.matches.length; i++) { var match = this.matches[i]; if(match == null || match.length == 0) continue; this.AddBit(Copy(this.code, pos, match.index), null); this.AddBit(match.value, match.css); pos = match.index + match.length; } this.AddBit(this.code.substr(pos), null); this.SwitchToList(); this.div.appendChild(this.ol); } dp.sh.Highlighter.prototype.GetKeywords = function(str) { return '\\b' + str.replace(/ /g, '\\b|\\b') + '\\b'; } dp.sh.Brushes.Cpp=function() {var datatypes='ATOM BOOL BOOLEAN BYTE CHAR COLORREF DWORD DWORDLONG DWORD_PTR '+'DWORD32 DWORD64 FLOAT HACCEL HALF_PTR HANDLE HBITMAP HBRUSH '+'HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP '+'HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY '+'HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRESULT '+'HRGN HRSRC HSZ HWINSTA HWND INT INT_PTR INT32 INT64 LANGID LCID LCTYPE '+'LGRPID LONG LONGLONG LONG_PTR LONG32 LONG64 LPARAM LPBOOL LPBYTE LPCOLORREF '+'LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR '+'LPVOID LPWORD LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR '+'PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR PHANDLE PHKEY PINT '+'PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 '+'POINTER_64 PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR '+'PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 '+'PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SHORT '+'SIZE_T SSIZE_T TBYTE TCHAR UCHAR UHALF_PTR UINT UINT_PTR UINT32 UINT64 ULONG '+'ULONGLONG ULONG_PTR ULONG32 ULONG64 USHORT USN VOID WCHAR WORD WPARAM WPARAM WPARAM '+'char bool short int __int32 __int64 __int8 __int16 long float double __wchar_t '+'clock_t _complex _dev_t _diskfree_t div_t ldiv_t _exception _EXCEPTION_POINTERS '+'FILE _finddata_t _finddatai64_t _wfinddata_t _wfinddatai64_t __finddata64_t '+'__wfinddata64_t _FPIEEE_RECORD fpos_t _HEAPINFO _HFILE lconv intptr_t '+'jmp_buf mbstate_t _off_t _onexit_t _PNH ptrdiff_t _purecall_handler '+'sig_atomic_t size_t _stat __stat64 _stati64 terminate_function '+'time_t __time64_t _timeb __timeb64 tm uintptr_t _utimbuf '+'va_list wchar_t wctrans_t wctype_t wint_t signed';var keywords='break case catch class const __finally __exception __try '+'const_cast continue private public protected __declspec '+'default delete deprecated dllexport dllimport do dynamic_cast '+'else enum explicit extern if for friend goto inline '+'mutable naked namespace new noinline noreturn nothrow '+'register reinterpret_cast return selectany '+'sizeof static static_cast struct switch template this '+'thread throw true false try typedef typeid typename union '+'using uuid virtual void volatile whcar_t while';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('^ *#.*','gm'),css:'preprocessor'},{regex:new RegExp(this.GetKeywords(datatypes),'gm'),css:'datatypes'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-cpp';} dp.sh.Brushes.Cpp.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Cpp.Aliases=['cpp','c','c++']; dp.sh.Brushes.CSharp=function() {var keywords='abstract as base bool break byte case catch char checked class const '+'continue decimal default delegate do double else enum event explicit '+'extern false finally fixed float for foreach get goto if implicit in int '+'interface internal is lock long namespace new null object operator out '+'override params private protected public readonly ref return sbyte sealed set '+'short sizeof stackalloc static string struct switch this throw true try '+'typeof uint ulong unchecked unsafe ushort using virtual void while';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('^\\s*#.*','gm'),css:'preprocessor'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-c';} dp.sh.Brushes.CSharp.prototype=new dp.sh.Highlighter();dp.sh.Brushes.CSharp.Aliases=['c#','c-sharp','csharp']; dp.sh.Brushes.CSS=function() {var keywords='ascent azimuth background-attachment background-color background-image background-position '+'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top '+'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color '+'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width '+'border-bottom-width border-left-width border-width border cap-height caption-side centerline clear clip color '+'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display '+'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font '+'height letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top '+'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans '+'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page '+'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position '+'quotes richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress '+'table-layout text-align text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em '+'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';var values='above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';var fonts='[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif';this.regexList=[{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('\\#[a-zA-Z0-9]{3,6}','g'),css:'value'},{regex:new RegExp('(-?\\d+)(\.\\d+)?(px|em|pt|\:|\%|)','g'),css:'value'},{regex:new RegExp('!important','g'),css:'important'},{regex:new RegExp(this.GetKeywordsCSS(keywords),'gm'),css:'keyword'},{regex:new RegExp(this.GetValuesCSS(values),'g'),css:'value'},{regex:new RegExp(this.GetValuesCSS(fonts),'g'),css:'value'}];this.CssClass='dp-css';} dp.sh.Highlighter.prototype.GetKeywordsCSS=function(str) {return'\\b([a-z_]|)'+str.replace(/ /g,'(?=:)\\b|\\b([a-z_\\*]|\\*|)')+'(?=:)\\b';} dp.sh.Highlighter.prototype.GetValuesCSS=function(str) {return'\\b'+str.replace(/ /g,'(?!-)(?!:)\\b|\\b()')+'\:\\b';} dp.sh.Brushes.CSS.prototype=new dp.sh.Highlighter();dp.sh.Brushes.CSS.Aliases=['css']; dp.sh.Brushes.Delphi=function() {var keywords='abs addr and ansichar ansistring array as asm begin boolean byte cardinal '+'case char class comp const constructor currency destructor div do double '+'downto else end except exports extended false file finalization finally '+'for function goto if implementation in inherited int64 initialization '+'integer interface is label library longint longword mod nil not object '+'of on or packed pansichar pansistring pchar pcurrency pdatetime pextended '+'pint64 pointer private procedure program property pshortstring pstring '+'pvariant pwidechar pwidestring protected public published raise real real48 '+'record repeat set shl shortint shortstring shr single smallint string then '+'threadvar to true try type unit until uses val var varirnt while widechar '+'widestring with word write writeln xor';this.regexList=[{regex:new RegExp('\\(\\*[\\s\\S]*?\\*\\)','gm'),css:'comment'},{regex:new RegExp('{(?!\\$)[\\s\\S]*?}','gm'),css:'comment'},{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('\\{\\$[a-zA-Z]+ .+\\}','g'),css:'directive'},{regex:new RegExp('\\b[\\d\\.]+\\b','g'),css:'number'},{regex:new RegExp('\\$[a-zA-Z0-9]+\\b','g'),css:'number'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-delphi';} dp.sh.Brushes.Delphi.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Delphi.Aliases=['delphi','pascal']; dp.sh.Brushes.Java=function() {var keywords='abstract assert boolean break byte case catch char class const '+'continue default do double else enum extends '+'false final finally float for goto if implements import '+'instanceof int interface long native new null '+'package private protected public return '+'short static strictfp super switch synchronized this throw throws true '+'transient try void volatile while';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b','gi'),css:'number'},{regex:new RegExp('(?!\\@interface\\b)\\@[\\$\\w]+\\b','g'),css:'annotation'},{regex:new RegExp('\\@interface\\b','g'),css:'keyword'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-j';} dp.sh.Brushes.Java.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Java.Aliases=['java']; dp.sh.Brushes.JScript=function() {var keywords='abstract boolean break byte case catch char class const continue debugger '+'default delete do double else enum export extends false final finally float '+'for function goto if implements import in instanceof int interface long native '+'new null package private protected public return short static super switch '+'synchronized this throw throws transient true try typeof var void volatile while with';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('^\\s*#.*','gm'),css:'preprocessor'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-c';} dp.sh.Brushes.JScript.prototype=new dp.sh.Highlighter();dp.sh.Brushes.JScript.Aliases=['js','jscript','javascript']; dp.sh.Brushes.Php=function() {var funcs='abs acos acosh addcslashes addslashes '+'array_change_key_case array_chunk array_combine array_count_values array_diff '+'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+'array_push array_rand array_reduce array_reverse array_search array_shift '+'array_slice array_splice array_sum array_udiff array_udiff_assoc '+'array_udiff_uassoc array_uintersect array_uintersect_assoc '+'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+'parse_ini_file parse_str parse_url passthru pathinfo readlink realpath rewind rewinddir rmdir '+'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+'strtoupper strtr strval substr substr_compare';var keywords='and or xor __FILE__ __LINE__ array as break case '+'cfunction class const continue declare default die do else '+'elseif empty enddeclare endfor endforeach endif endswitch endwhile '+'extends for foreach function include include_once global if '+'new old_function return static switch use require require_once '+'var while __FUNCTION__ __CLASS__ '+'__METHOD__ abstract interface public implements extends private protected throw';this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:'comment'},{regex:dp.sh.RegexLib.MultiLineCComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp('\\$\\w+','g'),css:'vars'},{regex:new RegExp(this.GetKeywords(funcs),'gmi'),css:'func'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-c';} dp.sh.Brushes.Php.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Php.Aliases=['php']; dp.sh.Brushes.Python=function() {var keywords='and assert break class continue def del elif else '+'except exec finally for from global if import in is '+'lambda not or pass print raise return try yield while';var special='None True False self cls class_' this.regexList=[{regex:dp.sh.RegexLib.SingleLinePerlComments,css:'comment'},{regex:new RegExp("^\\s*@\\w+",'gm'),css:'decorator'},{regex:new RegExp("(['\"]{3})([^\\1])*?\\1",'gm'),css:'comment'},{regex:new RegExp('"(?!")(?:\\.|\\\\\\"|[^\\""\\n\\r])*"','gm'),css:'string'},{regex:new RegExp("'(?!')*(?:\\.|(\\\\\\')|[^\\''\\n\\r])*'",'gm'),css:'string'},{regex:new RegExp("\\b\\d+\\.?\\w*",'g'),css:'number'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'},{regex:new RegExp(this.GetKeywords(special),'gm'),css:'special'}];this.CssClass='dp-py';} dp.sh.Brushes.Python.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Python.Aliases=['py','python']; dp.sh.Brushes.Ruby=function() {var keywords='alias and BEGIN begin break case class def define_method defined do each else elsif '+'END end ensure false for if in module new next nil not or raise redo rescue retry return '+'self super then throw true undef unless until when while yield';var builtins='Array Bignum Binding Class Continuation Dir Exception FalseClass File::Stat File Fixnum Fload '+'Hash Integer IO MatchData Method Module NilClass Numeric Object Proc Range Regexp String Struct::TMS Symbol '+'ThreadGroup Thread Time TrueClass' this.regexList=[{regex:dp.sh.RegexLib.SingleLinePerlComments,css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp(':[a-z][A-Za-z0-9_]*','g'),css:'symbol'},{regex:new RegExp('(\\$|@@|@)\\w+','g'),css:'variable'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'},{regex:new RegExp(this.GetKeywords(builtins),'gm'),css:'builtin'}];this.CssClass='dp-rb';} dp.sh.Brushes.Ruby.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Ruby.Aliases=['ruby','rails','ror']; dp.sh.Brushes.Sql=function() {var funcs='abs avg case cast coalesce convert count current_timestamp '+'current_user day isnull left lower month nullif replace right '+'session_user space substring sum system_user upper user year';var keywords='absolute action add after alter as asc at authorization begin bigint '+'binary bit by cascade char character check checkpoint close collate '+'column commit committed connect connection constraint contains continue '+'create cube current current_date current_time cursor database date '+'deallocate dec decimal declare default delete desc distinct double drop '+'dynamic else end end-exec escape except exec execute false fetch first '+'float for force foreign forward free from full function global goto grant '+'group grouping having hour ignore index inner insensitive insert instead '+'int integer intersect into is isolation key last level load local max min '+'minute modify move name national nchar next no numeric of off on only '+'open option order out output partial password precision prepare primary '+'prior privileges procedure public read real references relative repeatable '+'restrict return returns revoke rollback rollup rows rule schema scroll '+'second section select sequence serializable set size smallint static '+'statistics table temp temporary then time timestamp to top transaction '+'translation trigger true truncate uncommitted union unique update values '+'varchar varying view when where with work';var operators='all and any between cross in join like not null or outer some';this.regexList=[{regex:new RegExp('--(.*)$','gm'),css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:dp.sh.RegexLib.SingleQuotedString,css:'string'},{regex:new RegExp(this.GetKeywords(funcs),'gmi'),css:'func'},{regex:new RegExp(this.GetKeywords(operators),'gmi'),css:'op'},{regex:new RegExp(this.GetKeywords(keywords),'gmi'),css:'keyword'}];this.CssClass='dp-sql';} dp.sh.Brushes.Sql.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Sql.Aliases=['sql']; dp.sh.Brushes.Vb=function() {var keywords='AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto '+'Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate '+'CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType '+'Date Decimal Declare Default Delegate Dim DirectCast Do Double Each '+'Else ElseIf End Enum Erase Error Event Exit False Finally For Friend '+'Function Get GetType GoSub GoTo Handles If Implements Imports In '+'Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module '+'MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing '+'NotInheritable NotOverridable Object On Option Optional Or OrElse '+'Overloads Overridable Overrides ParamArray Preserve Private Property '+'Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume '+'Return Select Set Shadows Shared Short Single Static Step Stop String '+'Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until '+'Variant When While With WithEvents WriteOnly Xor';this.regexList=[{regex:new RegExp('\'.*$','gm'),css:'comment'},{regex:dp.sh.RegexLib.DoubleQuotedString,css:'string'},{regex:new RegExp('^\\s*#.*','gm'),css:'preprocessor'},{regex:new RegExp(this.GetKeywords(keywords),'gm'),css:'keyword'}];this.CssClass='dp-vb';} dp.sh.Brushes.Vb.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Vb.Aliases=['vb','vb.net']; dp.sh.Brushes.Xml=function(){this.CssClass = 'dp-xml';} dp.sh.Brushes.Xml.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Xml.Aliases=['xml','xhtml','xslt','html','xhtml'];dp.sh.Brushes.Xml.prototype.ProcessRegexList=function() {function push(array,value) {array[array.length]=value;} var index=0;var match=null;var regex=null;this.GetMatches(new RegExp('(\&lt;|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\&gt;|>)','gm'),'cdata');this.GetMatches(new RegExp('(\&lt;|<)!--\\s*.*?\\s*--(\&gt;|>)','gm'),'comments');regex=new RegExp('([:\\w-\.]+)\\s*=\\s*(".*?"|\'.*?\'|\\w+)*|(\\w+)','gm');while((match=regex.exec(this.code))!=null) {if(match[1]==null) {continue;} push(this.matches,new dp.sh.Match(match[1],match.index,'attribute'));if(match[2]!=undefined) {push(this.matches,new dp.sh.Match(match[2],match.index+match[0].indexOf(match[2]),'attribute-value'));}} this.GetMatches(new RegExp('(\&lt;|<)/*\\?*(?!\\!)|/*\\?*(\&gt;|>)','gm'),'tag');regex=new RegExp('(?:\&lt;|<)/*\\?*\\s*([:\\w-\.]+)','gm');while((match=regex.exec(this.code))!=null) {push(this.matches,new dp.sh.Match(match[1],match.index+match[0].indexOf(match[1]),'tag-name'));}}
JavaScript
// Automatically detect the correct document.domain (#123). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.parent.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; // Attention: FCKConfig must be available in the page. function GetCommonDialogCss( prefix ) { // CSS minified by http://iceyboard.no-ip.org/projects/css_compressor return FCKConfig.BasePath + 'dialog/common/' + '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}' ; } // Gets a element by its Id. Used for shorter coding. function GetE( elementId ) { return document.getElementById( elementId ) ; } function ShowE( element, isVisible ) { if ( typeof( element ) == 'string' ) element = GetE( element ) ; element.style.display = isVisible ? '' : 'none' ; } function SetAttribute( element, attName, attValue ) { if ( attValue == null || attValue.length == 0 ) element.removeAttribute( attName, 0 ) ; // 0 : Case Insensitive else element.setAttribute( attName, attValue, 0 ) ; // 0 : Case Insensitive } function GetAttribute( element, attName, valueIfNull ) { var oAtt = element.attributes[attName] ; if ( oAtt == null || !oAtt.specified ) return valueIfNull ? valueIfNull : '' ; var oValue = element.getAttribute( attName, 2 ) ; if ( oValue == null ) oValue = oAtt.nodeValue ; return ( oValue == null ? valueIfNull : oValue ) ; } function SelectField( elementId ) { var element = GetE( elementId ) ; element.focus() ; // element.select may not be available for some fields (like <select>). if ( element.select ) element.select() ; } // Functions used by text fields to accept numbers only. var IsDigit = ( function() { var KeyIdentifierMap = { End : 35, Home : 36, Left : 37, Right : 39, 'U+00007F' : 46 // Delete } ; return function ( e ) { if ( !e ) e = event ; var iCode = ( e.keyCode || e.charCode ) ; if ( !iCode && e.keyIdentifier && ( e.keyIdentifier in KeyIdentifierMap ) ) iCode = KeyIdentifierMap[ e.keyIdentifier ] ; return ( ( iCode >= 48 && iCode <= 57 ) // Numbers || (iCode >= 35 && iCode <= 40) // Arrows, Home, End || iCode == 8 // Backspace || iCode == 46 // Delete || iCode == 9 // Tab ) ; } } )() ; String.prototype.Trim = function() { return this.replace( /(^\s*)|(\s*$)/g, '' ) ; } String.prototype.StartsWith = function( value ) { return ( this.substr( 0, value.length ) == value ) ; } String.prototype.Remove = function( start, length ) { var s = '' ; if ( start > 0 ) s = this.substring( 0, start ) ; if ( start + length < this.length ) s += this.substring( start + length , this.length ) ; return s ; } String.prototype.ReplaceAll = function( searchArray, replaceArray ) { var replaced = this ; for ( var i = 0 ; i < searchArray.length ; i++ ) { replaced = replaced.replace( searchArray[i], replaceArray[i] ) ; } return replaced ; } /** Utility function to create/update an element with a name attribute in IE, so it behaves properly when moved around It also allows to change the name or other special attributes in an existing node oEditor : instance of FCKeditor where the element will be created oOriginal : current element being edited or null if it has to be created nodeName : string with the name of the element to create oAttributes : Hash object with the attributes that must be set at creation time in IE Those attributes will be set also after the element has been created for any other browser to avoid redudant code */ function CreateNamedElement( oEditor, oOriginal, nodeName, oAttributes ) { var oNewNode ; // IE doesn't allow easily to change properties of an existing object, // so remove the old and force the creation of a new one. var oldNode = null ; if ( oOriginal && oEditor.FCKBrowserInfo.IsIE ) { // Force the creation only if some of the special attributes have changed: var bChanged = false; for( var attName in oAttributes ) bChanged |= ( oOriginal.getAttribute( attName, 2) != oAttributes[attName] ) ; if ( bChanged ) { oldNode = oOriginal ; oOriginal = null ; } } // If the node existed (and it's not IE), then we just have to update its attributes if ( oOriginal ) { oNewNode = oOriginal ; } else { // #676, IE doesn't play nice with the name or type attribute if ( oEditor.FCKBrowserInfo.IsIE ) { var sbHTML = [] ; sbHTML.push( '<' + nodeName ) ; for( var prop in oAttributes ) { sbHTML.push( ' ' + prop + '="' + oAttributes[prop] + '"' ) ; } sbHTML.push( '>' ) ; if ( !oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()] ) sbHTML.push( '</' + nodeName + '>' ) ; oNewNode = oEditor.FCK.EditorDocument.createElement( sbHTML.join('') ) ; // Check if we are just changing the properties of an existing node: copy its properties if ( oldNode ) { CopyAttributes( oldNode, oNewNode, oAttributes ) ; oEditor.FCKDomTools.MoveChildren( oldNode, oNewNode ) ; oldNode.parentNode.removeChild( oldNode ) ; oldNode = null ; if ( oEditor.FCK.Selection.SelectionData ) { // Trick to refresh the selection object and avoid error in // fckdialog.html Selection.EnsureSelection var oSel = oEditor.FCK.EditorDocument.selection ; oEditor.FCK.Selection.SelectionData = oSel.createRange() ; // Now oSel.type will be 'None' reflecting the real situation } } oNewNode = oEditor.FCK.InsertElement( oNewNode ) ; // FCK.Selection.SelectionData is broken by now since we've // deleted the previously selected element. So we need to reassign it. if ( oEditor.FCK.Selection.SelectionData ) { var range = oEditor.FCK.EditorDocument.body.createControlRange() ; range.add( oNewNode ) ; oEditor.FCK.Selection.SelectionData = range ; } } else { oNewNode = oEditor.FCK.InsertElement( nodeName ) ; } } // Set the basic attributes for( var attName in oAttributes ) oNewNode.setAttribute( attName, oAttributes[attName], 0 ) ; // 0 : Case Insensitive return oNewNode ; } // Copy all the attributes from one node to the other, kinda like a clone // But oSkipAttributes is an object with the attributes that must NOT be copied function CopyAttributes( oSource, oDest, oSkipAttributes ) { var aAttributes = oSource.attributes ; for ( var n = 0 ; n < aAttributes.length ; n++ ) { var oAttribute = aAttributes[n] ; if ( oAttribute.specified ) { var sAttName = oAttribute.nodeName ; // We can set the type only once, so do it with the proper value, not copying it. if ( sAttName in oSkipAttributes ) continue ; var sAttValue = oSource.getAttribute( sAttName, 2 ) ; if ( sAttValue == null ) sAttValue = oAttribute.nodeValue ; oDest.setAttribute( sAttName, sAttValue, 0 ) ; // 0 : Case Insensitive } } // The style: oDest.style.cssText = oSource.style.cssText ; }
JavaScript
var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKTools = oEditor.FCKTools ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { //ShowE('divInfo' , ( tabCode == 'Info' ) ) ; } // Get the selected image (if available). var oImage = dialog.Selection.GetSelectedElement() ; if ( oImage && oImage.tagName != 'IMG' && !( oImage.tagName == 'INPUT' && oImage.type == 'image' ) ) oImage = null ; // Get the active link. var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Load the selected element information (if any). LoadSelection() ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oImage ) return ; var sUrl = oImage.getAttribute( '_fcksavedurl' ) ; if ( sUrl == null ) sUrl = GetAttribute( oImage, 'src', '' ) ; GetE('txtUrl').value = sUrl ; GetE('txtAlt').value = GetAttribute( oImage, 'alt', '' ) ; GetE('txtVSpace').value = GetAttribute( oImage, 'vspace', '' ) ; GetE('txtHSpace').value = GetAttribute( oImage, 'hspace', '' ) ; GetE('txtBorder').value = GetAttribute( oImage, 'border', '' ) ; GetE('cmbAlign').value = GetAttribute( oImage, 'align', '' ) ; var iWidth, iHeight ; var regexSize = /^\s*(\d+)px\s*$/i ; if ( oImage.style.width ) { var aMatchW = oImage.style.width.match( regexSize ) ; if ( aMatchW ) { iWidth = aMatchW[1] ; oImage.style.width = '' ; SetAttribute( oImage, 'width' , iWidth ) ; } } if ( oImage.style.height ) { var aMatchH = oImage.style.height.match( regexSize ) ; if ( aMatchH ) { iHeight = aMatchH[1] ; oImage.style.height = '' ; SetAttribute( oImage, 'height', iHeight ) ; } } GetE('txtWidth').value = iWidth ? iWidth : GetAttribute( oImage, "width", '' ) ; GetE('txtHeight').value = iHeight ? iHeight : GetAttribute( oImage, "height", '' ) ; if ( oLink ) { var sLinkUrl = oLink.getAttribute( '_fcksavedurl' ) ; if ( sLinkUrl == null ) sLinkUrl = oLink.getAttribute('href',2) ; GetE('txtLnkUrl').value = sLinkUrl ; GetE('cmbLnkTarget').value = oLink.target ; } } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { GetE('txtUrl').focus() ; alert( FCKLang.DlgImgAlertUrl ) ; return false ; } var bHasImage = ( oImage != null ) ; oEditor.FCKUndo.SaveUndoStep() ; if ( !bHasImage ) { oImage = FCK.InsertElement( 'img' ) ; } UpdateImage( oImage ) ; var sLnkUrl = GetE('txtLnkUrl').value.Trim() ; if ( sLnkUrl.length == 0 ) { if ( oLink ) FCK.ExecuteNamedCommand( 'Unlink' ) ; } else { if ( oLink ) // Modifying an existent link. oLink.href = sLnkUrl ; else // Creating a new link. { if ( !bHasImage ) oEditor.FCKSelection.SelectNode( oImage ) ; oLink = oEditor.FCK.CreateLink( sLnkUrl )[0] ; if ( !bHasImage ) { oEditor.FCKSelection.SelectNode( oLink ) ; oEditor.FCKSelection.Collapse( false ) ; } } SetAttribute( oLink, '_fcksavedurl', sLnkUrl ) ; SetAttribute( oLink, 'target', GetE('cmbLnkTarget').value ) ; } return true ; } function UpdateImage( e, skipId ) { e.src = GetE('txtUrl').value ; SetAttribute( e, "_fcksavedurl", GetE('txtUrl').value ) ; SetAttribute( e, "alt" , GetE('txtAlt').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; SetAttribute( e, "vspace", GetE('txtVSpace').value ) ; SetAttribute( e, "hspace", GetE('txtHSpace').value ) ; SetAttribute( e, "border", GetE('txtBorder').value ) ; SetAttribute( e, "align" , GetE('cmbAlign').value ) ; } var sActualBrowser ; function SetUrl( url, width, height, alt ) { if ( sActualBrowser == 'Link' ) { GetE('txtLnkUrl').value = url ; } else { GetE('txtUrl').value = url ; GetE('txtWidth').value = width ? width : '' ; GetE('txtHeight').value = height ? height : '' ; if ( alt ) GetE('txtAlt').value = alt; } }
JavaScript
var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKTools = oEditor.FCKTools ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { //ShowE('divInfo' , ( tabCode == 'Info' ) ) ; } // Get the selected flash embed (if available). var oFakeImage = dialog.Selection.GetSelectedElement() ; var oEmbed ; if ( oFakeImage ) { if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckflash') ) oEmbed = FCK.GetRealElement( oFakeImage ) ; else oFakeImage = null ; } window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Load the selected element information (if any). LoadSelection() ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oEmbed ) return ; GetE('txtUrl').value = GetAttribute( oEmbed, 'src', '' ) ; GetE('txtWidth').value = GetAttribute( oEmbed, 'width', '' ) ; GetE('txtHeight').value = GetAttribute( oEmbed, 'height', '' ) ; UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { GetE('txtUrl').focus() ; alert( oEditor.FCKLang.DlgAlertUrl ) ; return false ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !oEmbed ) { oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ; oFakeImage = null ; } UpdateEmbed( oEmbed ) ; if ( !oFakeImage ) { oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ; oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ; oFakeImage = FCK.InsertElement( oFakeImage ) ; } oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ; return true ; } function UpdateEmbed( e ) { SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ; SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; } var ePreview ; function SetPreviewElement( previewEl ) { ePreview = previewEl ; if ( GetE('txtUrl').value.length > 0 ) UpdatePreview() ; } function UpdatePreview() { if ( !ePreview ) return ; while ( ePreview.firstChild ) ePreview.removeChild( ePreview.firstChild ) ; if ( GetE('txtUrl').value.length == 0 ) ePreview.innerHTML = '&nbsp;' ; else { var oDoc = ePreview.ownerDocument || ePreview.document ; var e = oDoc.createElement( 'EMBED' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, 'type', 'application/x-shockwave-flash' ) ; SetAttribute( e, 'width', '100%' ) ; SetAttribute( e, 'height', '100%' ) ; ePreview.appendChild( e ) ; } } function SetUrl( url, width, height ) { GetE('txtUrl').value = url ; if ( width ) GetE('txtWidth').value = width ; if ( height ) GetE('txtHeight').value = height ; UpdatePreview() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This is the integration file for JavaScript. * * It defines the FCKeditor class that can be used to create editor * instances in a HTML page in the client side. For server side * operations, use the specific integration system. */ // FCKeditor Class var FCKeditor = function( instanceName, width, height, toolbarSet, value ) { // Properties this.InstanceName = instanceName ; this.Width = width || '100%' ; this.Height = height || '200' ; this.ToolbarSet = toolbarSet || 'Default' ; this.Value = value || '' ; this.BasePath = FCKeditor.BasePath ; this.CheckBrowser = true ; this.DisplayErrors = true ; this.Config = new Object() ; // Events this.OnError = null ; // function( source, errorNumber, errorDescription ) } /** * This is the default BasePath used by all editor instances. */ FCKeditor.BasePath = '/fckeditor/' ; /** * The minimum height used when replacing textareas. */ FCKeditor.MinHeight = 200 ; /** * The minimum width used when replacing textareas. */ FCKeditor.MinWidth = 750 ; FCKeditor.prototype.Version = '2.6' ; FCKeditor.prototype.VersionBuild = '18638' ; FCKeditor.prototype.Create = function() { document.write( this.CreateHtml() ) ; } FCKeditor.prototype.CreateHtml = function() { // Check for errors if ( !this.InstanceName || this.InstanceName.length == 0 ) { this._ThrowError( 701, 'You must specify an instance name.' ) ; return '' ; } var sHtml = '' ; if ( !this.CheckBrowser || this._IsCompatibleBrowser() ) { sHtml += '<input type="hidden" id="' + this.InstanceName + '" name="' + this.InstanceName + '" value="' + this._HTMLEncode( this.Value ) + '" style="display:none" />' ; sHtml += this._GetConfigHtml() ; sHtml += this._GetIFrameHtml() ; } else { var sWidth = this.Width.toString().indexOf('%') > 0 ? this.Width : this.Width + 'px' ; var sHeight = this.Height.toString().indexOf('%') > 0 ? this.Height : this.Height + 'px' ; sHtml += '<textarea name="' + this.InstanceName + '" rows="4" cols="40" style="width:' + sWidth + ';height:' + sHeight + '">' + this._HTMLEncode( this.Value ) + '<\/textarea>' ; } return sHtml ; } FCKeditor.prototype.ReplaceTextarea = function() { if ( !this.CheckBrowser || this._IsCompatibleBrowser() ) { // We must check the elements firstly using the Id and then the name. var oTextarea = document.getElementById( this.InstanceName ) ; var colElementsByName = document.getElementsByName( this.InstanceName ) ; var i = 0; while ( oTextarea || i == 0 ) { if ( oTextarea && oTextarea.tagName.toLowerCase() == 'textarea' ) break ; oTextarea = colElementsByName[i++] ; } if ( !oTextarea ) { alert( 'Error: The TEXTAREA with id or name set to "' + this.InstanceName + '" was not found' ) ; return ; } oTextarea.style.display = 'none' ; this._InsertHtmlBefore( this._GetConfigHtml(), oTextarea ) ; this._InsertHtmlBefore( this._GetIFrameHtml(), oTextarea ) ; } } FCKeditor.prototype._InsertHtmlBefore = function( html, element ) { if ( element.insertAdjacentHTML ) // IE element.insertAdjacentHTML( 'beforeBegin', html ) ; else // Gecko { var oRange = document.createRange() ; oRange.setStartBefore( element ) ; var oFragment = oRange.createContextualFragment( html ); element.parentNode.insertBefore( oFragment, element ) ; } } FCKeditor.prototype._GetConfigHtml = function() { var sConfig = '' ; for ( var o in this.Config ) { if ( sConfig.length > 0 ) sConfig += '&amp;' ; sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.Config[o] ) ; } return '<input type="hidden" id="' + this.InstanceName + '___Config" value="' + sConfig + '" style="display:none" />' ; } FCKeditor.prototype._GetIFrameHtml = function() { var sFile = 'fckeditor.html' ; try { if ( (/fcksource=true/i).test( window.top.location.search ) ) sFile = 'fckeditor.original.html' ; } catch (e) { /* Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error). */ } var sLink = this.BasePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.InstanceName ) ; if (this.ToolbarSet) sLink += '&amp;Toolbar=' + this.ToolbarSet ; return '<iframe id="' + this.InstanceName + '___Frame" src="' + sLink + '" width="' + this.Width + '" height="' + this.Height + '" frameborder="0" scrolling="no"></iframe>' ; } FCKeditor.prototype._IsCompatibleBrowser = function() { return FCKeditor_IsCompatibleBrowser() ; } FCKeditor.prototype._ThrowError = function( errorNumber, errorDescription ) { this.ErrorNumber = errorNumber ; this.ErrorDescription = errorDescription ; if ( this.DisplayErrors ) { document.write( '<div style="COLOR: #ff0000">' ) ; document.write( '[ FCKeditor Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]' ) ; document.write( '</div>' ) ; } if ( typeof( this.OnError ) == 'function' ) this.OnError( this, errorNumber, errorDescription ) ; } FCKeditor.prototype._HTMLEncode = function( text ) { if ( typeof( text ) != "string" ) text = text.toString() ; text = text.replace( /&/g, "&amp;").replace( /"/g, "&quot;").replace( /</g, "&lt;").replace( />/g, "&gt;") ; return text ; } ;(function() { var textareaToEditor = function( textarea ) { var editor = new FCKeditor( textarea.name ) ; editor.Width = Math.max( textarea.offsetWidth, FCKeditor.MinWidth ) ; editor.Height = Math.max( textarea.offsetHeight, FCKeditor.MinHeight ) ; return editor ; } /** * Replace all <textarea> elements available in the document with FCKeditor * instances. * * // Replace all <textarea> elements in the page. * FCKeditor.ReplaceAllTextareas() ; * * // Replace all <textarea class="myClassName"> elements in the page. * FCKeditor.ReplaceAllTextareas( 'myClassName' ) ; * * // Selectively replace <textarea> elements, based on custom assertions. * FCKeditor.ReplaceAllTextareas( function( textarea, editor ) * { * // Custom code to evaluate the replace, returning false if it * // must not be done. * // It also passes the "editor" parameter, so the developer can * // customize the instance. * } ) ; */ FCKeditor.ReplaceAllTextareas = function() { var textareas = document.getElementsByTagName( 'textarea' ) ; for ( var i = 0 ; i < textareas.length ; i++ ) { var editor = null ; var textarea = textareas[i] ; var name = textarea.name ; // The "name" attribute must exist. if ( !name || name.length == 0 ) continue ; if ( typeof arguments[0] == 'string' ) { // The textarea class name could be passed as the function // parameter. var classRegex = new RegExp( '(?:^| )' + arguments[0] + '(?:$| )' ) ; if ( !classRegex.test( textarea.className ) ) continue ; } else if ( typeof arguments[0] == 'function' ) { // An assertion function could be passed as the function parameter. // It must explicitly return "false" to ignore a specific <textarea>. editor = textareaToEditor( textarea ) ; if ( arguments[0]( textarea, editor ) === false ) continue ; } if ( !editor ) editor = textareaToEditor( textarea ) ; editor.ReplaceTextarea() ; } } })() ; function FCKeditor_IsCompatibleBrowser() { var sAgent = navigator.userAgent.toLowerCase() ; // Internet Explorer 5.5+ if ( /*@cc_on!@*/false && sAgent.indexOf("mac") == -1 ) { var sBrowserVersion = navigator.appVersion.match(/MSIE (.\..)/)[1] ; return ( sBrowserVersion >= 5.5 ) ; } // Gecko (Opera 9 tries to behave like Gecko at this point). if ( navigator.product == "Gecko" && navigator.productSub >= 20030210 && !( typeof(opera) == 'object' && opera.postError ) ) return true ; // Opera 9.50+ if ( window.opera && window.opera.version && parseFloat( window.opera.version() ) >= 9.5 ) return true ; // Adobe AIR // Checked before Safari because AIR have the WebKit rich text editor // features from Safari 3.0.4, but the version reported is 420. if ( sAgent.indexOf( ' adobeair/' ) != -1 ) return ( sAgent.match( / adobeair\/(\d+)/ )[1] >= 1 ) ; // Build must be at least v1 // Safari 3+ if ( sAgent.indexOf( ' applewebkit/' ) != -1 ) return ( sAgent.match( / applewebkit\/(\d+)/ )[1] >= 522 ) ; // Build must be at least 522 (v3) return false ; }
JavaScript
FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/' ; FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ; FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ; FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ; // FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = false ; FCKConfig.DefaultLanguage = 'zh-cn' ; FCKConfig.ContentLangDirection = 'ltr' ; FCKConfig.ProcessHTMLEntities = true ; FCKConfig.IncludeLatinEntities = true ; FCKConfig.IncludeGreekEntities = true ; FCKConfig.ProcessNumericEntities = false ; FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" FCKConfig.FillEmptyBlocks = true ; FCKConfig.FormatSource = true ; FCKConfig.FormatOutput = true ; FCKConfig.FormatIndentator = ' ' ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.ToolbarSets["Default"] = [ ['Source','Preview','-','PasteText','PasteWord','-','RemoveFormat','-','Bold','Italic','Underline','StrikeThrough','-','OrderedList','UnorderedList','-','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','-','Link','Unlink','Anchor','-','TextColor','BGColor','-','MyCode','About'], '/', ['FontFormat','FontName','FontSize'], ['Image','Flash','Media','Addon','-','DedePage','Quote','Br','-','Rule','Codes','Table','Smiley'] ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Source','Preview','-','PasteText','PasteWord','-','RemoveFormat','-','Bold','Italic','Underline','StrikeThrough','-','OrderedList','UnorderedList','-','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','-','Link','Unlink','Anchor','-','TextColor','BGColor','-','MyCode','About'], '/', ['FontFormat','FontName','FontSize'], ['Image','Flash','Media','Addon','-','DedePage','Quote','Br','-','Rule','Codes','Table','Smiley'] ] ; FCKConfig.ToolbarSets["Small"] = [ ['Source','Preview','-','PasteText','PasteWord','-','Bold','Italic','Underline','StrikeThrough','-','OrderedList','UnorderedList'], ['Link','Unlink','Anchor','-','TextColor','BGColor'], ['Image','Flash','Media','Addon','-','Quote','Br','-','Rule','Codes','Table','Smiley'] ] ; FCKConfig.ToolbarSets["Member"] = [ ['Source','Preview','-','PasteText','PasteWord','-','Bold','Italic','Underline','StrikeThrough'], ['ImageUser','FlashUser','-','Link','Unlink','-','Table','Rule','Codes','Quote','Br','-','TextColor','FontSize'] ] ; FCKConfig.ToolbarSets["Diy"] = [ ['Source','Preview','-','PasteText','-','Bold','Italic','Underline','StrikeThrough'], ['Link','Unlink','-','Table','Rule','Codes','Quote','Br','-','TextColor','FontSize'] ] ; FCKConfig.ToolbarSets["MemberLit"] = [ ['Source','Preview','-','PasteText','PasteWord','-','Bold','Italic','Underline','StrikeThrough'], ['ImageUser','FlashUser','-','Link','Unlink','-','Table','Rule','Codes','Quote','Br','-','TextColor','FontSize'] ] ; FCKConfig.EnterMode = 'p' ; // p | div | br FCKConfig.ShiftEnterMode = 'br' ; // p | div | br FCKConfig.Keystrokes = [ [ CTRL + 65 /*A*/, true ], [ CTRL + 67 /*C*/, true ], [ CTRL + 70 /*F*/, true ], [ CTRL + 83 /*S*/, true ], [ CTRL + 84 /*T*/, true ], [ CTRL + 88 /*X*/, true ], [ CTRL + 86 /*V*/, 'Paste' ], [ SHIFT + 45 /*INS*/, 'Paste' ], [ CTRL + 88 /*X*/, 'Cut' ], [ SHIFT + 46 /*DEL*/, 'Cut' ], [ CTRL + 90 /*Z*/, 'Undo' ], [ CTRL + 89 /*Y*/, 'Redo' ], [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], [ CTRL + 76 /*L*/, 'Link' ], [ CTRL + 66 /*B*/, 'Bold' ], [ CTRL + 73 /*I*/, 'Italic' ], [ CTRL + 85 /*U*/, 'Underline' ] ] ; FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ; FCKConfig.FontNames = '宋体;黑体;隶书;幼圆;Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.ProtectedTags = '' ; FCKConfig.DefaultStyleLabel = '' ; FCKConfig.DefaultFontFormatLabel = '' ; FCKConfig.DefaultFontLabel = '' ; FCKConfig.DefaultFontSizeLabel = '' ; FCKConfig.DefaultLinkTarget = '' ; // The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word FCKConfig.CleanWordKeepsStructure = false ; // Only inline elements are valid. FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; // Attributes that will be removed FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ; FCKConfig.CustomStyles = { 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } }; // Do not add, rename or remove styles here. Only apply definition changes. FCKConfig.CoreStyles = { // Basic Inline Styles. 'Bold' : { Element : 'strong', Overrides : 'b' }, 'Italic' : { Element : 'em', Overrides : 'i' }, 'Underline' : { Element : 'u' }, 'StrikeThrough' : { Element : 'strike' }, // Basic Block Styles (Font Format Combo). 'p' : { Element : 'p' }, 'div' : { Element : 'div' }, 'pre' : { Element : 'pre' }, 'address' : { Element : 'address' }, 'h1' : { Element : 'h1' }, 'h2' : { Element : 'h2' }, 'h3' : { Element : 'h3' }, 'h4' : { Element : 'h4' }, 'h5' : { Element : 'h5' }, 'h6' : { Element : 'h6' }, // Other formatting features. 'FontFace' : { Element : 'span', Styles : { 'font-family' : '#("Font")' }, Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] }, 'Size' : { Element : 'span', Styles : { 'font-size' : '#("Size","fontSize")' }, Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] }, 'Color' : { Element : 'span', Styles : { 'color' : '#("Color","color")' }, Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] }, 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } }, 'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } } }; // The distance of an indentation step. FCKConfig.IndentLength = 40 ; FCKConfig.IndentUnit = 'px' ; // Alternatively, FCKeditor allows the use of CSS classes for block indentation. // This overrides the IndentLength/IndentUnit settings. FCKConfig.IndentClasses = [] ; // [ Left, Center, Right, Justified ] FCKConfig.JustifyClasses = [] ; FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/' ; FCKConfig.SmileyImages = ['1.gif','10.gif','11.gif','12.gif','13.gif','14.gif','15.gif','16.gif','17.gif','18.gif','19.gif','2.gif','20.gif','21.gif','22.gif','23.gif','24.gif','25.gif','26.gif','27.gif','28.gif','29.gif','3.gif','30.gif','31.gif','32.gif','33.gif','34.gif','35.gif','36.gif','37.gif','38.gif','39.gif','4.gif','40.gif','41.gif','42.gif','43.gif','44.gif','45.gif','46.gif','47.gif','48.gif','49.gif','5.gif','50.gif','51.gif','52.gif','53.gif','54.gif','55.gif','56.gif','57.gif','58.gif','59.gif','6.gif','60.gif','61.gif','62.gif','63.gif','64.gif','7.gif','8.gif','9.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 400 ; FCKConfig.SmileyWindowHeight = 400 ; FCKConfig.BackgroundBlockerColor = '#ffffff' ; FCKConfig.BackgroundBlockerOpacity = 0.50 ;
JavaScript
<!-- function ShowAddCatalog(){ $Obj('addCatalog').style.display='block'; } function CloseAddCatalog(){ $Obj('addCatalog').style.display='none'; } function CloseEditCatalog(){ $Obj('editCatalog').style.display='none'; } function DelCatalog(cid){ if(window.confirm("你确实要删除这个分类么?")) { location.href='story_catalog.php?catid='+cid+'&action=del'; } } function DelStory(bid){ if(window.confirm("你确实要删除这本图书么?")){ location.href='story_do.php?bid='+bid+'&action=delbook'; } } function DelStoryContent(cid){ if(window.confirm("删除内容后章节的其它内容排列序号不会发生变化,\r\n这可能导致管理混乱,你确实要删除这篇内容么?")){ location.href='story_do.php?cid='+cid+'&action=delcontent'; } } function CloseLayer(layerid){ $Obj(layerid).style.display='none'; } //预览内容 function PreViewCt(cid,booktype){ if(booktype==0){ window.open("../book/story.php?id="+cid); }else{ window.open("../book/show-photo.php?id="+cid); } } //编辑栏目 function EditCatalog(cid){ $Obj('editCatalog').style.display='block'; var myajax = new DedeAjax($Obj('editCatalogBody'),false,true,"","","请稍候,正在载入..."); myajax.SendGet2('story_catalog.php?catid='+cid+'&action=editload'); DedeXHTTP = null; } //图书章节,反向选择 function ReSelChapter(){ var ems = document.getElementsByName('ids[]'); for(var i=0;i<ems.length;i++){ if(!ems[i].checked) ems[i].checked = true; else ems[i].checked = false; } } //删除整章节图书内容 function DelStoryChapter(cid){ if(window.confirm("删除章节会删除章节下的所有内容,你确实要删除么?")){ location.href='story_do.php?cid='+cid+'&action=delChapter'; } } //增加图书的检查 function checkSubmitAdd() { if(document.form1.catid.value==0){ alert("请选择连载内容的栏目!"); document.form1.bookname.focus(); return false; } if(document.form1.bookname.value==""){ alert("连载图书名称不能为空!"); document.form1.bookname.focus(); return false; } } //增加小说内容的检查 function checkSubmitAddCt() { if(document.form1.title.value==0){ alert("文章标题不能为空!"); document.form1.title.focus(); return false; } if(document.form1.chapterid.selectedIndex==-1 && document.form1.chapternew.value==''){ alert("文章所属章节和新章节名称不能同时为空!"); return false; } } //增加漫画内容的检查 function checkSubmitAddPhoto() { if(document.form1.chapterid.selectedIndex==-1 && document.form1.chapternew.value==''){ alert("文章所属章节和新章节名称不能同时为空!"); return false; } document.form1.photonum.value = endNum; } //显示选择框与新增章节选项 function ShowHideSelChapter(selfield,newfield) { if(document.form1.addchapter.checked){ $Obj(selfield).style.display = 'none'; $Obj(newfield).style.display = 'block'; }else{ $Obj(selfield).style.display = 'block'; $Obj(newfield).style.display = 'none'; } } function selAll() { for(i=0;i<document.form2.ids.length;i++) { if(!document.form2.ids[i].checked){ document.form2.ids[i].checked=true; } } } function noSelAll() { for(i=0;i<document.form2.ids.length;i++) { if(document.form2.ids[i].checked){ document.form2.ids[i].checked=false; } } } //获得选中文件的文件名 function getCheckboxItem() { var allSel=""; if(document.form2.ids.value) return document.form2.ids.value; for(i=0;i<document.form2.ids.length;i++) { if(document.form2.ids[i].checked){ allSel += (allSel=='' ? document.form2.ids[i].value : ","+document.form2.ids[i].value); } } return allSel; } //删除多选 function DelAllBooks() { if(window.confirm("你确实要删除这些图书么?")){ var selbook = getCheckboxItem(); location.href='story_do.php?bid='+selbook+'&action=delbook'; } } -->
JavaScript
<!-- var cal; var isFocus=false; //是否为焦点 //以上为 寒羽枫 2006-06-25 添加的变量 //Download:http://www.codefans.net //选择日期 → 由 寒羽枫 2006-06-25 添加 function SelectDate(obj,strFormat) { var date = new Date(); var by = date.getFullYear()-50; //最小值 → 50 年前 var ey = date.getFullYear()+50; //最大值 → 50 年后 //cal = new Calendar(by, ey,1,strFormat); //初始化英文版,0 为中文版 cal = (cal==null) ? new Calendar(by, ey, 0) : cal; //不用每次都初始化 2006-12-03 修正 cal.dateFormatStyle = strFormat; cal.show(obj); } /**//**//**//** * 返回日期 * @param d the delimiter * @param p the pattern of your date 2006-06-25 由 寒羽枫 修改为根据用户指定的 style 来确定; */ //String.prototype.toDate = function(x, p) { String.prototype.toDate = function(style) { /**//**//**//* if(x == null) x = "-"; if(p == null) p = "ymd"; var a = this.split(x); var y = parseInt(a[p.indexOf("y")]); //remember to change this next century ;) if(y.toString().length <= 2) y += 2000; if(isNaN(y)) y = new Date().getFullYear(); var m = parseInt(a[p.indexOf("m")]) - 1; var d = parseInt(a[p.indexOf("d")]); if(isNaN(d)) d = 1; return new Date(y, m, d); */ var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年 var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月 var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日 if(isNaN(y)) y = new Date().getFullYear(); if(isNaN(m)) m = new Date().getMonth(); if(isNaN(d)) d = new Date().getDate(); var dt ; eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')"); return dt; } /**//**//**//** * 格式化日期 * @param d the delimiter * @param p the pattern of your date * @author meizz */ Date.prototype.format = function(style) { var o = { "M+" : this.getMonth() + 1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "w+" : "日一二三四五六".charAt(this.getDay()), //week "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(style)) { style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for(var k in o){ if(new RegExp("("+ k +")").test(style)){ style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return style; }; /**//**//**//** * 日历类 * @param beginYear 1990 * @param endYear 2010 * @param lang 0(中文)|1(英语) 可自由扩充 * @param dateFormatStyle "yyyy-MM-dd"; * @version 2006-04-01 * @author KimSoft (jinqinghua [at] gmail.com) * @update */ function Calendar(beginYear, endYear, lang, dateFormatStyle) { this.beginYear = 1990; this.endYear = 2010; this.lang = 0; //0(中文) | 1(英文) this.dateFormatStyle = "yyyy-MM-dd"; if (beginYear != null && endYear != null){ this.beginYear = beginYear; this.endYear = endYear; } if (lang != null){ this.lang = lang } if (dateFormatStyle != null){ this.dateFormatStyle = dateFormatStyle } this.dateControl = null; this.panel = this.getElementById("calendarPanel"); this.container = this.getElementById("ContainerPanel"); this.form = null; this.date = new Date(); this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.colors = { "cur_word" : "#FFFFFF", //当日日期文字颜色 "cur_bg" : "#00FF00", //当日日期单元格背影色 "sel_bg" : "#FFCCCC", //已被选择的日期单元格背影色 2006-12-03 寒羽枫添加 "sun_word" : "#FF0000", //星期天文字颜色 "sat_word" : "#0000FF", //星期六文字颜色 "td_word_light" : "#333333", //单元格文字颜色 "td_word_dark" : "#CCCCCC", //单元格文字暗色 "td_bg_out" : "#EFEFEF", //单元格背影色 "td_bg_over" : "#FFCC00", //单元格背影色 "tr_word" : "#FFFFFF", //日历头文字颜色 "tr_bg" : "#666666", //日历头背影色 "input_border" : "#CCCCCC", //input控件的边框颜色 "input_bg" : "#EFEFEF" //input控件的背影色 } this.draw(); this.bindYear(); this.bindMonth(); this.changeSelect(); this.bindData(); } /**//**//**//** * 日历类属性(语言包,可自由扩展) */ Calendar.language = { "year" : [[""], [""]], "months" : [["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"], ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"] ], "weeks" : [["日","一","二","三","四","五","六"], ["SUN","MON","TUR","WED","THU","FRI","SAT"] ], "clear" : [["清空"], ["CLS"]], "today" : [["今天"], ["TODAY"]], "close" : [["关闭"], ["CLOSE"]] } Calendar.prototype.draw = function() { calendar = this; var mvAry = []; //mvAry[mvAry.length] = ' <form name="calendarForm" style="margin: 0px;">'; //因 <form> 不能嵌套, 2006-12-01 由寒羽枫改用 Div mvAry[mvAry.length] = ' <div name="calendarForm" style="margin: 0px;">'; mvAry[mvAry.length] = ' <table width="100%" border="0" cellpadding="0" cellspacing="1">'; mvAry[mvAry.length] = ' <tr>'; mvAry[mvAry.length] = ' <th align="left" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="prevMonth" type="button" id="prevMonth" value="&lt;" /></th>'; mvAry[mvAry.length] = ' <th align="center" width="98%" nowrap="nowrap"><select name="calendarYear" id="calendarYear" style="font-size:12px;"></select><select name="calendarMonth" id="calendarMonth" style="font-size:12px;"></select></th>'; mvAry[mvAry.length] = ' <th align="right" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="nextMonth" type="button" id="nextMonth" value="&gt;" /></th>'; mvAry[mvAry.length] = ' </tr>'; mvAry[mvAry.length] = ' </table>'; mvAry[mvAry.length] = ' <table id="calendarTable" width="100%" style="border:0px solid #CCCCCC;background-color:#FFFFFF" border="0" cellpadding="3" cellspacing="1">'; mvAry[mvAry.length] = ' <tr>'; for(var i = 0; i < 7; i++) { mvAry[mvAry.length] = ' <th style="font-weight:normal;background-color:' + calendar.colors["tr_bg"] + ';color:' + calendar.colors["tr_word"] + ';">' + Calendar.language["weeks"][this.lang][i] + '</th>'; } mvAry[mvAry.length] = ' </tr>'; for(var i = 0; i < 6;i++){ mvAry[mvAry.length] = ' <tr align="center">'; for(var j = 0; j < 7; j++) { if (j == 0){ mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sun_word"] + ';"></td>'; } else if(j == 6) { mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sat_word"] + ';"></td>'; } else { mvAry[mvAry.length] = ' <td style="cursor:default;"></td>'; } } mvAry[mvAry.length] = ' </tr>'; } mvAry[mvAry.length] = ' <tr style="background-color:' + calendar.colors["input_bg"] + ';">'; mvAry[mvAry.length] = ' <th colspan="2"><input name="calendarClear" type="button" id="calendarClear" value="' + Calendar.language["clear"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' <th colspan="3"><input name="calendarToday" type="button" id="calendarToday" value="' + Calendar.language["today"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' <th colspan="2"><input name="calendarClose" type="button" id="calendarClose" value="' + Calendar.language["close"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' </tr>'; mvAry[mvAry.length] = ' </table>'; //mvAry[mvAry.length] = ' </from>'; mvAry[mvAry.length] = ' </div>'; this.panel.innerHTML = mvAry.join(""); /**//******** 以下代码由寒羽枫 2006-12-01 添加 **********/ var obj = this.getElementById("prevMonth"); obj.onclick = function () {calendar.goPrevMonth(calendar);} obj.onblur = function () {calendar.onblur();} this.prevMonth= obj; obj = this.getElementById("nextMonth"); obj.onclick = function () {calendar.goNextMonth(calendar);} obj.onblur = function () {calendar.onblur();} this.nextMonth= obj; obj = this.getElementById("calendarClear"); obj.onclick = function () {calendar.dateControl.value = "";calendar.hide();} this.calendarClear = obj; obj = this.getElementById("calendarClose"); obj.onclick = function () {calendar.hide();} this.calendarClose = obj; obj = this.getElementById("calendarYear"); obj.onchange = function () {calendar.update(calendar);} obj.onblur = function () {calendar.onblur();} this.calendarYear = obj; obj = this.getElementById("calendarMonth"); with(obj) { onchange = function () {calendar.update(calendar);} onblur = function () {calendar.onblur();} }this.calendarMonth = obj; obj = this.getElementById("calendarToday"); obj.onclick = function () { var today = new Date(); calendar.date = today; calendar.year = today.getFullYear(); calendar.month = today.getMonth(); calendar.changeSelect(); calendar.bindData(); calendar.dateControl.value = today.format(calendar.dateFormatStyle); calendar.hide(); } this.calendarToday = obj; /**//******** 以上代码由寒羽枫 2006-12-01 添加 **********/ /**//* //this.form = document.forms["calendarForm"]; this.form.prevMonth.onclick = function () {calendar.goPrevMonth(this);} this.form.nextMonth.onclick = function () {calendar.goNextMonth(this);} this.form.prevMonth.onblur = function () {calendar.onblur();} this.form.nextMonth.onblur = function () {calendar.onblur();} this.form.calendarClear.onclick = function () {calendar.dateControl.value = "";calendar.hide();} this.form.calendarClose.onclick = function () {calendar.hide();} this.form.calendarYear.onchange = function () {calendar.update(this);} this.form.calendarMonth.onchange = function () {calendar.update(this);} this.form.calendarYear.onblur = function () {calendar.onblur();} this.form.calendarMonth.onblur = function () {calendar.onblur();} this.form.calendarToday.onclick = function () { var today = new Date(); calendar.date = today; calendar.year = today.getFullYear(); calendar.month = today.getMonth(); calendar.changeSelect(); calendar.bindData(); calendar.dateControl.value = today.format(calendar.dateFormatStyle); calendar.hide(); } */ } //年份下拉框绑定数据 Calendar.prototype.bindYear = function() { //var cy = this.form.calendarYear; var cy = this.calendarYear;//2006-12-01 由寒羽枫修改 cy.length = 0; for (var i = this.beginYear; i <= this.endYear; i++){ cy.options[cy.length] = new Option(i + Calendar.language["year"][this.lang], i); } } //月份下拉框绑定数据 Calendar.prototype.bindMonth = function() { //var cm = this.form.calendarMonth; var cm = this.calendarMonth;//2006-12-01 由寒羽枫修改 cm.length = 0; for (var i = 0; i < 12; i++){ cm.options[cm.length] = new Option(Calendar.language["months"][this.lang][i], i); } } //向前一月 Calendar.prototype.goPrevMonth = function(e){ if (this.year == this.beginYear && this.month == 0){return;} this.month--; if (this.month == -1) { this.year--; this.month = 11; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //向后一月 Calendar.prototype.goNextMonth = function(e){ if (this.year == this.endYear && this.month == 11){return;} this.month++; if (this.month == 12) { this.year++; this.month = 0; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //改变SELECT选中状态 Calendar.prototype.changeSelect = function() { //var cy = this.form.calendarYear; //var cm = this.form.calendarMonth; var cy = this.calendarYear;//2006-12-01 由寒羽枫修改 var cm = this.calendarMonth; for (var i= 0; i < cy.length; i++){ if (cy.options[i].value == this.date.getFullYear()){ cy[i].selected = true; break; } } for (var i= 0; i < cm.length; i++){ if (cm.options[i].value == this.date.getMonth()){ cm[i].selected = true; break; } } } //更新年、月 Calendar.prototype.update = function (e){ //this.year = e.form.calendarYear.options[e.form.calendarYear.selectedIndex].value; //this.month = e.form.calendarMonth.options[e.form.calendarMonth.selectedIndex].value; this.year = e.calendarYear.options[e.calendarYear.selectedIndex].value;//2006-12-01 由寒羽枫修改 this.month = e.calendarMonth.options[e.calendarMonth.selectedIndex].value; this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //绑定数据到月视图 Calendar.prototype.bindData = function () { var calendar = this; var dateArray = this.getMonthViewArray(this.date.getYear(), this.date.getMonth()); var tds = this.getElementById("calendarTable").getElementsByTagName("td"); for(var i = 0; i < tds.length; i++) { //tds[i].style.color = calendar.colors["td_word_light"]; tds[i].style.backgroundColor = calendar.colors["td_bg_out"]; tds[i].onclick = function () {return;} tds[i].onmouseover = function () {return;} tds[i].onmouseout = function () {return;} if (i > dateArray.length - 1) break; tds[i].innerHTML = dateArray[i]; if (dateArray[i] != "&nbsp;"){ tds[i].onclick = function () { if (calendar.dateControl != null){ calendar.dateControl.value = new Date(calendar.date.getFullYear(), calendar.date.getMonth(), this.innerHTML).format(calendar.dateFormatStyle); } calendar.hide(); } tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["td_bg_out"]; } if (new Date().format(calendar.dateFormatStyle) == new Date(calendar.date.getFullYear(), calendar.date.getMonth(), dateArray[i]).format(calendar.dateFormatStyle)) { //tds[i].style.color = calendar.colors["cur_word"]; tds[i].style.backgroundColor = calendar.colors["cur_bg"]; tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["cur_bg"]; } //continue; //若不想当天单元格的背景被下面的覆盖,请取消注释 → 2006-12-03 寒羽枫添加 }//end if //设置已被选择的日期单元格背影色 2006-12-03 寒羽枫添加 if (calendar.dateControl != null && calendar.dateControl.value == new Date(calendar.date.getFullYear(), calendar.date.getMonth(), dateArray[i]).format(calendar.dateFormatStyle)) { tds[i].style.backgroundColor = calendar.colors["sel_bg"]; tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["sel_bg"]; } } } } } //根据年、月得到月视图数据(数组形式) Calendar.prototype.getMonthViewArray = function (y, m) { var mvArray = []; var dayOfFirstDay = new Date(y, m, 1).getDay(); var daysOfMonth = new Date(y, m + 1, 0).getDate(); for (var i = 0; i < 42; i++) { mvArray[i] = "&nbsp;"; } for (var i = 0; i < daysOfMonth; i++){ mvArray[i + dayOfFirstDay] = i + 1; } return mvArray; } //扩展 document.getElementById(id) 多浏览器兼容性 from meizz tree source Calendar.prototype.getElementById = function(id){ if (typeof(id) != "string" || id == "") return null; if (document.getElementById) return document.getElementById(id); if (document.all) return document.all(id); try {return eval(id);} catch(e){ return null;} } //扩展 object.getElementsByTagName(tagName) Calendar.prototype.getElementsByTagName = function(object, tagName){ if (document.getElementsByTagName) return document.getElementsByTagName(tagName); if (document.all) return document.all.tags(tagName); } //取得HTML控件绝对位置 Calendar.prototype.getAbsPoint = function (e){ var x = e.offsetLeft; var y = e.offsetTop; while(e = e.offsetParent){ x += e.offsetLeft; y += e.offsetTop; } return {"x": x, "y": y}; } //显示日历 Calendar.prototype.show = function (dateObj, popControl) { if (dateObj == null){ throw new Error("arguments[0] is necessary") } this.dateControl = dateObj; //if (dateObj.value.length > 0){ //this.date = new Date(dateObj.value.toDate()); //this.date = new Date(dateObj.value.toDate(this.dateFormatStyle));//由寒羽枫修改,带入用户指定的 style this.date = (dateObj.value.length > 0) ? new Date(dateObj.value.toDate(this.dateFormatStyle)) : new Date() ;//2006-12-03 寒羽枫添加 → 若为空则显示当前月份 this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.changeSelect(); this.bindData(); //} if (popControl == null){ popControl = dateObj; } var xy = this.getAbsPoint(popControl); this.panel.style.left = xy.x -25 + "px"; this.panel.style.top = (xy.y + dateObj.offsetHeight) + "px"; //由寒羽枫 2006-06-25 修改 → 把 visibility 变为 display,并添加失去焦点的事件 //this.setDisplayStyle("select", "hidden"); //this.panel.style.visibility = "visible"; //this.container.style.visibility = "visible"; this.panel.style.display = ""; this.container.style.display = ""; dateObj.onblur = function(){calendar.onblur();} this.container.onmouseover = function(){isFocus=true;} this.container.onmouseout = function(){isFocus=false;} } //隐藏日历 Calendar.prototype.hide = function() { //this.setDisplayStyle("select", "visible"); //this.panel.style.visibility = "hidden"; //this.container.style.visibility = "hidden"; this.panel.style.display = "none"; this.container.style.display = "none"; isFocus=false; } //焦点转移时隐藏日历 → 由寒羽枫 2006-06-25 添加 Calendar.prototype.onblur = function() { if(!isFocus){this.hide();} } //以下由寒羽枫 2006-06-25 修改 → 用<iframe> 遮住 IE 的下拉框 /**//**//**//* //设置控件显示或隐藏 Calendar.prototype.setDisplayStyle = function(tagName, style) { var tags = this.getElementsByTagName(null, tagName) for(var i = 0; i < tags.length; i++) { if (tagName.toLowerCase() == "select" && (tags[i].name == "calendarYear" || tags[i].name == "calendarMonth")){ continue; } //tags[i].style.visibility = style; tags[i].style.display = style; } } */ //document.write('<div id="ContainerPanel" style="visibility:hidden"><div id="calendarPanel" style="position: absolute;visibility: hidden;z-index: 9999;'); document.write('<div id="ContainerPanel" style="display:none"><div id="calendarPanel" style="position: absolute;display: none;z-index: 9999;'); document.write('background-color: #FFFFFF;border: 1px solid #CCCCCC;width:175px;font-size:12px;"></div>'); if(document.all) { document.write('<iframe style="position:absolute;z-index:2000;width:expression(this.previousSibling.offsetWidth);'); document.write('height:expression(this.previousSibling.offsetHeight);'); document.write('left:expression(this.previousSibling.offsetLeft);top:expression(this.previousSibling.offsetTop);'); document.write('display:expression(this.previousSibling.style.display);" scrolling="no" frameborder="no"></iframe>'); } document.write('</div>'); //-->
JavaScript
//---事件句并------------------------------ function fileQueueError(file, errorCode, message) { try { var imageName = "error.gif"; var errorName = ""; if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) { errorName = "你添加的文件超过了限制!"; } if (errorName !== "") { alert(errorName); return; } switch (errorCode) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: default: alert(message); break; } addImage("img/" + imageName, 0); } catch (ex) { this.debug(ex); } } function fileDialogComplete(numFilesSelected, numFilesQueued) { try { if (numFilesQueued > 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function uploadProgress(file, bytesLoaded) { try { var percent = Math.ceil((bytesLoaded / file.size) * 100); var progress = new FileProgress(file, this.customSettings.upload_target); progress.setProgress(percent); if (percent === 100) { progress.setStatus("创建缩略图..."); progress.toggleCancel(false, this); } else { progress.setStatus("上传中..."); progress.toggleCancel(true, this); } } catch (ex) { this.debug(ex); } } function uploadSuccess(file, serverData) { try { var progress = new FileProgress(file, this.customSettings.upload_target); if (serverData.substring(0, 7) === "FILEID:") { addImage("swfupload.php?dopost=thumbnail&id=" + serverData.substring(7), serverData.substring(7)); progress.setStatus("获取缩略图..."); progress.toggleCancel(false); } else { addImage("img/error.gif", 0); progress.setStatus("有错误!"); progress.toggleCancel(false); alert(serverData); } } catch (ex) { this.debug(ex); } } function uploadComplete(file) { try { /* I want the next upload to continue automatically so I'll call startUpload here */ if (this.getStats().files_queued > 0) { this.startUpload(); } else { var progress = new FileProgress(file, this.customSettings.upload_target); progress.setComplete(); progress.setStatus("所有图片上传完成..."); progress.toggleCancel(false); } } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { var imageName = "error.gif"; var progress; try { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Cancelled"); progress.toggleCancel(false); } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Stopped"); progress.toggleCancel(true); } catch (ex2) { this.debug(ex2); } case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: alert(message); break; } addImage("img/" + imageName, 0); } catch (ex3) { this.debug(ex3); } } var albImg = 0; function addImage(src, pid) { var newImgDiv = document.createElement("div"); var delstr = ''; albImg++; if(pid != 0) { albImg = 'ok' + pid; delstr = '<a href="javascript:DelAlbPic('+pid+')">[删除]</a>'; } else { albImg = 'err' + albImg; } newImgDiv.className = 'albCt'; newImgDiv.id = 'albCt'+albImg; document.getElementById("thumbnails").appendChild(newImgDiv); newImgDiv.innerHTML = '<img src="'+src+'" width="120" />'+delstr; newImgDiv.innerHTML += '<div style="margin-top:10px">注释:<input type="text" name="picinfo'+albImg+'" value="" style="width:190px;" /></div>'; } /* ****************************************** * FileProgress Object * Control object for displaying file info * ****************************************** */ function FileProgress(file, targetID) { this.fileProgressID = "divFileProgress"; this.fileProgressWrapper = document.getElementById(this.fileProgressID); if (!this.fileProgressWrapper) { this.fileProgressWrapper = document.createElement("div"); this.fileProgressWrapper.className = "progressWrapper"; this.fileProgressWrapper.id = this.fileProgressID; this.fileProgressElement = document.createElement("div"); this.fileProgressElement.className = "progressContainer"; var progressCancel = document.createElement("a"); progressCancel.className = "progressCancel"; progressCancel.href = "#"; progressCancel.style.visibility = "hidden"; progressCancel.appendChild(document.createTextNode(" ")); var progressText = document.createElement("div"); progressText.className = "progressName"; progressText.appendChild(document.createTextNode(file.name)); var progressBar = document.createElement("div"); progressBar.className = "progressBarInProgress"; var progressStatus = document.createElement("div"); progressStatus.className = "progressBarStatus"; progressStatus.innerHTML = "&nbsp;"; this.fileProgressElement.appendChild(progressCancel); this.fileProgressElement.appendChild(progressText); this.fileProgressElement.appendChild(progressStatus); this.fileProgressElement.appendChild(progressBar); this.fileProgressWrapper.appendChild(this.fileProgressElement); document.getElementById(targetID).appendChild(this.fileProgressWrapper); } else { this.fileProgressElement = this.fileProgressWrapper.firstChild; this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name; } this.height = this.fileProgressWrapper.offsetHeight; } FileProgress.prototype.setProgress = function (percentage) { this.fileProgressElement.className = "progressContainer blue"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = percentage + "%"; }; FileProgress.prototype.setComplete = function () { this.fileProgressElement.className = "progressContainer green"; this.fileProgressElement.childNodes[3].className = "progressBarComplete"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setError = function () { this.fileProgressElement.className = "progressContainer red"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setCancelled = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setStatus = function (status) { this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) { this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"; if (swfuploadInstance) { var fileID = this.fileProgressID; this.fileProgressElement.childNodes[0].onclick = function () { swfuploadInstance.cancelUpload(fileID); return false; }; } };
JavaScript
<!-- function Nav(){ if(window.navigator.userAgent.indexOf("MSIE")>=1) return 'IE'; else if(window.navigator.userAgent.indexOf("Firefox")>=1) return 'FF'; else return "OT"; } function MyObj(oid) { return document.getElementById(oid); } function ShowHide(objname) { var obj = MyObj(objname); if(obj.style.display==null || obj.style.display=='none') { if(Nav()=='IE') obj.style.display = "block"; else obj.style.display = "table-row"; } else { obj.style.display = "none"; } } function ShowTestWin(surl) { window.open(surl, "testWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=450,left=100, top=100"); } function ShowItem(objname) { var obj = MyObj(objname); if(Nav()=='IE') obj.style.display = "block"; else obj.style.display = "table-row"; } function TestMore() { if(MyObj('usemore').checked) { if(Nav()=='IE') MyObj('usemoretr').style.display = 'block'; else MyObj('usemoretr').style.display = 'table-row'; MyObj('handset').style.display = 'none'; } else { MyObj('usemoretr').style.display = 'none'; if(Nav()=='IE') MyObj('handset').style.display = 'block'; else MyObj('handset').style.display = 'table-row'; } } function SelSourceSet() { if(MyObj('source3').checked) { if(Nav()=='IE') MyObj('rssset').style.display = 'block'; else MyObj('rssset').style.display = 'table-row'; MyObj('batchset').style.display = 'none'; MyObj('handset').style.display = 'none'; MyObj('arturl').style.display = 'none'; }else if(MyObj('source2').checked) { MyObj('rssset').style.display = 'none'; MyObj('batchset').style.display = 'none'; if(Nav()=='IE') MyObj('handset').style.display = 'block'; else MyObj('handset').style.display = 'table-row'; if(Nav()=='IE') MyObj('arturl').style.display = 'block'; else MyObj('arturl').style.display = 'table-row'; } else { MyObj('rssset').style.display = 'none'; if(Nav()=='IE') MyObj('batchset').style.display = 'block'; else MyObj('batchset').style.display = 'table-row'; if(Nav()=='IE') MyObj('handset').style.display = 'block'; else MyObj('handset').style.display = 'table-row'; if(Nav()=='IE') MyObj('arturl').style.display = 'block'; else MyObj('arturl').style.display = 'table-row'; } TestMore(); } function SelListenSet() { if(MyObj('islisten1').checked) { MyObj('listentr').style.display = 'none'; } else { if(Nav()=='IE') MyObj('listentr').style.display = 'block'; else MyObj('listentr').style.display = 'table-row'; } } function SelUrlruleSet() { if(MyObj('urlrule2').checked) { MyObj('arearuletr').style.display = 'none'; if(Nav()=='IE') MyObj('regxruletr').style.display = 'block'; else MyObj('regxruletr').style.display = 'table-row'; } else { if(Nav()=='IE') MyObj('arearuletr').style.display = 'block'; else MyObj('arearuletr').style.display = 'table-row'; MyObj('regxruletr').style.display = 'none'; } } function TestRss() { var surl = ''; surl = escape(MyObj('rssurl').value); ShowTestWin("co_do.php?dopost=testrss&rssurl="+surl); } function TestRegx() { var surl = escape(MyObj('regxurl').value); var sstart = MyObj('startid').value; var send = MyObj('endid').value; var saddv = MyObj('addv').value; ShowTestWin("co_do.php?dopost=testregx&regxurl="+surl+"&startid="+sstart+"&endid="+send+"&addv="+saddv); } function toHex( n ) { var digitArray = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); var result = '' var start = true; for ( var i=32; i>0; ) { i -= 4; var digit = ( n >> i ) & 0xf; if (!start || digit != 0) { start = false; result += digitArray[digit]; } } return ( result == '' ? '0' : result ); } function SelTrim(selfield) { var tagobj = MyObj(selfield); if(Nav()=='IE'){ var posLeft = window.event.clientX-200; var posTop = window.event.clientY; } else{ var posLeft = 100;var posTop = 100; } window.open("templets/co_trimrule.html?"+selfield, "coRule", "scrollbars=no,resizable=yes,statebar=no,width=320,height=180,left="+posLeft+", top="+posTop); } -->
JavaScript
// JavaScript Document function ShowHide2(objname){ var obj = $Obj(objname); if(obj.style.display != 'block'){ obj.style.display = 'block' } else{ obj.style.display = 'none'; } }
JavaScript
<!-- if(moz) { extendEventObject(); extendElementModel(); emulateAttachEvent(); } function viewArc(aid){ if(aid==0) aid = getOneItem(); window.open("archives_do.php?aid="+aid+"&dopost=viewArchives"); } function kwArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); if(qstr=='') { alert('必须选择一个或多个文档!'); return; } location="archives_do.php?aid="+aid+"&dopost=makekw&qstr="+qstr; } function editArc(aid){ if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=editArchives"; } function updateArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=makeArchives&qstr="+qstr; } function checkArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=checkArchives&qstr="+qstr; } function moveArc(e, obj, cid){ var qstr=getCheckboxItem(); if(qstr=='') { alert('必须选择一个或多个文档!'); return; } LoadQuickDiv(e, 'archives_do.php?dopost=moveArchives&qstr='+qstr+'&channelid='+cid+'&rnd='+Math.random(), 'moveArchives', '450px', '180px'); ChangeFullDiv('show'); } function adArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=commendArchives&qstr="+qstr; } function cAtts(jname, e, obj) { var qstr=getCheckboxItem(); if(qstr=='') { alert('必须选择一个或多个文档!'); return; } LoadQuickDiv(e, 'archives_do.php?dopost=attsDlg&qstr='+qstr+'&dojob='+jname+'&rnd='+Math.random(), 'attsDlg', '450px', '160px'); ChangeFullDiv('show'); } function delArc(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?qstr="+qstr+"&aid="+aid+"&dopost=delArchives"; } function QuickEdit(aid, e, obj) { LoadQuickDiv(e, 'archives_do.php?dopost=quickEdit&aid='+aid+'&rnd='+Math.random(), 'quickEdit', '450px', '300px'); ChangeFullDiv('show'); } //上下文菜单 function ShowMenu(evt,obj,aid,atitle) { var popupoptions popupoptions = [ new ContextItem("浏览文档",function(){ viewArc(aid); }), new ContextItem("编辑属性",function(){ QuickEdit(aid, evt, obj); }), new ContextItem("编辑文档",function(){ editArc(aid); }), new ContextSeperator(), new ContextItem("更新HTML",function(){ updateArc(aid); }), new ContextItem("审核文档",function(){ checkArc(aid); }), new ContextItem("推荐文档",function(){ adArc(aid); }), new ContextItem("删除文档",function(){ delArc(aid); }), new ContextSeperator(), new ContextItem("复制(<u>C</u>)",function(){ copyToClipboard(atitle); }), new ContextItem("重载页面",function(){ location.reload(); }), new ContextSeperator(), new ContextItem("全部选择",function(){ selAll(); }), new ContextItem("取消选择",function(){ noSelAll(); }), new ContextSeperator(), new ContextItem("关闭菜单",function(){}) ] ContextMenu.display(evt,popupoptions); //location="catalog_main.php"; } //获得选中文件的文件名 function getCheckboxItem() { var allSel=""; if(document.form2.arcID.value) return document.form2.arcID.value; for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { if(allSel=="") allSel=document.form2.arcID[i].value; else allSel=allSel+"`"+document.form2.arcID[i].value; } } return allSel; } //获得选中其中一个的id function getOneItem() { var allSel=""; if(document.form2.arcID.value) return document.form2.arcID.value; for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { allSel = document.form2.arcID[i].value; break; } } return allSel; } function selAll() { for(i=0;i<document.form2.arcID.length;i++) { if(!document.form2.arcID[i].checked) { document.form2.arcID[i].checked=true; } } } function noSelAll() { for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { document.form2.arcID[i].checked=false; } } } -->
JavaScript
<!-- function AddNew() { $DE('addTab').style.display = 'block'; } function CloseTab(tb) { $DE(tb).style.display = 'none'; } function ListAll() { $DE('editTab').style.display = 'block'; var myajax = new DedeAjax($DE('editTabBody')); myajax.SendGet('index_body.php?dopost=editshow'); } function LoadUpdateInfos() { var myajax = new DedeAjax($DE('updateinfos')); myajax.SendGet('update_guide.php?dopost=test'); } function SkipReload(nnum) { if( window.confirm("忽略后以后都不会再提示这个日期前的升级信息,你确定要忽略这些更新吗?") ) { DedeXHTTP = null; $DE('updateinfos').innerHTML = "<img src='img/loadinglit.gif' /> 正在处理中..."; var myajax = new DedeAjax($DE('updateinfos')); myajax.SendGet('update_guide.php?dopost=skip&vtime='+nnum); } } function ShowWaitDiv() { $DE('loaddiv').style.display = 'block'; return true; } window.onload = function() { var myajax = new DedeAjax($DE('rightajax')); myajax.SendGet('index_body.php?dopost=getRightSide'); }; -->
JavaScript
<!-- self.onError=null; currentX = currentY = 0; whichIt = null; lastScrollX = 0; lastScrollY = 0; NS = (document.layers) ? 1 : 0; IE = (document.all) ? 1: 0; function heartBeat() { if(IE) { diffY = document.body.scrollTop; diffX = document.body.scrollLeft; } if(NS) { diffY = self.pageYOffset; diffX = self.pageXOffset; } if(diffY != lastScrollY) { percent = .1 * (diffY - lastScrollY); if(percent > 0) percent = Math.ceil(percent); else percent = Math.floor(percent); if(IE) document.all.floater.style.pixelTop += percent; if(NS) document.floater.top += percent; lastScrollY = lastScrollY + percent; } if(diffX != lastScrollX) { percent = .1 * (diffX - lastScrollX); if(percent > 0) percent = Math.ceil(percent); else percent = Math.floor(percent); if(IE) document.all.floater.style.pixelLeft += percent; if(NS) document.floater.left += percent; lastScrollX = lastScrollX + percent; } } function checkFocus(x,y) { stalkerx = document.floater.pageX; stalkery = document.floater.pageY; stalkerwidth = document.floater.clip.width; stalkerheight = document.floater.clip.height; if( (x > stalkerx && x < (stalkerx+stalkerwidth)) && (y > stalkery && y < (stalkery+stalkerheight))) return true; else return false; } function grabIt(e) { if(IE) { whichIt = event.srcElement; while (whichIt.id.indexOf("floater") == -1) { whichIt = whichIt.parentElement; if (whichIt == null) { return true; } } whichIt.style.pixelLeft = whichIt.offsetLeft; whichIt.style.pixelTop = whichIt.offsetTop; currentX = (event.clientX + document.body.scrollLeft); currentY = (event.clientY + document.body.scrollTop); } else { window.captureEvents(Event.MOUSEMOVE); if(checkFocus (e.pageX,e.pageY)) { whichIt = document.floater; StalkerTouchedX = e.pageX-document.floater.pageX; StalkerTouchedY = e.pageY-document.floater.pageY; } } return true; } function moveIt(e) { if (whichIt == null) { return false; } if(IE) { newX = (event.clientX + document.body.scrollLeft); newY = (event.clientY + document.body.scrollTop); distanceX = (newX - currentX); distanceY = (newY - currentY); currentX = newX; currentY = newY; whichIt.style.pixelLeft += distanceX; whichIt.style.pixelTop += distanceY; if(whichIt.style.pixelTop < document.body.scrollTop) whichIt.style.pixelTop = document.body.scrollTop; if(whichIt.style.pixelLeft < document.body.scrollLeft) whichIt.style.pixelLeft = document.body.scrollLeft; if(whichIt.style.pixelLeft > document.body.offsetWidth - document.body.scrollLeft - whichIt.style.pixelWidth - 20) whichIt.style.pixelLeft = document.body.offsetWidth - whichIt.style.pixelWidth - 20; if(whichIt.style.pixelTop > document.body.offsetHeight + document.body.scrollTop - whichIt.style.pixelHeight - 5) whichIt.style.pixelTop = document.body.offsetHeight + document.body.scrollTop - whichIt.style.pixelHeight - 5; event.returnValue = false; } else { whichIt.moveTo(e.pageX-StalkerTouchedX,e.pageY-StalkerTouchedY); if(whichIt.left < 0+self.pageXOffset) whichIt.left = 0+self.pageXOffset; if(whichIt.top < 0+self.pageYOffset) whichIt.top = 0+self.pageYOffset; if( (whichIt.left + whichIt.clip.width) >= (window.innerWidth+self.pageXOffset-17)) whichIt.left = ((window.innerWidth+self.pageXOffset)-whichIt.clip.width)-17; if( (whichIt.top + whichIt.clip.height) >= (window.innerHeight+self.pageYOffset+50)) whichIt.top = ((window.innerHeight+self.pageYOffset)-whichIt.clip.height)-17; return false; } return false; } function dropIt() { whichIt = null; if(NS) window.releaseEvents (Event.MOUSEMOVE); return true; } if(NS) { window.captureEvents(Event.MOUSEUPEvent.MOUSEDOWN); window.onmousedown = grabIt; window.onmousemove = moveIt; window.onmouseup = dropIt; } if(IE) { document.onmousedown = grabIt; document.onmousemove = moveIt; document.onmouseup = dropIt; } if(NS || IE) action = window.setInterval("heartBeat()",1); -->
JavaScript
<!-- var fixupPos = false; var canMove = false; var leftLeaning = 0; //异步上传缩略图相关变量 var nForm = null; var nFrame = null; var picnameObj = null; var vImg = null; function $Nav() { if(window.navigator.userAgent.indexOf("MSIE")>=1) return 'IE'; else if(window.navigator.userAgent.indexOf("Firefox")>=1) return 'FF'; else return "OT"; } function $Obj(objname) { return document.getElementById(objname); } //旧的颜色选择框(已经过期) function ShowColor() { var fcolor=showModalDialog("img/color.htm?ok",false,"dialogWidth:106px;dialogHeight:110px;status:0;dialogTop:"+(+120)+";dialogLeft:"+(+120)); if(fcolor!=null && fcolor!="undefined") document.form1.color.value = fcolor; } function ColorSel(c, oname) { var tobj = $Obj(oname); if( !tobj ) tobj = eval('document.form1.' + oname); if( !tobj ) { $Obj('colordlg').style.display = 'none'; return false; } else { tobj.value = c; $Obj('colordlg').style.display = 'none'; return true; } } function ShowColor(e, o) { LoadNewDiv(e, 'img/colornew.htm', 'colordlg'); } function ShowHide(objname) { var obj = $Obj(objname); if(obj.style.display != "none" ) obj.style.display = "none"; else obj.style.display = "block"; } function ShowHideT(objname) { var obj = $Obj(objname); if(obj.style.display != "none" ) obj.style.display = "none"; else obj.style.display = ($Nav()=="IE" ? "block" : "table"); } function ShowObj(objname) { var obj = $Obj(objname); obj.style.display = ($Nav()=="IE" ? "block" : "table"); } function ShowObjRow(objname) { var obj = $Obj(objname); obj.style.display = ($Nav()=="IE" ? "block" : "table-row"); } function AddTypeid2() { ShowObjRow('typeid2tr'); //$Obj('typeid2ct').innerHTML = $Obj('typeidct').innerHTML.replace('typeid','typeid2'); } function HideObj(objname) { var obj = $Obj(objname); obj.style.display = "none"; } function ShowItem1() { ShowObj('head1'); ShowObj('needset'); HideObj('head2'); HideObj('adset'); } function ShowItem2() { ShowObj('head2'); ShowObj('adset'); HideObj('head1'); HideObj('needset'); } function SeePic(img,f) { if( f.value != '' ) img.src = f.value; } function SeePicNew(f, imgdid, frname, hpos, acname) { var newobj = null; if(f.value=='') return ; vImg = $Obj(imgdid); picnameObj = document.getElementById('picname'); nFrame = $Nav()=='IE' ? eval('document.frames.'+frname) : $Obj(frname); nForm = f.form; //修改form的action等参数 if(nForm.detachEvent) nForm.detachEvent("onsubmit", checkSubmit); else nForm.removeEventListener("submit", checkSubmit, false); nForm.action = 'archives_do.php'; nForm.target = frname; nForm.dopost.value = 'uploadLitpic'; nForm.submit(); picnameObj.value = ''; newobj = $Obj('uploadwait'); if(!newobj) { newobj = document.createElement("DIV"); newobj.id = 'uploadwait'; newobj.style.position = 'absolute'; newobj.className = 'uploadwait'; newobj.style.width = 120; newobj.style.height = 20; newobj.style.top = hpos; newobj.style.left = 100; newobj.style.display = 'block'; document.body.appendChild(newobj); newobj.innerHTML = '<img src="img/loadinglit.gif" width="16" height="16" alit="" />上传中...'; } newobj.style.display = 'block'; //提交后还原form的action等参数 nForm.action = acname; nForm.dopost.value = 'save'; nForm.target = ''; nForm.litpic.disabled = true; //nForm.litpic = null; //if(nForm.attachEvent) nForm.attachEvent("onsubmit", checkSubmit); //else nForm.addEventListener("submit", checkSubmit, true); } function SelectFlash() { if($Nav()=='IE'){ var posLeft = window.event.clientX-300; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } window.open("../include/dialog/select_media.php?f=form1.flashurl", "popUpFlashWin", "scrollbars=yes,resizable=yes,statebar=no,width=500,height=350,left="+posLeft+", top="+posTop); } function SelectMedia(fname) { if($Nav()=='IE'){ var posLeft = window.event.clientX-200; var posTop = window.event.clientY; } else{ var posLeft = 100;var posTop = 100; } window.open("../include/dialog/select_media.php?f="+fname, "popUpFlashWin", "scrollbars=yes,resizable=yes,statebar=no,width=500,height=350,left="+posLeft+", top="+posTop); } function SelectSoft(fname) { if($Nav()=='IE'){ var posLeft = window.event.clientX-200; var posTop = window.event.clientY-50; } else{ var posLeft = 100; var posTop = 100; } window.open("../include/dialog/select_soft.php?f="+fname, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=400,left="+posLeft+", top="+posTop); } function SelectImage(fname,stype) { if($Nav()=='IE'){ var posLeft = window.event.clientX-100; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } if(!fname) fname = 'form1.picname'; if(!stype) stype = ''; window.open("../include/dialog/select_images.php?f="+fname+"&imgstick="+stype, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=650,height=400,left="+posLeft+", top="+posTop); } function imageCut(fname) { if($Nav()=='IE'){ var posLeft = window.event.clientX-100; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } if(!fname) fname = 'picname'; file = document.getElementById(fname).value; if(file == '') { alert('请先选择网站内已上传的图片'); return false; } window.open("imagecut.php?f="+fname+"&file="+file, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=800,height=600,left="+posLeft+", top="+posTop); } function SelectImageN(fname,stype,vname) { if($Nav()=='IE'){ var posLeft = window.event.clientX-100; var posTop = window.event.clientY; } else{ var posLeft = 100; var posTop = 100; } if(!fname) fname = 'form1.picname'; if(!stype) stype = ''; window.open("../include/dialog/select_images.php?f="+fname+"&imgstick="+stype+"&v="+vname, "popUpImagesWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=400,left="+posLeft+", top="+posTop); } function SelectKeywords(f) { if($Nav()=='IE'){ var posLeft = window.event.clientX-350; var posTop = window.event.clientY-200; } else{ var posLeft = 100; var posTop = 100; } window.open("article_keywords_select.php?f="+f, "popUpkwWin", "scrollbars=yes,resizable=yes,statebar=no,width=600,height=450,left="+posLeft+", top="+posTop); } function InitPage() { var selsource = $Obj('selsource'); var selwriter = $Obj('selwriter'); var titlechange = $Obj('title'); var colorbt = $Obj('color'); if(selsource){ selsource.onmousedown=function(e){ SelectSource(e); } } if(selwriter){ selwriter.onmousedown=function(e){ SelectWriter(e); } } if(titlechange){ titlechange.onchange=function(e){ TestHasTitle(e); } } if(colorbt){ colorbt.onmousedown=function(e){ ShowColor2(e); } } } function OpenMyWin(surl) { window.open(surl, "popUpMyWin", "scrollbars=yes,resizable=yes,statebar=no,width=500,height=350,left=200, top=100"); } function OpenMyWinCoOne(surl) { window.open(surl, "popUpMyWin2", "scrollbars=yes,resizable=yes,statebar=no,width=700,height=450,left=100,top=50"); } function PutSource(str) { var osource = $Obj('source'); if(osource) osource.value = str; $Obj('mysource').style.display = 'none'; ChangeFullDiv('hide'); } function PutWriter(str) { var owriter = $Obj('writer'); if(owriter) owriter.value = str; $Obj('mywriter').style.display = 'none'; ChangeFullDiv('hide'); } function ClearDivCt(objname) { if(!$Obj(objname)) return; $Obj(objname).innerHTML = ''; $Obj(objname).style.display = 'none'; ChangeFullDiv("hide"); } function ChangeFullDiv(showhide) { var newobj = $Obj('fullpagediv'); if(showhide=='show') { if(!newobj) { newobj = document.createElement("DIV"); newobj.id = 'fullpagediv'; newobj.style.position='absolute'; newobj.className = 'fullpagediv'; document.body.appendChild(newobj); } else { newobj.style.display = 'block'; } } else { if(newobj) newobj.style.display = 'none'; } } function SelectSource(e) { LoadNewDiv(e,'article_select_sw.php?t=source&k=8&rnd='+Math.random(), 'mysource'); //ChangeFullDiv('show'); } function SelectWriter(e) { LoadNewDiv(e,'article_select_sw.php?t=writer&k=8&rnd='+Math.random(), 'mywriter'); //ChangeFullDiv('show'); } function LoadNewDiv(e,surl,oname) { if($Nav()=='IE') { var posLeft = window.event.clientX-20; var posTop = window.event.clientY-30; posTop += document.body.scrollTop; } else { var posLeft = e.pageX-20; var posTop = e.pageY-30; } posLeft = posLeft - 100; var newobj = $Obj(oname); if(!newobj){ newobj = document.createElement("DIV"); newobj.id = oname; newobj.style.position = 'absolute'; newobj.className = oname; newobj.className += ' dlgws'; newobj.style.top = posTop; newobj.style.left = posLeft; document.body.appendChild(newobj); } else{ newobj.style.display = "block"; } if(newobj.innerHTML.length<10){ var myajax = new DedeAjax(newobj); myajax.SendGet(surl); } } function TestHasTitle(e) { LoadNewDiv2(e,'article_test_title.php?t='+$Obj('title').value,'mytitle',"dlgTesttitle"); } function LoadNewDiv2(e,surl,oname,dlgcls) { var posLeft = 300; var posTop = 50; var newobj = $Obj(oname); if(!newobj) { newobj = document.createElement("DIV"); newobj.id = oname; newobj.style.position='absolute'; newobj.className = dlgcls; newobj.style.top = posTop; newobj.style.left = posLeft; newobj.style.display = 'none'; document.body.appendChild(newobj); } newobj.innerHTML = ''; var myajax = new DedeAjax(newobj); myajax.SendGet2(surl); if(newobj.innerHTML=='') newobj.style.display = 'none'; else newobj.style.display = 'block'; DedeXHTTP = null; } function ShowUrlTr() { var jumpTest = $Obj('flagsj'); var jtr = $Obj('redirecturltr'); var jf = $Obj('redirecturl'); if(jumpTest.checked) jtr.style.display = "block"; else{ jf.value = ''; jtr.style.display = "none"; } } function ShowUrlTrEdit() { ShowUrlTr(); var jumpTest = $Obj('isjump'); var rurl = $Obj('redirecturl'); if(!jumpTest.checked) rurl.value=""; } function CkRemote() { document.getElementById('picname').value = ''; } //载入指定宽高的AJAX窗体 function LoadQuickDiv(e, surl, oname, w, h) { if($Nav()=='IE') { if(window.event) { var posLeft = window.event.clientX - 20; var posTop = window.event.clientY - 30; } else { var posLeft = e.clientX - 20; var posTop = e.clientY + 30; } } else { var posLeft = e.pageX - 20; var posTop = e.pageY - 30; } posTop += MyGetScrollTop(); posLeft = posLeft - 400; //固定位置的高度 if(fixupPos) { posLeft = posTop = 50; } var newobj = $Obj(oname); if(!newobj) { newobj = document.createElement("DIV"); newobj.id = oname; newobj.style.position = 'absolute'; newobj.className = 'pubdlg'; newobj.style.width = w; newobj.style.height = h; document.body.appendChild(newobj); } if(posTop > 500) posTop = 500; if(posLeft < 50) posLeft = 50; newobj.style.top = posTop; newobj.style.left = posLeft; newobj.innerHTML = '<div style="margin-top:10px;margin-left:10px;"><img src="img/loadinglit.gif" /> Loading...</div>'; newobj.style.display = 'block'; var myajax = new DedeAjax(newobj); myajax.SendGet(surl); fixupPos = false; } function MyGetScrollTop() { return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; } //通用事件获取接口 function getEvent() { if($Nav()=='IE') return window.event; func=getEvent.caller; while(func!=null) { var arg0 = func.arguments[0]; if(arg0) { if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)) { return arg0; } } func=func.caller; } return null; } //模拟ondrop事件相关代码 /*---------------------------- leftLeaning = 300; 如果对象内容固定,用onmousedown=DropStart去除底下的DropStop newobj.ondblclick = DropStart; newobj.onmousemove = DropMove; newobj.onmousedown = DropStop; ----------------------------*/ function DropStart() { this.style.cursor = 'move'; } function DropStop() { this.style.cursor = 'default'; } function DropMove() { if(this.style.cursor != 'move') return; var event = getEvent(); if($Nav()=='IE') { var posLeft = event.clientX-20; var posTop = event.clientY-30; posTop += document.body.scrollTop; } else { var posLeft = event.pageX-20; var posTop = event.pageY-30; } this.style.top = posTop; this.style.left = posLeft-leftLeaning; } //对指定的元素绑定move事件 /*----------------------------- onmousemove="DropMoveHand('divname', 225);" onmousedown="DropStartHand();" onmouseup="DropStopHand();" -----------------------------*/ function DropStartHand() { canMove = (canMove ? false : true); } function DropStopHand() { canMove = false; } function DropMoveHand(objid, mleftLeaning) { var event = getEvent(); var obj = $Obj(objid); if(!canMove) return; if($Nav()=='IE') { var posLeft = event.clientX-20; var posTop = event.clientY-20; posTop += document.body.scrollTop; } else { var posLeft = event.pageX-20; var posTop = event.pageY-20; } obj.style.top = posTop; obj.style.left = posLeft - mleftLeaning; } //复制内容到剪切板 function copyToClipboard(txt) { if(txt==null || txt=='') { alert("没有选择任何内容!"); return; } if(window.clipboardData) { window.clipboardData.clearData(); window.clipboardData.setData("Text", txt); } else if(navigator.userAgent.indexOf('Opera') != -1) { window.location = txt; } else { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'"); } var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); if (!clip) return; var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); if (!trans) return; trans.addDataFlavor('text/unicode'); var str = new Object(); var len = new Object(); var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); var copytext = txt; str.data = copytext; trans.setTransferData("text/unicode",str,copytext.length*2); var clipid = Components.interfaces.nsIClipboard; if (!clip) return false; clip.setData(trans,null,clipid.kGlobalClipboard); } } function getSelTxt() { var g, r; if(document.all){ g = document.selection.createRange().text; }else{ g = document.getSelection(); } return g; } //显示栏目Map地图 function ShowCatMap(e, obj, cid, targetId, oldvalue) { fixupPos = true; LoadQuickDiv(e, 'archives_do.php?dopost=getCatMap&targetid='+targetId+'&channelid='+cid+'&oldvalue='+oldvalue+'&rnd='+Math.random(), 'getCatMap', '700px', '500px'); ChangeFullDiv('show'); } function getSelCat(targetId) { var selBox = document.quicksel.seltypeid; var targetObj = $Obj(targetId); var selvalue = ''; //副栏目(多选) if(targetId=='typeid2') { var j = 0; for(var i=0; i< selBox.length; i++) { if(selBox[i].checked) { j++; if(j==10) break; selvalue += (selvalue=='' ? selBox[i].value : ','+selBox[i].value); } } if(targetObj) targetObj.value = selvalue; } //主栏目(单选) else { if(selBox) { for(var i=0; i< selBox.length; i++) { if(selBox[i].checked) selvalue = selBox[i].value; } } if(selvalue=='') { alert('你没有选中任何项目!'); return ; } if(targetObj) { for(var j=0; j < targetObj.length; j++) { op=targetObj.options[j]; if(op.value==selvalue) op.selected=true; } } } HideObj("getCatMap"); ChangeFullDiv("hide"); } //收费 免费 $(document).ready(function(){ var isfree = $("input:radio[@name=isfree]:checked"); if(isfree.val() == '免费'){ $("input:text[@name=integral]").parent().parent().parent().parent().hide(); }else{ } $("input:radio[@name=isfree]").bind("click",function(){ if($(this).val() == "免费"){ $("input:text[@name=integral]").val(0); $("input:text[@name=integral]").parent().parent().parent().parent().hide(); }else{ $("input:text[@name=integral]").parent().parent().parent().parent().show(); } }); }); -->
JavaScript
var ie = document.all != null; var moz = !ie && document.getElementById != null && document.layers == null; /* * Extends the event object with srcElement, cancelBubble, returnValue, * fromElement and toElement */ function extendEventObject() { Event.prototype.__defineSetter__("returnValue", function (b) { if (!b) this.preventDefault(); }); Event.prototype.__defineSetter__("cancelBubble", function (b) { if (b) this.stopPropagation(); }); Event.prototype.__defineGetter__("srcElement", function () { var node = this.target; while (node.nodeType != 1) node = node.parentNode; return node; }); Event.prototype.__defineGetter__("fromElement", function () { var node; if (this.type == "mouseover") node = this.relatedTarget; else if (this.type == "mouseout") node = this.target; if (!node) return; while (node.nodeType != 1) node = node.parentNode; return node; }); Event.prototype.__defineGetter__("toElement", function () { var node; if (this.type == "mouseout") node = this.relatedTarget; else if (this.type == "mouseover") node = this.target; if (!node) return; while (node.nodeType != 1) node = node.parentNode; return node; }); Event.prototype.__defineGetter__("offsetX", function () { return this.layerX; }); Event.prototype.__defineGetter__("offsetY", function () { return this.layerY; }); } /* * Emulates element.attachEvent as well as detachEvent */ function emulateAttachEvent() { HTMLDocument.prototype.attachEvent = HTMLElement.prototype.attachEvent = function (sType, fHandler) { var shortTypeName = sType.replace(/on/, ""); fHandler._ieEmuEventHandler = function (e) { window.event = e; return fHandler(); }; this.addEventListener(shortTypeName, fHandler._ieEmuEventHandler, false); }; HTMLDocument.prototype.detachEvent = HTMLElement.prototype.detachEvent = function (sType, fHandler) { var shortTypeName = sType.replace(/on/, ""); if (typeof fHandler._ieEmuEventHandler == "function") this.removeEventListener(shortTypeName, fHandler._ieEmuEventHandler, false); else this.removeEventListener(shortTypeName, fHandler, true); }; } /* * This function binds the event object passed along in an * event to window.event */ function emulateEventHandlers(eventNames) { for (var i = 0; i < eventNames.length; i++) { document.addEventListener(eventNames[i], function (e) { window.event = e; }, true); // using capture } } /* * Simple emulation of document.all * this one is far from complete. Be cautious */ function emulateAllModel() { var allGetter = function () { var a = this.getElementsByTagName("*"); var node = this; a.tags = function (sTagName) { return node.getElementsByTagName(sTagName); }; return a; }; HTMLDocument.prototype.__defineGetter__("all", allGetter); HTMLElement.prototype.__defineGetter__("all", allGetter); } function extendElementModel() { HTMLElement.prototype.__defineGetter__("parentElement", function () { if (this.parentNode == this.ownerDocument) return null; return this.parentNode; }); HTMLElement.prototype.__defineGetter__("children", function () { var tmp = []; var j = 0; var n; for (var i = 0; i < this.childNodes.length; i++) { n = this.childNodes[i]; if (n.nodeType == 1) { tmp[j++] = n; if (n.name) { // named children if (!tmp[n.name]) tmp[n.name] = []; tmp[n.name][tmp[n.name].length] = n; } if (n.id) // child with id tmp[n.id] = n } } return tmp; }); HTMLElement.prototype.contains = function (oEl) { if (oEl == this) return true; if (oEl == null) return false; return this.contains(oEl.parentNode); }; } /* document.defaultView.getComputedStyle(el1,<BR>null).getPropertyValue('top'); */ function emulateCurrentStyle(properties) { HTMLElement.prototype.__defineGetter__("currentStyle", function () { var cs = {}; var el = this; for (var i = 0; i < properties.length; i++) { //cs.__defineGetter__(properties[i], function () { // window.status = "i: " + i ; // return document.defaultView.getComputedStyle(el, null).getPropertyValue(properties[i]); //}); cs.__defineGetter__(properties[i], encapsulateObjects(el, properties[i])); } return cs; }); } // used internally for emualteCurrentStyle function encapsulateObjects(el, sProperty) { return function () { return document.defaultView.getComputedStyle(el, null).getPropertyValue(sProperty); }; } function emulateHTMLModel() { // This function is used to generate a html string for the text properties/methods // It replaces '\n' with "<BR"> as well as fixes consecutive white spaces // It also repalaces some special characters function convertTextToHTML(s) { s = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<BR>"); while (/\s\s/.test(s)) s = s.replace(/\s\s/, "&nbsp; "); return s.replace(/\s/g, " "); } HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) { var df; // : DocumentFragment var r = this.ownerDocument.createRange(); switch (String(sWhere).toLowerCase()) { case "beforebegin": r.setStartBefore(this); df = r.createContextualFragment(sHTML); this.parentNode.insertBefore(df, this); break; case "afterbegin": r.selectNodeContents(this); r.collapse(true); df = r.createContextualFragment(sHTML); this.insertBefore(df, this.firstChild); break; case "beforeend": r.selectNodeContents(this); r.collapse(false); df = r.createContextualFragment(sHTML); this.appendChild(df); break; case "afterend": r.setStartAfter(this); df = r.createContextualFragment(sHTML); this.parentNode.insertBefore(df, this.nextSibling); break; } }; HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) { var r = this.ownerDocument.createRange(); r.setStartBefore(this); var df = r.createContextualFragment(sHTML); this.parentNode.replaceChild(df, this); return sHTML; }); HTMLElement.prototype.__defineGetter__("canHaveChildren", function () { switch (this.tagName) { case "AREA": case "BASE": case "BASEFONT": case "COL": case "FRAME": case "HR": case "IMG": case "BR": case "INPUT": case "ISINDEX": case "LINK": case "META": case "PARAM": return false; } return true; }); HTMLElement.prototype.__defineGetter__("outerHTML", function () { var attr, attrs = this.attributes; var str = "<" + this.tagName; for (var i = 0; i < attrs.length; i++) { attr = attrs[i]; if (attr.specified) str += " " + attr.name + '="' + attr.value + '"'; } if (!this.canHaveChildren) return str + ">"; return str + ">" + this.innerHTML + "</" + this.tagName + ">"; }); HTMLElement.prototype.__defineSetter__("innerText", function (sText) { this.innerHTML = convertTextToHTML(sText); return sText; }); var tmpGet; HTMLElement.prototype.__defineGetter__("innerText", tmpGet = function () { var r = this.ownerDocument.createRange(); r.selectNodeContents(this); return r.toString(); }); HTMLElement.prototype.__defineSetter__("outerText", function (sText) { this.outerHTML = convertTextToHTML(sText); return sText; }); HTMLElement.prototype.__defineGetter__("outerText", tmpGet); HTMLElement.prototype.insertAdjacentText = function (sWhere, sText) { this.insertAdjacentHTML(sWhere, convertTextToHTML(sText)); }; }
JavaScript
<!-- function CheckSubmit() { return true; } -->
JavaScript
<!-- function selAll() { var celements = document.getElementsByName('aids[]'); for(i=0;i<celements.length;i++) { if(!celements[i].checked) celements[i].checked = true; else celements[i].checked = false; } } function noselAll() { var celements = document.getElementsByName('aids[]'); for(i=0;i<celements.length;i++) { if(celements[i].checked = true) { celements[i].checked = false; } } } function delkey() { if(window.confirm("你确实要删除选定的关键字么?")) { document.form3.dopost.value = 'del'; document.form3.submit(); } } function diskey() { if(window.confirm("你确实要禁用选定的关键字么?")) { document.form3.dopost.value = 'dis'; document.form3.submit(); } } function enakey() { if(window.confirm("你确实要启用选定的关键字么?")) { document.form3.dopost.value = 'ena'; document.form3.submit(); } } function urlkey() { if(window.confirm("你确实要更新选定的关键字的网址么?")) { document.form3.dopost.value = 'url'; document.form3.submit(); } } function rankey() { if(window.confirm("你确实要改变选定的关键字的频率么?")) { document.form3.dopost.value = 'ran'; document.form3.submit(); } } <!--批量删除搜多关键字--> function delall() { if(window.confirm("你确实要删除选定的关键字么?")) { document.form3.dopost.value = 'delall'; document.form3.submit(); } } -->
JavaScript
document.write("<style type=\"text/css\">.close{float:right;cursor:default}</style>") function editTitle(aid) { var show = document.getElementById("show_news"); var myajax = new DedeAjax(show,false,false,"","",""); myajax.SendGet2("catalog_edit.php?dopost=time&id="+aid); DedeXHTTP = null; } function $(id){ return document.getElementById(id)} function AlertMsg(title,id){ var msgw,msgh,msgbg,msgcolor,bordercolor,titlecolor,titlebg,content; //弹出窗口设置 msgw = 600; //窗口宽度 msgh = 400; //窗口高度 msgbg = "#FFF"; //内容背景 msgcolor = "#000"; //内容颜色 bordercolor = "#5A6D58"; //边框颜色 titlecolor = "#254015"; //标题颜色 titlebg = "#369 url(img/tbg.gif)"; //标题背景 //遮罩背景设置 content = "<div id=show_news>对不起,载入失败</div>"; var sWidth,sHeight; sWidth = screen.availWidth; if(screen.availHeight > document.body.scrollHeight){ sHeight = screen.availHeight; //少于一屏 }else{ sHeight = document.body.scrollHeight; //多于一屏 } //创建遮罩背景 var maskObj = document.createElement("div"); maskObj.setAttribute('id','maskdiv'); maskObj.style.position = "absolute"; maskObj.style.top = "0"; maskObj.style.left = "0"; maskObj.style.background = "#777"; maskObj.style.filter = "Alpha(opacity=30);"; maskObj.style.opacity = "0.3"; maskObj.style.width = sWidth + "px"; maskObj.style.height = sHeight + "px"; maskObj.style.zIndex = "10000"; document.body.appendChild(maskObj); //创建弹出窗口 var msgObj = document.createElement("div") msgObj.setAttribute("id","msgdiv"); msgObj.style.position ="absolute"; //msgObj.style.top = (screen.availHeight - msgh) / 4 + "px"; //msgObj.style.left = (screen.availWidth - msgw) / 2 + "px"; msgObj.style.top = "100px"; msgObj.style.left = "100px"; msgObj.style.width = msgw + "px"; msgObj.style.height = msgh + "px"; msgObj.style.fontSize = "12px"; msgObj.style.background = msgbg; msgObj.style.border = "1px solid " + bordercolor; msgObj.style.zIndex = "10001"; //创建标题 var thObj = document.createElement("div"); thObj.setAttribute("id","msgth"); thObj.className = "DragAble"; thObj.title = "按住鼠标左键可以拖动窗口!"; thObj.style.cursor = "move"; thObj.style.padding = "4px 6px"; thObj.style.color = titlecolor; thObj.style.fontWeight = 'bold'; thObj.style.background = titlebg; var titleStr = "<a class='close' title='关闭' style='cursor:pointer' onclick='CloseMsg()'>关闭</a>"+"<span>"+ title +"</span>"; thObj.innerHTML = titleStr; //创建内容 var bodyObj = document.createElement("div"); bodyObj.setAttribute("id","msgbody"); bodyObj.style.padding = "0px"; bodyObj.style.lineHeight = "1.5em"; var txt = document.createTextNode(content); bodyObj.appendChild(txt); bodyObj.innerHTML = content; //生成窗口 document.body.appendChild(msgObj); $("msgdiv").appendChild(thObj); $("msgdiv").appendChild(bodyObj); editTitle(id); } function CloseMsg(){ //移除对象 document.body.removeChild($("maskdiv")); $("msgdiv").removeChild($("msgth")); $("msgdiv").removeChild($("msgbody")); document.body.removeChild($("msgdiv")); } //拖动窗口 var ie = document.all; var nn6 = document.getElementById&&!document.all; var isdrag = false; var y,x; var oDragObj; function moveMouse(e) { if (isdrag) { oDragObj.style.top = (nn6 ? nTY + e.clientY - y : nTY + event.clientY - y)+"px"; oDragObj.style.left = (nn6 ? nTX + e.clientX - x : nTX + event.clientX - x)+"px"; return false; } } function initDrag(e) { var oDragHandle = nn6 ? e.target : event.srcElement; var topElement = "HTML"; while (oDragHandle.tagName != topElement && oDragHandle.className != "DragAble") { oDragHandle = nn6 ? oDragHandle.parentNode : oDragHandle.parentElement; } if (oDragHandle.className=="DragAble") { isdrag = true; oDragObj = oDragHandle.parentNode; nTY = parseInt(oDragObj.style.top); y = nn6 ? e.clientY : event.clientY; nTX = parseInt(oDragObj.style.left); x = nn6 ? e.clientX : event.clientX; document.onmousemove = moveMouse; return false; } } document.onmousedown = initDrag; document.onmouseup = new Function("isdrag=false");
JavaScript
var MenuWidth = 120; var ItemHeight = 16; var ItemNumber = 0; function CurNav() { if(window.navigator.userAgent.indexOf("MSIE")>=1) return 'IE'; else if(window.navigator.userAgent.indexOf("Firefox")>=1) return 'FF'; else return 'OT'; } function InsertHtm(op,code,isStart) { if(CurNav()=='IE') { op.insertAdjacentHTML(isStart ? "beforeEnd" : "afterEnd",code); } else { var range=op.ownerDocument.createRange(); range.setStartBefore(op); var fragment = range.createContextualFragment(code); if(isStart) op.insertBefore(fragment,op.firstChild); else op.appendChild(fragment); } } ContextMenu.WebFX_PopUp = null; ContextMenu.WbFX_PopUpcss = null; ContextMenu.intializeContextMenu=function() { InsertHtm(document.body,'<iframe src="#" scrolling="no" class="WebFX-ContextMenu" marginwidth="0" marginheight="0" frameborder="0" style="position:absolute;display:none;z-index:50000000;" id="WebFX_PopUp"></iframe>',true); if(CurNav()=='IE') WebFX_PopUp = document.frames['WebFX_PopUp']; else WebFX_PopUp = document.getElementById('WebFX_PopUp'); WebFX_PopUpcss = document.getElementById('WebFX_PopUp'); WebFX_PopUpcss.onfocus = function(){WebFX_PopUpcss.style.display="inline"}; WebFX_PopUpcss.onblur = function(){WebFX_PopUpcss.style.display="none"}; if(CurNav()=='IE') document.body.attachEvent("onmousedown",function(){WebFX_PopUpcss.style.display="none"}); else document.addEventListener("onblur",function(){WebFX_PopUpcss.style.display="none"},false); if(CurNav()=='IE') document.attachEvent("onblur",function(){WebFX_PopUpcss.style.display="none"}); else document.addEventListener("onblur",function(){WebFX_PopUpcss.style.display="none"},false); } function ContextSeperator(){} function ContextMenu(){} ContextMenu.showPopup=function(x,y) { WebFX_PopUpcss.style.display = "block" } ContextMenu.display=function(evt,popupoptions) { var eobj,x,y; eobj = evt ? evt:(window.event ? window.event : null); if(CurNav()=='IE') { x = eobj.x;y = eobj.y } else { x = eobj.clientX; y = eobj.clientY; } ContextMenu.populatePopup(popupoptions,window) ContextMenu.showPopup(x,y); ContextMenu.fixSize(); ContextMenu.fixPos(x,y); eobj.cancelBubble = true; eobj.returnValue = false; } //TODO ContextMenu.getScrollTop=function() { return document.body.scrollTop; //window.pageXOffset and window.pageYOffset for moz } ContextMenu.getScrollLeft=function() { return document.body.scrollLeft; } ContextMenu.fixPos=function(x,y) { var docheight,docwidth,dh,dw; if(!x) { x=0; y=0; } docheight = document.body.clientHeight; docwidth = document.body.clientWidth; dh = (WebFX_PopUpcss.offsetHeight+y) - docheight; dw = (WebFX_PopUpcss.offsetWidth+x) - docwidth; if(dw>0) { WebFX_PopUpcss.style.left = (x - dw) + ContextMenu.getScrollLeft() + "px"; } else { WebFX_PopUpcss.style.left = x + ContextMenu.getScrollLeft(); } if(dh>0) { WebFX_PopUpcss.style.top = (y - dh) + ContextMenu.getScrollTop() + "px" } else { WebFX_PopUpcss.style.top = y + ContextMenu.getScrollTop(); } } ContextMenu.fixSize=function() { WebFX_PopUpcss.style.height = ItemHeight * ItemNember + "px"; WebFX_PopUpcss.style.width = MenuWidth + "px"; ItemNember = 0; } ContextMenu.populatePopup=function(arr,win) { var alen,i,tmpobj,doc,height,htmstr; alen = arr.length; ItemNember = alen; if(CurNav()=='IE') doc = WebFX_PopUp.document; else doc = WebFX_PopUp.contentWindow.document; doc.body.innerHTML = ''; if (doc.getElementsByTagName("LINK").length == 0) { doc.open(); doc.write('<html><head><link rel="StyleSheet" type="text/css" href="js/contextmenu.css"></head><body></body></html>'); doc.close(); } for(i=0;i<alen;i++) { if(arr[i].constructor==ContextItem) { tmpobj=doc.createElement("DIV"); tmpobj.noWrap = true; tmpobj.className = "WebFX-ContextMenu-Item"; if(arr[i].disabled) { htmstr = '<span class="WebFX-ContextMenu-DisabledContainer">' htmstr += arr[i].text+'</span>' tmpobj.innerHTML = htmstr tmpobj.className = "WebFX-ContextMenu-Disabled"; tmpobj.onmouseover = function(){this.className="WebFX-ContextMenu-Disabled-Over"} tmpobj.onmouseout = function(){this.className="WebFX-ContextMenu-Disabled"} } else { tmpobj.innerHTML = arr[i].text; tmpobj.onclick = (function (f) { return function () { win.WebFX_PopUpcss.style.display='none' if (typeof(f)=="function"){ f(); } }; })(arr[i].action); tmpobj.onmouseover = function(){this.className="WebFX-ContextMenu-Over"} tmpobj.onmouseout = function(){this.className="WebFX-ContextMenu-Item"} } doc.body.appendChild(tmpobj); } else { doc.body.appendChild(doc.createElement("DIV")).className = "WebFX-ContextMenu-Separator"; } } doc.body.className = "WebFX-ContextMenu-Body" ; doc.body.onselectstart = function(){return false;} } function ContextItem(str,fnc,disabled) { this.text = str; this.action = fnc; this.disabled = disabled || false; }
JavaScript
<!-- function showHide(objname) { //只对主菜单设置cookie var obj = document.getElementById(objname); if(objname.indexOf('_1')<0 || objname.indexOf('_10')>0) { if(obj.style.display == 'block' || obj.style.display =='') obj.style.display = 'none'; else obj.style.display = 'block'; return true; } //正常设置cookie var ckstr = getCookie('menuitems'); var ckstrs = null; var okstr =''; var ischange = false; if(ckstr==null) ckstr = ''; ckstrs = ckstr.split(','); objname = objname.replace('items',''); if(obj.style.display == 'block' || obj.style.display =='') { obj.style.display = 'none'; for(var i=0; i < ckstrs.length; i++) { if(ckstrs[i]=='') continue; if(ckstrs[i]==objname){ ischange = true; } else okstr += (okstr=='' ? ckstrs[i] : ','+ckstrs[i] ); } if(ischange) setCookie('menuitems',okstr,7); } else { obj.style.display = 'block'; ischange = true; for(var i=0; i < ckstrs.length; i++) { if(ckstrs[i]==objname) { ischange = false; break; } } if(ischange) { ckstr = (ckstr==null ? objname : ckstr+','+objname); setCookie('menuitems',ckstr,7); } } } //读写cookie函数 function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=") if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";",c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start,c_end)); } } return null } function setCookie(c_name,value,expiredays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie = c_name + "=" +escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()); //使设置的有效时间正确。增加toGMTString() } //检查以前用户展开的菜单项 var totalitem = 12; function CheckOpenMenu() { //setCookie('menuitems',''); var ckstr = getCookie('menuitems'); var curitem = ''; var curobj = null; //cross_obj = document.getElementById("staticbuttons"); //setInterval("initializeIT()",20); if(ckstr==null) { ckstr='1_1,2_1,3_1'; setCookie('menuitems',ckstr,7); } ckstr = ','+ckstr+','; for(i=0;i<totalitem;i++) { curitem = i+'_'+curopenItem; curobj = document.getElementById('items'+curitem); if(ckstr.indexOf(curitem) > 0 && curobj != null) { curobj.style.display = 'block'; } else { if(curobj != null) curobj.style.display = 'none'; } } } var curitem = 1; function ShowMainMenu(n) { var curLink = $DE('link'+curitem); var targetLink = $DE('link'+n); var curCt = $DE('ct'+curitem); var targetCt = $DE('ct'+n); if(curitem==n) return false; if(targetCt.innerHTML!='') { curCt.style.display = 'none'; targetCt.style.display = 'block'; curLink.className = 'mm'; targetLink.className = 'mmac'; curitem = n; } else { var myajax = new DedeAjax(targetCt); myajax.SendGet2("index_menu_load.php?openitem="+n); if(targetCt.innerHTML!='') { curCt.style.display = 'none'; targetCt.style.display = 'block'; curLink.className = 'mm'; targetLink.className = 'mmac'; curitem = n; } DedeXHTTP = null; } } -->
JavaScript
<!-- function checkSubmitAlb() { if(document.form1.title.value==''){ alert("档案标题不能为空!"); return false; } if(document.form1.typeid.value==0){ alert("请选择档案的主类别!"); return false; } document.form1.imagebody.value = $Obj('copyhtml').innerHTML; return true; } function TestGet() { LoadTestDiv(); } function checkMuList(psid,cmid) { if($Obj('pagestyle3').checked) { $Obj('cfgmulist').style.display = 'block'; $Obj('spagelist').style.display = 'none'; } else if($Obj('pagestyle1').checked) { $Obj('cfgmulist').style.display = 'none'; $Obj('spagelist').style.display = 'block'; } else { $Obj('cfgmulist').style.display = 'none'; $Obj('spagelist').style.display = 'none'; } } //图集,显示与隐藏zip文件选项 function ShowZipField(formitem,zipid,upid) { if(formitem.checked){ $Obj(zipid).style.display = 'block'; $Obj(upid).style.display = 'none'; //$Obj('handfield').style.display = 'none'; $Obj('formhtml').checked = false; $Obj('copyhtml').innerHTML = ''; }else { $Obj(zipid).style.display = 'none'; //$Obj('handfield').style.display = 'block'; } } //图集,显示与隐藏Html编辑框 function ShowHtmlField(formitem,htmlid,upid) { if($Nav()!="IE"){ alert("该方法不适用于非IE浏览器!"); return ; } if(formitem.checked){ $Obj(htmlid).style.display = 'block'; $Obj(upid).style.display = 'none'; //$Obj('handfield').style.display = 'none'; $Obj('formzip').checked = false; }else { $Obj(htmlid).style.display = 'none'; //$Obj('handfield').style.display = 'block'; $Obj('copyhtml').innerHTML = ''; } } function SeePicNewAlb(f, imgdid, frname, hpos, acname) { var newobj = null; if(f.value=='') return ; vImg = $Obj(imgdid); picnameObj = document.getElementById('picname'); nFrame = $Nav()=='IE' ? eval('document.frames.'+frname) : $Obj(frname); nForm = f.form; //修改form的action等参数 if(nForm.detachEvent) nForm.detachEvent("onsubmit", checkSubmitAlb); else nForm.removeEventListener("submit", checkSubmitAlb, false); nForm.action = 'archives_do.php'; nForm.target = frname; nForm.dopost.value = 'uploadLitpic'; nForm.submit(); picnameObj.value = ''; newobj = $Obj('uploadwait'); if(!newobj) { newobj = document.createElement("DIV"); newobj.id = 'uploadwait'; newobj.style.position = 'absolute'; newobj.className = 'uploadwait'; newobj.style.width = 120; newobj.style.height = 20; newobj.style.top = hpos; newobj.style.left = 100; document.body.appendChild(newobj); newobj.innerHTML = '<img src="img/loadinglit.gif" width="16" height="16" alit="" />上传中...'; } newobj.style.display = 'block'; //提交后还原form的action等参数 nForm.action = acname; nForm.dopost.value = 'save'; nForm.target = ''; nForm.litpic.disabled = true; //nForm.litpic = null; //if(nForm.attachEvent) nForm.attachEvent("onsubmit", checkSubmit); //else nForm.addEventListener("submit", checkSubmit, true); } //删除已经上传的图片 function DelAlbPic(pid) { var tgobj = $Obj('albCtok'+pid); var myajax = new DedeAjax(tgobj); myajax.SendGet2('swfupload.php?dopost=del&id='+pid); $Obj('thumbnails').removeChild(tgobj); } //删除已经上传的图片(编辑时用) function DelAlbPicOld(picfile, pid) { var tgobj = $Obj('albold'+pid); var myajax = new DedeAjax(tgobj); myajax.SendGet2('swfupload.php?dopost=delold&picfile='+picfile); $Obj('thumbnailsEdit').removeChild(tgobj); } -->
JavaScript
<!-- if(moz) { extendEventObject(); extendElementModel(); emulateAttachEvent(); } function delArc(mid){ var qstr=getCheckboxItem(); if(mid==0) mid = getOneItem(); location="member_do.php?id="+qstr+"&dopost=delmembers"; } //获得选中文件的文件名 function getCheckboxItem() { var allSel=""; if(document.form2.mid.value) return document.form2.mid.value; for(i=0;i<document.form2.mid.length;i++) { if(document.form2.mid[i].checked) { if(allSel=="") allSel=document.form2.mid[i].value; else allSel=allSel+"`"+document.form2.mid[i].value; } } return allSel; } //获得选中其中一个的id function getOneItem() { var allSel=""; if(document.form2.mid.value) return document.form2.mid.value; for(i=0;i<document.form2.mid.length;i++) { if(document.form2.mid[i].checked) { allSel = document.form2.mid[i].value; break; } } return allSel; } function selAll() { for(i=0;i<document.form2.mid.length;i++) { if(!document.form2.mid[i].checked) { document.form2.mid[i].checked=true; } } } function noSelAll() { for(i=0;i<document.form2.mid.length;i++) { if(document.form2.mid[i].checked) { document.form2.mid[i].checked=false; } } } -->
JavaScript
<!-- //xmlhttp和xmldom对象 DedeXHTTP = null; DedeXDOM = null; DedeContainer = null; //获取指定ID的元素 function $(eid){ return document.getElementById(eid); } function $DE(id) { return document.getElementById(id); } //参数 gcontainer 是保存下载完成的内容的容器 function DedeAjax(gcontainer){ DedeContainer = gcontainer; //post或get发送数据的键值对 this.keys = Array(); this.values = Array(); this.keyCount = -1; //http请求头 this.rkeys = Array(); this.rvalues = Array(); this.rkeyCount = -1; //请求头类型 this.rtype = 'text'; //初始化xmlhttp if(window.ActiveXObject){//IE6、IE5 try { DedeXHTTP = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { } if (DedeXHTTP == null) try { DedeXHTTP = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { } } else{ DedeXHTTP = new XMLHttpRequest(); } DedeXHTTP.onreadystatechange = function(){ if(DedeXHTTP.readyState == 4){ if(DedeXHTTP.status == 200){ DedeContainer.innerHTML = DedeXHTTP.responseText; DedeXHTTP = null; } else DedeContainer.innerHTML = "下载数据失败"; } else DedeContainer.innerHTML = "正在下载数据..."; }; //增加一个POST或GET键值对 this.AddKey = function(skey,svalue){ this.keyCount++; this.keys[this.keyCount] = skey; this.values[this.keyCount] = escape(svalue); }; //增加一个Http请求头键值对 this.AddHead = function(skey,svalue){ this.rkeyCount++; this.rkeys[this.rkeyCount] = skey; this.rvalues[this.rkeyCount] = svalue; }; //清除当前对象的哈希表参数 this.ClearSet = function(){ this.keyCount = -1; this.keys = Array(); this.values = Array(); this.rkeyCount = -1; this.rkeys = Array(); this.rvalues = Array(); }; //发送http请求头 this.SendHead = function(){ if(this.rkeyCount!=-1){ //发送用户自行设定的请求头 for(;i<=this.rkeyCount;i++){ DedeXHTTP.setRequestHeader(this.rkeys[i],this.rvalues[i]); } }  if(this.rtype=='binary'){ DedeXHTTP.setRequestHeader("Content-Type","multipart/form-data"); }else{ DedeXHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } }; //用Post方式发送数据 this.SendPost = function(purl){ var pdata = ""; var i=0; this.state = 0; DedeXHTTP.open("POST", purl, true); this.SendHead(); if(this.keyCount!=-1){ //post数据 for(;i<=this.keyCount;i++){ if(pdata=="") pdata = this.keys[i]+'='+this.values[i]; else pdata += "&"+this.keys[i]+'='+this.values[i]; } } DedeXHTTP.send(pdata); }; //用GET方式发送数据 this.SendGet = function(purl){ var gkey = ""; var i=0; this.state = 0; if(this.keyCount!=-1){ //get参数 for(;i<=this.keyCount;i++){ if(gkey=="") gkey = this.keys[i]+'='+this.values[i]; else gkey += "&"+this.keys[i]+'='+this.values[i]; } if(purl.indexOf('?')==-1) purl = purl + '?' + gkey; else purl = purl + '&' + gkey; } DedeXHTTP.open("GET", purl, true); this.SendHead(); DedeXHTTP.send(null); }; } // End Class DedeAjax //初始化xmldom function InitXDom(){ if(DedeXDOM!=null) return; var obj = null; if (typeof(DOMParser) != "undefined") { // Gecko、Mozilla、Firefox var parser = new DOMParser(); obj = parser.parseFromString(xmlText, "text/xml"); } else { // IE try { obj = new ActiveXObject("MSXML2.DOMDocument");} catch (e) { } if (obj == null) try { obj = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) { } } DedeXDOM = obj; }; -->
JavaScript
$(function(){ //文本框Style $(".txt").mouseover(function(){ $(this).addClass("txt_o"); }).mouseout(function(){ $(this).removeClass("txt_o"); }).focus(function(){ $(this).addClass("txt_s"); }).blur(function(){ $(this).removeClass("txt_s"); }); //表格折叠 $(".tform").find("tbody tr th[_show]").each(function(i){ //加入折叠提示 if($(this).attr("_show")=="no"){ $(this).append(" <button type=\"button\" class=\"tbody_up\"></button>"); }else{ $(this).append(" <button type=\"button\" class=\"tbody_down\"></button>"); } //折叠动作 $(this).click(function(){ if($(this).find("button[class^='tbody_']").attr("class")=="tbody_up"){ $(this).find("button[class^='tbody_']").attr("class","tbody_down"); $(this).parent("tr").parent("tbody").find("tr").not($(this).parent("tr")).hide(); }else if($(this).find("button[class^='tbody_']").attr("class")=="tbody_down"){ $(this).find("button[class^='tbody_']").attr("class","tbody_up"); $(this).parent("tr").parent("tbody").find("tr").not($(this).parent("tr")).show(); } }).mouseover(function(){ $(this).addClass("mouseon"); }).mouseout(function(){ $(this).removeClass("mouseon"); }).click(); }); //列表行高亮 $("table[_dlist*='light']").children("tbody").children("tr").mouseover(function(){ if($(this).attr("_nolight")!="yes")$(this).addClass("t_on"); }).mouseout(function(){ $(this).removeClass("t_on"); }); //列表行整行选择 $("table[_dlist*='check']").each(function(){ //处理行点击 $(this).find("tbody tr").click(function(){ checkbox = $(this).find("td input[type='checkbox']"); tr = $(this); if(checkbox.attr("checked")===false){ checkbox.attr("checked","checked"); tr.addClass("t_sl"); }else{ checkbox.removeAttr("checked"); tr.removeClass("t_sl"); } }); //处理checkbox点击 $(this).find("td input[type='checkbox']").click(function(){ tr = $(this).parent("td").parent("tr"); if($(this).attr("checked")===false){ $(this).attr("checked","checked"); tr.removeClass("t_sl"); }else{ $(this).removeAttr("checked"); tr.addClass("t_sl"); } }); //排除链接及按钮点击 $(this).find("tbody tr td a,tbody tr td button,tbody tr td table").click(function(){ tr = $(this).parent("td").parent("tr"); checkbox = tr.find("td input[type='checkbox']"); if(checkbox.attr("checked")===false){ checkbox.attr("checked","checked"); tr.removeClass("t_sl"); }else{ checkbox.removeAttr("checked"); tr.addClass("t_sl"); } }); }); //高亮初始化 setChecklight(); //全选按钮 $("button[_click='allSelect']").click(function(){ ckbox = $(this).parent("td").parent("tr").parent("tbody").find("td input[type='checkbox']"); ckbox.attr("checked","checked"); setChecklight(); }); //反选按钮 $("button[_click='unSelect']").click(function(){ ckbox = $(this).parent("td").parent("tr").parent("tbody").find("td input[type='checkbox']"); ckbox.each(function(){ $(this).attr("checked") === false ? $(this).attr("checked","checked") : $(this).removeAttr("checked"); }); setChecklight(); }); //自定义提交 $("button[_submit]").click(function(){ url = $(this).attr("_submit"); if(/\[new\].*/.test(url)){ url = url.replace(/\[new\]/,""); }else{ url = $(this).parents("form").attr("action")+url; } $(this).parents("form").attr("action",url).submit(); }); }); /*高亮初始化*/ function setChecklight(){ $(".tlist[_dlist*='check']").find("tbody tr td input[type='checkbox']").each(function(i){ tr = $(this).parent("td").parent("tr"); if($(this).attr("checked")){ tr.addClass("t_sl"); }else{ tr.removeClass("t_sl"); } }); } /*栏目跳转*/ function AC(mid){ f = $(window.parent.document); mlink = f.find("a[id='"+mid+"']"); if(mlink.size()>0){ box = mlink.parents("div[id^='menu_']"); boxid = box.attr("id").substring(5,128); if($("body").attr("class")!="showmenu")$("#togglemenu").click(); if(mlink.attr("_url")){ $("#menu").find("div[id^=menu]").hide(); box.show(); mlink.addClass("thisclass").blur().parents("#menu").find("ul li a").not(mlink).removeClass("thisclass"); if($("#mod_"+boxid).attr("class")==""){ $("#nav").find("a").removeClass("thisclass"); $("#nav").find("a[id='mod_"+boxid+"']").addClass("thisclass").blur(); } window.location.href = mlink.attr("_url"); }else if(mlink.attr("_open") && mlink.attr("_open")!=undefined){ window.open(mlink.attr("_open")); } } }
JavaScript
<!-- var thespeed = 5; var navIE = document.all && navigator.userAgent.indexOf("Firefox")==-1; var myspeed=0; $(function(){ //快捷菜单 bindQuickMenu(); //左侧菜单开关 LeftMenuToggle(); //全部功能开关 AllMenuToggle(); //取消菜单链接虚线 $(".head").find("a").click(function(){$(this).blur()}); $(".menu").find("a").click(function(){$(this).blur()}); /* //载入滚动消息 $.get('getdedesysmsg.php',function(data){ if(data != ''){ $(".scroll").html(data); $(".scroll").Scroll({line:1,speed:500,timer:3000}); } else { $(".scroll").html("无法读取织梦官方消息"); } }); */ }).keydown(function(event){//快捷键 if(event.keyCode ==116 ){ //url = $("#main").attr("src"); //main.location.href = url; //return false; } if(event.keyCode ==27 ){ $("#qucikmenu").slideToggle("fast") } }); function bindQuickMenu(){//快捷菜单 $("#ac_qucikmenu").bind("mouseenter",function(){ $("#qucikmenu").slideDown("fast"); }).dblclick(function(){ $("#qucikmenu").slideToggle("fast"); }).bind("mouseleave",function(){ hidequcikmenu=setTimeout('$("#qucikmenu").slideUp("fast");',700); $(this).bind("mouseenter",function(){clearTimeout(hidequcikmenu);}); }); $("#qucikmenu").bind("mouseleave",function(){ hidequcikmenu=setTimeout('$("#qucikmenu").slideUp("fast");',700); $(this).bind("mouseenter",function(){clearTimeout(hidequcikmenu);}); }).find("a").click(function(){ $(this).blur(); $("#qucikmenu").slideUp("fast"); //$("#ac_qucikmenu").text($(this).text()); }); } function LeftMenuToggle(){//左侧菜单开关 $("#togglemenu").click(function(){ if($("body").attr("class")=="showmenu"){ $("body").attr("class","hidemenu"); $(this).html("显示菜单"); }else{ $("body").attr("class","showmenu"); $(this).html("隐藏菜单"); } }); } function AllMenuToggle(){//全部功能开关 mask = $(".pagemask,.iframemask,.allmenu"); $("#allmenu").click(function(){ mask.show(); }); //mask.mousedown(function(){alert("123");}); mask.click(function(){mask.hide();}); } function AC(act){ //alert(act); mlink = $("a[id='"+act+"']"); if(mlink.size()>0){ box = mlink.parents("div[id^='menu_']"); boxid = box.attr("id").substring(5,128); if($("body").attr("class")!="showmenu")$("#togglemenu").click(); if(mlink.attr("_url")){ $("#menu").find("div[id^=menu]").hide(); box.show(); mlink.addClass("thisclass").blur().parents("#menu").find("ul li a").not(mlink).removeClass("thisclass"); if($("#mod_"+boxid).attr("class")==""){ $("#nav").find("a").removeClass("thisclass"); $("#nav").find("a[id='mod_"+boxid+"']").addClass("thisclass").blur(); } main.location.href = mlink.attr("_url"); }else if(mlink.attr("_open") && mlink.attr("_open")!=undefined){ window.open(mlink.attr("_open")); } } } /********************* * 滚动按钮设置 *********************/ function scrollwindow() { parent.frames['menu'].scrollBy(0,myspeed); } function initializeIT() { if (myspeed!=0) { scrollwindow(); } } //滚动插件 /* (function($){ $.fn.extend({ Scroll:function(opt,callback){ //参数初始化 if(!opt) var opt={}; var _this=this.eq(0).find("ul:first"); var lineH=_this.find("li:first").height(), //获取行高 line=opt.line?parseInt(opt.line,10):parseInt(this.height()/lineH,10), //每次滚动的行数,默认为一屏,即父容器高度 speed=opt.speed?parseInt(opt.speed,10):500, //卷动速度,数值越大,速度越慢(毫秒) timer=opt.timer?parseInt(opt.timer,10):3000; //滚动的时间间隔(毫秒) if(line==0) line=1; var upHeight=0-line*lineH; //滚动函数 scrollUp=function(){ _this.animate({ marginTop:upHeight },speed,function(){ for(i=1;i<=line;i++){ _this.find("li:first").appendTo(_this); } _this.css({marginTop:0}); }); } //鼠标事件绑定 var timerID; timerID=setInterval("scrollUp()",timer); _this.mouseover(function(){ clearInterval(timerID); }).mouseout(function(){ timerID=setInterval("scrollUp()",timer); }); } }) })(jQuery); */ -->
JavaScript
/*! * jQuery corner plugin: simple corner rounding * Examples and documentation at: http://jquery.malsup.com/corner/ * version 2.12 (23-MAY-2011) * Requires jQuery v1.3.2 or later * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * Authors: Dave Methvin and Mike Alsup */ /** * corner() takes a single string argument: $('#myDiv').corner("effect corners width") * * effect: name of the effect to apply, such as round, bevel, notch, bite, etc (default is round). * corners: one or more of: top, bottom, tr, tl, br, or bl. (default is all corners) * width: width of the effect; in the case of rounded corners this is the radius. * specify this value using the px suffix such as 10px (yes, it must be pixels). */ ;(function($) { var style = document.createElement('div').style, moz = style['MozBorderRadius'] !== undefined, webkit = style['WebkitBorderRadius'] !== undefined, radius = style['borderRadius'] !== undefined || style['BorderRadius'] !== undefined, mode = document.documentMode || 0, noBottomFold = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8), expr = $.browser.msie && (function() { var div = document.createElement('div'); try { div.style.setExpression('width','0+0'); div.style.removeExpression('width'); } catch(e) { return false; } return true; })(); $.support = $.support || {}; $.support.borderRadius = moz || webkit || radius; // so you can do: if (!$.support.borderRadius) $('#myDiv').corner(); function sz(el, p) { return parseInt($.css(el,p))||0; }; function hex2(s) { s = parseInt(s).toString(16); return ( s.length < 2 ) ? '0'+s : s; }; function gpc(node) { while(node) { var v = $.css(node,'backgroundColor'), rgb; if (v && v != 'transparent' && v != 'rgba(0, 0, 0, 0)') { if (v.indexOf('rgb') >= 0) { rgb = v.match(/\d+/g); return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]); } return v; } if (node.nodeName.toLowerCase() == 'html') break; node = node.parentNode; // keep walking if transparent } return '#ffffff'; }; function getWidth(fx, i, width) { switch(fx) { case 'round': return Math.round(width*(1-Math.cos(Math.asin(i/width)))); case 'cool': return Math.round(width*(1+Math.cos(Math.asin(i/width)))); case 'sharp': return width-i; case 'bite': return Math.round(width*(Math.cos(Math.asin((width-i-1)/width)))); case 'slide': return Math.round(width*(Math.atan2(i,width/i))); case 'jut': return Math.round(width*(Math.atan2(width,(width-i-1)))); case 'curl': return Math.round(width*(Math.atan(i))); case 'tear': return Math.round(width*(Math.cos(i))); case 'wicked': return Math.round(width*(Math.tan(i))); case 'long': return Math.round(width*(Math.sqrt(i))); case 'sculpt': return Math.round(width*(Math.log((width-i-1),width))); case 'dogfold': case 'dog': return (i&1) ? (i+1) : width; case 'dog2': return (i&2) ? (i+1) : width; case 'dog3': return (i&3) ? (i+1) : width; case 'fray': return (i%2)*width; case 'notch': return width; case 'bevelfold': case 'bevel': return i+1; case 'steep': return i/2 + 1; case 'invsteep':return (width-i)/2+1; } }; $.fn.corner = function(options) { // in 1.3+ we can fix mistakes with the ready state if (this.length == 0) { if (!$.isReady && this.selector) { var s = this.selector, c = this.context; $(function() { $(s,c).corner(options); }); } return this; } return this.each(function(index){ var $this = $(this), // meta values override options o = [$this.attr($.fn.corner.defaults.metaAttr) || '', options || ''].join(' ').toLowerCase(), keep = /keep/.test(o), // keep borders? cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]), // corner color sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]), // strip color width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10, // corner width re = /round|bevelfold|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dogfold|dog|invsteep|steep/, fx = ((o.match(re)||['round'])[0]), fold = /dogfold|bevelfold/.test(o), edges = { T:0, B:1 }, opts = { TL: /top|tl|left/.test(o), TR: /top|tr|right/.test(o), BL: /bottom|bl|left/.test(o), BR: /bottom|br|right/.test(o) }, // vars used in func later strip, pad, cssHeight, j, bot, d, ds, bw, i, w, e, c, common, $horz; if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR ) opts = { TL:1, TR:1, BL:1, BR:1 }; // support native rounding if ($.fn.corner.defaults.useNative && fx == 'round' && (radius || moz || webkit) && !cc && !sc) { if (opts.TL) $this.css(radius ? 'border-top-left-radius' : moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px'); if (opts.TR) $this.css(radius ? 'border-top-right-radius' : moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px'); if (opts.BL) $this.css(radius ? 'border-bottom-left-radius' : moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px'); if (opts.BR) $this.css(radius ? 'border-bottom-right-radius' : moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px'); return; } strip = document.createElement('div'); $(strip).css({ overflow: 'hidden', height: '1px', minHeight: '1px', fontSize: '1px', backgroundColor: sc || 'transparent', borderStyle: 'solid' }); pad = { T: parseInt($.css(this,'paddingTop'))||0, R: parseInt($.css(this,'paddingRight'))||0, B: parseInt($.css(this,'paddingBottom'))||0, L: parseInt($.css(this,'paddingLeft'))||0 }; if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE if (!keep) this.style.border = 'none'; strip.style.borderColor = cc || gpc(this.parentNode); cssHeight = $(this).outerHeight(); for (j in edges) { bot = edges[j]; // only add stips if needed if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) { strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none'); d = document.createElement('div'); $(d).addClass('jquery-corner'); ds = d.style; bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild); if (bot && cssHeight != 'auto') { if ($.css(this,'position') == 'static') this.style.position = 'relative'; ds.position = 'absolute'; ds.bottom = ds.left = ds.padding = ds.margin = '0'; if (expr) ds.setExpression('width', 'this.parentNode.offsetWidth'); else ds.width = '100%'; } else if (!bot && $.browser.msie) { if ($.css(this,'position') == 'static') this.style.position = 'relative'; ds.position = 'absolute'; ds.top = ds.left = ds.right = ds.padding = ds.margin = '0'; // fix ie6 problem when blocked element has a border width if (expr) { bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth'); ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"'); } else ds.width = '100%'; } else { ds.position = 'relative'; ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px'; } for (i=0; i < width; i++) { w = Math.max(0,getWidth(fx,i, width)); e = strip.cloneNode(false); e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px'; bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild); } if (fold && $.support.boxModel) { if (bot && noBottomFold) continue; for (c in opts) { if (!opts[c]) continue; if (bot && (c == 'TL' || c == 'TR')) continue; if (!bot && (c == 'BL' || c == 'BR')) continue; common = { position: 'absolute', border: 'none', margin: 0, padding: 0, overflow: 'hidden', backgroundColor: strip.style.borderColor }; $horz = $('<div/>').css(common).css({ width: width + 'px', height: '1px' }); switch(c) { case 'TL': $horz.css({ bottom: 0, left: 0 }); break; case 'TR': $horz.css({ bottom: 0, right: 0 }); break; case 'BL': $horz.css({ top: 0, left: 0 }); break; case 'BR': $horz.css({ top: 0, right: 0 }); break; } d.appendChild($horz[0]); var $vert = $('<div/>').css(common).css({ top: 0, bottom: 0, width: '1px', height: width + 'px' }); switch(c) { case 'TL': $vert.css({ left: width }); break; case 'TR': $vert.css({ right: width }); break; case 'BL': $vert.css({ left: width }); break; case 'BR': $vert.css({ right: width }); break; } d.appendChild($vert[0]); } } } } }); }; $.fn.uncorner = function() { if (radius || moz || webkit) this.css(radius ? 'border-radius' : moz ? '-moz-border-radius' : '-webkit-border-radius', 0); $('div.jquery-corner', this).remove(); return this; }; // expose options $.fn.corner.defaults = { useNative: true, // true if plugin should attempt to use native browser support for border radius rounding metaAttr: 'data-corner' // name of meta attribute to use for options }; })(jQuery);
JavaScript