code
stringlengths
1
2.08M
language
stringclasses
1 value
//////////////////////////////////////////////////// // controlWindow object //////////////////////////////////////////////////// function controlWindow( controlForm ) { // private properties this._form = controlForm; // public properties this.windowType = "controlWindow"; // this.noSuggestionSelection = "- No suggestions -"; // by FredCK this.noSuggestionSelection = FCKLang.DlgSpellNoSuggestions ; // set up the properties for elements of the given control form this.suggestionList = this._form.sugg; this.evaluatedText = this._form.misword; this.replacementText = this._form.txtsugg; this.undoButton = this._form.btnUndo; // public methods this.addSuggestion = addSuggestion; this.clearSuggestions = clearSuggestions; this.selectDefaultSuggestion = selectDefaultSuggestion; this.resetForm = resetForm; this.setSuggestedText = setSuggestedText; this.enableUndo = enableUndo; this.disableUndo = disableUndo; } function resetForm() { if( this._form ) { this._form.reset(); } } function setSuggestedText() { var slct = this.suggestionList; var txt = this.replacementText; var str = ""; if( (slct.options[0].text) && slct.options[0].text != this.noSuggestionSelection ) { str = slct.options[slct.selectedIndex].text; } txt.value = str; } function selectDefaultSuggestion() { var slct = this.suggestionList; var txt = this.replacementText; if( slct.options.length == 0 ) { this.addSuggestion( this.noSuggestionSelection ); } else { slct.options[0].selected = true; } this.setSuggestedText(); } function addSuggestion( sugg_text ) { var slct = this.suggestionList; if( sugg_text ) { var i = slct.options.length; var newOption = new Option( sugg_text, 'sugg_text'+i ); slct.options[i] = newOption; } } function clearSuggestions() { var slct = this.suggestionList; for( var j = slct.length - 1; j > -1; j-- ) { if( slct.options[j] ) { slct.options[j] = null; } } } function enableUndo() { if( this.undoButton ) { if( this.undoButton.disabled == true ) { this.undoButton.disabled = false; } } } function disableUndo() { if( this.undoButton ) { if( this.undoButton.disabled == false ) { this.undoButton.disabled = true; } } }
JavaScript
//////////////////////////////////////////////////// // spellChecker.js // // spellChecker object // // This file is sourced on web pages that have a textarea object to evaluate // for spelling. It includes the implementation for the spellCheckObject. // //////////////////////////////////////////////////// // constructor function spellChecker( textObject ) { // public properties - configurable // this.popUpUrl = '/speller/spellchecker.html'; // by FredCK this.popUpUrl = 'fck_spellerpages/spellerpages/spellchecker.html'; // by FredCK this.popUpName = 'spellchecker'; // this.popUpProps = "menu=no,width=440,height=350,top=70,left=120,resizable=yes,status=yes"; // by FredCK this.popUpProps = null ; // by FredCK // this.spellCheckScript = '/speller/server-scripts/spellchecker.php'; // by FredCK //this.spellCheckScript = '/cgi-bin/spellchecker.pl'; // values used to keep track of what happened to a word this.replWordFlag = "R"; // single replace this.ignrWordFlag = "I"; // single ignore this.replAllFlag = "RA"; // replace all occurances this.ignrAllFlag = "IA"; // ignore all occurances this.fromReplAll = "~RA"; // an occurance of a "replace all" word this.fromIgnrAll = "~IA"; // an occurance of a "ignore all" word // properties set at run time this.wordFlags = new Array(); this.currentTextIndex = 0; this.currentWordIndex = 0; this.spellCheckerWin = null; this.controlWin = null; this.wordWin = null; this.textArea = textObject; // deprecated this.textInputs = arguments; // private methods this._spellcheck = _spellcheck; this._getSuggestions = _getSuggestions; this._setAsIgnored = _setAsIgnored; this._getTotalReplaced = _getTotalReplaced; this._setWordText = _setWordText; this._getFormInputs = _getFormInputs; // public methods this.openChecker = openChecker; this.startCheck = startCheck; this.checkTextBoxes = checkTextBoxes; this.checkTextAreas = checkTextAreas; this.spellCheckAll = spellCheckAll; this.ignoreWord = ignoreWord; this.ignoreAll = ignoreAll; this.replaceWord = replaceWord; this.replaceAll = replaceAll; this.terminateSpell = terminateSpell; this.undo = undo; // set the current window's "speller" property to the instance of this class. // this object can now be referenced by child windows/frames. window.speller = this; } // call this method to check all text boxes (and only text boxes) in the HTML document function checkTextBoxes() { this.textInputs = this._getFormInputs( "^text$" ); this.openChecker(); } // call this method to check all textareas (and only textareas ) in the HTML document function checkTextAreas() { this.textInputs = this._getFormInputs( "^textarea$" ); this.openChecker(); } // call this method to check all text boxes and textareas in the HTML document function spellCheckAll() { this.textInputs = this._getFormInputs( "^text(area)?$" ); this.openChecker(); } // call this method to check text boxe(s) and/or textarea(s) that were passed in to the // object's constructor or to the textInputs property function openChecker() { this.spellCheckerWin = window.open( this.popUpUrl, this.popUpName, this.popUpProps ); if( !this.spellCheckerWin.opener ) { this.spellCheckerWin.opener = window; } } function startCheck( wordWindowObj, controlWindowObj ) { // set properties from args this.wordWin = wordWindowObj; this.controlWin = controlWindowObj; // reset properties this.wordWin.resetForm(); this.controlWin.resetForm(); this.currentTextIndex = 0; this.currentWordIndex = 0; // initialize the flags to an array - one element for each text input this.wordFlags = new Array( this.wordWin.textInputs.length ); // each element will be an array that keeps track of each word in the text for( var i=0; i<this.wordFlags.length; i++ ) { this.wordFlags[i] = []; } // start this._spellcheck(); return true; } function ignoreWord() { var wi = this.currentWordIndex; var ti = this.currentTextIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } if( !this.wordWin.getTextVal( ti, wi )) { alert( 'Error: "Not in dictionary" text is missing.' ); return false; } // set as ignored if( this._setAsIgnored( ti, wi, this.ignrWordFlag )) { this.currentWordIndex++; this._spellcheck(); } return true; } function ignoreAll() { var wi = this.currentWordIndex; var ti = this.currentTextIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } // get the word that is currently being evaluated. var s_word_to_repl = this.wordWin.getTextVal( ti, wi ); if( !s_word_to_repl ) { alert( 'Error: "Not in dictionary" text is missing' ); return false; } // set this word as an "ignore all" word. this._setAsIgnored( ti, wi, this.ignrAllFlag ); // loop through all the words after this word for( var i = ti; i < this.wordWin.textInputs.length; i++ ) { for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == ti && j > wi ) || i > ti ) { // future word: set as "from ignore all" if // 1) do not already have a flag and // 2) have the same value as current word if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl ) && ( !this.wordFlags[i][j] )) { this._setAsIgnored( i, j, this.fromIgnrAll ); } } } } // finally, move on this.currentWordIndex++; this._spellcheck(); return true; } function replaceWord() { var wi = this.currentWordIndex; var ti = this.currentTextIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } if( !this.wordWin.getTextVal( ti, wi )) { alert( 'Error: "Not in dictionary" text is missing' ); return false; } if( !this.controlWin.replacementText ) { return false ; } var txt = this.controlWin.replacementText; if( txt.value ) { var newspell = new String( txt.value ); if( this._setWordText( ti, wi, newspell, this.replWordFlag )) { this.currentWordIndex++; this._spellcheck(); } } return true; } function replaceAll() { var ti = this.currentTextIndex; var wi = this.currentWordIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } var s_word_to_repl = this.wordWin.getTextVal( ti, wi ); if( !s_word_to_repl ) { alert( 'Error: "Not in dictionary" text is missing' ); return false; } var txt = this.controlWin.replacementText; if( !txt.value ) return false; var newspell = new String( txt.value ); // set this word as a "replace all" word. this._setWordText( ti, wi, newspell, this.replAllFlag ); // loop through all the words after this word for( var i = ti; i < this.wordWin.textInputs.length; i++ ) { for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == ti && j > wi ) || i > ti ) { // future word: set word text to s_word_to_repl if // 1) do not already have a flag and // 2) have the same value as s_word_to_repl if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl ) && ( !this.wordFlags[i][j] )) { this._setWordText( i, j, newspell, this.fromReplAll ); } } } } // finally, move on this.currentWordIndex++; this._spellcheck(); return true; } function terminateSpell() { // called when we have reached the end of the spell checking. var msg = ""; // by FredCK var numrepl = this._getTotalReplaced(); if( numrepl == 0 ) { // see if there were no misspellings to begin with if( !this.wordWin ) { msg = ""; } else { if( this.wordWin.totalMisspellings() ) { // msg += "No words changed."; // by FredCK msg += FCKLang.DlgSpellNoChanges ; // by FredCK } else { // msg += "No misspellings found."; // by FredCK msg += FCKLang.DlgSpellNoMispell ; // by FredCK } } } else if( numrepl == 1 ) { // msg += "One word changed."; // by FredCK msg += FCKLang.DlgSpellOneChange ; // by FredCK } else { // msg += numrepl + " words changed."; // by FredCK msg += FCKLang.DlgSpellManyChanges.replace( /%1/g, numrepl ) ; } if( msg ) { // msg += "\n"; // by FredCK alert( msg ); } if( numrepl > 0 ) { // update the text field(s) on the opener window for( var i = 0; i < this.textInputs.length; i++ ) { // this.textArea.value = this.wordWin.text; if( this.wordWin ) { if( this.wordWin.textInputs[i] ) { this.textInputs[i].value = this.wordWin.textInputs[i]; } } } } // return back to the calling window // this.spellCheckerWin.close(); // by FredCK if ( typeof( this.OnFinished ) == 'function' ) // by FredCK this.OnFinished(numrepl) ; // by FredCK return true; } function undo() { // skip if this is the first word! var ti = this.currentTextIndex; var wi = this.currentWordIndex; if( this.wordWin.totalPreviousWords( ti, wi ) > 0 ) { this.wordWin.removeFocus( ti, wi ); // go back to the last word index that was acted upon do { // if the current word index is zero then reset the seed if( this.currentWordIndex == 0 && this.currentTextIndex > 0 ) { this.currentTextIndex--; this.currentWordIndex = this.wordWin.totalWords( this.currentTextIndex )-1; if( this.currentWordIndex < 0 ) this.currentWordIndex = 0; } else { if( this.currentWordIndex > 0 ) { this.currentWordIndex--; } } } while ( this.wordWin.totalWords( this.currentTextIndex ) == 0 || this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromIgnrAll || this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromReplAll ); var text_idx = this.currentTextIndex; var idx = this.currentWordIndex; var preReplSpell = this.wordWin.originalSpellings[text_idx][idx]; // if we got back to the first word then set the Undo button back to disabled if( this.wordWin.totalPreviousWords( text_idx, idx ) == 0 ) { this.controlWin.disableUndo(); } var i, j, origSpell ; // examine what happened to this current word. switch( this.wordFlags[text_idx][idx] ) { // replace all: go through this and all the future occurances of the word // and revert them all to the original spelling and clear their flags case this.replAllFlag : for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) { for( j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == text_idx && j >= idx ) || i > text_idx ) { origSpell = this.wordWin.originalSpellings[i][j]; if( origSpell == preReplSpell ) { this._setWordText ( i, j, origSpell, undefined ); } } } } break; // ignore all: go through all the future occurances of the word // and clear their flags case this.ignrAllFlag : for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) { for( j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == text_idx && j >= idx ) || i > text_idx ) { origSpell = this.wordWin.originalSpellings[i][j]; if( origSpell == preReplSpell ) { this.wordFlags[i][j] = undefined; } } } } break; // replace: revert the word to its original spelling case this.replWordFlag : this._setWordText ( text_idx, idx, preReplSpell, undefined ); break; } // For all four cases, clear the wordFlag of this word. re-start the process this.wordFlags[text_idx][idx] = undefined; this._spellcheck(); } } function _spellcheck() { var ww = this.wordWin; // check if this is the last word in the current text element if( this.currentWordIndex == ww.totalWords( this.currentTextIndex) ) { this.currentTextIndex++; this.currentWordIndex = 0; // keep going if we're not yet past the last text element if( this.currentTextIndex < this.wordWin.textInputs.length ) { this._spellcheck(); return; } else { this.terminateSpell(); return; } } // if this is after the first one make sure the Undo button is enabled if( this.currentWordIndex > 0 ) { this.controlWin.enableUndo(); } // skip the current word if it has already been worked on if( this.wordFlags[this.currentTextIndex][this.currentWordIndex] ) { // increment the global current word index and move on. this.currentWordIndex++; this._spellcheck(); } else { var evalText = ww.getTextVal( this.currentTextIndex, this.currentWordIndex ); if( evalText ) { this.controlWin.evaluatedText.value = evalText; ww.setFocus( this.currentTextIndex, this.currentWordIndex ); this._getSuggestions( this.currentTextIndex, this.currentWordIndex ); } } } function _getSuggestions( text_num, word_num ) { this.controlWin.clearSuggestions(); // add suggestion in list for each suggested word. // get the array of suggested words out of the // three-dimensional array containing all suggestions. var a_suggests = this.wordWin.suggestions[text_num][word_num]; if( a_suggests ) { // got an array of suggestions. for( var ii = 0; ii < a_suggests.length; ii++ ) { this.controlWin.addSuggestion( a_suggests[ii] ); } } this.controlWin.selectDefaultSuggestion(); } function _setAsIgnored( text_num, word_num, flag ) { // set the UI this.wordWin.removeFocus( text_num, word_num ); // do the bookkeeping this.wordFlags[text_num][word_num] = flag; return true; } function _getTotalReplaced() { var i_replaced = 0; for( var i = 0; i < this.wordFlags.length; i++ ) { for( var j = 0; j < this.wordFlags[i].length; j++ ) { if(( this.wordFlags[i][j] == this.replWordFlag ) || ( this.wordFlags[i][j] == this.replAllFlag ) || ( this.wordFlags[i][j] == this.fromReplAll )) { i_replaced++; } } } return i_replaced; } function _setWordText( text_num, word_num, newText, flag ) { // set the UI and form inputs this.wordWin.setText( text_num, word_num, newText ); // keep track of what happened to this word: this.wordFlags[text_num][word_num] = flag; return true; } function _getFormInputs( inputPattern ) { var inputs = new Array(); for( var i = 0; i < document.forms.length; i++ ) { for( var j = 0; j < document.forms[i].elements.length; j++ ) { if( document.forms[i].elements[j].type.match( inputPattern )) { inputs[inputs.length] = document.forms[i].elements[j]; } } } return inputs; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Useful functions used by almost all dialog window pages. * Dialogs should link to this file as the very first script on the page. */ // Automatically detect the correct document.domain (#123). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.parent.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; // Attention: FCKConfig must be available in the page. function GetCommonDialogCss( prefix ) { // CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see _dev/css_compression.txt). return FCKConfig.BasePath + 'dialog/common/' + '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}.BtnReset{float:left;background-position:center center;background-image:url(images/reset.gif);width:16px;height:16px;background-repeat:no-repeat;border:1px none;font-size:1px}.BtnLocked,.BtnUnlocked{float:left;background-position:center center;background-image:url(images/locked.gif);width:16px;height:16px;background-repeat:no-repeat;border:none 1px;font-size:1px}.BtnUnlocked{background-image:url(images/unlocked.gif)}.BtnOver{border:outset 1px;cursor:pointer;cursor:hand}' ; } // Gets a element by its Id. Used for shorter coding. function GetE( elementId ) { return document.getElementById( elementId ) ; } function ShowE( element, isVisible ) { if ( typeof( element ) == 'string' ) element = GetE( element ) ; element.style.display = isVisible ? '' : 'none' ; } function SetAttribute( element, attName, attValue ) { if ( attValue == null || attValue.length == 0 ) element.removeAttribute( attName, 0 ) ; // 0 : Case Insensitive else element.setAttribute( attName, attValue, 0 ) ; // 0 : Case Insensitive } function GetAttribute( element, attName, valueIfNull ) { var oAtt = element.attributes[attName] ; if ( oAtt == null || !oAtt.specified ) return valueIfNull ? valueIfNull : '' ; var oValue = element.getAttribute( attName, 2 ) ; if ( oValue == null ) oValue = oAtt.nodeValue ; return ( oValue == null ? valueIfNull : oValue ) ; } function SelectField( elementId ) { var element = GetE( elementId ) ; element.focus() ; // element.select may not be available for some fields (like <select>). if ( element.select ) element.select() ; } // Functions used by text fields to accept numbers only. var IsDigit = ( function() { var KeyIdentifierMap = { End : 35, Home : 36, Left : 37, Right : 39, 'U+00007F' : 46 // Delete } ; return function ( e ) { if ( !e ) e = event ; var iCode = ( e.keyCode || e.charCode ) ; if ( !iCode && e.keyIdentifier && ( e.keyIdentifier in KeyIdentifierMap ) ) iCode = KeyIdentifierMap[ e.keyIdentifier ] ; return ( ( iCode >= 48 && iCode <= 57 ) // Numbers || (iCode >= 35 && iCode <= 40) // Arrows, Home, End || iCode == 8 // Backspace || iCode == 46 // Delete || iCode == 9 // Tab ) ; } } )() ; String.prototype.Trim = function() { return this.replace( /(^\s*)|(\s*$)/g, '' ) ; } String.prototype.StartsWith = function( value ) { return ( this.substr( 0, value.length ) == value ) ; } String.prototype.Remove = function( start, length ) { var s = '' ; if ( start > 0 ) s = this.substring( 0, start ) ; if ( start + length < this.length ) s += this.substring( start + length , this.length ) ; return s ; } String.prototype.ReplaceAll = function( searchArray, replaceArray ) { var replaced = this ; for ( var i = 0 ; i < searchArray.length ; i++ ) { replaced = replaced.replace( searchArray[i], replaceArray[i] ) ; } return replaced ; } function OpenFileBrowser( url, width, height ) { // oEditor must be defined. var iLeft = ( oEditor.FCKConfig.ScreenWidth - width ) / 2 ; var iTop = ( oEditor.FCKConfig.ScreenHeight - height ) / 2 ; var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes" ; sOptions += ",width=" + width ; sOptions += ",height=" + height ; sOptions += ",left=" + iLeft ; sOptions += ",top=" + iTop ; window.open( url, 'FCKBrowseWindow', sOptions ) ; } /** Utility function to create/update an element with a name attribute in IE, so it behaves properly when moved around It also allows to change the name or other special attributes in an existing node oEditor : instance of FCKeditor where the element will be created oOriginal : current element being edited or null if it has to be created nodeName : string with the name of the element to create oAttributes : Hash object with the attributes that must be set at creation time in IE Those attributes will be set also after the element has been created for any other browser to avoid redudant code */ function CreateNamedElement( oEditor, oOriginal, nodeName, oAttributes ) { var oNewNode ; // IE doesn't allow easily to change properties of an existing object, // so remove the old and force the creation of a new one. var oldNode = null ; if ( oOriginal && oEditor.FCKBrowserInfo.IsIE ) { // Force the creation only if some of the special attributes have changed: var bChanged = false; for( var attName in oAttributes ) bChanged |= ( oOriginal.getAttribute( attName, 2) != oAttributes[attName] ) ; if ( bChanged ) { oldNode = oOriginal ; oOriginal = null ; } } // If the node existed (and it's not IE), then we just have to update its attributes if ( oOriginal ) { oNewNode = oOriginal ; } else { // #676, IE doesn't play nice with the name or type attribute if ( oEditor.FCKBrowserInfo.IsIE ) { var sbHTML = [] ; sbHTML.push( '<' + nodeName ) ; for( var prop in oAttributes ) { sbHTML.push( ' ' + prop + '="' + oAttributes[prop] + '"' ) ; } sbHTML.push( '>' ) ; if ( !oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()] ) sbHTML.push( '</' + nodeName + '>' ) ; oNewNode = oEditor.FCK.EditorDocument.createElement( sbHTML.join('') ) ; // Check if we are just changing the properties of an existing node: copy its properties if ( oldNode ) { CopyAttributes( oldNode, oNewNode, oAttributes ) ; oEditor.FCKDomTools.MoveChildren( oldNode, oNewNode ) ; oldNode.parentNode.removeChild( oldNode ) ; oldNode = null ; if ( oEditor.FCK.Selection.SelectionData ) { // Trick to refresh the selection object and avoid error in // fckdialog.html Selection.EnsureSelection var oSel = oEditor.FCK.EditorDocument.selection ; oEditor.FCK.Selection.SelectionData = oSel.createRange() ; // Now oSel.type will be 'None' reflecting the real situation } } oNewNode = oEditor.FCK.InsertElement( oNewNode ) ; // FCK.Selection.SelectionData is broken by now since we've // deleted the previously selected element. So we need to reassign it. if ( oEditor.FCK.Selection.SelectionData ) { var range = oEditor.FCK.EditorDocument.body.createControlRange() ; range.add( oNewNode ) ; oEditor.FCK.Selection.SelectionData = range ; } } else { oNewNode = oEditor.FCK.InsertElement( nodeName ) ; } } // Set the basic attributes for( var attName in oAttributes ) oNewNode.setAttribute( attName, oAttributes[attName], 0 ) ; // 0 : Case Insensitive return oNewNode ; } // Copy all the attributes from one node to the other, kinda like a clone // But oSkipAttributes is an object with the attributes that must NOT be copied function CopyAttributes( oSource, oDest, oSkipAttributes ) { var aAttributes = oSource.attributes ; for ( var n = 0 ; n < aAttributes.length ; n++ ) { var oAttribute = aAttributes[n] ; if ( oAttribute.specified ) { var sAttName = oAttribute.nodeName ; // We can set the type only once, so do it with the proper value, not copying it. if ( sAttName in oSkipAttributes ) continue ; var sAttValue = oSource.getAttribute( sAttName, 2 ) ; if ( sAttValue == null ) sAttValue = oAttribute.nodeValue ; oDest.setAttribute( sAttName, sAttValue, 0 ) ; // 0 : Case Insensitive } } // The style: if ( oSource.style.cssText !== '' ) oDest.style.cssText = oSource.style.cssText ; } /** * Replaces a tag with another one, keeping its contents: * for example TD --> TH, and TH --> TD. * input: the original node, and the new tag name * http://www.w3.org/TR/DOM-Level-3-Core/core.html#Document3-renameNode */ function RenameNode( oNode , newTag ) { // TODO: if the browser natively supports document.renameNode call it. // does any browser currently support it in order to test? // Only rename element nodes. if ( oNode.nodeType != 1 ) return null ; // If it's already correct exit here. if ( oNode.nodeName == newTag ) return oNode ; var oDoc = oNode.ownerDocument ; // Create the new node var newNode = oDoc.createElement( newTag ) ; // Copy all attributes CopyAttributes( oNode, newNode, {} ) ; // Move children to the new node FCKDomTools.MoveChildren( oNode, newNode ) ; // Finally replace the node and return the new one oNode.parentNode.replaceChild( newNode, oNode ) ; return newNode ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Image dialog window (see fck_image.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKDebug = oEditor.FCKDebug ; var FCKTools = oEditor.FCKTools ; var bImageButton = ( document.location.search.length > 0 && document.location.search.substr(1) == 'ImageButton' ) ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', FCKLang.DlgImgInfoTab ) ; if ( !bImageButton && !FCKConfig.ImageDlgHideLink ) dialog.AddTab( 'Link', FCKLang.DlgImgLinkTab ) ; if ( FCKConfig.ImageUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ; if ( !FCKConfig.ImageDlgHideAdvanced ) dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divLink' , ( tabCode == 'Link' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ; } // Get the selected image (if available). var oImage = dialog.Selection.GetSelectedElement() ; if ( oImage && oImage.tagName != 'IMG' && !( oImage.tagName == 'INPUT' && oImage.type == 'image' ) ) oImage = null ; // Get the active link. var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ; var oImageOriginal ; function UpdateOriginal( resetSize ) { if ( !eImgPreview ) return ; if ( GetE('txtUrl').value.length == 0 ) { oImageOriginal = null ; return ; } oImageOriginal = document.createElement( 'IMG' ) ; // new Image() ; if ( resetSize ) { oImageOriginal.onload = function() { this.onload = null ; ResetSizes() ; } } oImageOriginal.src = eImgPreview.src ; } var bPreviewInitialized ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; GetE('btnLockSizes').title = FCKLang.DlgImgLockRatio ; GetE('btnResetSize').title = FCKLang.DlgBtnResetSize ; // Load the selected element information (if any). LoadSelection() ; // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = FCKConfig.ImageBrowser ? '' : 'none' ; GetE('divLnkBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ; UpdateOriginal() ; // Set the actual uploader URL. if ( FCKConfig.ImageUpload ) GetE('frmUpload').action = FCKConfig.ImageUploadURL ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oImage ) return ; var sUrl = oImage.getAttribute( '_fcksavedurl' ) ; if ( sUrl == null ) sUrl = GetAttribute( oImage, 'src', '' ) ; GetE('txtUrl').value = sUrl ; GetE('txtAlt').value = GetAttribute( oImage, 'alt', '' ) ; GetE('txtVSpace').value = GetAttribute( oImage, 'vspace', '' ) ; GetE('txtHSpace').value = GetAttribute( oImage, 'hspace', '' ) ; GetE('txtBorder').value = GetAttribute( oImage, 'border', '' ) ; GetE('cmbAlign').value = GetAttribute( oImage, 'align', '' ) ; var iWidth, iHeight ; var regexSize = /^\s*(\d+)px\s*$/i ; if ( oImage.style.width ) { var aMatchW = oImage.style.width.match( regexSize ) ; if ( aMatchW ) { iWidth = aMatchW[1] ; oImage.style.width = '' ; SetAttribute( oImage, 'width' , iWidth ) ; } } if ( oImage.style.height ) { var aMatchH = oImage.style.height.match( regexSize ) ; if ( aMatchH ) { iHeight = aMatchH[1] ; oImage.style.height = '' ; SetAttribute( oImage, 'height', iHeight ) ; } } GetE('txtWidth').value = iWidth ? iWidth : GetAttribute( oImage, "width", '' ) ; GetE('txtHeight').value = iHeight ? iHeight : GetAttribute( oImage, "height", '' ) ; // Get Advances Attributes GetE('txtAttId').value = oImage.id ; GetE('cmbAttLangDir').value = oImage.dir ; GetE('txtAttLangCode').value = oImage.lang ; GetE('txtAttTitle').value = oImage.title ; GetE('txtLongDesc').value = oImage.longDesc ; if ( oEditor.FCKBrowserInfo.IsIE ) { GetE('txtAttClasses').value = oImage.className || '' ; GetE('txtAttStyle').value = oImage.style.cssText ; } else { GetE('txtAttClasses').value = oImage.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oImage.getAttribute('style',2) ; } if ( oLink ) { var sLinkUrl = oLink.getAttribute( '_fcksavedurl' ) ; if ( sLinkUrl == null ) sLinkUrl = oLink.getAttribute('href',2) ; GetE('txtLnkUrl').value = sLinkUrl ; GetE('cmbLnkTarget').value = oLink.target ; } UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( FCKLang.DlgImgAlertUrl ) ; return false ; } var bHasImage = ( oImage != null ) ; if ( bHasImage && bImageButton && oImage.tagName == 'IMG' ) { if ( confirm( 'Do you want to transform the selected image on a image button?' ) ) oImage = null ; } else if ( bHasImage && !bImageButton && oImage.tagName == 'INPUT' ) { if ( confirm( 'Do you want to transform the selected image button on a simple image?' ) ) oImage = null ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !bHasImage ) { if ( bImageButton ) { oImage = FCK.EditorDocument.createElement( 'input' ) ; oImage.type = 'image' ; oImage = FCK.InsertElement( oImage ) ; } else oImage = FCK.InsertElement( 'img' ) ; } UpdateImage( oImage ) ; var sLnkUrl = GetE('txtLnkUrl').value.Trim() ; if ( sLnkUrl.length == 0 ) { if ( oLink ) FCK.ExecuteNamedCommand( 'Unlink' ) ; } else { if ( oLink ) // Modifying an existent link. oLink.href = sLnkUrl ; else // Creating a new link. { if ( !bHasImage ) oEditor.FCKSelection.SelectNode( oImage ) ; oLink = oEditor.FCK.CreateLink( sLnkUrl )[0] ; if ( !bHasImage ) { oEditor.FCKSelection.SelectNode( oLink ) ; oEditor.FCKSelection.Collapse( false ) ; } } SetAttribute( oLink, '_fcksavedurl', sLnkUrl ) ; SetAttribute( oLink, 'target', GetE('cmbLnkTarget').value ) ; } return true ; } function UpdateImage( e, skipId ) { e.src = GetE('txtUrl').value ; SetAttribute( e, "_fcksavedurl", GetE('txtUrl').value ) ; SetAttribute( e, "alt" , GetE('txtAlt').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; SetAttribute( e, "vspace", GetE('txtVSpace').value ) ; SetAttribute( e, "hspace", GetE('txtHSpace').value ) ; SetAttribute( e, "border", GetE('txtBorder').value ) ; SetAttribute( e, "align" , GetE('cmbAlign').value ) ; // Advances Attributes if ( ! skipId ) SetAttribute( e, 'id', GetE('txtAttId').value ) ; SetAttribute( e, 'dir' , GetE('cmbAttLangDir').value ) ; SetAttribute( e, 'lang' , GetE('txtAttLangCode').value ) ; SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ; SetAttribute( e, 'longDesc' , GetE('txtLongDesc').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { e.className = GetE('txtAttClasses').value ; e.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( e, 'class' , GetE('txtAttClasses').value ) ; SetAttribute( e, 'style', GetE('txtAttStyle').value ) ; } } var eImgPreview ; var eImgPreviewLink ; function SetPreviewElements( imageElement, linkElement ) { eImgPreview = imageElement ; eImgPreviewLink = linkElement ; UpdatePreview() ; UpdateOriginal() ; bPreviewInitialized = true ; } function UpdatePreview() { if ( !eImgPreview || !eImgPreviewLink ) return ; if ( GetE('txtUrl').value.length == 0 ) eImgPreviewLink.style.display = 'none' ; else { UpdateImage( eImgPreview, true ) ; if ( GetE('txtLnkUrl').value.Trim().length > 0 ) eImgPreviewLink.href = 'javascript:void(null);' ; else SetAttribute( eImgPreviewLink, 'href', '' ) ; eImgPreviewLink.style.display = '' ; } } var bLockRatio = true ; function SwitchLock( lockButton ) { bLockRatio = !bLockRatio ; lockButton.className = bLockRatio ? 'BtnLocked' : 'BtnUnlocked' ; lockButton.title = bLockRatio ? 'Lock sizes' : 'Unlock sizes' ; if ( bLockRatio ) { if ( GetE('txtWidth').value.length > 0 ) OnSizeChanged( 'Width', GetE('txtWidth').value ) ; else OnSizeChanged( 'Height', GetE('txtHeight').value ) ; } } // Fired when the width or height input texts change function OnSizeChanged( dimension, value ) { // Verifies if the aspect ration has to be maintained if ( oImageOriginal && bLockRatio ) { var e = dimension == 'Width' ? GetE('txtHeight') : GetE('txtWidth') ; if ( value.length == 0 || isNaN( value ) ) { e.value = '' ; return ; } if ( dimension == 'Width' ) value = value == 0 ? 0 : Math.round( oImageOriginal.height * ( value / oImageOriginal.width ) ) ; else value = value == 0 ? 0 : Math.round( oImageOriginal.width * ( value / oImageOriginal.height ) ) ; if ( !isNaN( value ) ) e.value = value ; } UpdatePreview() ; } // Fired when the Reset Size button is clicked function ResetSizes() { if ( ! oImageOriginal ) return ; if ( oEditor.FCKBrowserInfo.IsGecko && !oImageOriginal.complete ) { setTimeout( ResetSizes, 50 ) ; return ; } GetE('txtWidth').value = oImageOriginal.width ; GetE('txtHeight').value = oImageOriginal.height ; UpdatePreview() ; } function BrowseServer() { OpenServerBrowser( 'Image', FCKConfig.ImageBrowserURL, FCKConfig.ImageBrowserWindowWidth, FCKConfig.ImageBrowserWindowHeight ) ; } function LnkBrowseServer() { OpenServerBrowser( 'Link', FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ; } function OpenServerBrowser( type, url, width, height ) { sActualBrowser = type ; OpenFileBrowser( url, width, height ) ; } var sActualBrowser ; function SetUrl( url, width, height, alt ) { if ( sActualBrowser == 'Link' ) { GetE('txtLnkUrl').value = url ; UpdatePreview() ; } else { GetE('txtUrl').value = url ; GetE('txtWidth').value = width ? width : '' ; GetE('txtHeight').value = height ? height : '' ; if ( alt ) GetE('txtAlt').value = alt; UpdatePreview() ; UpdateOriginal( true ) ; } dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors //alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } sActualBrowser = '' ; SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } function UploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } sActualBrowser = '' ; SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.ImageUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.ImageUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.ImageUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.ImageUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; } document.write("<link href=\""+FCKConfig.PUBLIC_DIR+"/style/uploadify.css\" rel=\"stylesheet\" type=\"text/css\" />"); document.write("<script type=\"text/javascript\" src=\""+FCKConfig.PUBLIC_DIR+"/javascript/jquery.js\"></script>"); document.write("<script type=\"text/javascript\" src=\""+FCKConfig.PUBLIC_DIR+"/javascript/swfobject.js\"></script>"); document.write("<script type=\"text/javascript\" src=\""+FCKConfig.PUBLIC_DIR+"/javascript/jquery.uploadify.v2.1.0.min.js\"></script>");
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Flash dialog window (see fck_flash.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKTools = oEditor.FCKTools ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ; if ( FCKConfig.FlashUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ; if ( !FCKConfig.FlashDlgHideAdvanced ) dialog.AddTab( 'Advanced', oEditor.FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ; } // Get the selected flash embed (if available). var oFakeImage = dialog.Selection.GetSelectedElement() ; var oEmbed ; if ( oFakeImage ) { if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckflash') ) oEmbed = FCK.GetRealElement( oFakeImage ) ; else oFakeImage = null ; } window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Load the selected element information (if any). LoadSelection() ; // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = FCKConfig.FlashBrowser ? '' : 'none' ; // Set the actual uploader URL. if ( FCKConfig.FlashUpload ) GetE('frmUpload').action = FCKConfig.FlashUploadURL ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oEmbed ) return ; GetE('txtUrl').value = GetAttribute( oEmbed, 'src', '' ) ; GetE('txtWidth').value = GetAttribute( oEmbed, 'width', '' ) ; GetE('txtHeight').value = GetAttribute( oEmbed, 'height', '' ) ; // Get Advances Attributes GetE('txtAttId').value = oEmbed.id ; GetE('chkAutoPlay').checked = GetAttribute( oEmbed, 'play', 'true' ) == 'true' ; GetE('chkLoop').checked = GetAttribute( oEmbed, 'loop', 'true' ) == 'true' ; GetE('chkMenu').checked = GetAttribute( oEmbed, 'menu', 'true' ) == 'true' ; GetE('cmbScale').value = GetAttribute( oEmbed, 'scale', '' ).toLowerCase() ; GetE('txtAttTitle').value = oEmbed.title ; if ( oEditor.FCKBrowserInfo.IsIE ) { GetE('txtAttClasses').value = oEmbed.getAttribute('className') || '' ; GetE('txtAttStyle').value = oEmbed.style.cssText ; } else { GetE('txtAttClasses').value = oEmbed.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oEmbed.getAttribute('style',2) || '' ; } UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( oEditor.FCKLang.DlgAlertUrl ) ; return false ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !oEmbed ) { oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ; oFakeImage = null ; } UpdateEmbed( oEmbed ) ; if ( !oFakeImage ) { oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ; oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ; oFakeImage = FCK.InsertElement( oFakeImage ) ; } oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ; return true ; } function UpdateEmbed( e ) { SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ; SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; // Advances Attributes SetAttribute( e, 'id' , GetE('txtAttId').value ) ; SetAttribute( e, 'scale', GetE('cmbScale').value ) ; SetAttribute( e, 'play', GetE('chkAutoPlay').checked ? 'true' : 'false' ) ; SetAttribute( e, 'loop', GetE('chkLoop').checked ? 'true' : 'false' ) ; SetAttribute( e, 'menu', GetE('chkMenu').checked ? 'true' : 'false' ) ; SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { SetAttribute( e, 'className', GetE('txtAttClasses').value ) ; e.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( e, 'class', GetE('txtAttClasses').value ) ; SetAttribute( e, 'style', GetE('txtAttStyle').value ) ; } } var ePreview ; function SetPreviewElement( previewEl ) { ePreview = previewEl ; if ( GetE('txtUrl').value.length > 0 ) UpdatePreview() ; } function UpdatePreview() { if ( !ePreview ) return ; while ( ePreview.firstChild ) ePreview.removeChild( ePreview.firstChild ) ; if ( GetE('txtUrl').value.length == 0 ) ePreview.innerHTML = '&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 ) ; } } // <embed id="ePreview" src="fck_flash/claims.swf" width="100%" height="100%" style="visibility:hidden" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> function BrowseServer() { OpenFileBrowser( FCKConfig.FlashBrowserURL, FCKConfig.FlashBrowserWindowWidth, FCKConfig.FlashBrowserWindowHeight ) ; } function SetUrl( url, width, height ) { GetE('txtUrl').value = url ; if ( width ) GetE('txtWidth').value = width ; if ( height ) GetE('txtHeight').value = height ; UpdatePreview() ; dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.FlashUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.FlashUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value ; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.FlashUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.FlashUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Plugin to insert "Placeholders" in the editor. */ // Register the related command. FCKCommands.RegisterCommand( 'Placeholder', new FCKDialogCommand( 'Placeholder', FCKLang.PlaceholderDlgTitle, FCKPlugins.Items['placeholder'].Path + 'fck_placeholder.html', 340, 160 ) ) ; // Create the "Plaholder" toolbar button. var oPlaceholderItem = new FCKToolbarButton( 'Placeholder', FCKLang.PlaceholderBtn ) ; oPlaceholderItem.IconPath = FCKPlugins.Items['placeholder'].Path + 'placeholder.gif' ; FCKToolbarItems.RegisterItem( 'Placeholder', oPlaceholderItem ) ; // The object used for all Placeholder operations. var FCKPlaceholders = new Object() ; // Add a new placeholder at the actual selection. FCKPlaceholders.Add = function( name ) { var oSpan = FCK.InsertElement( 'span' ) ; this.SetupSpan( oSpan, name ) ; } FCKPlaceholders.SetupSpan = function( span, name ) { span.innerHTML = '[[ ' + name + ' ]]' ; span.style.backgroundColor = '#ffff00' ; span.style.color = '#000000' ; if ( FCKBrowserInfo.IsGecko ) span.style.cursor = 'default' ; span._fckplaceholder = name ; span.contentEditable = false ; // To avoid it to be resized. span.onresizestart = function() { FCK.EditorWindow.event.returnValue = false ; return false ; } } // On Gecko we must do this trick so the user select all the SPAN when clicking on it. FCKPlaceholders._SetupClickListener = function() { FCKPlaceholders._ClickListener = function( e ) { if ( e.target.tagName == 'SPAN' && e.target._fckplaceholder ) FCKSelection.SelectNode( e.target ) ; } FCK.EditorDocument.addEventListener( 'click', FCKPlaceholders._ClickListener, true ) ; } // Open the Placeholder dialog on double click. FCKPlaceholders.OnDoubleClick = function( span ) { if ( span.tagName == 'SPAN' && span._fckplaceholder ) FCKCommands.GetCommand( 'Placeholder' ).Execute() ; } FCK.RegisterDoubleClickHandler( FCKPlaceholders.OnDoubleClick, 'SPAN' ) ; // Check if a Placholder name is already in use. FCKPlaceholders.Exist = function( name ) { var aSpans = FCK.EditorDocument.getElementsByTagName( 'SPAN' ) ; for ( var i = 0 ; i < aSpans.length ; i++ ) { if ( aSpans[i]._fckplaceholder == name ) return true ; } return false ; } if ( FCKBrowserInfo.IsIE ) { FCKPlaceholders.Redraw = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; var aPlaholders = FCK.EditorDocument.body.innerText.match( /\[\[[^\[\]]+\]\]/g ) ; if ( !aPlaholders ) return ; var oRange = FCK.EditorDocument.body.createTextRange() ; for ( var i = 0 ; i < aPlaholders.length ; i++ ) { if ( oRange.findText( aPlaholders[i] ) ) { var sName = aPlaholders[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ; oRange.pasteHTML( '<span style="color: #000000; background-color: #ffff00" contenteditable="false" _fckplaceholder="' + sName + '">' + aPlaholders[i] + '</span>' ) ; } } } } else { FCKPlaceholders.Redraw = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; var oInteractor = FCK.EditorDocument.createTreeWalker( FCK.EditorDocument.body, NodeFilter.SHOW_TEXT, FCKPlaceholders._AcceptNode, true ) ; var aNodes = new Array() ; while ( ( oNode = oInteractor.nextNode() ) ) { aNodes[ aNodes.length ] = oNode ; } for ( var n = 0 ; n < aNodes.length ; n++ ) { var aPieces = aNodes[n].nodeValue.split( /(\[\[[^\[\]]+\]\])/g ) ; for ( var i = 0 ; i < aPieces.length ; i++ ) { if ( aPieces[i].length > 0 ) { if ( aPieces[i].indexOf( '[[' ) == 0 ) { var sName = aPieces[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ; var oSpan = FCK.EditorDocument.createElement( 'span' ) ; FCKPlaceholders.SetupSpan( oSpan, sName ) ; aNodes[n].parentNode.insertBefore( oSpan, aNodes[n] ) ; } else aNodes[n].parentNode.insertBefore( FCK.EditorDocument.createTextNode( aPieces[i] ) , aNodes[n] ) ; } } aNodes[n].parentNode.removeChild( aNodes[n] ) ; } FCKPlaceholders._SetupClickListener() ; } FCKPlaceholders._AcceptNode = function( node ) { if ( /\[\[[^\[\]]+\]\]/.test( node.nodeValue ) ) return NodeFilter.FILTER_ACCEPT ; else return NodeFilter.FILTER_SKIP ; } } FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKPlaceholders.Redraw ) ; // We must process the SPAN tags to replace then with the real resulting value of the placeholder. FCKXHtml.TagProcessors['span'] = function( node, htmlNode ) { if ( htmlNode._fckplaceholder ) node = FCKXHtml.XML.createTextNode( '[[' + htmlNode._fckplaceholder + ']]' ) ; else FCKXHtml._AppendChildNodes( node, htmlNode, false ) ; return node ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder Italian language file. */ FCKLang.PlaceholderBtn = 'Aggiungi/Modifica Placeholder' ; FCKLang.PlaceholderDlgTitle = 'Proprietà del Placeholder' ; FCKLang.PlaceholderDlgName = 'Nome del Placeholder' ; FCKLang.PlaceholderErrNoName = 'Digitare il nome del placeholder' ; FCKLang.PlaceholderErrNameInUse = 'Il nome inserito è già in uso' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder German language file. */ FCKLang.PlaceholderBtn = 'Einfügen/editieren Platzhalter' ; FCKLang.PlaceholderDlgTitle = 'Platzhalter Eigenschaften' ; FCKLang.PlaceholderDlgName = 'Platzhalter Name' ; FCKLang.PlaceholderErrNoName = 'Bitte den Namen des Platzhalters schreiben' ; FCKLang.PlaceholderErrNameInUse = 'Der angegebene Namen ist schon in Gebrauch' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder Polish language file. */ FCKLang.PlaceholderBtn = 'Wstaw/Edytuj nagłówek' ; FCKLang.PlaceholderDlgTitle = 'Właśności nagłówka' ; FCKLang.PlaceholderDlgName = 'Nazwa nagłówka' ; FCKLang.PlaceholderErrNoName = 'Proszę wprowadzić nazwę nagłówka' ; FCKLang.PlaceholderErrNameInUse = 'Podana nazwa jest już w użyciu' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placeholder French language file. */ FCKLang.PlaceholderBtn = "Insérer/Modifier l'Espace réservé" ; FCKLang.PlaceholderDlgTitle = "Propriétés de l'Espace réservé" ; FCKLang.PlaceholderDlgName = "Nom de l'Espace réservé" ; FCKLang.PlaceholderErrNoName = "Veuillez saisir le nom de l'Espace réservé" ; FCKLang.PlaceholderErrNameInUse = "Ce nom est déjà utilisé" ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder English language file. */ FCKLang.PlaceholderBtn = 'Insert/Edit Placeholder' ; FCKLang.PlaceholderDlgTitle = 'Placeholder Properties' ; FCKLang.PlaceholderDlgName = 'Placeholder Name' ; FCKLang.PlaceholderErrNoName = 'Please type the placeholder name' ; FCKLang.PlaceholderErrNameInUse = 'The specified name is already in use' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder Spanish language file. */ FCKLang.PlaceholderBtn = 'Insertar/Editar contenedor' ; FCKLang.PlaceholderDlgTitle = 'Propiedades del contenedor ' ; FCKLang.PlaceholderDlgName = 'Nombre de contenedor' ; FCKLang.PlaceholderErrNoName = 'Por favor escriba el nombre de contenedor' ; FCKLang.PlaceholderErrNameInUse = 'El nombre especificado ya esta en uso' ;
JavaScript
var FCKDragTableHandler = { "_DragState" : 0, "_LeftCell" : null, "_RightCell" : null, "_MouseMoveMode" : 0, // 0 - find candidate cells for resizing, 1 - drag to resize "_ResizeBar" : null, "_OriginalX" : null, "_MinimumX" : null, "_MaximumX" : null, "_LastX" : null, "_TableMap" : null, "_doc" : document, "_IsInsideNode" : function( w, domNode, pos ) { var myCoords = FCKTools.GetWindowPosition( w, domNode ) ; var xMin = myCoords.x ; var yMin = myCoords.y ; var xMax = parseInt( xMin, 10 ) + parseInt( domNode.offsetWidth, 10 ) ; var yMax = parseInt( yMin, 10 ) + parseInt( domNode.offsetHeight, 10 ) ; if ( pos.x >= xMin && pos.x <= xMax && pos.y >= yMin && pos.y <= yMax ) return true; return false; }, "_GetBorderCells" : function( w, tableNode, tableMap, mouse ) { // Enumerate all the cells in the table. var cells = [] ; for ( var i = 0 ; i < tableNode.rows.length ; i++ ) { var r = tableNode.rows[i] ; for ( var j = 0 ; j < r.cells.length ; j++ ) cells.push( r.cells[j] ) ; } if ( cells.length < 1 ) return null ; // Get the cells whose right or left border is nearest to the mouse cursor's x coordinate. var minRxDist = null ; var lxDist = null ; var minYDist = null ; var rbCell = null ; var lbCell = null ; for ( var i = 0 ; i < cells.length ; i++ ) { var pos = FCKTools.GetWindowPosition( w, cells[i] ) ; var rightX = pos.x + parseInt( cells[i].clientWidth, 10 ) ; var rxDist = mouse.x - rightX ; var yDist = mouse.y - ( pos.y + ( cells[i].clientHeight / 2 ) ) ; if ( minRxDist == null || ( Math.abs( rxDist ) <= Math.abs( minRxDist ) && ( minYDist == null || Math.abs( yDist ) <= Math.abs( minYDist ) ) ) ) { minRxDist = rxDist ; minYDist = yDist ; rbCell = cells[i] ; } } /* var rowNode = FCKTools.GetElementAscensor( rbCell, "tr" ) ; var cellIndex = rbCell.cellIndex + 1 ; if ( cellIndex >= rowNode.cells.length ) return null ; lbCell = rowNode.cells.item( cellIndex ) ; */ var rowIdx = rbCell.parentNode.rowIndex ; var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, rbCell ) ; var colSpan = isNaN( rbCell.colSpan ) ? 1 : rbCell.colSpan ; lbCell = tableMap[rowIdx][colIdx + colSpan] ; if ( ! lbCell ) return null ; // Abort if too far from the border. lxDist = mouse.x - FCKTools.GetWindowPosition( w, lbCell ).x ; if ( lxDist < 0 && minRxDist < 0 && minRxDist < -2 ) return null ; if ( lxDist > 0 && minRxDist > 0 && lxDist > 3 ) return null ; return { "leftCell" : rbCell, "rightCell" : lbCell } ; }, "_GetResizeBarPosition" : function() { var row = FCKTools.GetElementAscensor( this._RightCell, "tr" ) ; return FCKTableHandler._GetCellIndexSpan( this._TableMap, row.rowIndex, this._RightCell ) ; }, "_ResizeBarMouseDownListener" : function( evt ) { if ( FCKDragTableHandler._LeftCell ) FCKDragTableHandler._MouseMoveMode = 1 ; if ( FCKBrowserInfo.IsIE ) FCKDragTableHandler._ResizeBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 50 ; else FCKDragTableHandler._ResizeBar.style.opacity = 0.5 ; FCKDragTableHandler._OriginalX = evt.clientX ; // Calculate maximum and minimum x-coordinate delta. var borderIndex = FCKDragTableHandler._GetResizeBarPosition() ; var offset = FCKDragTableHandler._GetIframeOffset(); var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ); var minX = null ; var maxX = null ; for ( var r = 0 ; r < FCKDragTableHandler._TableMap.length ; r++ ) { var leftCell = FCKDragTableHandler._TableMap[r][borderIndex - 1] ; var rightCell = FCKDragTableHandler._TableMap[r][borderIndex] ; var leftPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, leftCell ) ; var rightPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, rightCell ) ; var leftPadding = FCKDragTableHandler._GetCellPadding( table, leftCell ) ; var rightPadding = FCKDragTableHandler._GetCellPadding( table, rightCell ) ; if ( minX == null || leftPosition.x + leftPadding > minX ) minX = leftPosition.x + leftPadding ; if ( maxX == null || rightPosition.x + rightCell.clientWidth - rightPadding < maxX ) maxX = rightPosition.x + rightCell.clientWidth - rightPadding ; } FCKDragTableHandler._MinimumX = minX + offset.x ; FCKDragTableHandler._MaximumX = maxX + offset.x ; FCKDragTableHandler._LastX = null ; if (evt.preventDefault) evt.preventDefault(); else evt.returnValue = false; }, "_ResizeBarMouseUpListener" : function( evt ) { FCKDragTableHandler._MouseMoveMode = 0 ; FCKDragTableHandler._HideResizeBar() ; if ( FCKDragTableHandler._LastX == null ) return ; // Calculate the delta value. var deltaX = FCKDragTableHandler._LastX - FCKDragTableHandler._OriginalX ; // Then, build an array of current column width values. // This algorithm can be very slow if the cells have insane colSpan values. (e.g. colSpan=1000). var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ) ; var colArray = [] ; var tableMap = FCKDragTableHandler._TableMap ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; var width = FCKDragTableHandler._GetCellWidth( table, cell ) ; var colSpan = isNaN( cell.colSpan) ? 1 : cell.colSpan ; if ( colArray.length <= j ) colArray.push( { width : width / colSpan, colSpan : colSpan } ) ; else { var guessItem = colArray[j] ; if ( guessItem.colSpan > colSpan ) { guessItem.width = width / colSpan ; guessItem.colSpan = colSpan ; } } } } // Find out the equivalent column index of the two cells selected for resizing. colIndex = FCKDragTableHandler._GetResizeBarPosition() ; // Note that colIndex must be at least 1 here, so it's safe to subtract 1 from it. colIndex-- ; // Modify the widths in the colArray according to the mouse coordinate delta value. colArray[colIndex].width += deltaX ; colArray[colIndex + 1].width -= deltaX ; // Clear all cell widths, delete all <col> elements from the table. for ( var r = 0 ; r < table.rows.length ; r++ ) { var row = table.rows.item( r ) ; for ( var c = 0 ; c < row.cells.length ; c++ ) { var cell = row.cells.item( c ) ; cell.width = "" ; cell.style.width = "" ; } } var colElements = table.getElementsByTagName( "col" ) ; for ( var i = colElements.length - 1 ; i >= 0 ; i-- ) colElements[i].parentNode.removeChild( colElements[i] ) ; // Set new cell widths. var processedCells = [] ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; if ( cell._Processed ) continue ; if ( tableMap[i][j-1] != cell ) cell.width = colArray[j].width ; else cell.width = parseInt( cell.width, 10 ) + parseInt( colArray[j].width, 10 ) ; if ( tableMap[i][j+1] != cell ) { processedCells.push( cell ) ; cell._Processed = true ; } } } for ( var i = 0 ; i < processedCells.length ; i++ ) { if ( FCKBrowserInfo.IsIE ) processedCells[i].removeAttribute( '_Processed' ) ; else delete processedCells[i]._Processed ; } FCKDragTableHandler._LastX = null ; }, "_ResizeBarMouseMoveListener" : function( evt ) { if ( FCKDragTableHandler._MouseMoveMode == 0 ) return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; else return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; }, // Calculate the padding of a table cell. // It returns the value of paddingLeft + paddingRight of a table cell. // This function is used, in part, to calculate the width parameter that should be used for setting cell widths. // The equation in question is clientWidth = paddingLeft + paddingRight + width. // So that width = clientWidth - paddingLeft - paddingRight. // The return value of this function must be pixel accurate acorss all supported browsers, so be careful if you need to modify it. "_GetCellPadding" : function( table, cell ) { var attrGuess = parseInt( table.cellPadding, 10 ) * 2 ; var cssGuess = null ; if ( typeof( window.getComputedStyle ) == "function" ) { var styleObj = window.getComputedStyle( cell, null ) ; cssGuess = parseInt( styleObj.getPropertyValue( "padding-left" ), 10 ) + parseInt( styleObj.getPropertyValue( "padding-right" ), 10 ) ; } else cssGuess = parseInt( cell.currentStyle.paddingLeft, 10 ) + parseInt (cell.currentStyle.paddingRight, 10 ) ; var cssRuntime = cell.style.padding ; if ( isFinite( cssRuntime ) ) cssGuess = parseInt( cssRuntime, 10 ) * 2 ; else { cssRuntime = cell.style.paddingLeft ; if ( isFinite( cssRuntime ) ) cssGuess = parseInt( cssRuntime, 10 ) ; cssRuntime = cell.style.paddingRight ; if ( isFinite( cssRuntime ) ) cssGuess += parseInt( cssRuntime, 10 ) ; } attrGuess = parseInt( attrGuess, 10 ) ; cssGuess = parseInt( cssGuess, 10 ) ; if ( isNaN( attrGuess ) ) attrGuess = 0 ; if ( isNaN( cssGuess ) ) cssGuess = 0 ; return Math.max( attrGuess, cssGuess ) ; }, // Calculate the real width of the table cell. // The real width of the table cell is the pixel width that you can set to the width attribute of the table cell and after // that, the table cell should be of exactly the same width as before. // The real width of a table cell can be calculated as: // width = clientWidth - paddingLeft - paddingRight. "_GetCellWidth" : function( table, cell ) { var clientWidth = cell.clientWidth ; if ( isNaN( clientWidth ) ) clientWidth = 0 ; return clientWidth - this._GetCellPadding( table, cell ) ; }, "MouseMoveListener" : function( FCK, evt ) { if ( FCKDragTableHandler._MouseMoveMode == 0 ) return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; else return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; }, "_MouseFindHandler" : function( FCK, evt ) { if ( FCK.MouseDownFlag ) return ; var node = evt.srcElement || evt.target ; try { if ( ! node || node.nodeType != 1 ) { this._HideResizeBar() ; return ; } } catch ( e ) { this._HideResizeBar() ; return ; } // Since this function might be called from the editing area iframe or the outer fckeditor iframe, // the mouse point coordinates from evt.clientX/Y can have different reference points. // We need to resolve the mouse pointer position relative to the editing area iframe. var mouseX = evt.clientX ; var mouseY = evt.clientY ; if ( FCKTools.GetElementDocument( node ) == document ) { var offset = this._GetIframeOffset() ; mouseX -= offset.x ; mouseY -= offset.y ; } if ( this._ResizeBar && this._LeftCell ) { var leftPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._LeftCell ) ; var rightPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._RightCell ) ; var rxDist = mouseX - ( leftPos.x + this._LeftCell.clientWidth ) ; var lxDist = mouseX - rightPos.x ; var inRangeFlag = false ; if ( lxDist >= 0 && rxDist <= 0 ) inRangeFlag = true ; else if ( rxDist > 0 && lxDist <= 3 ) inRangeFlag = true ; else if ( lxDist < 0 && rxDist >= -2 ) inRangeFlag = true ; if ( inRangeFlag ) { this._ShowResizeBar( FCK.EditorWindow, FCKTools.GetElementAscensor( this._LeftCell, "table" ), { "x" : mouseX, "y" : mouseY } ) ; return ; } } var tagName = node.tagName.toLowerCase() ; if ( tagName != "table" && tagName != "td" && tagName != "th" ) { if ( this._LeftCell ) this._LeftCell = this._RightCell = this._TableMap = null ; this._HideResizeBar() ; return ; } node = FCKTools.GetElementAscensor( node, "table" ) ; var tableMap = FCKTableHandler._CreateTableMap( node ) ; var cellTuple = this._GetBorderCells( FCK.EditorWindow, node, tableMap, { "x" : mouseX, "y" : mouseY } ) ; if ( cellTuple == null ) { if ( this._LeftCell ) this._LeftCell = this._RightCell = this._TableMap = null ; this._HideResizeBar() ; } else { this._LeftCell = cellTuple["leftCell"] ; this._RightCell = cellTuple["rightCell"] ; this._TableMap = tableMap ; this._ShowResizeBar( FCK.EditorWindow, FCKTools.GetElementAscensor( this._LeftCell, "table" ), { "x" : mouseX, "y" : mouseY } ) ; } }, "_MouseDragHandler" : function( FCK, evt ) { var mouse = { "x" : evt.clientX, "y" : evt.clientY } ; // Convert mouse coordinates in reference to the outer iframe. var node = evt.srcElement || evt.target ; if ( FCKTools.GetElementDocument( node ) == FCK.EditorDocument ) { var offset = this._GetIframeOffset() ; mouse.x += offset.x ; mouse.y += offset.y ; } // Calculate the mouse position delta and see if we've gone out of range. if ( mouse.x >= this._MaximumX - 5 ) mouse.x = this._MaximumX - 5 ; if ( mouse.x <= this._MinimumX + 5 ) mouse.x = this._MinimumX + 5 ; var docX = mouse.x + FCKTools.GetScrollPosition( window ).X ; this._ResizeBar.style.left = ( docX - this._ResizeBar.offsetWidth / 2 ) + "px" ; this._LastX = mouse.x ; }, "_ShowResizeBar" : function( w, table, mouse ) { if ( this._ResizeBar == null ) { this._ResizeBar = this._doc.createElement( "div" ) ; var paddingBar = this._ResizeBar ; var paddingStyles = { 'position' : 'absolute', 'cursor' : 'e-resize' } ; if ( FCKBrowserInfo.IsIE ) paddingStyles.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=10,enabled=true)" ; else paddingStyles.opacity = 0.10 ; FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; this._avoidStyles( paddingBar ); paddingBar.setAttribute('_fcktemp', true); this._doc.body.appendChild( paddingBar ) ; FCKTools.AddEventListener( paddingBar, "mousemove", this._ResizeBarMouseMoveListener ) ; FCKTools.AddEventListener( paddingBar, "mousedown", this._ResizeBarMouseDownListener ) ; FCKTools.AddEventListener( document, "mouseup", this._ResizeBarMouseUpListener ) ; FCKTools.AddEventListener( FCK.EditorDocument, "mouseup", this._ResizeBarMouseUpListener ) ; // IE doesn't let the tranparent part of the padding block to receive mouse events unless there's something inside. // So we need to create a spacer image to fill the block up. var filler = this._doc.createElement( "img" ) ; filler.setAttribute('_fcktemp', true); filler.border = 0 ; filler.src = FCKConfig.BasePath + "images/spacer.gif" ; filler.style.position = "absolute" ; paddingBar.appendChild( filler ) ; // Disable drag and drop, and selection for the filler image. var disabledListener = function( evt ) { if ( evt.preventDefault ) evt.preventDefault() ; else evt.returnValue = false ; } FCKTools.AddEventListener( filler, "dragstart", disabledListener ) ; FCKTools.AddEventListener( filler, "selectstart", disabledListener ) ; } var paddingBar = this._ResizeBar ; var offset = this._GetIframeOffset() ; var tablePos = this._GetTablePosition( w, table ) ; var barHeight = table.offsetHeight ; var barTop = offset.y + tablePos.y ; // Do not let the resize bar intrude into the toolbar area. if ( tablePos.y < 0 ) { barHeight += tablePos.y ; barTop -= tablePos.y ; } var bw = parseInt( table.border, 10 ) ; if ( isNaN( bw ) ) bw = 0 ; var cs = parseInt( table.cellSpacing, 10 ) ; if ( isNaN( cs ) ) cs = 0 ; var barWidth = Math.max( bw+100, cs+100 ) ; var paddingStyles = { 'top' : barTop + 'px', 'height' : barHeight + 'px', 'width' : barWidth + 'px', 'left' : ( offset.x + mouse.x + FCKTools.GetScrollPosition( w ).X - barWidth / 2 ) + 'px' } ; if ( FCKBrowserInfo.IsIE ) paddingBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 10 ; else paddingStyles.opacity = 0.1 ; FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; var filler = paddingBar.getElementsByTagName( "img" )[0] ; FCKDomTools.SetElementStyles( filler, { width : paddingBar.offsetWidth + 'px', height : barHeight + 'px' } ) ; barWidth = Math.max( bw, cs, 3 ) ; var visibleBar = null ; if ( paddingBar.getElementsByTagName( "div" ).length < 1 ) { visibleBar = this._doc.createElement( "div" ) ; this._avoidStyles( visibleBar ); visibleBar.setAttribute('_fcktemp', true); paddingBar.appendChild( visibleBar ) ; } else visibleBar = paddingBar.getElementsByTagName( "div" )[0] ; FCKDomTools.SetElementStyles( visibleBar, { position : 'absolute', backgroundColor : 'blue', width : barWidth + 'px', height : barHeight + 'px', left : '50px', top : '0px' } ) ; }, "_HideResizeBar" : function() { if ( this._ResizeBar ) // IE bug: display : none does not hide the resize bar for some reason. // so set the position to somewhere invisible. FCKDomTools.SetElementStyles( this._ResizeBar, { top : '-100000px', left : '-100000px' } ) ; }, "_GetIframeOffset" : function () { return FCKTools.GetDocumentPosition( window, FCK.EditingArea.IFrame ) ; }, "_GetTablePosition" : function ( w, table ) { return FCKTools.GetWindowPosition( w, table ) ; }, "_avoidStyles" : function( element ) { FCKDomTools.SetElementStyles( element, { padding : '0', backgroundImage : 'none', border : '0' } ) ; }, "Reset" : function() { FCKDragTableHandler._LeftCell = FCKDragTableHandler._RightCell = FCKDragTableHandler._TableMap = null ; } }; FCK.Events.AttachEvent( "OnMouseMove", FCKDragTableHandler.MouseMoveListener ) ; FCK.Events.AttachEvent( "OnAfterSetHTML", FCKDragTableHandler.Reset ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Plugin: automatically resizes the editor until a configurable maximun * height (FCKConfig.AutoGrowMax), based on its contents. */ var FCKAutoGrow = { MIN_HEIGHT : window.frameElement.offsetHeight, Check : function() { var delta = FCKAutoGrow.GetHeightDelta() ; if ( delta != 0 ) { var newHeight = window.frameElement.offsetHeight + delta ; newHeight = FCKAutoGrow.GetEffectiveHeight( newHeight ) ; if ( newHeight != window.frameElement.height ) { window.frameElement.style.height = newHeight + "px" ; // Gecko browsers use an onresize handler to update the innermost // IFRAME's height. If the document is modified before the onresize // is triggered, the plugin will miscalculate the new height. Thus, // forcibly trigger onresize. #1336 if ( typeof window.onresize == 'function' ) { window.onresize() ; } } } }, CheckEditorStatus : function( sender, status ) { if ( status == FCK_STATUS_COMPLETE ) FCKAutoGrow.Check() ; }, GetEffectiveHeight : function( height ) { if ( height < FCKAutoGrow.MIN_HEIGHT ) height = FCKAutoGrow.MIN_HEIGHT; else { var max = FCKConfig.AutoGrowMax; if ( max && max > 0 && height > max ) height = max; } return height; }, GetHeightDelta : function() { var oInnerDoc = FCK.EditorDocument ; var iFrameHeight ; var iInnerHeight ; if ( FCKBrowserInfo.IsIE ) { iFrameHeight = FCK.EditorWindow.frameElement.offsetHeight ; iInnerHeight = oInnerDoc.body.scrollHeight ; } else { iFrameHeight = FCK.EditorWindow.innerHeight ; iInnerHeight = oInnerDoc.body.offsetHeight + ( parseInt( FCKDomTools.GetCurrentElementStyle( oInnerDoc.body, 'margin-top' ), 10 ) || 0 ) + ( parseInt( FCKDomTools.GetCurrentElementStyle( oInnerDoc.body, 'margin-bottom' ), 10 ) || 0 ) ; } return iInnerHeight - iFrameHeight ; }, SetListeners : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; FCK.EditorWindow.attachEvent( 'onscroll', FCKAutoGrow.Check ) ; FCK.EditorDocument.attachEvent( 'onkeyup', FCKAutoGrow.Check ) ; } }; FCK.AttachToOnSelectionChange( FCKAutoGrow.Check ) ; if ( FCKBrowserInfo.IsIE ) FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKAutoGrow.SetListeners ) ; FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow.CheckEditorStatus ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 a sample implementation for a custom Data Processor for basic BBCode. */ FCK.DataProcessor = { /* * Returns a string representing the HTML format of "data". The returned * value will be loaded in the editor. * The HTML must be from <html> to </html>, eventually including * the DOCTYPE. * @param {String} data The data to be converted in the * DataProcessor specific format. */ ConvertToHtml : function( data ) { // Convert < and > to their HTML entities. data = data.replace( /</g, '&lt;' ) ; data = data.replace( />/g, '&gt;' ) ; // Convert line breaks to <br>. data = data.replace( /(?:\r\n|\n|\r)/g, '<br>' ) ; // [url] data = data.replace( /\[url\](.+?)\[\/url]/gi, '<a href="$1">$1</a>' ) ; data = data.replace( /\[url\=([^\]]+)](.+?)\[\/url]/gi, '<a href="$1">$2</a>' ) ; // [b] data = data.replace( /\[b\](.+?)\[\/b]/gi, '<b>$1</b>' ) ; // [i] data = data.replace( /\[i\](.+?)\[\/i]/gi, '<i>$1</i>' ) ; // [u] data = data.replace( /\[u\](.+?)\[\/u]/gi, '<u>$1</u>' ) ; return '<html><head><title></title></head><body>' + data + '</body></html>' ; }, /* * Converts a DOM (sub-)tree to a string in the data format. * @param {Object} rootNode The node that contains the DOM tree to be * converted to the data format. * @param {Boolean} excludeRoot Indicates that the root node must not * be included in the conversion, only its children. * @param {Boolean} format Indicates that the data must be formatted * for human reading. Not all Data Processors may provide it. */ ConvertToDataFormat : function( rootNode, excludeRoot, ignoreIfEmptyParagraph, format ) { var data = rootNode.innerHTML ; // Convert <br> to line breaks. data = data.replace( /<br(?=[ \/>]).*?>/gi, '\r\n') ; // [url] data = data.replace( /<a .*?href=(["'])(.+?)\1.*?>(.+?)<\/a>/gi, '[url=$2]$3[/url]') ; // [b] data = data.replace( /<(?:b|strong)>/gi, '[b]') ; data = data.replace( /<\/(?:b|strong)>/gi, '[/b]') ; // [i] data = data.replace( /<(?:i|em)>/gi, '[i]') ; data = data.replace( /<\/(?:i|em)>/gi, '[/i]') ; // [u] data = data.replace( /<u>/gi, '[u]') ; data = data.replace( /<\/u>/gi, '[/u]') ; // Remove remaining tags. data = data.replace( /<[^>]+>/g, '') ; return data ; }, /* * Makes any necessary changes to a piece of HTML for insertion in the * editor selection position. * @param {String} html The HTML to be fixed. */ FixHtml : function( html ) { return html ; } } ; // This Data Processor doesn't support <p>, so let's use <br>. FCKConfig.EnterMode = 'br' ; // To avoid pasting invalid markup (which is discarded in any case), let's // force pasting to plain text. FCKConfig.ForcePasteAsPlainText = true ; // Rename the "Source" buttom to "BBCode". FCKToolbarItems.RegisterItem( 'Source', new FCKToolbarButton( 'Source', 'BBCode', null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ) ; // Let's enforce the toolbar to the limits of this Data Processor. A custom // toolbar set may be defined in the configuration file with more or less entries. FCKConfig.ToolbarSets["Default"] = [ ['Source'], ['Bold','Italic','Underline','-','Link'], ['About'] ] ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Sample custom configuration settings used by the BBCode plugin. It simply * loads the plugin. All the rest is done by the plugin itself. */ // Add the BBCode plugin. FCKConfig.Plugins.Add( 'bbcode' ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 plugin register the required Toolbar items to be able to insert the * table commands in the toolbar. */ FCKToolbarItems.RegisterItem( 'TableInsertRowAfter' , new FCKToolbarButton( 'TableInsertRowAfter' , FCKLang.InsertRowAfter, null, null, null, true, 62 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteRows' , new FCKToolbarButton( 'TableDeleteRows' , FCKLang.DeleteRows, null, null, null, true, 63 ) ) ; FCKToolbarItems.RegisterItem( 'TableInsertColumnAfter' , new FCKToolbarButton( 'TableInsertColumnAfter' , FCKLang.InsertColumnAfter, null, null, null, true, 64 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteColumns' , new FCKToolbarButton( 'TableDeleteColumns', FCKLang.DeleteColumns, null, null, null, true, 65 ) ) ; FCKToolbarItems.RegisterItem( 'TableInsertCellAfter' , new FCKToolbarButton( 'TableInsertCellAfter' , FCKLang.InsertCellAfter, null, null, null, true, 58 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteCells' , new FCKToolbarButton( 'TableDeleteCells' , FCKLang.DeleteCells, null, null, null, true, 59 ) ) ; FCKToolbarItems.RegisterItem( 'TableMergeCells' , new FCKToolbarButton( 'TableMergeCells' , FCKLang.MergeCells, null, null, null, true, 60 ) ) ; FCKToolbarItems.RegisterItem( 'TableHorizontalSplitCell' , new FCKToolbarButton( 'TableHorizontalSplitCell' , FCKLang.SplitCell, null, null, null, true, 61 ) ) ; FCKToolbarItems.RegisterItem( 'TableCellProp' , new FCKToolbarButton( 'TableCellProp' , FCKLang.CellProperties, null, null, null, true, 57 ) ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 plugin register Toolbar items for the combos modifying the style to * not show the box. */ FCKToolbarItems.RegisterItem( 'SourceSimple' , new FCKToolbarButton( 'Source', FCKLang.Source, null, FCK_TOOLBARITEM_ONLYICON, true, true, 1 ) ) ; FCKToolbarItems.RegisterItem( 'StyleSimple' , new FCKToolbarStyleCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontNameSimple' , new FCKToolbarFontsCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontSizeSimple' , new FCKToolbarFontSizeCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontFormatSimple', new FCKToolbarFontFormatCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Common objects and functions shared by all pages that compose the * File Browser dialog window. */ // Automatically detect the correct document.domain (#1919). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.top.opener.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 ; } } })() ; function AddSelectOption( selectElement, optionText, optionValue ) { var oOption = document.createElement("OPTION") ; oOption.text = optionText ; oOption.value = optionValue ; selectElement.options.add(oOption) ; return oOption ; } var oConnector = window.parent.oConnector ; var oIcons = window.parent.oIcons ; function StringBuilder( value ) { this._Strings = new Array( value || '' ) ; } StringBuilder.prototype.Append = function( value ) { if ( value ) this._Strings.push( value ) ; } StringBuilder.prototype.ToString = function() { return this._Strings.join( '' ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Defines the FCKXml object that is used for XML data calls * and XML processing. * * This script is shared by almost all pages that compose the * File Browser frameset. */ var FCKXml = function() {} FCKXml.prototype.GetHttpRequest = function() { // Gecko / IE7 try { return new XMLHttpRequest(); } catch(e) {} // IE6 try { return new ActiveXObject( 'Msxml2.XMLHTTP' ) ; } catch(e) {} // IE5 try { return new ActiveXObject( 'Microsoft.XMLHTTP' ) ; } catch(e) {} return null ; } FCKXml.prototype.LoadUrl = function( urlToCall, asyncFunctionPointer ) { var oFCKXml = this ; var bAsync = ( typeof(asyncFunctionPointer) == 'function' ) ; var oXmlHttp = this.GetHttpRequest() ; oXmlHttp.open( "GET", urlToCall, bAsync ) ; if ( bAsync ) { oXmlHttp.onreadystatechange = function() { if ( oXmlHttp.readyState == 4 ) { var oXml ; try { // this is the same test for an FF2 bug as in fckxml_gecko.js // but we've moved the responseXML assignment into the try{} // so we don't even have to check the return status codes. var test = oXmlHttp.responseXML.firstChild ; oXml = oXmlHttp.responseXML ; } catch ( e ) { try { oXml = (new DOMParser()).parseFromString( oXmlHttp.responseText, 'text/xml' ) ; } catch ( e ) {} } if ( !oXml || !oXml.firstChild || oXml.firstChild.nodeName == 'parsererror' ) { alert( 'The server didn\'t send back a proper XML response. Please contact your system administrator.\n\n' + 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')\n\n' + 'Requested URL:\n' + urlToCall + '\n\n' + 'Response text:\n' + oXmlHttp.responseText ) ; return ; } oFCKXml.DOMDocument = oXml ; asyncFunctionPointer( oFCKXml ) ; } } } oXmlHttp.send( null ) ; if ( ! bAsync ) { if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 ) this.DOMDocument = oXmlHttp.responseXML ; else { alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ; } } } FCKXml.prototype.SelectNodes = function( xpath ) { if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE return this.DOMDocument.selectNodes( xpath ) ; else // Gecko { var aNodeArray = new Array(); var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ; if ( xPathResult ) { var oNode = xPathResult.iterateNext() ; while( oNode ) { aNodeArray[aNodeArray.length] = oNode ; oNode = xPathResult.iterateNext(); } } return aNodeArray ; } } FCKXml.prototype.SelectSingleNode = function( xpath ) { if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE return this.DOMDocument.selectSingleNode( xpath ) ; else // Gecko { var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null); if ( xPathResult && xPathResult.singleNodeValue ) return xPathResult.singleNodeValue ; else return null ; } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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.4' ; FCKeditor.prototype.VersionBuild = '21629' ; 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 ; if ( this.TabIndex ) sHtml += '" tabindex="' + this.TabIndex ; sHtml += '">' + this._HTMLEncode( this.Value ) + '<\/textarea>' ; } return sHtml ; } FCKeditor.prototype.ReplaceTextarea = function() { if ( document.getElementById( this.InstanceName + '___Frame' ) ) return ; 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' ; if ( oTextarea.tabIndex ) this.TabIndex = oTextarea.tabIndex ; 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 ; var html = '<iframe id="' + this.InstanceName + '___Frame" src="' + sLink + '" width="' + this.Width + '" height="' + this.Height ; if ( this.TabIndex ) html += '" tabindex="' + this.TabIndex ; html += '" frameborder="0" scrolling="no"></iframe>' ; return html ; } 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
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Editor configuration settings. * * Follow this link for more information: * http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.FullPage = false ; // The following option determines whether the "Show Blocks" feature is enabled or not at startup. FCKConfig.StartupShowBlocks = false ; FCKConfig.Debug = false ; FCKConfig.AllowQueryStringDebug = true ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/silver/' ; 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.PluginsPath = FCKConfig.BasePath + 'plugins/' ; //FCKConfig.Plugins.Add( 'autogrow' ) ; //FCKConfig.Plugins.Add( 'dragresizetable' ); FCKConfig.AutoGrowMax = 400 ; FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code FCKConfig.AutoDetectLanguage = true ; 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.EMailProtection = 'none' ; // none | encode | function FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.ShowBorders = true ; FCKConfig.SourcePopup = false ; FCKConfig.ToolbarStartExpanded = true ; FCKConfig.ToolbarCanCollapse = true ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.TemplateReplaceAll = true ; FCKConfig.TemplateReplaceCheckbox = true ; FCKConfig.ToolbarLocation = 'In' ; FCKConfig.ToolbarSets["Default"] = [ ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'], '/', ['Style','FontFormat','FontName','FontSize'], ['TextColor','BGColor'], ['FitWindow','ShowBlocks','-','About'] // No comma for the last row. ] ; FCKConfig.ToolbarSets["01cms"] = [ ['Source'], ['PasteText','PasteWord'], ['Find','RemoveFormat'], ['Bold','Italic','Underline','StrikeThrough','SpecialChar'], ['TextColor','BGColor'], ['JustifyLeft','JustifyCenter','JustifyRight'], ['FitWindow'], '/', ['PageBreak','Image','Flash','Table','Link','Unlink'], ['FontFormat','FontName','FontSize'] ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Source','PasteText','PasteWord','Bold','Italic','OrderedList','UnorderedList','Link','Unlink','Image','Flash','TextColor','BGColor','FontName','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' ], [ CTRL + 45 /*INS*/, true ], [ 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' ], [ CTRL + SHIFT + 83 /*S*/, 'Save' ], [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], [ SHIFT + 32 /*SPACE*/, 'Nbsp' ] ] ; FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ; FCKConfig.BrowserContextMenuOnCtrl = false ; FCKConfig.BrowserContextMenu = false ; FCKConfig.EnableMoreFontColors = true ; 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.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; FCKConfig.SpellChecker = 'WSC' ; // 'WSC' | 'SpellerPages' | 'ieSpell' FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl FCKConfig.FirefoxSpellChecker = false ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.DisableObjectResizing = false ; FCKConfig.DisableFFTableHandles = true ; FCKConfig.LinkDlgHideTarget = false ; FCKConfig.LinkDlgHideAdvanced = false ; FCKConfig.ImageDlgHideLink = false ; FCKConfig.ImageDlgHideAdvanced = false ; FCKConfig.FlashDlgHideAdvanced = false ; FCKConfig.ProtectedTags = '' ; // This will be applied to the body element of the editor FCKConfig.BodyId = '' ; FCKConfig.BodyClass = '' ; 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' }, 'Subscript' : { Element : 'sub' }, 'Superscript' : { Element : 'sup' }, // 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 = [] ; // The following value defines which File Browser connector and Quick Upload // "uploader" to use. It is valid for the default implementaion and it is here // just to make this configuration file cleaner. // It is not possible to change this value using an external file or even // inline when creating the editor instance. In that cases you must set the // values of LinkBrowserURL, ImageBrowserURL and so on. // Custom implementations should just ignore it. var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py // Don't care about the following two lines. It just calculates the correct connector // extension to use for the default File Browser (Perl uses "cgi"). var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ; FCKConfig.LinkBrowser = true ; FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% FCKConfig.ImageBrowser = true ; //FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.ImageBrowserURL = FCKURLParams['BOOT_URL']+'/file/fckeditor'; FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; FCKConfig.FlashBrowser = true ; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; FCKConfig.LinkUpload = true ; FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ; FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one FCKConfig.ImageUpload = true ; //FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ; FCKConfig.ROOT_DIR = FCKURLParams['ROOT_DIR']; FCKConfig.PUBLIC_DIR = FCKURLParams['PUBLIC_DIR']; FCKConfig.BOOT_URL = FCKURLParams['BOOT_URL']; FCKConfig.ImageUploadURL = FCKConfig.BOOT_URL+'/file/upload/doEdit/NewFile'; FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png)$" ; // empty for all FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one FCKConfig.FlashUpload = true ; FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ; FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 320 ; FCKConfig.SmileyWindowHeight = 210 ; FCKConfig.BackgroundBlockerColor = '#ffffff' ; FCKConfig.BackgroundBlockerOpacity = 0.50 ; FCKConfig.MsWebBrowserControlCompat = false ; FCKConfig.PreventSubmitHandler = false ;
JavaScript
/* * jQuery UI 1.7.2 * * 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 */ ;jQuery.ui || (function($) { var _remove = $.fn.remove, isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); //Helper functions and ui object $.ui = { version: "1.7.2", // $.ui.plugin is deprecated. Use the proxy pattern instead. 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 || !instance.element[0].parentNode) { return; } for (var i = 0; i < set.length; i++) { if (instance.options[set[i][0]]) { set[i][1].apply(instance.element, args); } } } }, contains: function(a, b) { return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b); }, hasScroll: function(el, a) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ($(el).css('overflow') == 'hidden') { return false; } var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', has = false; if (el[scroll] > 0) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[scroll] = 1; has = (el[scroll] > 0); el[scroll] = 0; return has; }, isOverAxis: function(x, reference, size) { //Determines when x coordinate is over "b" element axis return (x > reference) && (x < (reference + size)); }, isOver: function(y, x, top, left, height, width) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); }, keyCode: { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 } }; // WAI-ARIA normalization if (isFF2) { var attr = $.attr, removeAttr = $.fn.removeAttr, ariaNS = "http://www.w3.org/2005/07/aaa", ariaState = /^aria-/, ariaRole = /^wairole:/; $.attr = function(elem, name, value) { var set = value !== undefined; return (name == 'role' ? (set ? attr.call(this, elem, name, "wairole:" + value) : (attr.apply(this, arguments) || "").replace(ariaRole, "")) : (ariaState.test(name) ? (set ? elem.setAttributeNS(ariaNS, name.replace(ariaState, "aaa:"), value) : attr.call(this, elem, name.replace(ariaState, "aaa:"))) : attr.apply(this, arguments))); }; $.fn.removeAttr = function(name) { return (ariaState.test(name) ? this.each(function() { this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); }) : removeAttr.call(this, name)); }; } //jQuery plugins $.fn.extend({ remove: function() { // Safari has a native remove event which actually removes DOM elements, // so we have to use triggerHandler instead of trigger (#3037). $("*", this).add(this).each(function() { $(this).triggerHandler("remove"); }); return _remove.apply(this, arguments ); }, enableSelection: function() { return this .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); }, disableSelection: function() { return this .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); }, scrollParent: function() { var scrollParent; if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; } }); //Additional selectors $.extend($.expr[':'], { data: function(elem, i, match) { return !!$.data(elem, match[3]); }, focusable: function(element) { var nodeName = element.nodeName.toLowerCase(), tabIndex = $.attr(element, 'tabindex'); return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled : 'a' == nodeName || 'area' == nodeName ? element.href || !isNaN(tabIndex) : !isNaN(tabIndex)) // the element and all of its ancestors must be visible // the browser may report that the area is hidden && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; }, tabbable: function(element) { var tabIndex = $.attr(element, 'tabindex'); return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); } }); // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code function getter(namespace, plugin, method, args) { function getMethods(type) { var methods = $[namespace][plugin][type] || []; return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); } var methods = getMethods('getter'); if (args.length == 1 && typeof args[0] == 'string') { methods = methods.concat(getMethods('getterSetter')); } 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); // prevent calls to internal methods if (isMethodCall && options.substring(0, 1) == '_') { return this; } // handle getter methods if (isMethodCall && getter(namespace, name, options, args)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } // handle initialization and non-getter methods return this.each(function() { var instance = $.data(this, name); // constructor (!instance && !isMethodCall && $.data(this, name, new $[namespace][name](this, options))._init()); // method call (instance && isMethodCall && $.isFunction(instance[options]) && instance[options].apply(instance, args)); }); }; // create widget constructor $[namespace] = $[namespace] || {}; $[namespace][name] = function(element, options) { var self = this; this.namespace = namespace; this.widgetName = name; this.widgetEventPrefix = $[namespace][name].eventPrefix || name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, $.metadata && $.metadata.get(element)[name], options); this.element = $(element) .bind('setData.' + name, function(event, key, value) { if (event.target == element) { return self._setData(key, value); } }) .bind('getData.' + name, function(event, key) { if (event.target == element) { return self._getData(key); } }) .bind('remove', function() { return self.destroy(); }); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); // TODO: merge getter and getterSetter properties from widget prototype // and plugin prototype $[namespace][name].getterSetter = 'option'; }; $.widget.prototype = { _init: function() {}, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); }, option: function(key, value) { var options = key, self = this; if (typeof key == "string") { if (value === undefined) { return this._getData(key); } options = {}; options[key] = value; } $.each(options, function(key, value) { self._setData(key, value); }); }, _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' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, enable: function() { this._setData('disabled', false); }, disable: function() { this._setData('disabled', true); }, _trigger: function(type, event, data) { var callback = this.options[type], eventName = (type == this.widgetEventPrefix ? type : this.widgetEventPrefix + type); event = $.Event(event); event.type = eventName; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if (event.originalEvent) { for (var i = $.event.props.length, prop; i;) { prop = $.event.props[--i]; event[prop] = event.originalEvent[prop]; } } this.element.trigger(event, data); return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false || event.isDefaultPrevented()); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { _mouseInit: function() { var self = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return self._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if(self._preventClickEvent) { self._preventClickEvent = false; event.stopImmediatePropagation(); return false; } }); // 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(event) { // don't let more than one widget handle mouseStart // TODO: figure out why we have to use originalEvent event.originalEvent = event.originalEvent || {}; if (event.originalEvent.mouseHandled) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var self = this, btnIsLeft = (event.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return self._mouseMove(event); }; this._mouseUpDelegate = function(event) { return self._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); // preventDefault() is used to prevent the selection of text here - // however, in Safari, this causes select boxes not to be selectable // anymore, so this fix is needed ($.browser.safari || event.preventDefault()); event.originalEvent.mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = (event.target == this._mouseDownEvent.target); this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(jQuery);
JavaScript
/* * jQuery UI Effects Scale 1.7.2 * * 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/Effects/Scale * * Depends: * effects.core.js */ (function($) { $.effects.puff = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var options = $.extend(true, {}, o.options); var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var percent = parseInt(o.options.percent,10) || 150; // Set default puff percent options.fade = true; // It's not a puff if it doesn't fade! :) var original = {height: el.height(), width: el.width()}; // Save original // Adjust var factor = percent / 100; el.from = (mode == 'hide') ? original : {height: original.height * factor, width: original.width * factor}; // Animation options.from = el.from; options.percent = (mode == 'hide') ? percent : 100; options.mode = mode; // Animate el.effect('scale', options, o.duration, o.callback); el.dequeue(); }); }; $.effects.scale = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var options = $.extend(true, {}, o.options); var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode var percent = parseInt(o.options.percent,10) || (parseInt(o.options.percent,10) == 0 ? 0 : (mode == 'hide' ? 0 : 100)); // Set default scaling percent var direction = o.options.direction || 'both'; // Set default axis var origin = o.options.origin; // The origin of the scaling if (mode != 'effect') { // Set default origin and restore for show/hide options.origin = origin || ['middle','center']; options.restore = true; } var original = {height: el.height(), width: el.width()}; // Save original el.from = o.options.from || (mode == 'show' ? {height: 0, width: 0} : original); // Default from state // Adjust var factor = { // Set scaling factor y: direction != 'horizontal' ? (percent / 100) : 1, x: direction != 'vertical' ? (percent / 100) : 1 }; el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state if (o.options.fade) { // Fade option to support puff if (mode == 'show') {el.from.opacity = 0; el.to.opacity = 1;}; if (mode == 'hide') {el.from.opacity = 1; el.to.opacity = 0;}; }; // Animation options.from = el.from; options.to = el.to; options.mode = mode; // Animate el.effect('size', options, o.duration, o.callback); el.dequeue(); }); }; $.effects.size = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left','width','height','overflow','opacity']; var props1 = ['position','top','left','overflow','opacity']; // Always restore var props2 = ['width','height','overflow']; // Copy for children var cProps = ['fontSize']; var vProps = ['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom']; var hProps = ['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode var restore = o.options.restore || false; // Default restore var scale = o.options.scale || 'both'; // Default scale mode var origin = o.options.origin; // The origin of the sizing var original = {height: el.height(), width: el.width()}; // Save original el.from = o.options.from || original; // Default from state el.to = o.options.to || original; // Default to state // Adjust if (origin) { // Calculate baseline shifts var baseline = $.effects.getBaseline(origin, original); el.from.top = (original.height - el.from.height) * baseline.y; el.from.left = (original.width - el.from.width) * baseline.x; el.to.top = (original.height - el.to.height) * baseline.y; el.to.left = (original.width - el.to.width) * baseline.x; }; var factor = { // Set scaling factor from: {y: el.from.height / original.height, x: el.from.width / original.width}, to: {y: el.to.height / original.height, x: el.to.width / original.width} }; if (scale == 'box' || scale == 'both') { // Scale the css box if (factor.from.y != factor.to.y) { // Vertical props scaling props = props.concat(vProps); el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from); el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to); }; if (factor.from.x != factor.to.x) { // Horizontal props scaling props = props.concat(hProps); el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from); el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to); }; }; if (scale == 'content' || scale == 'both') { // Scale the content if (factor.from.y != factor.to.y) { // Vertical props scaling props = props.concat(cProps); el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from); el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to); }; }; $.effects.save(el, restore ? props : props1); el.show(); // Save & Show $.effects.createWrapper(el); // Create Wrapper el.css('overflow','hidden').css(el.from); // Shift // Animate if (scale == 'content' || scale == 'both') { // Scale the children vProps = vProps.concat(['marginTop','marginBottom']).concat(cProps); // Add margins/font-size hProps = hProps.concat(['marginLeft','marginRight']); // Add margins props2 = props.concat(vProps).concat(hProps); // Concat el.find("*[width]").each(function(){ child = $(this); if (restore) $.effects.save(child, props2); var c_original = {height: child.height(), width: child.width()}; // Save original child.from = {height: c_original.height * factor.from.y, width: c_original.width * factor.from.x}; child.to = {height: c_original.height * factor.to.y, width: c_original.width * factor.to.x}; if (factor.from.y != factor.to.y) { // Vertical props scaling child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from); child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to); }; if (factor.from.x != factor.to.x) { // Horizontal props scaling child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from); child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to); }; child.css(child.from); // Shift children child.animate(child.to, o.duration, o.options.easing, function(){ if (restore) $.effects.restore(child, props2); // Restore children }); // Animate children }); }; // Animate el.animate(el.to, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, restore ? props : props1); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
JavaScript
/* Chinese initialisation for the jQuery UI date picker plugin. */ /* Written by Cloudream (cloudream@gmail.com). */ jQuery(function($){ $.datepicker.regional['zh-CN'] = { closeText: '关闭', prevText: '&#x3c;上月', nextText: '下月&#x3e;', currentText: '今天', monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'], monthNamesShort: ['一','二','三','四','五','六', '七','八','九','十','十一','十二'], dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'], dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], dayNamesMin: ['日','一','二','三','四','五','六'], dateFormat: 'yy-mm-dd', firstDay: 1, isRTL: false}; $.datepicker.setDefaults($.datepicker.regional['zh-CN']); });
JavaScript
function postDialog() { $(':submit').attr('disabled',true); if($('#autoFrame').length == 0) { $('body').append('<iframe class="hidden" id="autoFrame" name="autoFrame" ></iframe>'); } if($('.ui-dialog').length > 0) { $('.ui-dialog').remove(); } $('<div class="ui-dialog-message"><span class="ui-dialog-loading">&nbsp;</span>正在处理,请稍候...</div>').dialog({ close: function(){$(".ui-dialog").remove();$(".ui-dialog-message").remove();$(':submit').attr('disabled',false);}, title: '提示信息', resizable : false }); } function postResponse(response) { $(".ui-dialog-message").html(response.message); if (response.javascript) { eval(response.javascript); } if (response.goUrl) { redirect(response.goUrl, response.stayTime) } else if (response.stayTime > 0) { window.setTimeout(function(){$(':submit').attr('disabled',false);$(".ui-dialog").hide('slow',function(){$(".ui-dialog").remove();$(".ui-dialog-message").remove();});},response.stayTime * 1000); } } function getDialog(url, goUrl, stayTime) { if(stayTime == undefined) { stayTime = 3; } if($('.ui-dialog').length > 0) { $('.ui-dialog').remove(); } $('<div class="ui-dialog-message"><span class="ui-dialog-loading">&nbsp;</span>正在处理,请稍候...</div>').dialog({ title:'提示信息', resizable : false }); $.ajax({ type : 'get', dataType : 'json', url : url, success : function(response) { $(".ui-dialog-message").html(response.message); if (response.javascript) { eval(response.javascript); } if (response.success && goUrl) { redirect(goUrl, stayTime); } else if (stayTime > 0) { window.setTimeout(function(){$(".ui-dialog").hide('slow');},stayTime*1000); } } }); } function selAll(name) { $("input[name='"+name+"']").attr("checked", true); return false; } function selNone(name) { $("input[name='"+name+"']").attr("checked", false); return false; } function selAnti(name) { $("input[name='"+name+"']").each(function(i){ this.checked=!this.checked; }); return false; } function redirect(goUrl, time) { if(time == undefined) { time = 2; } window.setTimeout(function(){window.location.href=goUrl;},time*1000); } $(document).ready(function(){ $(".content table tr,.rowLine") .mouseover(function(){ if($(this).find("input[name='selected[]']").length > 0 && $(this).parents().find("input[name='selected[]']").length > 2) { $(this).removeClass("selected"); $(this).addClass("titleBg"); } }) .mouseout(function(){ if($(this).find("input[name='selected[]']").length > 0 && $(this).parents().find("input[name='selected[]']").length > 2) { if($(this).find("input[name='selected[]']").get(0).checked) { $(this).addClass("selected"); } else { $(this).removeClass("selected"); } $(this).removeClass("titleBg"); } }) });
JavaScript
/* * jQuery UI Progressbar 1.7.2 * * 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/Progressbar * * Depends: * ui.core.js */ (function($) { $.widget("ui.progressbar", { _init: function() { this.element .addClass("ui-progressbar" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .attr({ role: "progressbar", "aria-valuemin": this._valueMin(), "aria-valuemax": this._valueMax(), "aria-valuenow": this._value() }); this.valueDiv = $('<div class="ui-progressbar-value ui-widget-header ui-corner-left"></div>').appendTo(this.element); this._refreshValue(); }, destroy: function() { this.element .removeClass("ui-progressbar" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .removeAttr("role") .removeAttr("aria-valuemin") .removeAttr("aria-valuemax") .removeAttr("aria-valuenow") .removeData("progressbar") .unbind(".progressbar"); this.valueDiv.remove(); $.widget.prototype.destroy.apply(this, arguments); }, value: function(newValue) { if (newValue === undefined) { return this._value(); } this._setData('value', newValue); return this; }, _setData: function(key, value) { switch (key) { case 'value': this.options.value = value; this._refreshValue(); this._trigger('change', null, {}); break; } $.widget.prototype._setData.apply(this, arguments); }, _value: function() { var val = this.options.value; if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; }, _valueMin: function() { var valueMin = 0; return valueMin; }, _valueMax: function() { var valueMax = 100; return valueMax; }, _refreshValue: function() { var value = this.value(); this.valueDiv[value == this._valueMax() ? 'addClass' : 'removeClass']("ui-corner-right"); this.valueDiv.width(value + '%'); this.element.attr("aria-valuenow", value); } }); $.extend($.ui.progressbar, { version: "1.7.2", defaults: { value: 0 } }); })(jQuery);
JavaScript
/* * jQuery UI Slider 1.7.2 * * 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/Slider * * Depends: * ui.core.js */ (function($) { $.widget("ui.slider", $.extend({}, $.ui.mouse, { _init: function() { var self = this, o = this.options; this._keySliding = false; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass("ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this.range = $([]); if (o.range) { if (o.range === true) { this.range = $('<div></div>'); if (!o.values) o.values = [this._valueMin(), this._valueMin()]; if (o.values.length && o.values.length != 2) { o.values = [o.values[0], o.values[0]]; } } else { this.range = $('<div></div>'); } this.range .appendTo(this.element) .addClass("ui-slider-range"); if (o.range == "min" || o.range == "max") { this.range.addClass("ui-slider-range-" + o.range); } // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes this.range.addClass("ui-widget-header"); } if ($(".ui-slider-handle", this.element).length == 0) $('<a href="#"></a>') .appendTo(this.element) .addClass("ui-slider-handle"); if (o.values && o.values.length) { while ($(".ui-slider-handle", this.element).length < o.values.length) $('<a href="#"></a>') .appendTo(this.element) .addClass("ui-slider-handle"); } this.handles = $(".ui-slider-handle", this.element) .addClass("ui-state-default" + " ui-corner-all"); this.handle = this.handles.eq(0); this.handles.add(this.range).filter("a") .click(function(event) { event.preventDefault(); }) .hover(function() { if (!o.disabled) { $(this).addClass('ui-state-hover'); } }, function() { $(this).removeClass('ui-state-hover'); }) .focus(function() { if (!o.disabled) { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); } else { $(this).blur(); } }) .blur(function() { $(this).removeClass('ui-state-focus'); }); this.handles.each(function(i) { $(this).data("index.ui-slider-handle", i); }); this.handles.keydown(function(event) { var ret = true; var index = $(this).data("index.ui-slider-handle"); if (self.options.disabled) return; switch (event.keyCode) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: ret = false; if (!self._keySliding) { self._keySliding = true; $(this).addClass("ui-state-active"); self._start(event, index); } break; } var curVal, newVal, step = self._step(); if (self.options.values && self.options.values.length) { curVal = newVal = self.values(index); } else { curVal = newVal = self.value(); } switch (event.keyCode) { case $.ui.keyCode.HOME: newVal = self._valueMin(); break; case $.ui.keyCode.END: newVal = self._valueMax(); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if(curVal == self._valueMax()) return; newVal = curVal + step; break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if(curVal == self._valueMin()) return; newVal = curVal - step; break; } self._slide(event, index, newVal); return ret; }).keyup(function(event) { var index = $(this).data("index.ui-slider-handle"); if (self._keySliding) { self._stop(event, index); self._change(event, index); self._keySliding = false; $(this).removeClass("ui-state-active"); } }); this._refreshValue(); }, destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass("ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-slider-disabled" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .removeData("slider") .unbind(".slider"); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; if (o.disabled) return false; this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); var position = { x: event.pageX, y: event.pageY }; var normValue = this._normValueFromMouse(position); var distance = this._valueMax() - this._valueMin() + 1, closestHandle; var self = this, index; this.handles.each(function(i) { var thisDistance = Math.abs(normValue - self.values(i)); if (distance > thisDistance) { distance = thisDistance; closestHandle = $(this); index = i; } }); // workaround for bug #3736 (if both handles of a range are at 0, // the first is always used as the one with least distance, // and moving it is obviously prevented by preventing negative ranges) if(o.range == true && this.values(1) == o.min) { closestHandle = $(this.handles[++index]); } this._start(event, index); self._handleIndex = index; closestHandle .addClass("ui-state-active") .focus(); var offset = closestHandle.offset(); var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle'); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - (closestHandle.width() / 2), top: event.pageY - offset.top - (closestHandle.height() / 2) - (parseInt(closestHandle.css('borderTopWidth'),10) || 0) - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0) + (parseInt(closestHandle.css('marginTop'),10) || 0) }; normValue = this._normValueFromMouse(position); this._slide(event, index, normValue); return true; }, _mouseStart: function(event) { return true; }, _mouseDrag: function(event) { var position = { x: event.pageX, y: event.pageY }; var normValue = this._normValueFromMouse(position); this._slide(event, this._handleIndex, normValue); return false; }, _mouseStop: function(event) { this.handles.removeClass("ui-state-active"); this._stop(event, this._handleIndex); this._change(event, this._handleIndex); this._handleIndex = null; this._clickOffset = null; return false; }, _detectOrientation: function() { this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal'; }, _normValueFromMouse: function(position) { var pixelTotal, pixelMouse; if ('horizontal' == this.orientation) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0); } var percentMouse = (pixelMouse / pixelTotal); if (percentMouse > 1) percentMouse = 1; if (percentMouse < 0) percentMouse = 0; if ('vertical' == this.orientation) percentMouse = 1 - percentMouse; var valueTotal = this._valueMax() - this._valueMin(), valueMouse = percentMouse * valueTotal, valueMouseModStep = valueMouse % this.options.step, normValue = this._valueMin() + valueMouse - valueMouseModStep; if (valueMouseModStep > (this.options.step / 2)) normValue += this.options.step; // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat(normValue.toFixed(5)); }, _start: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("start", event, uiHash); }, _slide: function(event, index, newVal) { var handle = this.handles[index]; if (this.options.values && this.options.values.length) { var otherVal = this.values(index ? 0 : 1); if ((this.options.values.length == 2 && this.options.range === true) && ((index == 0 && newVal > otherVal) || (index == 1 && newVal < otherVal))){ newVal = otherVal; } if (newVal != this.values(index)) { var newValues = this.values(); newValues[index] = newVal; // A slide can be canceled by returning false from the slide callback var allowed = this._trigger("slide", event, { handle: this.handles[index], value: newVal, values: newValues }); var otherVal = this.values(index ? 0 : 1); if (allowed !== false) { this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true); } } } else { if (newVal != this.value()) { // A slide can be canceled by returning false from the slide callback var allowed = this._trigger("slide", event, { handle: this.handles[index], value: newVal }); if (allowed !== false) { this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate )); } } } }, _stop: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("stop", event, uiHash); }, _change: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("change", event, uiHash); }, value: function(newValue) { if (arguments.length) { this._setData("value", newValue); this._change(null, 0); } return this._value(); }, values: function(index, newValue, animated, noPropagation) { if (arguments.length > 1) { this.options.values[index] = newValue; this._refreshValue(animated); if(!noPropagation) this._change(null, index); } if (arguments.length) { if (this.options.values && this.options.values.length) { return this._values(index); } else { return this.value(); } } else { return this._values(); } }, _setData: function(key, value, animated) { $.widget.prototype._setData.apply(this, arguments); switch (key) { case 'disabled': if (value) { this.handles.filter(".ui-state-focus").blur(); this.handles.removeClass("ui-state-hover"); this.handles.attr("disabled", "disabled"); } else { this.handles.removeAttr("disabled"); } case 'orientation': this._detectOrientation(); this.element .removeClass("ui-slider-horizontal ui-slider-vertical") .addClass("ui-slider-" + this.orientation); this._refreshValue(animated); break; case 'value': this._refreshValue(animated); break; } }, _step: function() { var step = this.options.step; return step; }, _value: function() { var val = this.options.value; if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; }, _values: function(index) { if (arguments.length) { var val = this.options.values[index]; if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; } else { return this.options.values; } }, _valueMin: function() { var valueMin = this.options.min; return valueMin; }, _valueMax: function() { var valueMax = this.options.max; return valueMax; }, _refreshValue: function(animate) { var oRange = this.options.range, o = this.options, self = this; if (this.options.values && this.options.values.length) { var vp0, vp1; this.handles.each(function(i, j) { var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100; var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); if (self.options.range === true) { if (self.orientation == 'horizontal') { (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate); (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); } else { (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate); (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); } } lastValPercent = valPercent; }); } else { var value = this.value(), valueMin = this._valueMin(), valueMax = this._valueMax(), valPercent = valueMax != valueMin ? (value - valueMin) / (valueMax - valueMin) * 100 : 0; var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate); (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate); (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); } } })); $.extend($.ui.slider, { getter: "value values", version: "1.7.2", eventPrefix: "slide", defaults: { animate: false, delay: 0, distance: 0, max: 100, min: 0, orientation: 'horizontal', range: false, step: 1, value: 0, values: null } }); })(jQuery);
JavaScript
/* * jQuery UI Effects Fold 1.7.2 * * 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/Effects/Fold * * Depends: * effects.core.js */ (function($) { $.effects.fold = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var size = o.options.size || 15; // Default fold size var horizFirst = !(!o.options.horizFirst); // Ensure a boolean value var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2; // Adjust $.effects.save(el, props); el.show(); // Save & Show var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper var widthFirst = ((mode == 'show') != horizFirst); var ref = widthFirst ? ['width', 'height'] : ['height', 'width']; var distance = widthFirst ? [wrapper.width(), wrapper.height()] : [wrapper.height(), wrapper.width()]; var percent = /([0-9]+)%/.exec(size); if(percent) size = parseInt(percent[1],10) / 100 * distance[mode == 'hide' ? 0 : 1]; if(mode == 'show') wrapper.css(horizFirst ? {height: 0, width: size} : {height: size, width: 0}); // Shift // Animation var animation1 = {}, animation2 = {}; animation1[ref[0]] = mode == 'show' ? distance[0] : size; animation2[ref[1]] = mode == 'show' ? distance[1] : 0; // Animate wrapper.animate(animation1, duration, o.options.easing) .animate(animation2, duration, o.options.easing, function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(el[0], arguments); // Callback el.dequeue(); }); }); }; })(jQuery);
JavaScript
/* * jQuery UI Selectable 1.7.2 * * 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/Selectables * * Depends: * ui.core.js */ (function($) { $.widget("ui.selectable", $.extend({}, $.ui.mouse, { _init: function() { var self = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter var selectees; this.refresh = function() { selectees = $(self.options.filter, self.element[0]); selectees.each(function() { var $this = $(this); var pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass('ui-selected'), selecting: $this.hasClass('ui-selecting'), unselecting: $this.hasClass('ui-unselecting') }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $(document.createElement('div')) .css({border:'1px dotted black'}) .addClass("ui-selectable-helper"); }, destroy: function() { this.element .removeClass("ui-selectable ui-selectable-disabled") .removeData("selectable") .unbind(".selectable"); this._mouseDestroy(); }, _mouseStart: function(event) { var self = this; this.opos = [event.pageX, event.pageY]; if (this.options.disabled) return; var options = this.options; this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "z-index": 100, "position": "absolute", "left": event.clientX, "top": event.clientY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter('.ui-selected').each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; // selectable UNSELECTING callback self._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().andSelf().each(function() { var selectee = $.data(this, "selectable-item"); if (selectee) { selectee.$element.removeClass("ui-unselecting").addClass('ui-selecting'); selectee.unselecting = false; selectee.selecting = true; selectee.selected = true; // selectable SELECTING callback self._trigger("selecting", event, { selecting: selectee.element }); return false; } }); }, _mouseDrag: function(event) { var self = this; this.dragged = true; if (this.options.disabled) return; var options = this.options; var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"); //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element == self.element[0]) return; var hit = false; if (options.tolerance == 'touch') { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance == 'fit') { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass('ui-unselecting'); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass('ui-selecting'); selectee.selecting = true; // selectable SELECTING callback self._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if (event.metaKey && selectee.startselected) { selectee.$element.removeClass('ui-selecting'); selectee.selecting = false; selectee.$element.addClass('ui-selected'); selectee.selected = true; } else { selectee.$element.removeClass('ui-selecting'); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; } // selectable UNSELECTING callback self._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !selectee.startselected) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; // selectable UNSELECTING callback self._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var self = this; this.dragged = false; var options = this.options; $('.ui-unselecting', this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass('ui-unselecting'); selectee.unselecting = false; selectee.startselected = false; self._trigger("unselected", event, { unselected: selectee.element }); }); $('.ui-selecting', this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass('ui-selecting').addClass('ui-selected'); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; self._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } })); $.extend($.ui.selectable, { version: "1.7.2", defaults: { appendTo: 'body', autoRefresh: true, cancel: ":input,option", delay: 0, distance: 0, filter: '*', tolerance: 'touch' } }); })(jQuery);
JavaScript
/* * jQuery UI Effects Slide 1.7.2 * * 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/Effects/Slide * * Depends: * effects.core.js */ (function($) { $.effects.slide = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var direction = o.options.direction || 'left'; // Default Direction // Adjust $.effects.save(el, props); el.show(); // Save & Show $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true})); if (mode == 'show') el.css(ref, motion == 'pos' ? -distance : distance); // Shift // Animation var animation = {}; animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance; // Animate el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
JavaScript
/* * jQuery UI Accordion 1.7.2 * * 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/Accordion * * Depends: * ui.core.js */ (function($) { $.widget("ui.accordion", { _init: function() { var o = this.options, self = this; this.running = 0; // if the user set the alwaysOpen option on init // then we need to set the collapsible option // if they set both on init, collapsible will take priority if (o.collapsible == $.ui.accordion.defaults.collapsible && o.alwaysOpen != $.ui.accordion.defaults.alwaysOpen) { o.collapsible = !o.alwaysOpen; } if ( o.navigation ) { var current = this.element.find("a").filter(o.navigationFilter); if ( current.length ) { if ( current.filter(o.header).length ) { this.active = current; } else { this.active = current.parent().parent().prev(); current.addClass("ui-accordion-content-active"); } } } this.element.addClass("ui-accordion ui-widget ui-helper-reset"); // in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix if (this.element[0].nodeName == "UL") { this.element.children("li").addClass("ui-accordion-li-fix"); } this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all") .bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); }) .bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); }) .bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); }) .bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); }); this.headers .next() .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"); this.active.next().addClass('ui-accordion-content-active'); //Append icon elements $("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers); this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected); // IE7-/Win - Extra vertical space in lists fixed if ($.browser.msie) { this.element.find('a').css('zoom', '1'); } this.resize(); //ARIA this.element.attr('role','tablist'); this.headers .attr('role','tab') .bind('keydown', function(event) { return self._keydown(event); }) .next() .attr('role','tabpanel'); this.headers .not(this.active || "") .attr('aria-expanded','false') .attr("tabIndex", "-1") .next() .hide(); // make sure at least one header is in the tab order if (!this.active.length) { this.headers.eq(0).attr('tabIndex','0'); } else { this.active .attr('aria-expanded','true') .attr('tabIndex', '0'); } // only need links in taborder for Safari if (!$.browser.safari) this.headers.find('a').attr('tabIndex','-1'); if (o.event) { this.headers.bind((o.event) + ".accordion", function(event) { return self._clickHandler.call(self, event, this); }); } }, destroy: function() { var o = this.options; this.element .removeClass("ui-accordion ui-widget ui-helper-reset") .removeAttr("role") .unbind('.accordion') .removeData('accordion'); this.headers .unbind(".accordion") .removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top") .removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex"); this.headers.find("a").removeAttr("tabindex"); this.headers.children(".ui-icon").remove(); var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active"); if (o.autoHeight || o.fillHeight) { contents.css("height", ""); } }, _setData: function(key, value) { if(key == 'alwaysOpen') { key = 'collapsible'; value = !value; } $.widget.prototype._setData.apply(this, arguments); }, _keydown: function(event) { var o = this.options, keyCode = $.ui.keyCode; if (o.disabled || event.altKey || event.ctrlKey) return; var length = this.headers.length; var currentIndex = this.headers.index(event.target); var toFocus = false; switch(event.keyCode) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[(currentIndex + 1) % length]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[(currentIndex - 1 + length) % length]; break; case keyCode.SPACE: case keyCode.ENTER: return this._clickHandler({ target: event.target }, event.target); } if (toFocus) { $(event.target).attr('tabIndex','-1'); $(toFocus).attr('tabIndex','0'); toFocus.focus(); return false; } return true; }, resize: function() { var o = this.options, maxHeight; if (o.fillSpace) { if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); } maxHeight = this.element.parent().height(); if($.browser.msie) { this.element.parent().css('overflow', defOverflow); } this.headers.each(function() { maxHeight -= $(this).outerHeight(); }); var maxPadding = 0; this.headers.next().each(function() { maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height()); }).height(Math.max(0, maxHeight - maxPadding)) .css('overflow', 'auto'); } else if ( o.autoHeight ) { maxHeight = 0; this.headers.next().each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }).height(maxHeight); } }, activate: function(index) { // call clickHandler with custom event var active = this._findActive(index)[0]; this._clickHandler({ target: active }, active); }, _findActive: function(selector) { return selector ? typeof selector == "number" ? this.headers.filter(":eq(" + selector + ")") : this.headers.not(this.headers.not(selector)) : selector === false ? $([]) : this.headers.filter(":eq(0)"); }, _clickHandler: function(event, target) { var o = this.options; if (o.disabled) return false; // called only when using activate(false) to close all parts programmatically if (!event.target && o.collapsible) { this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all") .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header); this.active.next().addClass('ui-accordion-content-active'); var toHide = this.active.next(), data = { options: o, newHeader: $([]), oldHeader: o.active, newContent: $([]), oldContent: toHide }, toShow = (this.active = $([])); this._toggle(toShow, toHide, data); return false; } // get the click target var clicked = $(event.currentTarget || target); var clickedIsActive = clicked[0] == this.active[0]; // if animations are still active, or the active header is the target, ignore click if (this.running || (!o.collapsible && clickedIsActive)) { return false; } // switch classes this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all") .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header); this.active.next().addClass('ui-accordion-content-active'); if (!clickedIsActive) { clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top") .find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected); clicked.next().addClass('ui-accordion-content-active'); } // find elements to show and hide var toShow = clicked.next(), toHide = this.active.next(), data = { options: o, newHeader: clickedIsActive && o.collapsible ? $([]) : clicked, oldHeader: this.active, newContent: clickedIsActive && o.collapsible ? $([]) : toShow.find('> *'), oldContent: toHide.find('> *') }, down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] ); this.active = clickedIsActive ? $([]) : clicked; this._toggle(toShow, toHide, data, clickedIsActive, down); return false; }, _toggle: function(toShow, toHide, data, clickedIsActive, down) { var o = this.options, self = this; this.toShow = toShow; this.toHide = toHide; this.data = data; var complete = function() { if(!self) return; return self._completed.apply(self, arguments); }; // trigger changestart event this._trigger("changestart", null, this.data); // count elements to animate this.running = toHide.size() === 0 ? toShow.size() : toHide.size(); if (o.animated) { var animOptions = {}; if ( o.collapsible && clickedIsActive ) { animOptions = { toShow: $([]), toHide: toHide, complete: complete, down: down, autoHeight: o.autoHeight || o.fillSpace }; } else { animOptions = { toShow: toShow, toHide: toHide, complete: complete, down: down, autoHeight: o.autoHeight || o.fillSpace }; } if (!o.proxied) { o.proxied = o.animated; } if (!o.proxiedDuration) { o.proxiedDuration = o.duration; } o.animated = $.isFunction(o.proxied) ? o.proxied(animOptions) : o.proxied; o.duration = $.isFunction(o.proxiedDuration) ? o.proxiedDuration(animOptions) : o.proxiedDuration; var animations = $.ui.accordion.animations, duration = o.duration, easing = o.animated; if (!animations[easing]) { animations[easing] = function(options) { this.slide(options, { easing: easing, duration: duration || 700 }); }; } animations[easing](animOptions); } else { if (o.collapsible && clickedIsActive) { toShow.toggle(); } else { toHide.hide(); toShow.show(); } complete(true); } toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur(); toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus(); }, _completed: function(cancel) { var o = this.options; this.running = cancel ? 0 : --this.running; if (this.running) return; if (o.clearStyle) { this.toShow.add(this.toHide).css({ height: "", overflow: "" }); } this._trigger('change', null, this.data); } }); $.extend($.ui.accordion, { version: "1.7.2", defaults: { active: null, alwaysOpen: true, //deprecated, use collapsible animated: 'slide', autoHeight: true, clearStyle: false, collapsible: false, event: "click", fillSpace: false, header: "> li > :first-child,> :not(li):even", icons: { header: "ui-icon-triangle-1-e", headerSelected: "ui-icon-triangle-1-s" }, navigation: false, navigationFilter: function() { return this.href.toLowerCase() == location.href.toLowerCase(); } }, animations: { slide: function(options, additions) { options = $.extend({ easing: "swing", duration: 300 }, options, additions); if ( !options.toHide.size() ) { options.toShow.animate({height: "show"}, options); return; } if ( !options.toShow.size() ) { options.toHide.animate({height: "hide"}, options); return; } var overflow = options.toShow.css('overflow'), percentDone, showProps = {}, hideProps = {}, fxAttrs = [ "height", "paddingTop", "paddingBottom" ], originalWidth; // fix width before calculating height of hidden element var s = options.toShow; originalWidth = s[0].style.width; s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - (parseInt(s.css("borderLeftWidth"),10) || 0) - (parseInt(s.css("borderRightWidth"),10) || 0) ); $.each(fxAttrs, function(i, prop) { hideProps[prop] = 'hide'; var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/); showProps[prop] = { value: parts[1], unit: parts[2] || 'px' }; }); options.toShow.css({ height: 0, overflow: 'hidden' }).show(); options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{ step: function(now, settings) { // only calculate the percent when animating height // IE gets very inconsistent results when animating elements // with small values, which is common for padding if (settings.prop == 'height') { percentDone = (settings.now - settings.start) / (settings.end - settings.start); } options.toShow[0].style[settings.prop] = (percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit; }, duration: options.duration, easing: options.easing, complete: function() { if ( !options.autoHeight ) { options.toShow.css("height", ""); } options.toShow.css("width", originalWidth); options.toShow.css({overflow: overflow}); options.complete(); } }); }, bounceslide: function(options) { this.slide(options, { easing: options.down ? "easeOutBounce" : "swing", duration: options.down ? 1000 : 200 }); }, easeslide: function(options) { this.slide(options, { easing: "easeinout", duration: 700 }); } } }); })(jQuery);
JavaScript
/** * window 1.0 * * Copyright (c) 2009 www.01mvc.com * * http://www.01mvc.com * * Depends: * ui.core.js * ui.draggable.js * ui.resizable.js * ui.dialog.js */ $.fn.window = function(options){ var defaults = { defaultMsg: '<span class="dialogLoading">&nbsp;</span>正在处理,请稍候...', sendUrl: "", goUrl : "", style : "padding:15px; line-height:20px; font-size:13px; text-align:center;", dataClass : "posted", type : "post", dataType : "json", stayTime : 2, buttons : '', height : 'auto', width : 300, maxHeight : '', maxWidth : '', minHeight : '', minWidth : '', title : "提示信息", beforeclose : '', resizable : true, open : '', focus : '', position : 'center', dragStart : '', drag : '', dragStop : '', resizeStart : '', resize : '', resizeStop : '', close : function() {if($(":submit").length > 0)$(":submit").get(0).disabled = false;}, msgClass : 'dialog-message'+$(".ui-dialog").length }; var options = $.extend(defaults, options); var msgClass = options.msgClass; if(options.type == "post" && options.sendUrl != '') { $(this).submit(function(){ $(":submit").get(0).disabled = true; $('<div class="'+msgClass+'" style="'+options.style+'">'+options.defaultMsg+'</div>').dialog({ buttons : options.buttons, height : options.height, width : options.width, maxHeight : options.maxHeight, maxWidth : options.maxWidth, minHeight : options.minHeight, minWidth : options.minWidth, title : options.title, beforeclose : options.beforeclose, resizable : options.resizable, open : options.open, focus : options.focus, position : options.position, dragStart : options.dragStart, drag : options.drag, dragStop : options.dragStop, resizeStart : options.resizeStart, buttons: options.buttons, close : options.close }); $("."+options.dataClass).each(function(){ if(options.data == '') { and = ''; } else { and = '&'; } var value = ''; if(this.type == 'checkbox' || this.type == 'radio') { if(this.checked) { options.data += and + this.name + '=' + this.value; } } else { options.data += and + this.name + '=' + this.value; } }); $.ajax( { type : options.type, dataType : options.dataType, data : options.data, url : options.sendUrl, success : function(response) { $("."+msgClass).html(response.message); if (response.success && options.goUrl != '') { window.setTimeout(function(){ window.location.href = options.goUrl;} ,options.stayTime * 1000); } else { window.setTimeout(function(){$(".ui-dialog:has(."+msgClass+")").hide('slow');$(":submit").get(0).disabled = false;},options.stayTime*1000); } if (response.js != '') { eval(response.js); } } }); return false; }); } else { $('<div class="'+msgClass+'" style="padding:15px; font-size:13px">'+options.defaultMsg+'</div>').dialog({ buttons : options.buttons, height : options.height, width : options.width, maxHeight : options.maxHeight, maxWidth : options.maxWidth, minHeight : options.minHeight, minWidth : options.minWidth, title : options.title, beforeclose : options.beforeclose, resizable : options.resizable, open : options.open, focus : options.focus, position : options.position, dragStart : options.dragStart, drag : options.drag, dragStop : options.dragStop, resizeStart : options.resizeStart, buttons: options.buttons, close : options.close }); if(options.sendUrl != '') { $.ajax( { type : 'get', dataType : options.dataType, data : options.data, url : options.sendUrl, success : function(response) { $("."+msgClass).html(response.message); if (response.success && options.goUrl != '') { window.setTimeout(function(){ window.location.href = options.goUrl;} ,options.stayTime * 1000); } else if(options.stayTime > 0) { window.setTimeout(function(){$(".ui-dialog:has(."+msgClass+")").hide('slow');},options.stayTime*1000); } if (response.js != '') { eval(response.js); } } }); } return false; } };
JavaScript
/* * jQuery UI Dialog 1.7.2 * * 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/Dialog * * Depends: * ui.core.js * ui.draggable.js * ui.resizable.js */ (function($) { var setDataSwitch = { dragStart: "start.draggable", drag: "drag.draggable", dragStop: "stop.draggable", maxHeight: "maxHeight.resizable", minHeight: "minHeight.resizable", maxWidth: "maxWidth.resizable", minWidth: "minWidth.resizable", resizeStart: "start.resizable", resize: "drag.resizable", resizeStop: "stop.resizable" }, uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all '; $.widget("ui.dialog", { _init: function() { this.originalTitle = this.element.attr('title'); var self = this, options = this.options, title = options.title || this.originalTitle || '&nbsp;', titleId = $.ui.dialog.getTitleId(this.element), uiDialog = (this.uiDialog = $('<div/>')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ position: 'absolute', overflow: 'hidden', zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { (options.closeOnEscape && event.keyCode && event.keyCode == $.ui.keyCode.ESCAPE && self.close(event)); }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = this.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog), uiDialogTitlebarClose = $('<a href="#"/>') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .mousedown(function(ev) { ev.stopPropagation(); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose), uiDialogTitle = $('<span/>') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); (options.draggable && $.fn.draggable && this._makeDraggable()); (options.resizable && $.fn.resizable && this._makeResizable()); this._createButtons(options.buttons); this._isOpen = false; (options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe()); (options.autoOpen && this.open()); }, destroy: function() { (this.overlay && this.overlay.destroy()); this.uiDialog.hide(); this.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); this.uiDialog.remove(); (this.originalTitle && this.element.attr('title', this.originalTitle)); }, close: function(event) { var self = this; if (false === self._trigger('beforeclose', event)) { return; } (self.overlay && self.overlay.destroy()); self.uiDialog.unbind('keypress.ui-dialog'); (self.options.hide ? self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }) : self.uiDialog.hide() && self._trigger('close', event)); $.ui.dialog.overlay.resize(); self._isOpen = false; // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { var maxZ = 0; $('.ui-dialog').each(function() { if (this != self.uiDialog[0]) { maxZ = Math.max(maxZ, $(this).css('z-index')); } }); $.ui.dialog.maxZ = maxZ; } }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { if ((this.options.modal && !force) || (!this.options.stack && !this.options.modal)) { return this._trigger('focus', event); } if (this.options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = this.options.zIndex; } (this.overlay && this.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = ++$.ui.dialog.maxZ)); //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') }; this.uiDialog.css('z-index', ++$.ui.dialog.maxZ); this.element.attr(saveScroll); this._trigger('focus', event); }, open: function() { if (this._isOpen) { return; } var options = this.options, uiDialog = this.uiDialog; this.overlay = options.modal ? new $.ui.dialog.overlay(this) : null; (uiDialog.next().length && uiDialog.appendTo('body')); this._size(); this._position(options.position); uiDialog.show(options.show); this.moveToTop(true); // prevent tabbing out of modal dialogs (options.modal && uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode != $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first')[0], last = tabbables.filter(':last')[0]; if (event.target == last && !event.shiftKey) { setTimeout(function() { first.focus(); }, 1); } else if (event.target == first && event.shiftKey) { setTimeout(function() { last.focus(); }, 1); } })); // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $([]) .add(uiDialog.find('.ui-dialog-content :tabbable:first')) .add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first')) .add(uiDialog) .filter(':first') .focus(); this._trigger('open'); this._isOpen = true; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ); // if we already have a button pane, remove it this.uiDialog.find('.ui-dialog-buttonpane').remove(); (typeof buttons == 'object' && buttons !== null && $.each(buttons, function() { return !(hasButtons = true); })); if (hasButtons) { $.each(buttons, function(name, fn) { $('<button type="button"></button>') .addClass( 'ui-state-default ' + 'ui-corner-all' ) .text(name) .click(function() { fn.apply(self.element[0], arguments); }) .hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ) .focus(function() { $(this).addClass('ui-state-focus'); }) .blur(function() { $(this).removeClass('ui-state-focus'); }) .appendTo(uiDialogButtonPane); }); uiDialogButtonPane.appendTo(this.uiDialog); } }, _makeDraggable: function() { var self = this, options = this.options, heightBeforeDrag; this.uiDialog.draggable({ cancel: '.ui-dialog-content', handle: '.ui-dialog-titlebar', containment: 'document', start: function() { heightBeforeDrag = options.height; $(this).height($(this).height()).addClass("ui-dialog-dragging"); (options.dragStart && options.dragStart.apply(self.element[0], arguments)); }, drag: function() { (options.drag && options.drag.apply(self.element[0], arguments)); }, stop: function() { $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); (options.dragStop && options.dragStop.apply(self.element[0], arguments)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = this.options, resizeHandles = typeof handles == 'string' ? handles : 'n,e,s,w,se,sw,ne,nw'; this.uiDialog.resizable({ cancel: '.ui-dialog-content', alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: options.minHeight, start: function() { $(this).addClass("ui-dialog-resizing"); (options.resizeStart && options.resizeStart.apply(self.element[0], arguments)); }, resize: function() { (options.resize && options.resize.apply(self.element[0], arguments)); }, handles: resizeHandles, stop: function() { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); (options.resizeStop && options.resizeStop.apply(self.element[0], arguments)); $.ui.dialog.overlay.resize(); } }) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _position: function(pos) { var wnd = $(window), doc = $(document), pTop = doc.scrollTop(), pLeft = doc.scrollLeft(), minTop = pTop; if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) { pos = [ pos == 'right' || pos == 'left' ? pos : 'center', pos == 'top' || pos == 'bottom' ? pos : 'middle' ]; } if (pos.constructor != Array) { pos = ['center', 'middle']; } if (pos[0].constructor == Number) { pLeft += pos[0]; } else { switch (pos[0]) { case 'left': pLeft += 0; break; case 'right': pLeft += wnd.width() - this.uiDialog.outerWidth(); break; default: case 'center': pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2; } } if (pos[1].constructor == Number) { pTop += pos[1]; } else { switch (pos[1]) { case 'top': pTop += 0; break; case 'bottom': pTop += wnd.height() - this.uiDialog.outerHeight(); break; default: case 'middle': pTop += (wnd.height() - this.uiDialog.outerHeight()) / 2; } } // prevent the dialog from being too high (make sure the titlebar // is accessible) pTop = Math.max(pTop, minTop); this.uiDialog.css({top: pTop, left: pLeft}); }, _setData: function(key, value){ (setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value)); switch (key) { case "buttons": this._createButtons(value); break; case "closeText": this.uiDialogTitlebarCloseText.text(value); break; case "dialogClass": this.uiDialog .removeClass(this.options.dialogClass) .addClass(uiDialogClasses + value); break; case "draggable": (value ? this._makeDraggable() : this.uiDialog.draggable('destroy')); break; case "height": this.uiDialog.height(value); break; case "position": this._position(value); break; case "resizable": var uiDialog = this.uiDialog, isResizable = this.uiDialog.is(':data(resizable)'); // currently resizable, becoming non-resizable (isResizable && !value && uiDialog.resizable('destroy')); // currently resizable, changing handles (isResizable && typeof value == 'string' && uiDialog.resizable('option', 'handles', value)); // currently non-resizable, becoming resizable (isResizable || this._makeResizable(value)); break; case "title": $(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;'); break; case "width": this.uiDialog.width(value); break; } $.widget.prototype._setData.apply(this, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options; // reset content sizing this.element.css({ height: 0, minHeight: 0, width: 'auto' }); // reset wrapper sizing // determine the height of all the non-content elements var nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); this.element .css({ minHeight: Math.max(options.minHeight - nonContentHeight, 0), height: options.height == 'auto' ? 'auto' : Math.max(options.height - nonContentHeight, 0) }); } }); $.extend($.ui.dialog, { version: "1.7.2", defaults: { autoOpen: true, bgiframe: false, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 50, minWidth: 150, modal: false, position: 'center', resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, getter: 'isOpen', uuid: 0, maxZ: 0, getTitleId: function($el) { return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid); }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { var dialogZ = $(event.target).parents('.ui-dialog').css('zIndex') || 0; return (dialogZ > $.ui.dialog.overlay.maxZ); }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { (dialog.options.closeOnEscape && event.keyCode && event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event)); }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = $('<div></div>').appendTo(document.body) .addClass('ui-widget-overlay').css({ width: this.width(), height: this.height() }); (dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe()); this.instances.push($el); return $el; }, destroy: function($el) { this.instances.splice($.inArray(this.instances, $el), 1); if (this.instances.length === 0) { $([document, window]).unbind('.dialog-overlay'); } $el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { // handle IE 6 if ($.browser.msie && $.browser.version < 7) { var scrollHeight = Math.max( document.documentElement.scrollHeight, document.body.scrollHeight ); var offsetHeight = Math.max( document.documentElement.offsetHeight, document.body.offsetHeight ); if (scrollHeight < offsetHeight) { return $(window).height() + 'px'; } else { return scrollHeight + 'px'; } // handle "good" browsers } else { return $(document).height() + 'px'; } }, width: function() { // handle IE 6 if ($.browser.msie && $.browser.version < 7) { var scrollWidth = Math.max( document.documentElement.scrollWidth, document.body.scrollWidth ); var offsetWidth = Math.max( document.documentElement.offsetWidth, document.body.offsetWidth ); if (scrollWidth < offsetWidth) { return $(window).width() + 'px'; } else { return scrollWidth + 'px'; } // handle "good" browsers } else { return $(document).width() + 'px'; } }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); })(jQuery);
JavaScript
/* * jQuery UI Effects 1.7.2 * * 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/Effects/ */ ;jQuery.effects || (function($) { $.effects = { version: "1.7.2", // Saves a set of properties in a data storage save: function(element, set) { for(var i=0; i < set.length; i++) { if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]); } }, // Restores a set of previously saved properties from a data storage restore: function(element, set) { for(var i=0; i < set.length; i++) { if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i])); } }, setMode: function(el, mode) { if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle return mode; }, getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash var y, x; switch (origin[0]) { case 'top': y = 0; break; case 'middle': y = 0.5; break; case 'bottom': y = 1; break; default: y = origin[0] / original.height; }; switch (origin[1]) { case 'left': x = 0; break; case 'center': x = 0.5; break; case 'right': x = 1; break; default: x = origin[1] / original.width; }; return {x: x, y: y}; }, // Wraps the element around a wrapper that copies position properties createWrapper: function(element) { //if the element is already wrapped, return it if (element.parent().is('.ui-effects-wrapper')) return element.parent(); //Cache width,height and float properties of the element, and create a wrapper around it var props = { width: element.outerWidth(true), height: element.outerHeight(true), 'float': element.css('float') }; element.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>'); var wrapper = element.parent(); //Transfer the positioning of the element to the wrapper if (element.css('position') == 'static') { wrapper.css({ position: 'relative' }); element.css({ position: 'relative'} ); } else { var top = element.css('top'); if(isNaN(parseInt(top,10))) top = 'auto'; var left = element.css('left'); if(isNaN(parseInt(left,10))) left = 'auto'; wrapper.css({ position: element.css('position'), top: top, left: left, zIndex: element.css('z-index') }).show(); element.css({position: 'relative', top: 0, left: 0 }); } wrapper.css(props); return wrapper; }, removeWrapper: function(element) { if (element.parent().is('.ui-effects-wrapper')) return element.parent().replaceWith(element); return element; }, setTransition: function(element, list, factor, value) { value = value || {}; $.each(list, function(i, x){ unit = element.cssUnit(x); if (unit[0] > 0) value[x] = unit[0] * factor + unit[1]; }); return value; }, //Base function to animate from one class to another in a seamless transition animateClass: function(value, duration, easing, callback) { var cb = (typeof easing == "function" ? easing : (callback ? callback : null)); var ea = (typeof easing == "string" ? easing : null); return this.each(function() { var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || ''; if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */ if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; } //Let's get a style offset var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle)); if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove); var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle)); if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove); // The main function to form the object for animation for(var n in newStyle) { if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */ && n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */ && newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */ && (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */ && (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */ ) offset[n] = newStyle[n]; } that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object // Change style attribute back to original. For stupid IE, we need to clear the damn object. if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr); if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove); if(cb) cb.apply(this, arguments); }); }); } }; function _normalizeArguments(a, m) { var o = a[1] && a[1].constructor == Object ? a[1] : {}; if(m) o.mode = m; var speed = a[1] && a[1].constructor != Object ? a[1] : (o.duration ? o.duration : a[2]); //either comes from options.duration or the secon/third argument speed = $.fx.off ? 0 : typeof speed === "number" ? speed : $.fx.speeds[speed] || $.fx.speeds._default; var callback = o.callback || ( $.isFunction(a[1]) && a[1] ) || ( $.isFunction(a[2]) && a[2] ) || ( $.isFunction(a[3]) && a[3] ); return [a[0], o, speed, callback]; } //Extend the methods of jQuery $.fn.extend({ //Save old methods _show: $.fn.show, _hide: $.fn.hide, __toggle: $.fn.toggle, _addClass: $.fn.addClass, _removeClass: $.fn.removeClass, _toggleClass: $.fn.toggleClass, // New effect methods effect: function(fx, options, speed, callback) { return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: options || {}, duration: speed, callback: callback }) : null; }, show: function() { if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0]))) return this._show.apply(this, arguments); else { return this.effect.apply(this, _normalizeArguments(arguments, 'show')); } }, hide: function() { if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0]))) return this._hide.apply(this, arguments); else { return this.effect.apply(this, _normalizeArguments(arguments, 'hide')); } }, toggle: function(){ if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])) || ($.isFunction(arguments[0]) || typeof arguments[0] == 'boolean')) { return this.__toggle.apply(this, arguments); } else { return this.effect.apply(this, _normalizeArguments(arguments, 'toggle')); } }, addClass: function(classNames, speed, easing, callback) { return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames); }, removeClass: function(classNames,speed,easing,callback) { return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames); }, toggleClass: function(classNames,speed,easing,callback) { return ( (typeof speed !== "boolean") && speed ) ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames, speed); }, morph: function(remove,add,speed,easing,callback) { return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]); }, switchClass: function() { return this.morph.apply(this, arguments); }, // helper functions cssUnit: function(key) { var style = this.css(key), val = []; $.each( ['em','px','%','pt'], function(i, unit){ if(style.indexOf(unit) > 0) val = [parseFloat(style), unit]; }); return val; } }); /* * jQuery Color Animations * Copyright 2007 John Resig * Released under the MIT and GPL licenses. */ // We override the animation for all of these color styles $.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){ $.fx.step[attr] = function(fx) { if ( fx.state == 0 ) { fx.start = getColor( fx.elem, attr ); fx.end = getRGB( fx.end ); } fx.elem.style[attr] = "rgb(" + [ Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0],10), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1],10), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2],10), 255), 0) ].join(",") + ")"; }; }); // Color Conversion functions from highlightFade // By Blair Mitchelmore // http://jquery.offput.ca/highlightFade/ // Parse strings looking for color tuples [255,255,255] function getRGB(color) { var result; // Check if we're already dealing with an array of colors if ( color && color.constructor == Array && color.length == 3 ) return color; // Look for rgb(num,num,num) if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)]; // Look for rgb(num%,num%,num%) if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; // Look for #a0b1c2 if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; // Look for #fff if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; // Look for rgba(0, 0, 0, 0) == transparent in Safari 3 if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) return colors['transparent']; // Otherwise, we're most likely dealing with a named color return colors[$.trim(color).toLowerCase()]; } function getColor(elem, attr) { var color; do { color = $.curCSS(elem, attr); // Keep going until we find an element that has color, or we hit the body if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") ) break; attr = "backgroundColor"; } while ( elem = elem.parentNode ); return getRGB(color); }; // Some named colors to work with // From Interface by Stefan Petre // http://interface.eyecon.ro/ var colors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0], transparent: [255,255,255] }; /* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration $.easing.jswing = $.easing.swing; $.extend($.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert($.easing.default); return $.easing[$.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ })(jQuery);
JavaScript
/* * jQuery UI Effects Drop 1.7.2 * * 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/Effects/Drop * * Depends: * effects.core.js */ (function($) { $.effects.drop = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left','opacity']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var direction = o.options.direction || 'left'; // Default Direction // Adjust $.effects.save(el, props); el.show(); // Save & Show $.effects.createWrapper(el); // Create Wrapper var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 2 : el.outerWidth({margin:true}) / 2); if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift // Animation var animation = {opacity: mode == 'show' ? 1 : 0}; animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance; // Animate el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
JavaScript
/* * jQuery UI Effects Highlight 1.7.2 * * 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/Effects/Highlight * * Depends: * effects.core.js */ (function($) { $.effects.highlight = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['backgroundImage','backgroundColor','opacity']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var color = o.options.color || "#ffff99"; // Default highlight color var oldColor = el.css("backgroundColor"); // Adjust $.effects.save(el, props); el.show(); // Save & Show el.css({backgroundImage: 'none', backgroundColor: color}); // Shift // Animation var animation = {backgroundColor: oldColor }; if (mode == "hide") animation['opacity'] = 0; // Animate el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == "hide") el.hide(); $.effects.restore(el, props); if (mode == "show" && $.browser.msie) this.style.removeAttribute('filter'); if(o.callback) o.callback.apply(this, arguments); el.dequeue(); }}); }); }; })(jQuery);
JavaScript
/* * jQuery UI Resizable 1.7.2 * * 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/Resizables * * Depends: * ui.core.js */ (function($) { $.widget("ui.resizable", $.extend({}, $.ui.mouse, { _init: function() { var self = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null }); //Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { //Opera fix for relative positioning if (/relative/.test(this.element.css('position')) && $.browser.opera) this.element.css({ position: 'relative', top: 'auto', left: 'auto' }); //Create a wrapper element and set the wrapper to the new current internal element this.element.wrap( $('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({ position: this.element.css('position'), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css('top'), left: this.element.css('left') }) ); //Overwrite the original this.element this.element = this.element.parent().data( "resizable", this.element.data('resizable') ); this.elementIsWrapper = true; //Move margins to the wrapper this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css('resize'); this.originalElement.css('resize', 'none'); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css('margin') }); // fix handlers offset this._proportionallyResize(); } this.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(this.handles.constructor == String) { if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw'; var n = this.handles.split(","); this.handles = {}; for(var i = 0; i < n.length; i++) { var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>'); // increase zIndex of sw, se, ne, nw axis //TODO : this modifies original option if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex }); //TODO : What's going on here? if ('se' == handle) { axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); }; //Insert into internal handles object and append to element this.handles[handle] = '.ui-resizable-'+handle; this.element.append(axis); } } this._renderAxis = function(target) { target = target || this.element; for(var i in this.handles) { if(this.handles[i].constructor == String) this.handles[i] = $(this.handles[i], this.element).show(); //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { var axis = $(this.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(""); target.css(padPos, padWrapper); this._proportionallyResize(); } //TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) continue; } }; //TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $('.ui-resizable-handle', this.element) .disableSelection(); //Matching axis name this._handles.mouseover(function() { if (!self.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 = axis && axis[1] ? axis[1] : 'se'; } }); //If we want to auto hide the elements if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .hover(function() { $(this).removeClass("ui-resizable-autohide"); self._handles.show(); }, function(){ if (!self.resizing) { $(this).addClass("ui-resizable-autohide"); self._handles.hide(); } }); } //Initialize the mouse interaction this._mouseInit(); }, destroy: function() { this._mouseDestroy(); var _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); }; //TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); var wrapper = this.element; wrapper.parent().append( this.originalElement.css({ position: wrapper.css('position'), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css('top'), left: wrapper.css('left') }) ).end().remove(); } this.originalElement.css('resize', this.originalResizeStyle); _destroy(this.originalElement); }, _mouseCapture: function(event) { var handle = false; for(var i in this.handles) { if($(this.handles[i])[0] == event.target) handle = true; } return this.options.disabled || !!handle; }, _mouseStart: function(event) { var o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; // bugfix for http://dev.jquery.com/ticket/1749 if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); } //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 = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { 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: event.pageX, top: event.pageY }; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); var cursor = $('.ui-resizable-' + this.axis).css('cursor'); $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var el = this.helper, o = this.options, props = {}, self = this, smp = this.originalMousePosition, a = this.axis; var dx = (event.pageX-smp.left)||0, dy = (event.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, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; if (this._aspectRatio || event.shiftKey) data = this._updateRatio(data, event); data = this._respectSize(data, event); // plugins callbacks need to be called first this._propagate("resize", event); el.css({ top: this.position.top + "px", left: this.position.left + "px", width: this.size.width + "px", height: this.size.height + "px" }); if (!this._helper && this._proportionallyResizeElements.length) this._proportionallyResize(); this._updateCache(data); // calling the user callback at the end this._trigger('resize', event, this.ui()); return false; }, _mouseStop: function(event) { this.resizing = false; var o = this.options, self = this; if(this._helper) { var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[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 })); self.helper.height(self.size.height); self.helper.width(self.size.width); if (this._helper && !o.animate) this._proportionallyResize(); } $('body').css('cursor', 'auto'); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) this.helper.remove(); return false; }, _updateCache: function(data) { var o = this.options; this.offset = this.helper.offset(); if (isNumber(data.left)) this.position.left = data.left; if (isNumber(data.top)) this.position.top = data.top; if (isNumber(data.height)) this.size.height = data.height; if (isNumber(data.width)) this.size.width = data.width; }, _updateRatio: function(data, event) { var o = this.options, cpos = this.position, csize = this.size, a = this.axis; if (data.height) data.width = (csize.height * this.aspectRatio); else if (data.width) data.height = (csize.width / this.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, event) { var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(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 (!this._proportionallyResizeElements.length) return; var element = this.helper || this.element; for (var i=0; i < this._proportionallyResizeElements.length; i++) { var prel = this._proportionallyResizeElements[i]; if (!this.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')]; this.borderDif = $.map(b, function(v, i) { var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; return border + padding; }); } if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length))) continue; prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); }; }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $('<div style="overflow:hidden;"></div>'); // fix ie6 offset TODO: This seems broken var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), pxyoffset = ( ie6 ? 2 : -1 ); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() + pxyoffset, height: this.element.outerHeight() + pxyoffset, position: 'absolute', left: this.elementOffset.left - ie6offset +'px', top: this.elementOffset.top - ie6offset +'px', zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx, dy) { return { width: this.originalSize.width + dx }; }, w: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n != "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition }; } })); $.extend($.ui.resizable, { version: "1.7.2", eventPrefix: "resize", defaults: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, cancel: ":input,option", containment: false, delay: 0, distance: 1, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, zIndex: 1000 } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "alsoResize", { start: function(event, ui) { var self = $(this).data("resizable"), o = self.options; _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' && !o.alsoResize.parentNode) { 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(event, ui){ var self = $(this).data("resizable"), o = self.options, 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 el = $(this), 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; }); //Opera fixing relative position if (/relative/.test(el.css('position')) && $.browser.opera) { self._revertToRelativePosition = true; el.css({ position: 'absolute', top: 'auto', left: 'auto' }); } el.css(style); }); }; if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function(event, ui){ var self = $(this).data("resizable"); //Opera fixing relative position if (self._revertToRelativePosition && $.browser.opera) { self._revertToRelativePosition = false; el.css({ position: 'relative' }); } $(this).removeData("resizable-alsoresize-start"); } }); $.ui.plugin.add("resizable", "animate", { stop: function(event, ui) { var self = $(this).data("resizable"), o = self.options; var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[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, easing: o.animateEasing, 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.length) $(pr[0]).css({ width: data.width, height: data.height }); // propagating resize, and updating values for each animation step self._updateCache(data); self._propagate("resize", event); } } ); } }); $.ui.plugin.add("resizable", "containment", { start: function(event, ui) { var self = $(this).data("resizable"), o = self.options, 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 { var element = $(ce), p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); self.containerOffset = element.offset(); self.containerPosition = element.position(); self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; 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(event, ui) { var self = $(this).data("resizable"), o = self.options, ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, pRatio = self._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; if (cp.left < (self._helper ? co.left : 0)) { self.size.width = self.size.width + (self._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 : 0; } if (cp.top < (self._helper ? co.top : 0)) { self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top); if (pRatio) self.size.width = self.size.height * o.aspectRatio; self.position.top = self._helper ? co.top : 0; } self.offset.left = self.parentData.left+self.position.left; self.offset.top = self.parentData.top+self.position.top; var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ), hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height ); var isParent = self.containerElement.get(0) == self.element.parent().get(0), isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position')); if(isParent && isOffsetRelative) woset -= self.parentData.left; if (woset + self.size.width >= self.parentData.width) { self.size.width = self.parentData.width - woset; if (pRatio) self.size.height = self.size.width / self.aspectRatio; } if (hoset + self.size.height >= self.parentData.height) { self.size.height = self.parentData.height - hoset; if (pRatio) self.size.width = self.size.height * self.aspectRatio; } }, stop: function(event, ui){ var self = $(this).data("resizable"), o = self.options, cp = self.position, co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height; if (self._helper && !o.animate && (/relative/).test(ce.css('position'))) $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); if (self._helper && !o.animate && (/static/).test(ce.css('position'))) $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } }); $.ui.plugin.add("resizable", "ghost", { start: function(event, ui) { var self = $(this).data("resizable"), o = self.options, cs = self.size; self.ghost = self.originalElement.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(event, ui){ var self = $(this).data("resizable"), o = self.options; if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); }, stop: function(event, ui){ var self = $(this).data("resizable"), o = self.options; if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); } }); $.ui.plugin.add("resizable", "grid", { resize: function(event, ui) { var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.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; } } }); var num = function(v) { return parseInt(v, 10) || 0; }; var isNumber = function(value) { return !isNaN(parseInt(value, 10)); }; })(jQuery);
JavaScript
/* Uploadify v2.1.0 Release Date: August 24, 2009 Copyright (c) 2009 Ronnie Garcia, Travis Nickels Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ if(jQuery)( function(jQuery){ jQuery.extend(jQuery.fn,{ uploadify:function(options) { jQuery(this).each(function(){ settings = jQuery.extend({ id : jQuery(this).attr('id'), // The ID of the object being Uploadified uploader : 'uploadify.swf', // The path to the uploadify swf file script : 'uploadify.php', // The path to the uploadify backend upload script expressInstall : null, // The path to the express install swf file folder : '', // The path to the upload folder height : 30, // The height of the flash button width : 110, // The width of the flash button cancelImg : 'cancel.png', // The path to the cancel image for the default file queue item container wmode : 'opaque', // The wmode of the flash file scriptAccess : 'sameDomain', // Set to "always" to allow script access across domains fileDataName : 'Filedata', // The name of the file collection object in the backend upload script method : 'POST', // The method for sending variables to the backend upload script queueSizeLimit : 999, // The maximum size of the file queue simUploadLimit : 1, // The number of simultaneous uploads allowed queueID : false, // The optional ID of the queue container displayData : 'percentage', // Set to "speed" to show the upload speed in the default queue item onInit : function() {}, // Function to run when uploadify is initialized onSelect : function() {}, // Function to run when a file is selected onQueueFull : function() {}, // Function to run when the queue reaches capacity onCheck : function() {}, // Function to run when script checks for duplicate files on the server onCancel : function() {}, // Function to run when an item is cleared from the queue onError : function() {}, // Function to run when an upload item returns an error onProgress : function() {}, // Function to run each time the upload progress is updated onComplete : function() {}, // Function to run when an upload is completed onAllComplete : function() {} // Functino to run when all uploads are completed }, options); var pagePath = location.pathname; pagePath = pagePath.split('/'); pagePath.pop(); pagePath = pagePath.join('/') + '/'; var data = {}; data.uploadifyID = settings.id; data.pagepath = pagePath; if (settings.buttonImg) data.buttonImg = escape(settings.buttonImg); if (settings.buttonText) data.buttonText = escape(settings.buttonText); if (settings.rollover) data.rollover = true; data.script = settings.script; data.folder = escape(settings.folder); if (settings.scriptData) { var scriptDataString = ''; for (var name in settings.scriptData) { scriptDataString += '&' + name + '=' + settings.scriptData[name]; } data.scriptData = escape(scriptDataString.substr(1)); } data.width = settings.width; data.height = settings.height; data.wmode = settings.wmode; data.method = settings.method; data.queueSizeLimit = settings.queueSizeLimit; data.simUploadLimit = settings.simUploadLimit; if (settings.hideButton) data.hideButton = true; if (settings.fileDesc) data.fileDesc = settings.fileDesc; if (settings.fileExt) data.fileExt = settings.fileExt; if (settings.multi) data.multi = true; if (settings.auto) data.auto = true; if (settings.sizeLimit) data.sizeLimit = settings.sizeLimit; if (settings.checkScript) data.checkScript = settings.checkScript; if (settings.fileDataName) data.fileDataName = settings.fileDataName; if (settings.queueID) data.queueID = settings.queueID; if (settings.onInit() !== false) { jQuery(this).css('display','none'); jQuery(this).after('<div id="' + jQuery(this).attr('id') + 'Uploader"></div>'); swfobject.embedSWF(settings.uploader, settings.id + 'Uploader', settings.width, settings.height, '9.0.24', settings.expressInstall, data, {'quality':'high','wmode':settings.wmode,'allowScriptAccess':settings.scriptAccess}); if (settings.queueID == false) { jQuery("#" + jQuery(this).attr('id') + "Uploader").after('<div id="' + jQuery(this).attr('id') + 'Queue" class="uploadifyQueue"></div>'); } } if (typeof(settings.onOpen) == 'function') { jQuery(this).bind("uploadifyOpen", settings.onOpen); } jQuery(this).bind("uploadifySelect", {'action': settings.onSelect, 'queueID': settings.queueID}, function(event, ID, fileObj) { if (event.data.action(event, ID, fileObj) !== false) { var byteSize = Math.round(fileObj.size / 1024 * 100) * .01; var suffix = 'KB'; if (byteSize > 1000) { byteSize = Math.round(byteSize *.001 * 100) * .01; suffix = 'MB'; } var sizeParts = byteSize.toString().split('.'); if (sizeParts.length > 1) { byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2); } else { byteSize = sizeParts[0]; } if (fileObj.name.length > 20) { fileName = fileObj.name.substr(0,20) + '...'; } else { fileName = fileObj.name; } queue = '#' + jQuery(this).attr('id') + 'Queue'; if (event.data.queueID) { queue = '#' + event.data.queueID; } jQuery(queue).append('<div id="' + jQuery(this).attr('id') + ID + '" class="uploadifyQueueItem">\ <div class="cancel">\ <a href="javascript:jQuery(\'#' + jQuery(this).attr('id') + '\').uploadifyCancel(\'' + ID + '\')"><img src="' + settings.cancelImg + '" border="0" /></a>\ </div>\ <span class="fileName">' + fileName + ' (' + byteSize + suffix + ')</span><span class="percentage"></span>\ <div class="uploadifyProgress">\ <div id="' + jQuery(this).attr('id') + ID + 'ProgressBar" class="uploadifyProgressBar"><!--Progress Bar--></div>\ </div>\ </div>'); } }); if (typeof(settings.onSelectOnce) == 'function') { jQuery(this).bind("uploadifySelectOnce", settings.onSelectOnce); } jQuery(this).bind("uploadifyQueueFull", {'action': settings.onQueueFull}, function(event, queueSizeLimit) { if (event.data.action(event, queueSizeLimit) !== false) { alert('The queue is full. The max size is ' + queueSizeLimit + '.'); } }); jQuery(this).bind("uploadifyCheckExist", {'action': settings.onCheck}, function(event, checkScript, fileQueueObj, folder, single) { var postData = new Object(); postData = fileQueueObj; postData.folder = pagePath + folder; if (single) { for (var ID in fileQueueObj) { var singleFileID = ID; } } jQuery.post(checkScript, postData, function(data) { for(var key in data) { if (event.data.action(event, checkScript, fileQueueObj, folder, single) !== false) { var replaceFile = confirm("Do you want to replace the file " + data[key] + "?"); if (!replaceFile) { document.getElementById(jQuery(event.target).attr('id') + 'Uploader').cancelFileUpload(key, true,true); } } } if (single) { document.getElementById(jQuery(event.target).attr('id') + 'Uploader').startFileUpload(singleFileID, true); } else { document.getElementById(jQuery(event.target).attr('id') + 'Uploader').startFileUpload(null, true); } }, "json"); }); jQuery(this).bind("uploadifyCancel", {'action': settings.onCancel}, function(event, ID, fileObj, data, clearFast) { if (event.data.action(event, ID, fileObj, data, clearFast) !== false) { var fadeSpeed = (clearFast == true) ? 0 : 250; jQuery("#" + jQuery(this).attr('id') + ID).fadeOut(fadeSpeed, function() { jQuery(this).remove() }); } }); if (typeof(settings.onClearQueue) == 'function') { jQuery(this).bind("uploadifyClearQueue", settings.onClearQueue); } var errorArray = []; jQuery(this).bind("uploadifyError", {'action': settings.onError}, function(event, ID, fileObj, errorObj) { if (event.data.action(event, ID, fileObj, errorObj) !== false) { var fileArray = new Array(ID, fileObj, errorObj); errorArray.push(fileArray); jQuery("#" + jQuery(this).attr('id') + ID + " .percentage").text(" - " + errorObj.type + " Error"); jQuery("#" + jQuery(this).attr('id') + ID).addClass('uploadifyError'); } }); jQuery(this).bind("uploadifyProgress", {'action': settings.onProgress, 'toDisplay': settings.displayData}, function(event, ID, fileObj, data) { if (event.data.action(event, ID, fileObj, data) !== false) { jQuery("#" + jQuery(this).attr('id') + ID + "ProgressBar").css('width', data.percentage + '%'); if (event.data.toDisplay == 'percentage') displayData = ' - ' + data.percentage + '%'; if (event.data.toDisplay == 'speed') displayData = ' - ' + data.speed + 'KB/s'; if (event.data.toDisplay == null) displayData = ' '; jQuery("#" + jQuery(this).attr('id') + ID + " .percentage").text(displayData); } }); jQuery(this).bind("uploadifyComplete", {'action': settings.onComplete}, function(event, ID, fileObj, response, data) { if (event.data.action(event, ID, fileObj, unescape(response), data) !== false) { jQuery("#" + jQuery(this).attr('id') + ID + " .percentage").text(' - Completed'); jQuery("#" + jQuery(this).attr('id') + ID).fadeOut(250, function() { jQuery(this).remove()}); } }); if (typeof(settings.onAllComplete) == 'function') { jQuery(this).bind("uploadifyAllComplete", {'action': settings.onAllComplete}, function(event, uploadObj) { if (event.data.action(event, uploadObj) !== false) { errorArray = []; } }); } }); }, uploadifySettings:function(settingName, settingValue, resetObject) { var returnValue = false; jQuery(this).each(function() { if (settingName == 'scriptData' && settingValue != null) { if (resetObject) { var scriptData = settingValue; } else { var scriptData = jQuery.extend(settings.scriptData, settingValue); } var scriptDataString = ''; for (var name in scriptData) { scriptDataString += '&' + name + '=' + escape(scriptData[name]); } settingValue = scriptDataString.substr(1); } returnValue = document.getElementById(jQuery(this).attr('id') + 'Uploader').updateSettings(settingName, settingValue); }); if (settingValue == null) { if (settingName == 'scriptData') { var returnSplit = unescape(returnValue).split('&'); var returnObj = new Object(); for (var i = 0; i < returnSplit.length; i++) { var iSplit = returnSplit[i].split('='); returnObj[iSplit[0]] = iSplit[1]; } returnValue = returnObj; } return returnValue; } }, uploadifyUpload:function(ID) { jQuery(this).each(function() { document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, false); }); }, uploadifyCancel:function(ID) { jQuery(this).each(function() { document.getElementById(jQuery(this).attr('id') + 'Uploader').cancelFileUpload(ID, true, false); }); }, uploadifyClearQueue:function() { jQuery(this).each(function() { document.getElementById(jQuery(this).attr('id') + 'Uploader').clearFileUploadQueue(false); }); } }) })(jQuery);
JavaScript
/* * jQuery UI Sortable 1.7.2 * * 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/Sortables * * Depends: * ui.core.js */ (function($) { $.widget("ui.sortable", $.extend({}, $.ui.mouse, { _init: function() { var o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are floating this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); }, destroy: function() { this.element .removeClass("ui-sortable ui-sortable-disabled") .removeData("sortable") .unbind(".sortable"); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) this.items[i].item.removeData("sortable-item"); }, _mouseCapture: function(event, overrideHandle) { if (this.reverting) { return false; } if(this.options.disabled || this.options.type == 'static') return false; //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items var currentItem = null, self = this, nodes = $(event.target).parents().each(function() { if($.data(this, 'sortable-item') == self) { currentItem = $(this); return false; } }); if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target); if(!currentItem) return false; if(this.options.handle && !overrideHandle) { var validHandle = false; $(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; }); if(!validHandle) return false; } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var o = this.options, self = this; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied if(o.cursorAt) this._adjustOffsetFromHelper(o.cursorAt); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] != this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) this._setContainment(); if(o.cursor) { // cursor option if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor"); $('body').css("cursor", o.cursor); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity"); this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex"); this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') this.overflowOffset = this.scrollParent.offset(); //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) this._cacheHelperProportions(); //Post 'activate' events to possible containers if(!noActivation) { for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); } } //Prepare possible droppables if($.ui.ddmanager) $.ui.ddmanager.current = this; if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, event); this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { var o = this.options, scrolled = false; if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, event); } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper 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'; //Rearrange for (var i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item); if (!intersection) continue; if(itemElement != this.currentItem[0] //cannot intersect with itself && this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before && !$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked && (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true) ) { this.direction = intersection == 1 ? "down" : "up"; if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) $.ui.ddmanager.drag(this, event); //Call callbacks this._trigger('sort', event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) return; //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) $.ui.ddmanager.drop(this, event); if(this.options.revert) { var self = this; var cur = self.placeholder.offset(); self.reverting = true; $(this.helper).animate({ left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft), top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop) }, parseInt(this.options.revert, 10) || 500, function() { self._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { var self = this; if(this.dragging) { this._mouseUp(); if(this.options.helper == "original") this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); else this.currentItem.show(); //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, self._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, self._uiHash(this)); this.containers[i].containerCache.over = 0; } } } //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove(); $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } return true; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected); var str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/)); if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2])); }); return str.join('&'); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected); var ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height; var l = item.left, r = l + item.width, t = item.top, b = t + item.height; var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r; if( this.options.tolerance == "pointer" || this.options.forcePointerForContainers || (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height']) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) // Right Half && x2 - (this.helperProportions.width / 2) < r // Left Half && t < y1 + (this.helperProportions.height / 2) // Bottom Half && y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) return false; return this.floating ? ( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection == "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta != 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta != 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this.refreshPositions(); }, _connectWith: function() { var options = this.options; return options.connectWith.constructor == String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var self = this; var items = []; var queries = []; var connectWith = this._connectWith(); if(connectWith && connected) { for (var i = connectWith.length - 1; i >= 0; i--){ var cur = $(connectWith[i]); for (var j = cur.length - 1; j >= 0; j--){ var inst = $.data(cur[j], 'sortable'); if(inst && inst != this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper"), inst]); } }; }; } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper"), this]); for (var i = queries.length - 1; i >= 0; i--){ queries[i][0].each(function() { items.push(this); }); }; return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(sortable-item)"); for (var i=0; i < this.items.length; i++) { for (var j=0; j < list.length; j++) { if(list[j] == this.items[i].item[0]) this.items.splice(i,1); }; }; }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var items = this.items; var self = this; var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]]; var connectWith = this._connectWith(); if(connectWith) { for (var i = connectWith.length - 1; i >= 0; i--){ var cur = $(connectWith[i]); for (var j = cur.length - 1; j >= 0; j--){ var inst = $.data(cur[j], 'sortable'); if(inst && inst != this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } }; }; } for (var i = queries.length - 1; i >= 0; i--) { var targetData = queries[i][1]; var _queries = queries[i][0]; for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) { var item = $(_queries[j]); item.data('sortable-item', targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); }; }; }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } for (var i = this.items.length - 1; i >= 0; i--){ var item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0]) continue; var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } var p = t.offset(); item.left = p.left; item.top = p.top; }; if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (var i = this.containers.length - 1; i >= 0; i--){ var p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); }; } }, _createPlaceholder: function(that) { var self = that || this, o = self.options; if(!o.placeholder || o.placeholder.constructor == String) { var className = o.placeholder; o.placeholder = { element: function() { var el = $(document.createElement(self.currentItem[0].nodeName)) .addClass(className || self.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper")[0]; if(!className) el.style.visibility = "hidden"; return el; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) return; //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); }; if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); }; } }; } //Create the placeholder self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem)); //Append it after the actual current item self.currentItem.after(self.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(self, self.placeholder); }, _contactContainers: function(event) { for (var i = this.containers.length - 1; i >= 0; i--){ if(this._intersectsWith(this.containers[i].containerCache)) { if(!this.containers[i].containerCache.over) { if(this.currentContainer != this.containers[i]) { //When entering a new container, we will find the item with the least distance and append our item near it var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top']; for (var j = this.items.length - 1; j >= 0; j--) { if(!$.ui.contains(this.containers[i].element[0], this.items[j].item[0])) continue; var cur = this.items[j][this.containers[i].floating ? 'left' : 'top']; if(Math.abs(cur - base) < dist) { dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; } } if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled continue; this.currentContainer = this.containers[i]; itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[i].element, true); this._trigger("change", event, this._uiHash()); this.containers[i]._trigger("change", event, this._uiHash(this)); //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); } this.containers[i]._trigger("over", event, this._uiHash(this)); this.containers[i].containerCache.over = 1; } } else { if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } }; }, _createHelper: function(event) { var o = this.options; var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem); if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already $(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); if(helper[0] == this.currentItem[0]) this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width()); if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height()); return helper; }, _adjustOffsetFromHelper: function(obj) { if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left; if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top; if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix po = { top: 0, left: 0 }; return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition == "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), top: (parseInt(this.currentItem.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var o = this.options; 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.helperProportions.width - this.margins.left, ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; if(!(/^(document|window|parent)$/).test(o.containment)) { var ce = $(o.containment)[0]; var co = $(o.containment).offset(); var over = ($(ce).css("overflow") != 'hidden'); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) pos = this.position; var mod = d == "absolute" ? 1 : -1; var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top // The absolute mouse 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) - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left // The absolute mouse 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) - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } var pageX = event.pageX; var pageY = event.pageY; /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left; if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top; if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left; if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top; } if(o.grid) { var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( 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) + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( 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) + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var self = this, counter = this.counter; window.setTimeout(function() { if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove },0); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var delayedTriggers = [], self = this; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem[0].parentNode) this.placeholder.before(this.currentItem); this._noFinalSort = null; if(this.helper[0] == this.currentItem[0]) { for(var i in this._storedCSS) { if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = ''; } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); for (var i = this.containers.length - 1; i >= 0; i--){ if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) { delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.containers[i])); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.containers[i])); } }; }; //Post events to containers for (var i = this.containers.length - 1; i >= 0; i--){ if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); if(this.containers[i].containerCache.over) { delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset cursor if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } return false; } if(!noPropagation) this._trigger("beforeStop", event, this._uiHash()); //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null; if(!noPropagation) { for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return true; }, _trigger: function() { if ($.widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(inst) { var self = inst || this; return { helper: self.helper, placeholder: self.placeholder || $([]), position: self.position, absolutePosition: self.positionAbs, //deprecated offset: self.positionAbs, item: self.currentItem, sender: inst ? inst.element : null }; } })); $.extend($.ui.sortable, { getter: "serialize toArray", version: "1.7.2", eventPrefix: "sort", defaults: { appendTo: "parent", axis: false, cancel: ":input,option", connectWith: false, containment: false, cursor: 'auto', cursorAt: false, delay: 0, distance: 1, dropOnEmpty: true, forcePlaceholderSize: false, forceHelperSize: false, grid: false, handle: false, helper: "original", items: '> *', opacity: false, placeholder: false, revert: false, scroll: true, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1000 } }); })(jQuery);
JavaScript
/* * jQuery UI Effects Explode 1.7.2 * * 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/Effects/Explode * * Depends: * effects.core.js */ (function($) { $.effects.explode = function(o) { return this.queue(function() { var rows = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3; var cells = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3; o.options.mode = o.options.mode == 'toggle' ? ($(this).is(':visible') ? 'hide' : 'show') : o.options.mode; var el = $(this).show().css('visibility', 'hidden'); var offset = el.offset(); //Substract the margins - not fixing the problem yet. offset.top -= parseInt(el.css("marginTop"),10) || 0; offset.left -= parseInt(el.css("marginLeft"),10) || 0; var width = el.outerWidth(true); var height = el.outerHeight(true); for(var i=0;i<rows;i++) { // = for(var j=0;j<cells;j++) { // || el .clone() .appendTo('body') .wrap('<div></div>') .css({ position: 'absolute', visibility: 'visible', left: -j*(width/cells), top: -i*(height/rows) }) .parent() .addClass('ui-effects-explode') .css({ position: 'absolute', overflow: 'hidden', width: width/cells, height: height/rows, left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0), top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0), opacity: o.options.mode == 'show' ? 0 : 1 }).animate({ left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)), top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)), opacity: o.options.mode == 'show' ? 1 : 0 }, o.duration || 500); } } // Set a timeout, to call the callback approx. when the other animations have finished setTimeout(function() { o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide(); if(o.callback) o.callback.apply(el[0]); // Callback el.dequeue(); $('div.ui-effects-explode').remove(); }, o.duration || 500); }); }; })(jQuery);
JavaScript
/** * jQuery Tooltip Plugin *@requires jQuery v1.2.6 * http://www.socialembedded.com/labs * * Copyright (c) Hernan Amiune (hernan.amiune.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 */ (function($){ $.fn.tooltip = function(options){ var defaults = { cssClass: "", //CSS class or classes to style the tooltip delay : 0, //The number of milliseconds before displaying the tooltip duration : 200, //The number of milliseconds after moving the mouse cusor before removing the tooltip. xOffset : 15, //X offset will allow the tooltip to appear offset by x pixels. yOffset : 15, //Y offset will allow the tooltip to appear offset by y pixels. opacity : 0, //0 is completely opaque and 100 completely transparent fadeDuration: 400 //[toxi20090112] added fade duration in millis (default = "normal") }; var options = $.extend(defaults, options); return this.each(function(index) { var $this = $(this); //use just one div for all tooltips // [toxi20090112] allow the tooltip div to be already present (would break currently) $tooltip=$("#divTooltip"); if($tooltip.length == 0){ $tooltip = $('<div id="divTooltip"></div>'); $('body').append($tooltip); $tooltip.hide(); } //displays the tooltip $this.mouseover( function(e){ //compatibility issue e = e ? e : window.event; //don't hide the tooltip if the mouse is over the element again clearTimeout($tooltip.data("hideTimeoutId")); //set the tooltip class $tooltip.removeClass($tooltip.attr("class")); $tooltip.css("width",""); $tooltip.css("height",""); $tooltip.addClass(options.cssClass); $tooltip.css("opacity",1-options.opacity/100); $tooltip.css("position","absolute"); //save the title text and remove it from title to avoid showing the default tooltip $tooltip.data("title",$this.attr("title")); $this.attr("title",""); $tooltip.data("alt",$this.attr("alt")); $this.attr("alt",""); //set the tooltip content $tooltip.html($tooltip.data("title")); // [toxi20090112] only use ajax if there actually is an href attrib present //var href=$this.attr("href"); //if(href!=undefined && href != "#") // $tooltip.html($.ajax({url:$this.attr("href"),async:false}).responseText); //set the tooltip position winw = $(window).width(); w = $tooltip.width(); xOffset = options.xOffset; //right priority if(w+xOffset+50 < winw-e.clientX) $tooltip.css("left", $(document).scrollLeft() + e.clientX+xOffset); else if(w+xOffset+50 < e.clientX) $tooltip.css("left", $(document).scrollLeft() + e.clientX-(w+xOffset)); else{ //there is more space at left, fit the tooltip there if(e.clientX > winw/2){ $tooltip.width(e.clientX-50); $tooltip.css("left", $(document).scrollLeft() + 25); } //there is more space at right, fit the tooltip there else{ $tooltip.width((winw-e.clientX)-50); $tooltip.css("left", $(document).scrollLeft() + e.clientX+xOffset); } } winh = $(window).height(); h = $tooltip.height(); yOffset = options.yOffset; //top position priority if(h+yOffset + 50 < e.clientY) $tooltip.css("top", $(document).scrollTop() + e.clientY-(h+yOffset)); else if(h+yOffset + 50 < winh-e.clientY) $tooltip.css("top", $(document).scrollTop() + e.clientY+yOffset); else $tooltip.css("top", $(document).scrollTop() + 10); //start the timer to show the tooltip //[toxi20090112] modified to make use of fadeDuration option $tooltip.data("showTimeoutId", setTimeout("$tooltip.fadeIn("+options.fadeDuration+")",options.delay)); }); $this.mouseout(function(e){ //restore the title $this.attr("title",$tooltip.data("title")); $this.attr("alt",$tooltip.data("alt")); //don't show the tooltip if the mouse left the element before the delay time clearTimeout($tooltip.data("showTimeoutId")); //start the timer to hide the tooltip //[toxi20090112] modified to make use of fadeDuration option $tooltip.data("hideTimeoutId", setTimeout("$tooltip.fadeOut("+options.fadeDuration+")",options.duration)); }); //$this.click(function(e){ // e.preventDefault(); //}); }); }})(jQuery);
JavaScript
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $ * $Rev: 2446 $ * * Version 2.1.1 */ (function($){ /** * The bgiframe is chainable and applies the iframe hack to get * around zIndex issues in IE6. It will only apply itself in IE6 * and adds a class to the iframe called 'bgiframe'. The iframe * is appeneded as the first child of the matched element(s) * with a tabIndex and zIndex of -1. * * By default the plugin will take borders, sized with pixel units, * into account. If a different unit is used for the border's width, * then you will need to use the top and left settings as explained below. * * NOTICE: This plugin has been reported to cause perfromance problems * when used on elements that change properties (like width, height and * opacity) a lot in IE6. Most of these problems have been caused by * the expressions used to calculate the elements width, height and * borders. Some have reported it is due to the opacity filter. All * these settings can be changed if needed as explained below. * * @example $('div').bgiframe(); * @before <div><p>Paragraph</p></div> * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div> * * @param Map settings Optional settings to configure the iframe. * @option String|Number top The iframe must be offset to the top * by the width of the top border. This should be a negative * number representing the border-top-width. If a number is * is used here, pixels will be assumed. Otherwise, be sure * to specify a unit. An expression could also be used. * By default the value is "auto" which will use an expression * to get the border-top-width if it is in pixels. * @option String|Number left The iframe must be offset to the left * by the width of the left border. This should be a negative * number representing the border-left-width. If a number is * is used here, pixels will be assumed. Otherwise, be sure * to specify a unit. An expression could also be used. * By default the value is "auto" which will use an expression * to get the border-left-width if it is in pixels. * @option String|Number width This is the width of the iframe. If * a number is used here, pixels will be assume. Otherwise, be sure * to specify a unit. An experssion could also be used. * By default the value is "auto" which will use an experssion * to get the offsetWidth. * @option String|Number height This is the height of the iframe. If * a number is used here, pixels will be assume. Otherwise, be sure * to specify a unit. An experssion could also be used. * By default the value is "auto" which will use an experssion * to get the offsetHeight. * @option Boolean opacity This is a boolean representing whether or not * to use opacity. If set to true, the opacity of 0 is applied. If * set to false, the opacity filter is not applied. Default: true. * @option String src This setting is provided so that one could change * the src of the iframe to whatever they need. * Default: "javascript:false;" * * @name bgiframe * @type jQuery * @cat Plugins/bgiframe * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) */ $.fn.bgIframe = $.fn.bgiframe = function(s) { // This is only for IE6 if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) { s = $.extend({ top : 'auto', // auto == .currentStyle.borderTopWidth left : 'auto', // auto == .currentStyle.borderLeftWidth width : 'auto', // auto == offsetWidth height : 'auto', // auto == offsetHeight opacity : true, src : 'javascript:false;' }, s || {}); var prop = function(n){return n&&n.constructor==Number?n+'px':n;}, html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+ 'style="display:block;position:absolute;z-index:-1;'+ (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+ 'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+ 'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+ 'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+ 'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+ '"/>'; return this.each(function() { if ( $('> iframe.bgiframe', this).length == 0 ) this.insertBefore( document.createElement(html), this.firstChild ); }); } return this; }; })(jQuery);
JavaScript
/* * jQuery UI Draggable 1.7.2 * * 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/Draggables * * Depends: * ui.core.js */ (function($) { $.widget("ui.draggable", $.extend({}, $.ui.mouse, { _init: function() { if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position"))) this.element[0].style.position = 'relative'; (this.options.addClasses && this.element.addClass("ui-draggable")); (this.options.disabled && this.element.addClass("ui-draggable-disabled")); this._mouseInit(); }, destroy: function() { if(!this.element.data('draggable')) return; this.element .removeData("draggable") .unbind(".draggable") .removeClass("ui-draggable" + " ui-draggable-dragging" + " ui-draggable-disabled"); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle')) return false; //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) return false; return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if($.ui.ddmanager) $.ui.ddmanager.current = this; /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css("position"); this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied if(o.cursorAt) this._adjustOffsetFromHelper(o.cursorAt); //Set a containment if given in the options if(o.containment) this._setContainment(); //Call plugins and callbacks this._trigger("start", event); //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, event); this.helper.addClass("ui-draggable-dragging"); this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event, noPropagation) { //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); this._trigger('drag', event, ui); this.position = ui.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, event); return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) dropped = $.ui.ddmanager.drop(this, event); //if a drop comes from outside (a sortable) if(this.dropped) { dropped = this.dropped; this.dropped = false; } if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { var self = this; $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { self._trigger("stop", event); self._clear(); }); } else { this._trigger("stop", event); this._clear(); } return false; }, _getHandle: function(event) { var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false; $(this.options.handle, this.element) .find("*") .andSelf() .each(function() { if(this == event.target) handle = true; }); return handle; }, _createHelper: function(event) { var o = this.options; var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element); if(!helper.parents('body').length) helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)); if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) helper.css("position", "absolute"); return helper; }, _adjustOffsetFromHelper: function(obj) { if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left; if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top; if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix po = { top: 0, left: 0 }; return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition == "relative") { var p = this.element.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var o = this.options; 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.helperProportions.width - this.margins.left, ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) { var ce = $(o.containment)[0]; if(!ce) return; var co = $(o.containment).offset(); var over = ($(ce).css("overflow") != 'hidden'); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } else if(o.containment.constructor == Array) { this.containment = o.containment; } }, _convertPositionTo: function(d, pos) { if(!pos) pos = this.position; var mod = d == "absolute" ? 1 : -1; var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top // The absolute mouse 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) - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left // The absolute mouse 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) - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } var pageX = event.pageX; var pageY = event.pageY; /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left; if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top; if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left; if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top; } if(o.grid) { var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( 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) + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( 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) + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if(this.helper[0] != this.element[0] && !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 _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call(this, type, [event, ui]); if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins return $.widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function(event) { return { helper: this.helper, position: this.position, absolutePosition: this.positionAbs, //deprecated offset: this.positionAbs }; } })); $.extend($.ui.draggable, { version: "1.7.2", eventPrefix: "drag", defaults: { addClasses: true, appendTo: "parent", axis: false, cancel: ":input,option", connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, delay: 0, distance: 1, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function(event, ui) { var inst = $(this).data("draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $.data(this, 'sortable'); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable._refreshItems(); //Do a one-time refresh at start to refresh the containerCache sortable._trigger("activate", event, uiSortable); } }); }, stop: function(event, 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"), uiSortable = $.extend({}, ui, { item: inst.element }); $.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) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid' if(this.shouldRevert) this.instance.options.revert = true; //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if(inst.options.helper == 'original') this.instance.currentItem.css({ top: 'auto', left: 'auto' }); } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function(event, ui) { var inst = $(this).data("draggable"), self = this; var checkPos = function(o) { var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left; var itemHeight = o.height, itemWidth = o.width; var itemTop = o.top, itemLeft = o.left; return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth); }; $.each(inst.sortables, function(i) { //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if(this.instance._intersectsWith(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]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, 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._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //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(event); } 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; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger('out', event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, 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._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } }; }); } }); $.ui.plugin.add("draggable", "cursor", { start: function(event, ui) { var t = $('body'), o = $(this).data('draggable').options; if (t.css("cursor")) o._cursor = t.css("cursor"); t.css("cursor", o.cursor); }, stop: function(event, ui) { var o = $(this).data('draggable').options; if (o._cursor) $('body').css("cursor", o._cursor); } }); $.ui.plugin.add("draggable", "iframeFix", { start: function(event, ui) { var o = $(this).data('draggable').options; $(o.iframeFix === true ? "iframe" : o.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(event, ui) { $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers } }); $.ui.plugin.add("draggable", "opacity", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data('draggable').options; if(t.css("opacity")) o._opacity = t.css("opacity"); t.css('opacity', o.opacity); }, stop: function(event, ui) { var o = $(this).data('draggable').options; if(o._opacity) $(ui.helper).css('opacity', o._opacity); } }); $.ui.plugin.add("draggable", "scroll", { start: function(event, ui) { var i = $(this).data("draggable"); if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset(); }, drag: function(event, ui) { var i = $(this).data("draggable"), o = i.options, scrolled = false; if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') { if(!o.axis || o.axis != 'x') { if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } if(!o.axis || o.axis != 'y') { if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(!o.axis || o.axis != 'x') { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(!o.axis || o.axis != 'y') { if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(i, event); } }); $.ui.plugin.add("draggable", "snap", { start: function(event, ui) { var i = $(this).data("draggable"), o = i.options; i.snapElements = []; $(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() { var $t = $(this); var $o = $t.offset(); if(this != i.element[0]) i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); }); }, drag: function(event, ui) { var inst = $(this).data("draggable"), o = inst.options; var d = o.snapTolerance; var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.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))) { if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); inst.snapElements[i].snapping = false; continue; } if(o.snapMode != 'inner') { var ts = Math.abs(t - y2) <= d; var bs = Math.abs(b - y1) <= d; var ls = Math.abs(l - x2) <= d; var rs = Math.abs(r - x1) <= d; if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } var first = (ts || bs || ls || rs); if(o.snapMode != 'outer') { var ts = Math.abs(t - y1) <= d; var bs = Math.abs(b - y2) <= d; var ls = Math.abs(l - x1) <= d; var rs = Math.abs(r - x2) <= d; if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); inst.snapElements[i].snapping = (ts || bs || ls || rs || first); }; } }); $.ui.plugin.add("draggable", "stack", { start: function(event, ui) { var o = $(this).data("draggable").options; var group = $.makeArray($(o.stack.group)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || o.stack.min) - (parseInt($(b).css("zIndex"),10) || o.stack.min); }); $(group).each(function(i) { this.style.zIndex = o.stack.min + i; }); this[0].style.zIndex = o.stack.min + group.length; } }); $.ui.plugin.add("draggable", "zIndex", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("draggable").options; if(t.css("zIndex")) o._zIndex = t.css("zIndex"); t.css('zIndex', o.zIndex); }, stop: function(event, ui) { var o = $(this).data("draggable").options; if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex); } }); })(jQuery);
JavaScript
/* * jQuery UI Effects Clip 1.7.2 * * 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/Effects/Clip * * Depends: * effects.core.js */ (function($) { $.effects.clip = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left','height','width']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var direction = o.options.direction || 'vertical'; // Default direction // Adjust $.effects.save(el, props); el.show(); // Save & Show var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper var animate = el[0].tagName == 'IMG' ? wrapper : el; var ref = { size: (direction == 'vertical') ? 'height' : 'width', position: (direction == 'vertical') ? 'top' : 'left' }; var distance = (direction == 'vertical') ? animate.height() : animate.width(); if(mode == 'show') { animate.css(ref.size, 0); animate.css(ref.position, distance / 2); } // Shift // Animation var animation = {}; animation[ref.size] = mode == 'show' ? distance : 0; animation[ref.position] = mode == 'show' ? 0 : distance / 2; // Animate animate.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(el[0], arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
JavaScript
/* * jQuery UI Datepicker 1.7.2 * * 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: "1.7.2" } }); 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: '关闭', prevText: '&#x3c;上月', nextText: '下月&#x3e;', currentText: '今天', monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'], monthNamesShort: ['一','二','三','四','五','六', '七','八','九','十','十一','十二'], dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'], dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], dayNamesMin: ['日','一','二','三','四','五','六'], dateFormat: 'yy-mm-dd', firstDay: 1, isRTL: false }; 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 showMonthAfterYear: false, // True if the year select precedes month, false for month then year 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). 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 = 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 = // 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); } 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 @param endDate Date - the new end date for a range (optional) */ _setDateDatepicker: function(target, date, endDate) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date, endDate); 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 or Date[2] - the current dates for a range */ _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); } }, /* 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; inst.rangeStart = 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; if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems $('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4, height: inst.dpDiv.height() + 4}); }; 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 dims = {width: inst.dpDiv.width() + 4, height: inst.dpDiv.height() + 4}; var self = this; inst.dpDiv.empty().append(this._generateHTML(inst)) .find('iframe.ui-datepicker-cover'). css({width: dims.width, height: dims.height}) .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(); }, /* 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 = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft(); var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.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 (inst.stayOpen) this._selectDate('#' + inst.id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); inst.stayOpen = false; 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; if (inst.stayOpen) { inst.endDay = inst.endMonth = inst.endYear = null; } this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); if (inst.stayOpen) { inst.rangeStart = this._daylightSavingAdjust( new Date(inst.currentYear, inst.currentMonth, inst.currentDay)); this._updateDatepicker(inst); } }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); inst.stayOpen = false; inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null; 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 if (!inst.stayOpen) { 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.getFullYear(), date.getMonth(), date.getDate()); var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7 firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year return $.datepicker.iso8601Week(checkDate); } else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7; if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary return 1; } } return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date }, /* 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 origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2))); var size = origSize; var num = 0; while (size > 0 && iValue < value.length && value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') { num = num * 10 + parseInt(value.charAt(iValue++),10); size--; } if (size == origSize) throw 'Missing number at position ' + iValue; return num; }; // Extract a name from the string value and convert to an index var getName = function(match, shortNames, longNames) { var names = (lookAhead(match) ? longNames : shortNames); var size = 0; for (var j = 0; j < names.length; j++) size = Math.max(size, names[j].length); var name = ''; var iInit = iValue; while (size > 0 && iValue < value.length) { name += value.charAt(iValue++); for (var i = 0; i < names.length; i++) if (name == names[i]) return i + 1; size--; } throw 'Unknown name at position ' + iInit; }; // 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 "'": 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 TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 /* 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) '...' - 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': var doy = date.getDate(); for (var m = date.getMonth() - 1; m >= 0; m--) doy += this._getDaysInMonth(date.getFullYear(), m); output += formatNumber('o', doy, 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 "'": 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; inst.endDay = inst.endMonth = inst.endYear = 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) { var date = this._determineDate(this._get(inst, 'defaultDate'), new Date()); var minDate = this._getMinMaxDate(inst, 'min', true); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); return 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, endDate) { var clear = !(date); var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; date = 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 stepBigMonths = this._get(inst, 'stepBigMonths'); 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', true); 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 endDate = inst.endDay ? this._daylightSavingAdjust( new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate; 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, selectedDate, 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() && printDate.getTime() <= endDate.getTime() ? // in current range ' ' + 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() && printDate.getTime() <= endDate.getTime() ? // in current range ' 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, selectedDate, secondary, monthNames, monthNamesShort) { minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate); 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>'; } 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._daylightSavingAdjust(new Date(year, month, day)); // ensure it is within the bounds set var minDate = this._getMinMaxDate(inst, 'min', true); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst); }, /* 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 - may be overridden for a range. */ _getMinMaxDate: function(inst, minMax, checkRange) { var date = this._determineDate(this._get(inst, minMax + 'Date'), null); return (!checkRange || !inst.rangeStart ? date : (!date || inst.rangeStart > date ? inst.rangeStart : date)); }, /* 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) { // during range selection, use minimum of selected date and range start var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust( new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay))); newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate); var minDate = newMinDate || 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('body').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 = "1.7.2"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window.DP_jQuery = $; })(jQuery);
JavaScript
/* * jQuery UI Effects Transfer 1.7.2 * * 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/Effects/Transfer * * Depends: * effects.core.js */ (function($) { $.effects.transfer = function(o) { return this.queue(function() { var elem = $(this), target = $(o.options.to), endPosition = target.offset(), animation = { top: endPosition.top, left: endPosition.left, height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $('<div class="ui-effects-transfer"></div>') .appendTo(document.body) .addClass(o.options.className) .css({ top: startPosition.top, left: startPosition.left, height: elem.innerHeight(), width: elem.innerWidth(), position: 'absolute' }) .animate(animation, o.duration, o.options.easing, function() { transfer.remove(); (o.callback && o.callback.apply(elem[0], arguments)); elem.dequeue(); }); }); }; })(jQuery);
JavaScript
/** * upload 1.0 * * Copyright (c) 2009 www.01mvc.com * * http://www.01cms.com * * Depends: * ui.core.js * ui.draggable.js * ui.resizable.js * ui.dialog.js */ $.fn.upload = function(options){ var defaults = { url: "" }; var options = $.extend(defaults, options); $(this).click(function(){ if($('#uploadFrame').length == 0) { $('body').append('<iframe class="hidden" id="autoFrame" name="autoFrame" ></iframe>'); } if($('.ui-dialog').length > 0) { $('.ui-dialog').remove(); } $('<div class="ui-dialog-message"><span class="ui-dialog-loading">&nbsp;</span>正在处理,请稍候...</div>').dialog({ title:'上传图片', resizable : false, width : 400 }); $.ajax({ type : 'get', url : options.url, success : function(response) { $(".ui-dialog-message").html(response); } }); }); };
JavaScript
/* * jQuery UI Effects Blind 1.7.2 * * 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/Effects/Blind * * Depends: * effects.core.js */ (function($) { $.effects.blind = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var direction = o.options.direction || 'vertical'; // Default direction // Adjust $.effects.save(el, props); el.show(); // Save & Show var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper var ref = (direction == 'vertical') ? 'height' : 'width'; var distance = (direction == 'vertical') ? wrapper.height() : wrapper.width(); if(mode == 'show') wrapper.css(ref, 0); // Shift // Animation var animation = {}; animation[ref] = mode == 'show' ? distance : 0; // Animate wrapper.animate(animation, o.duration, o.options.easing, function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(el[0], arguments); // Callback el.dequeue(); }); }); }; })(jQuery);
JavaScript
/* * jQuery UI Droppable 1.7.2 * * 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/Droppables * * Depends: * ui.core.js * ui.draggable.js */ (function($) { $.widget("ui.droppable", { _init: function() { var o = this.options, accept = o.accept; this.isover = 0; this.isout = 1; this.options.accept = this.options.accept && $.isFunction(this.options.accept) ? this.options.accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[this.options.scope] = $.ui.ddmanager.droppables[this.options.scope] || []; $.ui.ddmanager.droppables[this.options.scope].push(this); (this.options.addClasses && this.element.addClass("ui-droppable")); }, destroy: function() { var drop = $.ui.ddmanager.droppables[this.options.scope]; for ( var i = 0; i < drop.length; i++ ) if ( drop[i] == this ) drop.splice(i, 1); this.element .removeClass("ui-droppable ui-droppable-disabled") .removeData("droppable") .unbind(".droppable"); }, _setData: function(key, value) { if(key == 'accept') { this.options.accept = value && $.isFunction(value) ? value : function(d) { return d.is(value); }; } else { $.widget.prototype._setData.apply(this, arguments); } }, _activate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.addClass(this.options.activeClass); (draggable && this._trigger('activate', event, this.ui(draggable))); }, _deactivate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.removeClass(this.options.activeClass); (draggable && this._trigger('deactivate', event, this.ui(draggable))); }, _over: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.addClass(this.options.hoverClass); this._trigger('over', event, this.ui(draggable)); } }, _out: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('out', event, this.ui(draggable)); } }, _drop: function(event,custom) { var draggable = custom || $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element var childrenIntersection = false; this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, 'droppable'); if(inst.options.greedy && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)) { childrenIntersection = true; return false; } }); if(childrenIntersection) return false; if(this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.activeClass) this.element.removeClass(this.options.activeClass); if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('drop', event, this.ui(draggable)); return this.element; } return false; }, ui: function(c) { return { draggable: (c.currentItem || c.element), helper: c.helper, position: c.position, absolutePosition: c.positionAbs, //deprecated offset: c.positionAbs }; } }); $.extend($.ui.droppable, { version: "1.7.2", eventPrefix: 'drop', defaults: { accept: '*', activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: 'default', tolerance: 'intersect' } }); $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) return false; var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height; var l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, b = t + droppable.proportions.height; switch (toleranceMode) { case 'fit': return (l < x1 && x2 < r && t < y1 && y2 < b); break; case 'intersect': return (l < x1 + (draggable.helperProportions.width / 2) // Right Half && x2 - (draggable.helperProportions.width / 2) < r // Left Half && t < y1 + (draggable.helperProportions.height / 2) // Bottom Half && y2 - (draggable.helperProportions.height / 2) < b ); // Top Half break; case 'pointer': var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left), draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top), isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width); return isOver; break; case 'touch': return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); break; default: return false; break; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { 'default': [] }, prepareOffsets: function(t, event) { var m = $.ui.ddmanager.droppables[t.options.scope]; var type = event ? event.type : null; // workaround for #2317 var list = (t.currentItem || t.element).find(":data(droppable)").andSelf(); droppablesLoop: for (var i = 0; i < m.length; i++) { if(m[i].options.disabled || (t && !m[i].options.accept.call(m[i].element[0],(t.currentItem || t.element)))) continue; //No disabled and non-accepted for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue m[i].offset = m[i].element.offset(); m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables } }, drop: function(draggable, event) { var dropped = false; $.each($.ui.ddmanager.droppables[draggable.options.scope], function() { if(!this.options) return; if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) dropped = this._drop.call(this, event); if (!this.options.disabled && this.visible && this.options.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { this.isout = 1; this.isover = 0; this._deactivate.call(this, event); } }); return dropped; }, drag: function(draggable, event) { //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event); //Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope], function() { if(this.options.disabled || this.greedyChild || !this.visible) return; var intersects = $.ui.intersect(draggable, this, this.options.tolerance); var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null); if(!c) return; var parentInstance; if (this.options.greedy) { var parent = this.element.parents(':data(droppable):eq(0)'); if (parent.length) { parentInstance = $.data(parent[0], 'droppable'); parentInstance.greedyChild = (c == 'isover' ? 1 : 0); } } // we just moved into a greedy child if (parentInstance && c == 'isover') { parentInstance['isover'] = 0; parentInstance['isout'] = 1; parentInstance._out.call(parentInstance, event); } this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0; this[c == "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c == 'isout') { parentInstance['isout'] = 0; parentInstance['isover'] = 1; parentInstance._over.call(parentInstance, event); } }); } }; })(jQuery);
JavaScript
/** * post 1.0 * * Copyright (c) 2009 www.01mvc.com * * http://www.01cms.com * * Depends: * ui.core.js * ui.draggable.js * ui.resizable.js * ui.dialog.js */ $.fn.post = function(options){ var defaults = { defaultMsg: '<span class="ui-dialog-loading">&nbsp;</span>正在处理,请稍候...', sendUrl: "", goUrl : "", trueJs : "", falseJs : "", falseCheck : true, style : "padding:15px; line-height:20px; font-size:13px; text-align:center;", dataClass : "posted", dataType : "json", stayTime : 2, buttons : '', height : 'auto', width : 300, maxHeight : '', maxWidth : '', minHeight : '', minWidth : '', title : "提示信息", beforeclose : '', resizable : false, open : '', focus : '', position : 'center', dragStart : '', drag : '', dragStop : '', resizeStart : '', resize : '', resizeStop : '', close : function() {$(':submit').attr('disabled',false);}, msgClass : 'ui-dialog-message'+$(".ui-dialog").length }; var options = $.extend(defaults, options); var msgClass = options.msgClass; $(this).submit(function(){ $(':submit').attr('disabled',true); $('<div class="'+msgClass+'" style="'+options.style+'">'+options.defaultMsg+'</div>').dialog({ buttons : options.buttons, height : options.height, width : options.width, maxHeight : options.maxHeight, maxWidth : options.maxWidth, minHeight : options.minHeight, minWidth : options.minWidth, title : options.title, beforeclose : options.beforeclose, resizable : options.resizable, open : options.open, focus : options.focus, position : options.position, dragStart : options.dragStart, drag : options.drag, dragStop : options.dragStop, resizeStart : options.resizeStart, buttons: options.buttons, close : options.close }); $("."+options.dataClass).each(function(){ if(options.data == '') { and = ''; } else { and = '&'; } var value = ''; if(this.type == 'checkbox' || this.type == 'radio') { if(this.checked) { options.data += and + this.name + '=' + this.value; } } else { options.data += and + this.name + '=' + this.value; } }); $.ajax( { type : 'post', dataType : options.dataType, data : options.data, url : options.sendUrl, success : function(response) { $("."+msgClass).html(response.message); if (response.success && options.goUrl != '') { window.setTimeout(function(){ window.location.href = options.goUrl;} ,options.stayTime * 1000); } else { window.setTimeout(function(){$(".ui-dialog:has(."+msgClass+")").hide('slow',function(){$(".ui-dialog:has(."+msgClass+")").remove();$("."+msgClass).remove();});$(':submit').attr('disabled',false);},options.stayTime*1000); } if (response.js != '') { eval(response.js); } if (options.falseCheck && !response.success) { $(".check").each(function(){ if($(this).val() == '') { $(this).addClass("yellowBg"); $(this).change(function(){ if($(this).val() != '') { $(this).removeClass("yellowBg"); } else { $(this).addClass("yellowBg"); } }); } else { $(this).removeClass("yellowBg"); } }); } if (response.success && options.trueJs != '') { eval(options.trueJs); } else if (options.falseJs != '') { eval(options.falseJs); } } }); return false; }); };
JavaScript
/* * jQuery UI Effects Pulsate 1.7.2 * * 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/Effects/Pulsate * * Depends: * effects.core.js */ (function($) { $.effects.pulsate = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var times = o.options.times || 5; // Default # of times var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2; // Adjust if (mode == 'hide') times--; if (el.is(':hidden')) { // Show fadeIn el.css('opacity', 0); el.show(); // Show el.animate({opacity: 1}, duration, o.options.easing); times = times-2; } // Animate for (var i = 0; i < times; i++) { // Pulsate el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing); }; if (mode == 'hide') { // Last Pulse el.animate({opacity: 0}, duration, o.options.easing, function(){ el.hide(); // Hide if(o.callback) o.callback.apply(this, arguments); // Callback }); } else { el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){ if(o.callback) o.callback.apply(this, arguments); // Callback }); }; el.queue('fx', function() { el.dequeue(); }); el.dequeue(); }); }; })(jQuery);
JavaScript
/* * jQuery UI Effects Shake 1.7.2 * * 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/Effects/Shake * * Depends: * effects.core.js */ (function($) { $.effects.shake = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode var direction = o.options.direction || 'left'; // Default direction var distance = o.options.distance || 20; // Default distance var times = o.options.times || 3; // Default # of times var speed = o.duration || o.options.duration || 140; // Default speed per shake // Adjust $.effects.save(el, props); el.show(); // Save & Show $.effects.createWrapper(el); // Create Wrapper var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; // Animation var animation = {}, animation1 = {}, animation2 = {}; animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance; animation1[ref] = (motion == 'pos' ? '+=' : '-=') + distance * 2; animation2[ref] = (motion == 'pos' ? '-=' : '+=') + distance * 2; // Animate el.animate(animation, speed, o.options.easing); for (var i = 1; i < times; i++) { // Shakes el.animate(animation1, speed, o.options.easing).animate(animation2, speed, o.options.easing); }; el.animate(animation1, speed, o.options.easing). animate(animation, speed / 2, o.options.easing, function(){ // Last shake $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback }); el.queue('fx', function() { el.dequeue(); }); el.dequeue(); }); }; })(jQuery);
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'E\']=h.i[\'y\'];h.F(h.i,{z:\'A\',y:9(x,t,b,c,d){6 h.i[h.i.z](x,t,b,c,d)},G:9(x,t,b,c,d){6 c*(t/=d)*t+b},A:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},H:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},I:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},K:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},L:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},N:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},O:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},P:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},R:9(x,t,b,c,d){6-c*8.B(t/d*(8.g/2))+c+b},S:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},T:9(x,t,b,c,d){6-c/2*(8.B(8.g*t/d)-1)+b},U:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},V:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},X:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},Y:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Z:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},11:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.r(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.u(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},12:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.r(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.u(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},13:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.r(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.u(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},14:9(x,t,b,c,d,s){e(s==v)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},15:9(x,t,b,c,d,s){e(s==v)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==v)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.C))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.C))+1)*t+s)+2)+b},D:9(x,t,b,c,d){6 c-h.i.w(x,d-t,0,c,d)+b},w:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.17/2.k))*t+.18)+b}m{6 c*(7.q*(t-=(2.19/2.k))*t+.1a)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.D(x,t*2,0,c,d)*.5+b;6 h.i.w(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|abs|||asin|undefined|easeOutBounce||swing|def|easeOutQuad|cos|525|easeInBounce|jswing|extend|easeInQuad|easeInOutQuad|easeInCubic|easeOutCubic|easeInOutCubic|easeInQuart|easeOutQuart|easeInOutQuart|easeInQuint|easeOutQuint|easeInOutQuint|easeInSine|easeOutSine|easeInOutSine|easeInExpo|easeOutExpo|easeInOutExpo|easeInCirc|easeOutCirc|easeInOutCirc||easeInElastic|easeOutElastic|easeInOutElastic|easeInBack|easeOutBack|easeInOutBack|25|9375|625|984375|easeInOutBounce'.split('|'),0,{})) /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/* * jQuery UI Tabs 1.7.2 * * 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/Tabs * * Depends: * ui.core.js */ (function($) { $.widget("ui.tabs", { _init: function() { if (this.options.deselectable !== undefined) { this.options.collapsible = this.options.deselectable; } this._tabify(true); }, _setData: function(key, value) { if (key == 'selected') { if (this.options.collapsible && value == this.options.selected) { return; } this.select(value); } else { this.options[key] = value; if (key == 'deselectable') { this.options.collapsible = value; } this._tabify(); } }, _tabId: function(a) { return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') || this.options.idPrefix + $.data(a); }, _sanitizeSelector: function(hash) { return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":" }, _cookie: function() { var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + $.data(this.list[0])); return $.cookie.apply(null, [cookie].concat($.makeArray(arguments))); }, _ui: function(tab, panel) { return { tab: tab, panel: panel, index: this.anchors.index(tab) }; }, _cleanup: function() { // restore all former loading tabs labels this.lis.filter('.ui-state-processing').removeClass('ui-state-processing') .find('span:data(label.tabs)') .each(function() { var el = $(this); el.html(el.data('label.tabs')).removeData('label.tabs'); }); }, _tabify: function(init) { this.list = this.element.children('ul:first'); this.lis = $('li:has(a[href])', this.list); this.anchors = this.lis.map(function() { return $('a', this)[0]; }); this.panels = $([]); var self = this, o = this.options; var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash this.anchors.each(function(i, a) { var href = $(a).attr('href'); // For dynamically created HTML that contains a hash as href IE < 8 expands // such href to the full page url with hash and then misinterprets tab as ajax. // Same consideration applies for an added tab with a fragment identifier // since a[href=#fragment-identifier] does unexpectedly not match. // Thus normalize href attribute... var hrefBase = href.split('#')[0], baseEl; if (hrefBase && (hrefBase === location.toString().split('#')[0] || (baseEl = $('base')[0]) && hrefBase === baseEl.href)) { href = a.hash; a.href = href; } // inline tab if (fragmentId.test(href)) { self.panels = self.panels.add(self._sanitizeSelector(href)); } // remote tab else if (href != '#') { // prevent loading the page itself if href is just "#" $.data(a, 'href.tabs', href); // required for restore on destroy // TODO until #3808 is fixed strip fragment identifier from url // (IE fails to load from such url) $.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data var id = self._tabId(a); a.href = '#' + id; var $panel = $('#' + id); if (!$panel.length) { $panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom') .insertAfter(self.panels[i - 1] || self.list); $panel.data('destroy.tabs', true); } self.panels = self.panels.add($panel); } // invalid tab href else { o.disabled.push(i); } }); // initialization from scratch if (init) { // attach necessary classes for styling this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all'); this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.lis.addClass('ui-state-default ui-corner-top'); this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom'); // Selected tab // use "selected" option or try to retrieve: // 1. from fragment identifier in url // 2. from cookie // 3. from selected class attribute on <li> if (o.selected === undefined) { if (location.hash) { this.anchors.each(function(i, a) { if (a.hash == location.hash) { o.selected = i; return false; // break } }); } if (typeof o.selected != 'number' && o.cookie) { o.selected = parseInt(self._cookie(), 10); } if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) { o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected')); } o.selected = o.selected || 0; } else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release o.selected = -1; } // sanity check - default to first tab... o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0; // Take disabling tabs via class attribute from HTML // into account and update option properly. // A selected tab cannot become disabled. o.disabled = $.unique(o.disabled.concat( $.map(this.lis.filter('.ui-state-disabled'), function(n, i) { return self.lis.index(n); } ) )).sort(); if ($.inArray(o.selected, o.disabled) != -1) { o.disabled.splice($.inArray(o.selected, o.disabled), 1); } // highlight selected tab this.panels.addClass('ui-tabs-hide'); this.lis.removeClass('ui-tabs-selected ui-state-active'); if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list this.panels.eq(o.selected).removeClass('ui-tabs-hide'); this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active'); // seems to be expected behavior that the show callback is fired self.element.queue("tabs", function() { self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected])); }); this.load(o.selected); } // clean up to avoid memory leaks in certain versions of IE 6 $(window).bind('unload', function() { self.lis.add(self.anchors).unbind('.tabs'); self.lis = self.anchors = self.panels = null; }); } // update selected after add/remove else { o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected')); } // update collapsible this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible'); // set or update cookie after init and add/remove respectively if (o.cookie) { this._cookie(o.selected, o.cookie); } // disable tabs for (var i = 0, li; (li = this.lis[i]); i++) { $(li)[$.inArray(i, o.disabled) != -1 && !$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled'); } // reset cache if switching from cached to not cached if (o.cache === false) { this.anchors.removeData('cache.tabs'); } // remove all handlers before, tabify may run on existing tabs after add or option change this.lis.add(this.anchors).unbind('.tabs'); if (o.event != 'mouseover') { var addState = function(state, el) { if (el.is(':not(.ui-state-disabled)')) { el.addClass('ui-state-' + state); } }; var removeState = function(state, el) { el.removeClass('ui-state-' + state); }; this.lis.bind('mouseover.tabs', function() { addState('hover', $(this)); }); this.lis.bind('mouseout.tabs', function() { removeState('hover', $(this)); }); this.anchors.bind('focus.tabs', function() { addState('focus', $(this).closest('li')); }); this.anchors.bind('blur.tabs', function() { removeState('focus', $(this).closest('li')); }); } // set up animations var hideFx, showFx; if (o.fx) { if ($.isArray(o.fx)) { hideFx = o.fx[0]; showFx = o.fx[1]; } else { hideFx = showFx = o.fx; } } // Reset certain styles left over from animation // and prevent IE's ClearType bug... function resetStyle($el, fx) { $el.css({ display: '' }); if ($.browser.msie && fx.opacity) { $el[0].style.removeAttribute('filter'); } } // Show a tab... var showTab = showFx ? function(clicked, $show) { $(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active'); $show.hide().removeClass('ui-tabs-hide') // avoid flicker that way .animate(showFx, showFx.duration || 'normal', function() { resetStyle($show, showFx); self._trigger('show', null, self._ui(clicked, $show[0])); }); } : function(clicked, $show) { $(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active'); $show.removeClass('ui-tabs-hide'); self._trigger('show', null, self._ui(clicked, $show[0])); }; // Hide a tab, $show is optional... var hideTab = hideFx ? function(clicked, $hide) { $hide.animate(hideFx, hideFx.duration || 'normal', function() { self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default'); $hide.addClass('ui-tabs-hide'); resetStyle($hide, hideFx); self.element.dequeue("tabs"); }); } : function(clicked, $hide, $show) { self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default'); $hide.addClass('ui-tabs-hide'); self.element.dequeue("tabs"); }; // attach tab event handler, unbind to avoid duplicates from former tabifying... this.anchors.bind(o.event + '.tabs', function() { var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'), $show = $(self._sanitizeSelector(this.hash)); // If tab is already selected and not collapsible or tab disabled or // or is already loading or click callback returns false stop here. // Check if click handler returns false last so that it is not executed // for a disabled or loading tab! if (($li.hasClass('ui-tabs-selected') && !o.collapsible) || $li.hasClass('ui-state-disabled') || $li.hasClass('ui-state-processing') || self._trigger('select', null, self._ui(this, $show[0])) === false) { this.blur(); return false; } o.selected = self.anchors.index(this); self.abort(); // if tab may be closed if (o.collapsible) { if ($li.hasClass('ui-tabs-selected')) { o.selected = -1; if (o.cookie) { self._cookie(o.selected, o.cookie); } self.element.queue("tabs", function() { hideTab(el, $hide); }).dequeue("tabs"); this.blur(); return false; } else if (!$hide.length) { if (o.cookie) { self._cookie(o.selected, o.cookie); } self.element.queue("tabs", function() { showTab(el, $show); }); self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171 this.blur(); return false; } } if (o.cookie) { self._cookie(o.selected, o.cookie); } // show new tab if ($show.length) { if ($hide.length) { self.element.queue("tabs", function() { hideTab(el, $hide); }); } self.element.queue("tabs", function() { showTab(el, $show); }); self.load(self.anchors.index(this)); } else { throw 'jQuery UI Tabs: Mismatching fragment identifier.'; } // Prevent IE from keeping other link focussed when using the back button // and remove dotted border from clicked link. This is controlled via CSS // in modern browsers; blur() removes focus from address bar in Firefox // which can become a usability and annoying problem with tabs('rotate'). if ($.browser.msie) { this.blur(); } }); // disable click in any case this.anchors.bind('click.tabs', function(){return false;}); }, destroy: function() { var o = this.options; this.abort(); this.element.unbind('.tabs') .removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible') .removeData('tabs'); this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.anchors.each(function() { var href = $.data(this, 'href.tabs'); if (href) { this.href = href; } var $this = $(this).unbind('.tabs'); $.each(['href', 'load', 'cache'], function(i, prefix) { $this.removeData(prefix + '.tabs'); }); }); this.lis.unbind('.tabs').add(this.panels).each(function() { if ($.data(this, 'destroy.tabs')) { $(this).remove(); } else { $(this).removeClass([ 'ui-state-default', 'ui-corner-top', 'ui-tabs-selected', 'ui-state-active', 'ui-state-hover', 'ui-state-focus', 'ui-state-disabled', 'ui-tabs-panel', 'ui-widget-content', 'ui-corner-bottom', 'ui-tabs-hide' ].join(' ')); } }); if (o.cookie) { this._cookie(null, o.cookie); } }, add: function(url, label, index) { if (index === undefined) { index = this.anchors.length; // append by default } var self = this, o = this.options, $li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)), id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]); $li.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true); // try to find an existing element before creating a new one var $panel = $('#' + id); if (!$panel.length) { $panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true); } $panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide'); if (index >= this.lis.length) { $li.appendTo(this.list); $panel.appendTo(this.list[0].parentNode); } else { $li.insertBefore(this.lis[index]); $panel.insertBefore(this.panels[index]); } o.disabled = $.map(o.disabled, function(n, i) { return n >= index ? ++n : n; }); this._tabify(); if (this.anchors.length == 1) { // after tabify $li.addClass('ui-tabs-selected ui-state-active'); $panel.removeClass('ui-tabs-hide'); this.element.queue("tabs", function() { self._trigger('show', null, self._ui(self.anchors[0], self.panels[0])); }); this.load(0); } // callback this._trigger('add', null, this._ui(this.anchors[index], this.panels[index])); }, remove: function(index) { var o = this.options, $li = this.lis.eq(index).remove(), $panel = this.panels.eq(index).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) { this.select(index + (index + 1 < this.anchors.length ? 1 : -1)); } o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }), function(n, i) { return n >= index ? --n : n; }); this._tabify(); // callback this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0])); }, enable: function(index) { var o = this.options; if ($.inArray(index, o.disabled) == -1) { return; } this.lis.eq(index).removeClass('ui-state-disabled'); o.disabled = $.grep(o.disabled, function(n, i) { return n != index; }); // callback this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index])); }, disable: function(index) { var self = this, o = this.options; if (index != o.selected) { // cannot disable already selected tab this.lis.eq(index).addClass('ui-state-disabled'); o.disabled.push(index); o.disabled.sort(); // callback this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index])); } }, select: function(index) { if (typeof index == 'string') { index = this.anchors.index(this.anchors.filter('[href$=' + index + ']')); } else if (index === null) { // usage of null is deprecated, TODO remove in next release index = -1; } if (index == -1 && this.options.collapsible) { index = this.options.selected; } this.anchors.eq(index).trigger(this.options.event + '.tabs'); }, load: function(index) { var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs'); this.abort(); // not remote or from cache if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) { this.element.dequeue("tabs"); return; } // load remote from here on this.lis.eq(index).addClass('ui-state-processing'); if (o.spinner) { var span = $('span', a); span.data('label.tabs', span.html()).html(o.spinner); } this.xhr = $.ajax($.extend({}, o.ajaxOptions, { url: url, success: function(r, s) { $(self._sanitizeSelector(a.hash)).html(r); // take care of tab labels self._cleanup(); if (o.cache) { $.data(a, 'cache.tabs', true); // if loaded once do not load them again } // callbacks self._trigger('load', null, self._ui(self.anchors[index], self.panels[index])); try { o.ajaxOptions.success(r, s); } catch (e) {} // last, so that load event is fired before show... self.element.dequeue("tabs"); } })); }, abort: function() { // stop possibly running animations this.element.queue([]); this.panels.stop(false, true); // terminate pending requests from other tabs if (this.xhr) { this.xhr.abort(); delete this.xhr; } // take care of tab labels this._cleanup(); }, url: function(index, url) { this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url); }, length: function() { return this.anchors.length; } }); $.extend($.ui.tabs, { version: '1.7.2', getter: 'length', defaults: { ajaxOptions: null, cache: false, cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } collapsible: false, disabled: [], event: 'click', fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 } idPrefix: 'ui-tabs-', panelTemplate: '<div></div>', spinner: '<em>Loading&#8230;</em>', tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>' } }); /* * Tabs Extensions */ /* * Rotate */ $.extend($.ui.tabs.prototype, { rotation: null, rotate: function(ms, continuing) { var self = this, o = this.options; var rotate = self._rotate || (self._rotate = function(e) { clearTimeout(self.rotation); self.rotation = setTimeout(function() { var t = o.selected; self.select( ++t < self.anchors.length ? t : 0 ); }, ms); if (e) { e.stopPropagation(); } }); var stop = self._unrotate || (self._unrotate = !continuing ? function(e) { if (e.clientX) { // in case of a true click self.rotate(null); } } : function(e) { t = o.selected; rotate(); }); // start rotation if (ms) { this.element.bind('tabsshow', rotate); this.anchors.bind(o.event + '.tabs', stop); rotate(); } // stop rotation else { clearTimeout(self.rotation); this.element.unbind('tabsshow', rotate); this.anchors.unbind(o.event + '.tabs', stop); delete this._rotate; delete this._unrotate; } } }); })(jQuery);
JavaScript
/* * jQuery UI Effects Bounce 1.7.2 * * 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/Effects/Bounce * * Depends: * effects.core.js */ (function($) { $.effects.bounce = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode var direction = o.options.direction || 'up'; // Default direction var distance = o.options.distance || 20; // Default distance var times = o.options.times || 5; // Default # of times var speed = o.duration || 250; // Default speed per bounce if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE // Adjust $.effects.save(el, props); el.show(); // Save & Show $.effects.createWrapper(el); // Create Wrapper var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3); if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift if (mode == 'hide') distance = distance / (times * 2); if (mode != 'hide') times--; // Animate if (mode == 'show') { // Show Bounce var animation = {opacity: 1}; animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance; el.animate(animation, speed / 2, o.options.easing); distance = distance / 2; times--; }; for (var i = 0; i < times; i++) { // Bounces var animation1 = {}, animation2 = {}; animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance; animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance; el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing); distance = (mode == 'hide') ? distance * 2 : distance / 2; }; if (mode == 'hide') { // Last Bounce var animation = {opacity: 0}; animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance; el.animate(animation, speed / 2, o.options.easing, function(){ el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback }); } else { var animation1 = {}, animation2 = {}; animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance; animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance; el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){ $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback }); }; el.queue('fx', function() { el.dequeue(); }); el.dequeue(); }); }; })(jQuery);
JavaScript
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title and description changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color. wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' == to ) { if ( 'remove-header' == _wpCustomizeSettings.values.header_image ) $( '.home-link' ).css( 'min-height', '0' ); $( '.site-title, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.home-link' ).css( 'min-height', '230px' ); $( '.site-title, .site-description' ).css( { 'clip': 'auto', 'color': to, 'position': 'relative' } ); } } ); } ); } )( jQuery );
JavaScript
/** * Functionality specific to Twenty Thirteen. * * Provides helper functions to enhance the theme experience. */ ( function( $ ) { var body = $( 'body' ), _window = $( window ); /** * Adds a top margin to the footer if the sidebar widget area is higher * than the rest of the page, to help the footer always visually clear * the sidebar. */ $( function() { if ( body.is( '.sidebar' ) ) { var sidebar = $( '#secondary .widget-area' ), secondary = ( 0 === sidebar.length ) ? -40 : sidebar.height(), margin = $( '#tertiary .widget-area' ).height() - $( '#content' ).height() - secondary; if ( margin > 0 && _window.innerWidth() > 999 ) { $( '#colophon' ).css( 'margin-top', margin + 'px' ); } } } ); /** * Enables menu toggle for small screens. */ ( function() { var nav = $( '#site-navigation' ), button, menu; if ( ! nav ) { return; } button = nav.find( '.menu-toggle' ); if ( ! button ) { return; } // Hide button if menu is missing or empty. menu = nav.find( '.nav-menu' ); if ( ! menu || ! menu.children().length ) { button.hide(); return; } button.on( 'click.twentythirteen', function() { nav.toggleClass( 'toggled-on' ); } ); // Better focus for hidden submenu items for accessibility. menu.find( 'a' ).on( 'focus.twentythirteen blur.twentythirteen', function() { $( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' ); } ); } )(); /** * Makes "skip to content" link work correctly in IE9 and Chrome for better * accessibility. * * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/ */ _window.on( 'hashchange.twentythirteen', function() { var element = document.getElementById( location.hash.substring( 1 ) ); if ( element ) { if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) { element.tabIndex = -1; } element.focus(); } } ); /** * Arranges footer widgets vertically. */ if ( $.isFunction( $.fn.masonry ) ) { var columnWidth = body.is( '.sidebar' ) ? 228 : 245; $( '#secondary .widget-area' ).masonry( { itemSelector: '.widget', columnWidth: columnWidth, gutterWidth: 20, isRTL: body.is( '.rtl' ) } ); } } )( jQuery );
JavaScript
/** * Twenty Fourteen keyboard support for image navigation. */ ( function( $ ) { $( document ).on( 'keydown.twentyfourteen', function( e ) { var url = false; // Left arrow key code. if ( e.which === 37 ) { url = $( '.previous-image a' ).attr( 'href' ); // Right arrow key code. } else if ( e.which === 39 ) { url = $( '.entry-attachment a' ).attr( 'href' ); } if ( url && ( !$( 'textarea, input' ).is( ':focus' ) ) ) { window.location = url; } } ); } )( jQuery );
JavaScript
/** * Twenty Fourteen Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color. wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' === to ) { $( '.site-title, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.site-title, .site-description' ).css( { 'clip': 'auto', 'position': 'static' } ); $( '.site-title a' ).css( { 'color': to } ); } } ); } ); } )( jQuery );
JavaScript
/** * Theme functions file * * Contains handlers for navigation, accessibility, header sizing * footer widgets and Featured Content slider * */ ( function( $ ) { var body = $( 'body' ), _window = $( window ); // Enable menu toggle for small screens. ( function() { var nav = $( '#primary-navigation' ), button, menu; if ( ! nav ) { return; } button = nav.find( '.menu-toggle' ); if ( ! button ) { return; } // Hide button if menu is missing or empty. menu = nav.find( '.nav-menu' ); if ( ! menu || ! menu.children().length ) { button.hide(); return; } $( '.menu-toggle' ).on( 'click.twentyfourteen', function() { nav.toggleClass( 'toggled-on' ); } ); } )(); /* * Makes "skip to content" link work correctly in IE9 and Chrome for better * accessibility. * * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/ */ _window.on( 'hashchange.twentyfourteen', function() { var element = document.getElementById( location.hash.substring( 1 ) ); if ( element ) { if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) { element.tabIndex = -1; } element.focus(); // Repositions the window on jump-to-anchor to account for header height. window.scrollBy( 0, -80 ); } } ); $( function() { // Search toggle. $( '.search-toggle' ).on( 'click.twentyfourteen', function( event ) { var that = $( this ), wrapper = $( '.search-box-wrapper' ); that.toggleClass( 'active' ); wrapper.toggleClass( 'hide' ); if ( that.is( '.active' ) || $( '.search-toggle .screen-reader-text' )[0] === event.target ) { wrapper.find( '.search-field' ).focus(); } } ); /* * Fixed header for large screen. * If the header becomes more than 48px tall, unfix the header. * * The callback on the scroll event is only added if there is a header * image and we are not on mobile. */ if ( _window.width() > 781 ) { var mastheadHeight = $( '#masthead' ).height(), toolbarOffset, mastheadOffset; if ( mastheadHeight > 48 ) { body.removeClass( 'masthead-fixed' ); } if ( body.is( '.header-image' ) ) { toolbarOffset = body.is( '.admin-bar' ) ? $( '#wpadminbar' ).height() : 0; mastheadOffset = $( '#masthead' ).offset().top - toolbarOffset; _window.on( 'scroll.twentyfourteen', function() { if ( ( window.scrollY > mastheadOffset ) && ( mastheadHeight < 49 ) ) { body.addClass( 'masthead-fixed' ); } else { body.removeClass( 'masthead-fixed' ); } } ); } } // Focus styles for menus. $( '.primary-navigation, .secondary-navigation' ).find( 'a' ).on( 'focus.twentyfourteen blur.twentyfourteen', function() { $( this ).parents().toggleClass( 'focus' ); } ); } ); _window.load( function() { // Arrange footer widgets vertically. if ( $.isFunction( $.fn.masonry ) ) { $( '#footer-sidebar' ).masonry( { itemSelector: '.widget', columnWidth: function( containerWidth ) { return containerWidth / 4; }, gutterWidth: 0, isResizable: true, isRTL: $( 'body' ).is( '.rtl' ) } ); } // Initialize Featured Content slider. if ( body.is( '.slider' ) ) { $( '.featured-content' ).featuredslider( { selector: '.featured-content-inner > article', controlsContainer: '.featured-content' } ); } } ); } )( jQuery );
JavaScript
/* * Twenty Fourteen Featured Content Slider * * Adapted from FlexSlider v2.2.0, copyright 2012 WooThemes * @link http://www.woothemes.com/flexslider/ */ /* global DocumentTouch:true,setImmediate:true,featuredSliderDefaults:true,MSGesture:true */ ( function( $ ) { // FeaturedSlider: object instance. $.featuredslider = function( el, options ) { var slider = $( el ), msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, touch = ( ( 'ontouchstart' in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch ), // MSFT specific. eventType = 'click touchend MSPointerUp', watchedEvent = '', watchedEventClearTimer, methods = {}, namespace; // Make variables public. slider.vars = $.extend( {}, $.featuredslider.defaults, options ); namespace = slider.vars.namespace, // Store a reference to the slider object. $.data( el, 'featuredslider', slider ); // Private slider methods. methods = { init: function() { slider.animating = false; slider.currentSlide = 0; slider.animatingTo = slider.currentSlide; slider.atEnd = ( slider.currentSlide === 0 || slider.currentSlide === slider.last ); slider.containerSelector = slider.vars.selector.substr( 0, slider.vars.selector.search( ' ' ) ); slider.slides = $( slider.vars.selector, slider ); slider.container = $( slider.containerSelector, slider ); slider.count = slider.slides.length; slider.prop = 'marginLeft'; slider.isRtl = $( 'body' ).hasClass( 'rtl' ); slider.args = {}; // TOUCH slider.transitions = ( function() { var obj = document.createElement( 'div' ), props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'], i; for ( i in props ) { if ( obj.style[ props[i] ] !== undefined ) { slider.pfx = props[i].replace( 'Perspective', '' ).toLowerCase(); slider.prop = '-' + slider.pfx + '-transform'; return true; } } return false; }() ); // CONTROLSCONTAINER if ( slider.vars.controlsContainer !== '' ) { slider.controlsContainer = $( slider.vars.controlsContainer ).length > 0 && $( slider.vars.controlsContainer ); } slider.doMath(); // INIT slider.setup( 'init' ); // CONTROLNAV methods.controlNav.setup(); // DIRECTIONNAV methods.directionNav.setup(); // KEYBOARD if ( $( slider.containerSelector ).length === 1 ) { $( document ).bind( 'keyup', function( event ) { var keycode = event.keyCode, target = false; if ( ! slider.animating && ( keycode === 39 || keycode === 37 ) ) { if ( keycode === 39 ) { target = slider.getTarget( 'next' ); } else if ( keycode === 37 ) { target = slider.getTarget( 'prev' ); } slider.featureAnimate( target ); } } ); } // TOUCH if ( touch ) { methods.touch(); } $( window ).bind( 'resize orientationchange focus', methods.resize ); slider.find( 'img' ).attr( 'draggable', 'false' ); }, controlNav: { setup: function() { methods.controlNav.setupPaging(); }, setupPaging: function() { var type = 'control-paging', j = 1, item, slide, i; slider.controlNavScaffold = $( '<ol class="' + namespace + 'control-nav ' + namespace + type + '"></ol>' ); if ( slider.pagingCount > 1 ) { for ( i = 0; i < slider.pagingCount; i++ ) { slide = slider.slides.eq( i ); item = '<a>' + j + '</a>'; slider.controlNavScaffold.append( '<li>' + item + '</li>' ); j++; } } // CONTROLSCONTAINER ( slider.controlsContainer ) ? $( slider.controlsContainer ).append( slider.controlNavScaffold ) : slider.append( slider.controlNavScaffold ); methods.controlNav.set(); methods.controlNav.active(); slider.controlNavScaffold.delegate( 'a, img', eventType, function( event ) { event.preventDefault(); if ( watchedEvent === '' || watchedEvent === event.type ) { var $this = $( this ), target = slider.controlNav.index( $this ); if ( ! $this.hasClass( namespace + 'active' ) ) { slider.direction = ( target > slider.currentSlide ) ? 'next' : 'prev'; slider.featureAnimate( target ); } } // Set up flags to prevent event duplication. if ( watchedEvent === '' ) { watchedEvent = event.type; } methods.setToClearWatchedEvent(); } ); }, set: function() { var selector = 'a'; slider.controlNav = $( '.' + namespace + 'control-nav li ' + selector, ( slider.controlsContainer ) ? slider.controlsContainer : slider ); }, active: function() { slider.controlNav.removeClass( namespace + 'active' ).eq( slider.animatingTo ).addClass( namespace + 'active' ); }, update: function( action, pos ) { if ( slider.pagingCount > 1 && action === 'add' ) { slider.controlNavScaffold.append( $( '<li><a>' + slider.count + '</a></li>' ) ); } else if ( slider.pagingCount === 1 ) { slider.controlNavScaffold.find( 'li' ).remove(); } else { slider.controlNav.eq( pos ).closest( 'li' ).remove(); } methods.controlNav.set(); ( slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length ) ? slider.update( pos, action ) : methods.controlNav.active(); } }, directionNav: { setup: function() { var directionNavScaffold = $( '<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + slider.vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + slider.vars.nextText + '</a></li></ul>' ); // CONTROLSCONTAINER if ( slider.controlsContainer ) { $( slider.controlsContainer ).append( directionNavScaffold ); slider.directionNav = $( '.' + namespace + 'direction-nav li a', slider.controlsContainer ); } else { slider.append( directionNavScaffold ); slider.directionNav = $( '.' + namespace + 'direction-nav li a', slider ); } methods.directionNav.update(); slider.directionNav.bind( eventType, function( event ) { event.preventDefault(); var target; if ( watchedEvent === '' || watchedEvent === event.type ) { target = ( $( this ).hasClass( namespace + 'next' ) ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' ); slider.featureAnimate( target ); } // Set up flags to prevent event duplication. if ( watchedEvent === '' ) { watchedEvent = event.type; } methods.setToClearWatchedEvent(); } ); }, update: function() { var disabledClass = namespace + 'disabled'; if ( slider.pagingCount === 1 ) { slider.directionNav.addClass( disabledClass ).attr( 'tabindex', '-1' ); } else { slider.directionNav.removeClass( disabledClass ).removeAttr( 'tabindex' ); } } }, touch: function() { var startX, startY, offset, cwidth, dx, startT, scrolling = false, localX = 0, localY = 0, accDx = 0; if ( ! msGesture ) { el.addEventListener( 'touchstart', onTouchStart, false ); } else { el.style.msTouchAction = 'none'; el._gesture = new MSGesture(); // MSFT specific. el._gesture.target = el; el.addEventListener( 'MSPointerDown', onMSPointerDown, false ); el._slider = slider; el.addEventListener( 'MSGestureChange', onMSGestureChange, false ); el.addEventListener( 'MSGestureEnd', onMSGestureEnd, false ); } function onTouchStart( e ) { if ( slider.animating ) { e.preventDefault(); } else if ( ( window.navigator.msPointerEnabled ) || e.touches.length === 1 ) { cwidth = slider.w; startT = Number( new Date() ); // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; offset = ( slider.currentSlide + slider.cloneOffset ) * cwidth; if ( slider.animatingTo === slider.last && slider.direction !== 'next' ) { offset = 0; } startX = localX; startY = localY; el.addEventListener( 'touchmove', onTouchMove, false ); el.addEventListener( 'touchend', onTouchEnd, false ); } } function onTouchMove( e ) { // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; dx = startX - localX; scrolling = Math.abs( dx ) < Math.abs( localY - startY ); if ( ! scrolling ) { e.preventDefault(); if ( slider.transitions ) { slider.setProps( offset + dx, 'setTouch' ); } } } function onTouchEnd() { // Finish the touch by undoing the touch session. el.removeEventListener( 'touchmove', onTouchMove, false ); if ( slider.animatingTo === slider.currentSlide && ! scrolling && dx !== null ) { var updateDx = dx, target = ( updateDx > 0 ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' ); slider.featureAnimate( target ); } el.removeEventListener( 'touchend', onTouchEnd, false ); startX = null; startY = null; dx = null; offset = null; } function onMSPointerDown( e ) { e.stopPropagation(); if ( slider.animating ) { e.preventDefault(); } else { el._gesture.addPointer( e.pointerId ); accDx = 0; cwidth = slider.w; startT = Number( new Date() ); offset = ( slider.currentSlide + slider.cloneOffset ) * cwidth; if ( slider.animatingTo === slider.last && slider.direction !== 'next' ) { offset = 0; } } } function onMSGestureChange( e ) { e.stopPropagation(); var slider = e.target._slider, transX, transY; if ( ! slider ) { return; } transX = -e.translationX, transY = -e.translationY; // Accumulate translations. accDx = accDx + transX; dx = accDx; scrolling = Math.abs( accDx ) < Math.abs( -transY ); if ( e.detail === e.MSGESTURE_FLAG_INERTIA ) { setImmediate( function () { // MSFT specific. el._gesture.stop(); } ); return; } if ( ! scrolling || Number( new Date() ) - startT > 500 ) { e.preventDefault(); if ( slider.transitions ) { slider.setProps( offset + dx, 'setTouch' ); } } } function onMSGestureEnd( e ) { e.stopPropagation(); var slider = e.target._slider, updateDx, target; if ( ! slider ) { return; } if ( slider.animatingTo === slider.currentSlide && ! scrolling && dx !== null ) { updateDx = dx, target = ( updateDx > 0 ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' ); slider.featureAnimate( target ); } startX = null; startY = null; dx = null; offset = null; accDx = 0; } }, resize: function() { if ( ! slider.animating && slider.is( ':visible' ) ) { slider.doMath(); // SMOOTH HEIGHT methods.smoothHeight(); slider.newSlides.width( slider.computedW ); slider.setProps( slider.computedW, 'setTotal' ); } }, smoothHeight: function( dur ) { var $obj = slider.viewport; ( dur ) ? $obj.animate( { 'height': slider.slides.eq( slider.animatingTo ).height() }, dur ) : $obj.height( slider.slides.eq( slider.animatingTo ).height() ); }, setToClearWatchedEvent: function() { clearTimeout( watchedEventClearTimer ); watchedEventClearTimer = setTimeout( function() { watchedEvent = ''; }, 3000 ); } }; // Public methods. slider.featureAnimate = function( target ) { if ( target !== slider.currentSlide ) { slider.direction = ( target > slider.currentSlide ) ? 'next' : 'prev'; } if ( ! slider.animating && slider.is( ':visible' ) ) { slider.animating = true; slider.animatingTo = target; // CONTROLNAV methods.controlNav.active(); slider.slides.removeClass( namespace + 'active-slide' ).eq( target ).addClass( namespace + 'active-slide' ); slider.atEnd = target === 0 || target === slider.last; // DIRECTIONNAV methods.directionNav.update(); var dimension = slider.computedW, slideString; if ( slider.currentSlide === 0 && target === slider.count - 1 && slider.direction !== 'next' ) { slideString = 0; } else if ( slider.currentSlide === slider.last && target === 0 && slider.direction !== 'prev' ) { slideString = ( slider.count + 1 ) * dimension; } else { slideString = ( target + slider.cloneOffset ) * dimension; } slider.setProps( slideString, '', slider.vars.animationSpeed ); if ( slider.transitions ) { if ( ! slider.atEnd ) { slider.animating = false; slider.currentSlide = slider.animatingTo; } slider.container.unbind( 'webkitTransitionEnd transitionend' ); slider.container.bind( 'webkitTransitionEnd transitionend', function() { slider.wrapup( dimension ); } ); } else { slider.container.animate( slider.args, slider.vars.animationSpeed, 'swing', function() { slider.wrapup( dimension ); } ); } // SMOOTH HEIGHT methods.smoothHeight( slider.vars.animationSpeed ); } }; slider.wrapup = function( dimension ) { if ( slider.currentSlide === 0 && slider.animatingTo === slider.last ) { slider.setProps( dimension, 'jumpEnd' ); } else if ( slider.currentSlide === slider.last && slider.animatingTo === 0 ) { slider.setProps( dimension, 'jumpStart' ); } slider.animating = false; slider.currentSlide = slider.animatingTo; }; slider.getTarget = function( dir ) { slider.direction = dir; // Swap for RTL. if ( slider.isRtl ) { dir = 'next' === dir ? 'prev' : 'next'; } if ( dir === 'next' ) { return ( slider.currentSlide === slider.last ) ? 0 : slider.currentSlide + 1; } else { return ( slider.currentSlide === 0 ) ? slider.last : slider.currentSlide - 1; } }; slider.setProps = function( pos, special, dur ) { var target = ( function() { var posCalc = ( function() { switch ( special ) { case 'setTotal': return ( slider.currentSlide + slider.cloneOffset ) * pos; case 'setTouch': return pos; case 'jumpEnd': return slider.count * pos; case 'jumpStart': return pos; default: return pos; } }() ); return ( posCalc * -1 ) + 'px'; }() ); if ( slider.transitions ) { target = 'translate3d(' + target + ',0,0 )'; dur = ( dur !== undefined ) ? ( dur / 1000 ) + 's' : '0s'; slider.container.css( '-' + slider.pfx + '-transition-duration', dur ); } slider.args[slider.prop] = target; if ( slider.transitions || dur === undefined ) { slider.container.css( slider.args ); } }; slider.setup = function( type ) { var sliderOffset; if ( type === 'init' ) { slider.viewport = $( '<div class="' + namespace + 'viewport"></div>' ).css( { 'overflow': 'hidden', 'position': 'relative' } ).appendTo( slider ).append( slider.container ); slider.cloneCount = 0; slider.cloneOffset = 0; } slider.cloneCount = 2; slider.cloneOffset = 1; // Clear out old clones. if ( type !== 'init' ) { slider.container.find( '.clone' ).remove(); } slider.container.append( slider.slides.first().clone().addClass( 'clone' ).attr( 'aria-hidden', 'true' ) ).prepend( slider.slides.last().clone().addClass( 'clone' ).attr( 'aria-hidden', 'true' ) ); slider.newSlides = $( slider.vars.selector, slider ); sliderOffset = slider.currentSlide + slider.cloneOffset; slider.container.width( ( slider.count + slider.cloneCount ) * 200 + '%' ); slider.setProps( sliderOffset * slider.computedW, 'init' ); setTimeout( function() { slider.doMath(); slider.newSlides.css( { 'width': slider.computedW, 'float': 'left', 'display': 'block' } ); // SMOOTH HEIGHT methods.smoothHeight(); }, ( type === 'init' ) ? 100 : 0 ); slider.slides.removeClass( namespace + 'active-slide' ).eq( slider.currentSlide ).addClass( namespace + 'active-slide' ); }; slider.doMath = function() { var slide = slider.slides.first(); slider.w = ( slider.viewport===undefined ) ? slider.width() : slider.viewport.width(); slider.h = slide.height(); slider.boxPadding = slide.outerWidth() - slide.width(); slider.itemW = slider.w; slider.pagingCount = slider.count; slider.last = slider.count - 1; slider.computedW = slider.itemW - slider.boxPadding; }; slider.update = function( pos, action ) { slider.doMath(); // Update currentSlide and slider.animatingTo if necessary. if ( pos < slider.currentSlide ) { slider.currentSlide += 1; } else if ( pos <= slider.currentSlide && pos !== 0 ) { slider.currentSlide -= 1; } slider.animatingTo = slider.currentSlide; // Update controlNav. if ( action === 'add' || slider.pagingCount > slider.controlNav.length ) { methods.controlNav.update( 'add' ); } else if ( action === 'remove' || slider.pagingCount < slider.controlNav.length ) { if ( slider.currentSlide > slider.last ) { slider.currentSlide -= 1; slider.animatingTo -= 1; } methods.controlNav.update( 'remove', slider.last ); } // Update directionNav. methods.directionNav.update(); }; // FeaturedSlider: initialize. methods.init(); }; // Default settings. $.featuredslider.defaults = { namespace: 'slider-', // String: prefix string attached to the class of every element generated by the plugin. selector: '.slides > li', // String: selector, must match a simple pattern. animationSpeed: 600, // Integer: Set the speed of animations, in milliseconds. controlsContainer: '', // jQuery Object/Selector: container navigation to append elements. // Text labels. prevText: featuredSliderDefaults.prevText, // String: Set the text for the "previous" directionNav item. nextText: featuredSliderDefaults.nextText // String: Set the text for the "next" directionNav item. }; // FeaturedSlider: plugin function. $.fn.featuredslider = function( options ) { if ( options === undefined ) { options = {}; } if ( typeof options === 'object' ) { return this.each( function() { var $this = $( this ), selector = ( options.selector ) ? options.selector : '.slides > li', $slides = $this.find( selector ); if ( $slides.length === 1 || $slides.length === 0 ) { $slides.fadeIn( 400 ); } else if ( $this.data( 'featuredslider' ) === undefined ) { new $.featuredslider( this, options ); } } ); } }; } )( jQuery );
JavaScript
/** * Twenty Fourteen Featured Content admin behavior: add a tag suggestion * when changing the tag. */ /* global ajaxurl:true */ jQuery( document ).ready( function( $ ) { $( '#customize-control-featured-content-tag-name input' ).suggest( ajaxurl + '?action=ajax-tag-search&tax=post_tag', { delay: 500, minchars: 2 } ); });
JavaScript
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title, description, and background color changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' === to ) { $( '.site-title, .site-title a, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.site-title, .site-title a, .site-description' ).css( { 'clip': 'auto', 'color': to, 'position': 'relative' } ); } } ); } ); // Hook into background color/image change and adjust body class value as needed. wp.customize( 'background_color', function( value ) { value.bind( function( to ) { var body = $( 'body' ); if ( ( '#ffffff' == to || '#fff' == to ) && 'none' == body.css( 'background-image' ) ) body.addClass( 'custom-background-white' ); else if ( '' == to && 'none' == body.css( 'background-image' ) ) body.addClass( 'custom-background-empty' ); else body.removeClass( 'custom-background-empty custom-background-white' ); } ); } ); wp.customize( 'background_image', function( value ) { value.bind( function( to ) { var body = $( 'body' ); if ( '' != to ) body.removeClass( 'custom-background-empty custom-background-white' ); else if ( 'rgb(255, 255, 255)' == body.css( 'background-color' ) ) body.addClass( 'custom-background-white' ); else if ( 'rgb(230, 230, 230)' == body.css( 'background-color' ) && '' == _wpCustomizeSettings.values.background_color ) body.addClass( 'custom-background-empty' ); } ); } ); } )( jQuery );
JavaScript
/** * Handles toggling the navigation menu for small screens and * accessibility for submenu items. */ ( function() { var nav = document.getElementById( 'site-navigation' ), button, menu; if ( ! nav ) { return; } button = nav.getElementsByTagName( 'h3' )[0]; menu = nav.getElementsByTagName( 'ul' )[0]; if ( ! button ) { return; } // Hide button if menu is missing or empty. if ( ! menu || ! menu.childNodes.length ) { button.style.display = 'none'; return; } button.onclick = function() { if ( -1 === menu.className.indexOf( 'nav-menu' ) ) { menu.className = 'nav-menu'; } if ( -1 !== button.className.indexOf( 'toggled-on' ) ) { button.className = button.className.replace( ' toggled-on', '' ); menu.className = menu.className.replace( ' toggled-on', '' ); } else { button.className += ' toggled-on'; menu.className += ' toggled-on'; } }; } )(); // Better focus for hidden submenu items for accessibility. ( function( $ ) { $( '.main-navigation' ).find( 'a' ).on( 'focus.twentytwelve blur.twentytwelve', function() { $( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' ); } ); } )( jQuery );
JavaScript
jQuery( function ( $ ) { var ak_js = $( '#ak_js' ); // If the form field already exists just use that if ( ak_js.length == 0 ) { ak_js = $( '<input type="hidden" id="ak_js" name="ak_js" />' ); } else { ak_js.remove(); } ak_js.val( ( new Date() ).getTime() ); // single page, front-end comment form // inline comment reply, wp-admin $( '#commentform, #replyrow td:first' ).append( ak_js ); } );
JavaScript
jQuery( function ( $ ) { $( 'a.activate-option' ).click( function(){ var link = $( this ); if ( link.hasClass( 'clicked' ) ) { link.removeClass( 'clicked' ); } else { link.addClass( 'clicked' ); } $( '.toggle-have-key' ).slideToggle( 'slow', function() {}); return false; }); $('.akismet-status').each(function () { var thisId = $(this).attr('commentid'); $(this).prependTo('#comment-' + thisId + ' .column-comment'); }); $('.akismet-user-comment-count').each(function () { var thisId = $(this).attr('commentid'); $(this).insertAfter('#comment-' + thisId + ' .author strong:first').show(); }); $('#the-comment-list').find('tr.comment, tr[id ^= "comment-"]').find('.column-author a[title ^= "http://"]').each(function () { var thisTitle = $(this).attr('title'); thisCommentId = $(this).parents('tr:first').attr('id').split("-"); $(this).attr("id", "author_comment_url_"+ thisCommentId[1]); if (thisTitle) { $(this).after( $( '<a href="#" class="remove_url">x</a>' ) .attr( 'commentid', thisCommentId[1] ) .attr( 'title', WPAkismet.strings['Remove this URL'] ) ); } }); $('.remove_url').live('click', function () { var thisId = $(this).attr('commentid'); var data = { action: 'comment_author_deurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId }; $.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Removes "x" link $("a[commentid='"+ thisId +"']").hide(); // Show temp status $("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Removing...'] ) ); }, success: function (response) { if (response) { // Show status/undo link $("#author_comment_url_"+ thisId) .attr('cid', thisId) .addClass('akismet_undo_link_removal') .html( $( '<span/>' ).text( WPAkismet.strings['URL removed'] ) ) .append( ' ' ) .append( $( '<span/>' ) .text( WPAkismet.strings['(undo)'] ) .addClass( 'akismet-span-link' ) ); } } }); return false; }); $('.akismet_undo_link_removal').live('click', function () { var thisId = $(this).attr('cid'); var thisUrl = $(this).attr('href').replace("http://www.", "").replace("http://", ""); var data = { action: 'comment_author_reurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId, url: thisUrl }; $.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Show temp status $("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Re-adding...'] ) ); }, success: function (response) { if (response) { // Add "x" link $("a[commentid='"+ thisId +"']").show(); // Show link $("#author_comment_url_"+ thisId).removeClass('akismet_undo_link_removal').html(thisUrl); } } }); return false; }); $('a[id^="author_comment_url"], tr.pingback td.column-author a:first-of-type').mouseover(function () { var wpcomProtocol = ( 'https:' === location.protocol ) ? 'https://' : 'http://'; // Need to determine size of author column var thisParentWidth = $(this).parent().width(); // It changes based on if there is a gravatar present thisParentWidth = ($(this).parent().find('.grav-hijack').length) ? thisParentWidth - 42 + 'px' : thisParentWidth + 'px'; if ($(this).find('.mShot').length == 0 && !$(this).hasClass('akismet_undo_link_removal')) { var self = $( this ); $('.widefat td').css('overflow', 'visible'); $(this).css('position', 'relative'); var thisHref = $.URLEncode( $(this).attr('href') ); $(this).append('<div class="mShot mshot-container" style="left: '+thisParentWidth+'"><div class="mshot-arrow"></div><img src="//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450" width="450" class="mshot-image" style="margin: 0;" /></div>'); setTimeout(function () { self.find( '.mshot-image' ).attr('src', '//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=2'); }, 6000); setTimeout(function () { self.find( '.mshot-image' ).attr('src', '//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=3'); }, 12000); } else { $(this).find('.mShot').css('left', thisParentWidth).show(); } }).mouseout(function () { $(this).find('.mShot').hide(); }); $('.checkforspam:not(.button-disabled)').click( function(e) { $('.checkforspam:not(.button-disabled)').addClass('button-disabled'); $('.checkforspam-spinner').show(); akismet_check_for_spam(0, 100); e.preventDefault(); }); function akismet_check_for_spam(offset, limit) { $.post( ajaxurl, { 'action': 'akismet_recheck_queue', 'offset': offset, 'limit': limit }, function(result) { if (result.processed < limit) { window.location.reload(); } else { akismet_check_for_spam(offset + limit, limit); } } ); } }); // URL encode plugin jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;} });
JavaScript
/* global _wpCustomizeWidgetsSettings */ (function( wp, $ ){ if ( ! wp || ! wp.customize ) { return; } // Set up our namespace... var api = wp.customize, l10n, OldPreviewer; api.Widgets = api.Widgets || {}; // Link settings api.Widgets.data = _wpCustomizeWidgetsSettings || {}; l10n = api.Widgets.data.l10n; delete api.Widgets.data.l10n; /** * wp.customize.Widgets.WidgetModel * * A single widget model. * * @constructor * @augments Backbone.Model */ api.Widgets.WidgetModel = Backbone.Model.extend({ id: null, temp_id: null, classname: null, control_tpl: null, description: null, is_disabled: null, is_multi: null, multi_number: null, name: null, id_base: null, transport: 'refresh', params: [], width: null, height: null, search_matched: true }); /** * wp.customize.Widgets.WidgetCollection * * Collection for widget models. * * @constructor * @augments Backbone.Model */ api.Widgets.WidgetCollection = Backbone.Collection.extend({ model: api.Widgets.WidgetModel, // Controls searching on the current widget collection // and triggers an update event doSearch: function( value ) { // Don't do anything if we've already done this search // Useful because the search handler fires multiple times per keystroke if ( this.terms === value ) { return; } // Updates terms with the value passed this.terms = value; // If we have terms, run a search... if ( this.terms.length > 0 ) { this.search( this.terms ); } // If search is blank, show all themes // Useful for resetting the views when you clean the input if ( this.terms === '' ) { this.each( function ( widget ) { widget.set( 'search_matched', true ); } ); } }, // Performs a search within the collection // @uses RegExp search: function( term ) { var match, haystack; // Escape the term string for RegExp meta characters term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' ); // Consider spaces as word delimiters and match the whole string // so matching terms can be combined term = term.replace( / /g, ')(?=.*' ); match = new RegExp( '^(?=.*' + term + ').+', 'i' ); this.each( function ( data ) { haystack = [ data.get( 'name' ), data.get( 'id' ), data.get( 'description' ) ].join( ' ' ); data.set( 'search_matched', match.test( haystack ) ); } ); } }); api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets ); /** * wp.customize.Widgets.SidebarModel * * A single sidebar model. * * @constructor * @augments Backbone.Model */ api.Widgets.SidebarModel = Backbone.Model.extend({ after_title: null, after_widget: null, before_title: null, before_widget: null, 'class': null, description: null, id: null, name: null, is_rendered: false }); /** * wp.customize.Widgets.SidebarCollection * * Collection for sidebar models. * * @constructor * @augments Backbone.Collection */ api.Widgets.SidebarCollection = Backbone.Collection.extend({ model: api.Widgets.SidebarModel }); api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars ); /** * wp.customize.Widgets.AvailableWidgetsPanelView * * View class for the available widgets panel. * * @constructor * @augments wp.Backbone.View * @augments Backbone.View */ api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend({ el: '#available-widgets', events: { 'input #widgets-search': 'search', 'keyup #widgets-search': 'search', 'change #widgets-search': 'search', 'search #widgets-search': 'search', 'focus .widget-tpl' : 'focus', 'click .widget-tpl' : '_submit', 'keypress .widget-tpl' : '_submit', 'keydown' : 'keyboardAccessible' }, // Cache current selected widget selected: null, // Cache sidebar control which has opened panel currentSidebarControl: null, $search: null, initialize: function() { var self = this; this.$search = $( '#widgets-search' ); _.bindAll( this, 'close' ); this.listenTo( this.collection, 'change', this.updateList ); this.updateList(); // If the available widgets panel is open and the customize controls are // interacted with (i.e. available widgets panel is blurred) then close the // available widgets panel. $( '#customize-controls' ).on( 'click keydown', function( e ) { var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' ); if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) { self.close(); } } ); // Close the panel if the URL in the preview changes api.Widgets.Previewer.bind( 'url', this.close ); }, // Performs a search and handles selected widget search: function( event ) { var firstVisible; this.collection.doSearch( event.target.value ); // Remove a widget from being selected if it is no longer visible if ( this.selected && ! this.selected.is( ':visible' ) ) { this.selected.removeClass( 'selected' ); this.selected = null; } // If a widget was selected but the filter value has been cleared out, clear selection if ( this.selected && ! event.target.value ) { this.selected.removeClass( 'selected' ); this.selected = null; } // If a filter has been entered and a widget hasn't been selected, select the first one shown if ( ! this.selected && event.target.value ) { firstVisible = this.$el.find( '> .widget-tpl:visible:first' ); if ( firstVisible.length ) { this.select( firstVisible ); } } }, // Changes visibility of available widgets updateList: function() { this.collection.each( function( widget ) { var widgetTpl = $( '#widget-tpl-' + widget.id ); widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) ); if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) { this.selected = null; } } ); }, // Highlights a widget select: function( widgetTpl ) { this.selected = $( widgetTpl ); this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' ); this.selected.addClass( 'selected' ); }, // Highlights a widget on focus focus: function( event ) { this.select( $( event.currentTarget ) ); }, // Submit handler for keypress and click on widget _submit: function( event ) { // Only proceed with keypress if it is Enter or Spacebar if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; } this.submit( $( event.currentTarget ) ); }, // Adds a selected widget to the sidebar submit: function( widgetTpl ) { var widgetId, widget; if ( ! widgetTpl ) { widgetTpl = this.selected; } if ( ! widgetTpl || ! this.currentSidebarControl ) { return; } this.select( widgetTpl ); widgetId = $( this.selected ).data( 'widget-id' ); widget = this.collection.findWhere( { id: widgetId } ); if ( ! widget ) { return; } this.currentSidebarControl.addWidget( widget.get( 'id_base' ) ); this.close(); }, // Opens the panel open: function( sidebarControl ) { this.currentSidebarControl = sidebarControl; // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) { if ( control.params.is_wide ) { control.collapseForm(); } } ); $( 'body' ).addClass( 'adding-widget' ); this.$el.find( '.selected' ).removeClass( 'selected' ); // Reset search this.collection.doSearch( '' ); this.$search.focus(); }, // Closes the panel close: function( options ) { options = options || {}; if ( options.returnFocus && this.currentSidebarControl ) { this.currentSidebarControl.container.find( '.add-new-widget' ).focus(); } this.currentSidebarControl = null; this.selected = null; $( 'body' ).removeClass( 'adding-widget' ); this.$search.val( '' ); }, // Add keyboard accessiblity to the panel keyboardAccessible: function( event ) { var isEnter = ( event.which === 13 ), isEsc = ( event.which === 27 ), isDown = ( event.which === 40 ), isUp = ( event.which === 38 ), selected = null, firstVisible = this.$el.find( '> .widget-tpl:visible:first' ), lastVisible = this.$el.find( '> .widget-tpl:visible:last' ), isSearchFocused = $( event.target ).is( this.$search ); if ( isDown || isUp ) { if ( isDown ) { if ( isSearchFocused ) { selected = firstVisible; } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) { selected = this.selected.nextAll( '.widget-tpl:visible:first' ); } } else if ( isUp ) { if ( isSearchFocused ) { selected = lastVisible; } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) { selected = this.selected.prevAll( '.widget-tpl:visible:first' ); } } this.select( selected ); if ( selected ) { selected.focus(); } else { this.$search.focus(); } return; } // If enter pressed but nothing entered, don't do anything if ( isEnter && ! this.$search.val() ) { return; } if ( isEnter ) { this.submit(); } else if ( isEsc ) { this.close( { returnFocus: true } ); } } }); /** * Handlers for the widget-synced event, organized by widget ID base. * Other widgets may provide their own update handlers by adding * listeners for the widget-synced event. */ api.Widgets.formSyncHandlers = { /** * @param {jQuery.Event} e * @param {jQuery} widget * @param {String} newForm */ rss: function( e, widget, newForm ) { var oldWidgetError = widget.find( '.widget-error:first' ), newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' ); if ( oldWidgetError.length && newWidgetError.length ) { oldWidgetError.replaceWith( newWidgetError ); } else if ( oldWidgetError.length ) { oldWidgetError.remove(); } else if ( newWidgetError.length ) { widget.find( '.widget-content:first' ).prepend( newWidgetError ); } } }; /** * wp.customize.Widgets.WidgetControl * * Customizer control for widgets. * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type * * @constructor * @augments wp.customize.Control */ api.Widgets.WidgetControl = api.Control.extend({ /** * Set up the control */ ready: function() { this._setupModel(); this._setupWideWidget(); this._setupControlToggle(); this._setupWidgetTitle(); this._setupReorderUI(); this._setupHighlightEffects(); this._setupUpdateUI(); this._setupRemoveUI(); }, /** * Handle changes to the setting */ _setupModel: function() { var self = this, rememberSavedWidgetId; api.Widgets.savedWidgetIds = api.Widgets.savedWidgetIds || []; // Remember saved widgets so we know which to trash (move to inactive widgets sidebar) rememberSavedWidgetId = function() { api.Widgets.savedWidgetIds[self.params.widget_id] = true; }; api.bind( 'ready', rememberSavedWidgetId ); api.bind( 'saved', rememberSavedWidgetId ); this._updateCount = 0; this.isWidgetUpdating = false; this.liveUpdateMode = true; // Update widget whenever model changes this.setting.bind( function( to, from ) { if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) { self.updateWidget( { instance: to } ); } } ); }, /** * Add special behaviors for wide widget controls */ _setupWideWidget: function() { var self = this, $widgetInside, $widgetForm, $customizeSidebar, $themeControlsContainer, positionWidget; if ( ! this.params.is_wide ) { return; } $widgetInside = this.container.find( '.widget-inside' ); $widgetForm = $widgetInside.find( '> .form' ); $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' ); this.container.addClass( 'wide-widget-control' ); this.container.find( '.widget-content:first' ).css( { 'max-width': this.params.width, 'min-height': this.params.height } ); /** * Keep the widget-inside positioned so the top of fixed-positioned * element is at the same top position as the widget-top. When the * widget-top is scrolled out of view, keep the widget-top in view; * likewise, don't allow the widget to drop off the bottom of the window. * If a widget is too tall to fit in the window, don't let the height * exceed the window height so that the contents of the widget control * will become scrollable (overflow:auto). */ positionWidget = function() { var offsetTop = self.container.offset().top, windowHeight = $( window ).height(), formHeight = $widgetForm.outerHeight(), top; $widgetInside.css( 'max-height', windowHeight ); top = Math.max( 0, // prevent top from going off screen Math.min( Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen windowHeight - formHeight // flush up against bottom of screen ) ); $widgetInside.css( 'top', top ); }; $themeControlsContainer = $( '#customize-theme-controls' ); this.container.on( 'expand', function() { positionWidget(); $customizeSidebar.on( 'scroll', positionWidget ); $( window ).on( 'resize', positionWidget ); $themeControlsContainer.on( 'expanded collapsed', positionWidget ); } ); this.container.on( 'collapsed', function() { $customizeSidebar.off( 'scroll', positionWidget ); $( window ).off( 'resize', positionWidget ); $themeControlsContainer.off( 'expanded collapsed', positionWidget ); } ); // Reposition whenever a sidebar's widgets are changed api.each( function( setting ) { if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) { setting.bind( function() { if ( self.container.hasClass( 'expanded' ) ) { positionWidget(); } } ); } } ); }, /** * Show/hide the control when clicking on the form title, when clicking * the close button */ _setupControlToggle: function() { var self = this, $closeBtn; this.container.find( '.widget-top' ).on( 'click', function( e ) { e.preventDefault(); var sidebarWidgetsControl = self.getSidebarWidgetsControl(); if ( sidebarWidgetsControl.isReordering ) { return; } self.toggleForm(); } ); $closeBtn = this.container.find( '.widget-control-close' ); $closeBtn.on( 'click', function( e ) { e.preventDefault(); self.collapseForm(); self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility } ); }, /** * Update the title of the form if a title field is entered */ _setupWidgetTitle: function() { var self = this, updateTitle; updateTitle = function() { var title = self.setting().title, inWidgetTitle = self.container.find( '.in-widget-title' ); if ( title ) { inWidgetTitle.text( ': ' + title ); } else { inWidgetTitle.text( '' ); } }; this.setting.bind( updateTitle ); updateTitle(); }, /** * Set up the widget-reorder-nav */ _setupReorderUI: function() { var self = this, selectSidebarItem, $moveWidgetArea, $reorderNav, updateAvailableSidebars; /** * select the provided sidebar list item in the move widget area * * @param {jQuery} li */ selectSidebarItem = function( li ) { li.siblings( '.selected' ).removeClass( 'selected' ); li.addClass( 'selected' ); var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id ); self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar ); }; /** * Add the widget reordering elements to the widget control */ this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) ); $moveWidgetArea = $( _.template( api.Widgets.data.tpl.moveWidgetArea, { sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' ) } ) ); this.container.find( '.widget-top' ).after( $moveWidgetArea ); /** * Update available sidebars when their rendered state changes */ updateAvailableSidebars = function() { var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem; selfSidebarItem = $sidebarItems.filter( function(){ return $( this ).data( 'id' ) === self.params.sidebar_id; } ); $sidebarItems.each( function() { var li = $( this ), sidebarId, sidebar; sidebarId = li.data( 'id' ); sidebar = api.Widgets.registeredSidebars.get( sidebarId ); li.toggle( sidebar.get( 'is_rendered' ) ); if ( li.hasClass( 'selected' ) && ! sidebar.get( 'is_rendered' ) ) { selectSidebarItem( selfSidebarItem ); } } ); }; updateAvailableSidebars(); api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars ); /** * Handle clicks for up/down/move on the reorder nav */ $reorderNav = this.container.find( '.widget-reorder-nav' ); $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).on( 'click keypress', function( event ) { if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; } $( this ).focus(); if ( $( this ).is( '.move-widget' ) ) { self.toggleWidgetMoveArea(); } else { var isMoveDown = $( this ).is( '.move-widget-down' ), isMoveUp = $( this ).is( '.move-widget-up' ), i = self.getWidgetSidebarPosition(); if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) { return; } if ( isMoveUp ) { self.moveUp(); } else { self.moveDown(); } $( this ).focus(); // re-focus after the container was moved } } ); /** * Handle selecting a sidebar to move to */ this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( e ) { if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; } e.preventDefault(); selectSidebarItem( $( this ) ); } ); /** * Move widget to another sidebar */ this.container.find( '.move-widget-btn' ).click( function() { self.getSidebarWidgetsControl().toggleReordering( false ); var oldSidebarId = self.params.sidebar_id, newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ), oldSidebarWidgetsSetting, newSidebarWidgetsSetting, oldSidebarWidgetIds, newSidebarWidgetIds, i; oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' ); newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' ); oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() ); newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() ); i = self.getWidgetSidebarPosition(); oldSidebarWidgetIds.splice( i, 1 ); newSidebarWidgetIds.push( self.params.widget_id ); oldSidebarWidgetsSetting( oldSidebarWidgetIds ); newSidebarWidgetsSetting( newSidebarWidgetIds ); self.focus(); } ); }, /** * Highlight widgets in preview when interacted with in the customizer */ _setupHighlightEffects: function() { var self = this; // Highlight whenever hovering or clicking over the form this.container.on( 'mouseenter click', function() { self.setting.previewer.send( 'highlight-widget', self.params.widget_id ); } ); // Highlight when the setting is updated this.setting.bind( function() { self.setting.previewer.send( 'highlight-widget', self.params.widget_id ); } ); }, /** * Set up event handlers for widget updating */ _setupUpdateUI: function() { var self = this, $widgetRoot, $widgetContent, $saveBtn, updateWidgetDebounced, formSyncHandler; $widgetRoot = this.container.find( '.widget:first' ); $widgetContent = $widgetRoot.find( '.widget-content:first' ); // Configure update button $saveBtn = this.container.find( '.widget-control-save' ); $saveBtn.val( l10n.saveBtnLabel ); $saveBtn.attr( 'title', l10n.saveBtnTooltip ); $saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' ); $saveBtn.on( 'click', function( e ) { e.preventDefault(); self.updateWidget( { disable_form: true } ); // @todo disable_form is unused? } ); updateWidgetDebounced = _.debounce( function() { self.updateWidget(); }, 250 ); // Trigger widget form update when hitting Enter within an input $widgetContent.on( 'keydown', 'input', function( e ) { if ( 13 === e.which ) { // Enter e.preventDefault(); self.updateWidget( { ignoreActiveElement: true } ); } } ); // Handle widgets that support live previews $widgetContent.on( 'change input propertychange', ':input', function( e ) { if ( self.liveUpdateMode ) { if ( e.type === 'change' ) { self.updateWidget(); } else if ( this.checkValidity && this.checkValidity() ) { updateWidgetDebounced(); } } } ); // Remove loading indicators when the setting is saved and the preview updates this.setting.previewer.channel.bind( 'synced', function() { self.container.removeClass( 'previewer-loading' ); } ); api.Widgets.Previewer.bind( 'widget-updated', function( updatedWidgetId ) { if ( updatedWidgetId === self.params.widget_id ) { self.container.removeClass( 'previewer-loading' ); } } ); // Update widget control to indicate whether it is currently rendered api.Widgets.Previewer.bind( 'rendered-widgets', function( renderedWidgets ) { var isRendered = !! renderedWidgets[self.params.widget_id]; self.container.toggleClass( 'widget-rendered', isRendered ); } ); formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ]; if ( formSyncHandler ) { $( document ).on( 'widget-synced', function( e, widget ) { if ( $widgetRoot.is( widget ) ) { formSyncHandler.apply( document, arguments ); } } ); } }, /** * Set up event handlers for widget removal */ _setupRemoveUI: function() { var self = this, $removeBtn, replaceDeleteWithRemove; // Configure remove button $removeBtn = this.container.find( 'a.widget-control-remove' ); $removeBtn.on( 'click', function( e ) { e.preventDefault(); // Find an adjacent element to add focus to when this widget goes away var $adjacentFocusTarget; if ( self.container.next().is( '.customize-control-widget_form' ) ) { $adjacentFocusTarget = self.container.next().find( '.widget-action:first' ); } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) { $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' ); } else { $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' ); } self.container.slideUp( function() { var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ), sidebarWidgetIds, i; if ( ! sidebarsWidgetsControl ) { return; } sidebarWidgetIds = sidebarsWidgetsControl.setting().slice(); i = _.indexOf( sidebarWidgetIds, self.params.widget_id ); if ( -1 === i ) { return; } sidebarWidgetIds.splice( i, 1 ); sidebarsWidgetsControl.setting( sidebarWidgetIds ); $adjacentFocusTarget.focus(); // keyboard accessibility } ); } ); replaceDeleteWithRemove = function() { $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete" $removeBtn.attr( 'title', l10n.removeBtnTooltip ); }; if ( this.params.is_new ) { api.bind( 'saved', replaceDeleteWithRemove ); } else { replaceDeleteWithRemove(); } }, /** * Find all inputs in a widget container that should be considered when * comparing the loaded form with the sanitized form, whose fields will * be aligned to copy the sanitized over. The elements returned by this * are passed into this._getInputsSignature(), and they are iterated * over when copying sanitized values over to the the form loaded. * * @param {jQuery} container element in which to look for inputs * @returns {jQuery} inputs * @private */ _getInputs: function( container ) { return $( container ).find( ':input[name]' ); }, /** * Iterate over supplied inputs and create a signature string for all of them together. * This string can be used to compare whether or not the form has all of the same fields. * * @param {jQuery} inputs * @returns {string} * @private */ _getInputsSignature: function( inputs ) { var inputsSignatures = _( inputs ).map( function( input ) { var $input = $( input ), signatureParts; if ( $input.is( ':checkbox, :radio' ) ) { signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ]; } else { signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ]; } return signatureParts.join( ',' ); } ); return inputsSignatures.join( ';' ); }, /** * Get the property that represents the state of an input. * * @param {jQuery|DOMElement} input * @returns {string} * @private */ _getInputStatePropertyName: function( input ) { var $input = $( input ); if ( $input.is( ':radio, :checkbox' ) ) { return 'checked'; } else { return 'value'; } }, /*********************************************************************** * Begin public API methods **********************************************************************/ /** * @return {wp.customize.controlConstructor.sidebar_widgets[]} */ getSidebarWidgetsControl: function() { var settingId, sidebarWidgetsControl; settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']'; sidebarWidgetsControl = api.control( settingId ); if ( ! sidebarWidgetsControl ) { return; } return sidebarWidgetsControl; }, /** * Submit the widget form via Ajax and get back the updated instance, * along with the new widget control form to render. * * @param {object} [args] * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used * @param {Function|null} [args.complete=null] Function which is called when the request finishes. Context is bound to the control. First argument is any error. Following arguments are for success. * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element. */ updateWidget: function( args ) { var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent, updateNumber, params, data, $inputs, processing, jqxhr, isChanged; args = $.extend( { instance: null, complete: null, ignoreActiveElement: false }, args ); instanceOverride = args.instance; completeCallback = args.complete; this._updateCount += 1; updateNumber = this._updateCount; $widgetRoot = this.container.find( '.widget:first' ); $widgetContent = $widgetRoot.find( '.widget-content:first' ); // Remove a previous error message $widgetContent.find( '.widget-error' ).remove(); this.container.addClass( 'widget-form-loading' ); this.container.addClass( 'previewer-loading' ); processing = api.state( 'processing' ); processing( processing() + 1 ); if ( ! this.liveUpdateMode ) { this.container.addClass( 'widget-form-disabled' ); } params = {}; params.action = 'update-widget'; params.wp_customize = 'on'; params.nonce = api.Widgets.data.nonce; params.theme = api.settings.theme.stylesheet; data = $.param( params ); $inputs = this._getInputs( $widgetContent ); // Store the value we're submitting in data so that when the response comes back, // we know if it got sanitized; if there is no difference in the sanitized value, // then we do not need to touch the UI and mess up the user's ongoing editing. $inputs.each( function() { var input = $( this ), property = self._getInputStatePropertyName( this ); input.data( 'state' + updateNumber, input.prop( property ) ); } ); if ( instanceOverride ) { data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } ); } else { data += '&' + $inputs.serialize(); } data += '&' + $widgetContent.find( '~ :input' ).serialize(); jqxhr = $.post( wp.ajax.settings.url, data ); jqxhr.done( function( r ) { var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse, isLiveUpdateAborted = false; // Check if the user is logged out. if ( '0' === r ) { api.Widgets.Previewer.preview.iframe.hide(); api.Widgets.Previewer.login().done( function() { self.updateWidget( args ); api.Widgets.Previewer.preview.iframe.show(); } ); return; } // Check for cheaters. if ( '-1' === r ) { api.Widgets.Previewer.cheatin(); return; } if ( r.success ) { sanitizedForm = $( '<div>' + r.data.form + '</div>' ); $sanitizedInputs = self._getInputs( sanitizedForm ); hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs ); // Restore live update mode if sanitized fields are now aligned with the existing fields if ( hasSameInputsInResponse && ! self.liveUpdateMode ) { self.liveUpdateMode = true; self.container.removeClass( 'widget-form-disabled' ); self.container.find( 'input[name="savewidget"]' ).hide(); } // Sync sanitized field states to existing fields if they are aligned if ( hasSameInputsInResponse && self.liveUpdateMode ) { $inputs.each( function( i ) { var $input = $( this ), $sanitizedInput = $( $sanitizedInputs[i] ), property = self._getInputStatePropertyName( this ), submittedState, sanitizedState, canUpdateState; submittedState = $input.data( 'state' + updateNumber ); sanitizedState = $sanitizedInput.prop( property ); $input.data( 'sanitized', sanitizedState ); canUpdateState = ( submittedState !== sanitizedState && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) ); if ( canUpdateState ) { $input.prop( property, sanitizedState ); } } ); $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] ); // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled } else if ( self.liveUpdateMode ) { self.liveUpdateMode = false; self.container.find( 'input[name="savewidget"]' ).show(); isLiveUpdateAborted = true; // Otherwise, replace existing form with the sanitized form } else { $widgetContent.html( r.data.form ); self.container.removeClass( 'widget-form-disabled' ); $( document ).trigger( 'widget-updated', [ $widgetRoot ] ); } /** * If the old instance is identical to the new one, there is nothing new * needing to be rendered, and so we can preempt the event for the * preview finishing loading. */ isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance ); if ( isChanged ) { self.isWidgetUpdating = true; // suppress triggering another updateWidget self.setting( r.data.instance ); self.isWidgetUpdating = false; } else { // no change was made, so stop the spinner now instead of when the preview would updates self.container.removeClass( 'previewer-loading' ); } if ( completeCallback ) { completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } ); } } else { // General error message message = l10n.error; if ( r.data && r.data.message ) { message = r.data.message; } if ( completeCallback ) { completeCallback.call( self, message ); } else { $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' ); } } } ); jqxhr.fail( function( jqXHR, textStatus ) { if ( completeCallback ) { completeCallback.call( self, textStatus ); } } ); jqxhr.always( function() { self.container.removeClass( 'widget-form-loading' ); $inputs.each( function() { $( this ).removeData( 'state' + updateNumber ); } ); processing( processing() - 1 ); } ); }, /** * Expand the accordion section containing a control */ expandControlSection: function() { var $section = this.container.closest( '.accordion-section' ); if ( ! $section.hasClass( 'open' ) ) { $section.find( '.accordion-section-title:first' ).trigger( 'click' ); } }, /** * Expand the widget form control */ expandForm: function() { this.toggleForm( true ); }, /** * Collapse the widget form control */ collapseForm: function() { this.toggleForm( false ); }, /** * Expand or collapse the widget control * * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility */ toggleForm: function( showOrHide ) { var self = this, $widget, $inside, complete; $widget = this.container.find( 'div.widget:first' ); $inside = $widget.find( '.widget-inside:first' ); if ( typeof showOrHide === 'undefined' ) { showOrHide = ! $inside.is( ':visible' ); } // Already expanded or collapsed, so noop if ( $inside.is( ':visible' ) === showOrHide ) { return; } if ( showOrHide ) { // Close all other widget controls before expanding this one api.control.each( function( otherControl ) { if ( self.params.type === otherControl.params.type && self !== otherControl ) { otherControl.collapseForm(); } } ); complete = function() { self.container.removeClass( 'expanding' ); self.container.addClass( 'expanded' ); self.container.trigger( 'expanded' ); }; if ( self.params.is_wide ) { $inside.fadeIn( 'fast', complete ); } else { $inside.slideDown( 'fast', complete ); } self.container.trigger( 'expand' ); self.container.addClass( 'expanding' ); } else { complete = function() { self.container.removeClass( 'collapsing' ); self.container.removeClass( 'expanded' ); self.container.trigger( 'collapsed' ); }; self.container.trigger( 'collapse' ); self.container.addClass( 'collapsing' ); if ( self.params.is_wide ) { $inside.fadeOut( 'fast', complete ); } else { $inside.slideUp( 'fast', function() { $widget.css( { width:'', margin:'' } ); complete(); } ); } } }, /** * Expand the containing sidebar section, expand the form, and focus on * the first input in the control */ focus: function() { this.expandControlSection(); this.expandForm(); this.container.find( '.widget-content :focusable:first' ).focus(); }, /** * Get the position (index) of the widget in the containing sidebar * * @returns {Number} */ getWidgetSidebarPosition: function() { var sidebarWidgetIds, position; sidebarWidgetIds = this.getSidebarWidgetsControl().setting(); position = _.indexOf( sidebarWidgetIds, this.params.widget_id ); if ( position === -1 ) { return; } return position; }, /** * Move widget up one in the sidebar */ moveUp: function() { this._moveWidgetByOne( -1 ); }, /** * Move widget up one in the sidebar */ moveDown: function() { this._moveWidgetByOne( 1 ); }, /** * @private * * @param {Number} offset 1|-1 */ _moveWidgetByOne: function( offset ) { var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId; i = this.getWidgetSidebarPosition(); sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting; sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone adjacentWidgetId = sidebarWidgetIds[i + offset]; sidebarWidgetIds[i + offset] = this.params.widget_id; sidebarWidgetIds[i] = adjacentWidgetId; sidebarWidgetsSetting( sidebarWidgetIds ); }, /** * Toggle visibility of the widget move area * * @param {Boolean} [showOrHide] */ toggleWidgetMoveArea: function( showOrHide ) { var self = this, $moveWidgetArea; $moveWidgetArea = this.container.find( '.move-widget-area' ); if ( typeof showOrHide === 'undefined' ) { showOrHide = ! $moveWidgetArea.hasClass( 'active' ); } if ( showOrHide ) { // reset the selected sidebar $moveWidgetArea.find( '.selected' ).removeClass( 'selected' ); $moveWidgetArea.find( 'li' ).filter( function() { return $( this ).data( 'id' ) === self.params.sidebar_id; } ).addClass( 'selected' ); this.container.find( '.move-widget-btn' ).prop( 'disabled', true ); } $moveWidgetArea.toggleClass( 'active', showOrHide ); }, /** * Highlight the widget control and section */ highlightSectionAndControl: function() { var $target; if ( this.container.is( ':hidden' ) ) { $target = this.container.closest( '.control-section' ); } else { $target = this.container; } $( '.highlighted' ).removeClass( 'highlighted' ); $target.addClass( 'highlighted' ); setTimeout( function() { $target.removeClass( 'highlighted' ); }, 500 ); } } ); /** * wp.customize.Widgets.SidebarControl * * Customizer control for widgets. * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type * * @constructor * @augments wp.customize.Control */ api.Widgets.SidebarControl = api.Control.extend({ /** * Set up the control */ ready: function() { this.$controlSection = this.container.closest( '.control-section' ); this.$sectionContent = this.container.closest( '.accordion-section-content' ); this._setupModel(); this._setupSortable(); this._setupAddition(); this._applyCardinalOrderClassNames(); }, /** * Update ordering of widget control forms when the setting is updated */ _setupModel: function() { var self = this, registeredSidebar = api.Widgets.registeredSidebars.get( this.params.sidebar_id ); this.setting.bind( function( newWidgetIds, oldWidgetIds ) { var widgetFormControls, $sidebarWidgetsAddControl, finalControlContainers, removedWidgetIds; removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds ); // Filter out any persistent widget IDs for widgets which have been deactivated newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) { var parsedWidgetId = parseWidgetId( newWidgetId ); return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } ); } ); widgetFormControls = _( newWidgetIds ).map( function( widgetId ) { var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( ! widgetFormControl ) { widgetFormControl = self.addWidget( widgetId ); } return widgetFormControl; } ); // Sort widget controls to their new positions widgetFormControls.sort( function( a, b ) { var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ), bIndex = _.indexOf( newWidgetIds, b.params.widget_id ); if ( aIndex === bIndex ) { return 0; } return aIndex < bIndex ? -1 : 1; } ); // Append the controls to put them in the right order finalControlContainers = _( widgetFormControls ).map( function( widgetFormControls ) { return widgetFormControls.container[0]; } ); $sidebarWidgetsAddControl = self.$sectionContent.find( '.customize-control-sidebar_widgets' ); $sidebarWidgetsAddControl.before( finalControlContainers ); // Re-sort widget form controls (including widgets form other sidebars newly moved here) self._applyCardinalOrderClassNames(); // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated _( widgetFormControls ).each( function( widgetFormControl ) { widgetFormControl.params.sidebar_id = self.params.sidebar_id; } ); // Cleanup after widget removal _( removedWidgetIds ).each( function( removedWidgetId ) { // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update setTimeout( function() { var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase, widget, isPresentInAnotherSidebar = false; // Check if the widget is in another sidebar api.each( function( otherSetting ) { if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) { return; } var otherSidebarWidgets = otherSetting(), i; i = _.indexOf( otherSidebarWidgets, removedWidgetId ); if ( -1 !== i ) { isPresentInAnotherSidebar = true; } } ); // If the widget is present in another sidebar, abort! if ( isPresentInAnotherSidebar ) { return; } removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId ); // Detect if widget control was dragged to another sidebar wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] ); // Delete any widget form controls for removed widgets if ( removedControl && ! wasDraggedToAnotherSidebar ) { api.control.remove( removedControl.id ); removedControl.container.remove(); } // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved // This prevents the inactive widgets sidebar from overflowing with throwaway widgets if ( api.Widgets.savedWidgetIds[removedWidgetId] ) { inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice(); inactiveWidgets.push( removedWidgetId ); api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() ); } // Make old single widget available for adding again removedIdBase = parseWidgetId( removedWidgetId ).id_base; widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } ); if ( widget && ! widget.get( 'is_multi' ) ) { widget.set( 'is_disabled', false ); } } ); } ); } ); // Update the model with whether or not the sidebar is rendered api.Widgets.Previewer.bind( 'rendered-sidebars', function( renderedSidebars ) { var isRendered = !! renderedSidebars[self.params.sidebar_id]; registeredSidebar.set( 'is_rendered', isRendered ); } ); // Show the sidebar section when it becomes visible registeredSidebar.on( 'change:is_rendered', function( ) { var sectionSelector = '#accordion-section-sidebar-widgets-' + this.get( 'id' ), $section; $section = $( sectionSelector ); if ( this.get( 'is_rendered' ) ) { $section.stop().slideDown( function() { $( this ).css( 'height', 'auto' ); // so that the .accordion-section-content won't overflow } ); } else { // Make sure that hidden sections get closed first if ( $section.hasClass( 'open' ) ) { // it would be nice if accordionSwitch() in accordion.js was public $section.find( '.accordion-section-title' ).trigger( 'click' ); } $section.stop().slideUp(); } } ); }, /** * Allow widgets in sidebar to be re-ordered, and for the order to be previewed */ _setupSortable: function() { var self = this; this.isReordering = false; /** * Update widget order setting when controls are re-ordered */ this.$sectionContent.sortable( { items: '> .customize-control-widget_form', handle: '.widget-top', axis: 'y', connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)', update: function() { var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds; widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) { return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val(); } ); self.setting( widgetIds ); } } ); /** * Expand other customizer sidebar section when dragging a control widget over it, * allowing the control to be dropped into another section */ this.$controlSection.find( '.accordion-section-title' ).droppable({ accept: '.customize-control-widget_form', over: function() { if ( ! self.$controlSection.hasClass( 'open' ) ) { self.$controlSection.addClass( 'open' ); self.$sectionContent.toggle( false ).slideToggle( 150, function() { self.$sectionContent.sortable( 'refreshPositions' ); } ); } } }); /** * Keyboard-accessible reordering */ this.container.find( '.reorder-toggle' ).on( 'click keydown', function( event ) { if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar return; } self.toggleReordering( ! self.isReordering ); } ); }, /** * Set up UI for adding a new widget */ _setupAddition: function() { var self = this; this.container.find( '.add-new-widget' ).on( 'click keydown', function( event ) { if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar return; } if ( self.$sectionContent.hasClass( 'reordering' ) ) { return; } if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) { api.Widgets.availableWidgetsPanel.open( self ); } else { api.Widgets.availableWidgetsPanel.close(); } } ); }, /** * Add classes to the widget_form controls to assist with styling */ _applyCardinalOrderClassNames: function() { this.$sectionContent.find( '.customize-control-widget_form' ) .removeClass( 'first-widget' ) .removeClass( 'last-widget' ) .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 ); this.$sectionContent.find( '.customize-control-widget_form:first' ) .addClass( 'first-widget' ) .find( '.move-widget-up' ).prop( 'tabIndex', -1 ); this.$sectionContent.find( '.customize-control-widget_form:last' ) .addClass( 'last-widget' ) .find( '.move-widget-down' ).prop( 'tabIndex', -1 ); }, /*********************************************************************** * Begin public API methods **********************************************************************/ /** * Enable/disable the reordering UI * * @param {Boolean} showOrHide to enable/disable reordering */ toggleReordering: function( showOrHide ) { showOrHide = Boolean( showOrHide ); if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) { return; } this.isReordering = showOrHide; this.$sectionContent.toggleClass( 'reordering', showOrHide ); if ( showOrHide ) { _( this.getWidgetFormControls() ).each( function( formControl ) { formControl.collapseForm(); } ); } }, /** * @return {wp.customize.controlConstructor.widget_form[]} */ getWidgetFormControls: function() { var formControls; formControls = _( this.setting() ).map( function( widgetId ) { var settingId = widgetIdToSettingId( widgetId ), formControl = api.control( settingId ); if ( ! formControl ) { return; } return formControl; } ); return formControls; }, /** * @param {string} widgetId or an id_base for adding a previously non-existing widget * @returns {object|false} widget_form control instance, or false on error */ addWidget: function( widgetId ) { var self = this, controlHtml, $widget, controlType = 'widget_form', $control, controlConstructor, parsedWidgetId = parseWidgetId( widgetId ), widgetNumber = parsedWidgetId.number, widgetIdBase = parsedWidgetId.id_base, widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ), settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs; if ( ! widget ) { return false; } if ( widgetNumber && ! widget.get( 'is_multi' ) ) { return false; } // Set up new multi widget if ( widget.get( 'is_multi' ) && ! widgetNumber ) { widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 ); widgetNumber = widget.get( 'multi_number' ); } controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() ); if ( widget.get( 'is_multi' ) ) { controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) { return m.replace( /__i__|%i%/g, widgetNumber ); } ); } else { widget.set( 'is_disabled', true ); // Prevent single widget from being added again now } $widget = $( controlHtml ); $control = $( '<li/>' ) .addClass( 'customize-control' ) .addClass( 'customize-control-' + controlType ) .append( $widget ); // Remove icon which is visible inside the panel $control.find( '> .widget-icon' ).remove(); if ( widget.get( 'is_multi' ) ) { $control.find( 'input[name="widget_number"]' ).val( widgetNumber ); $control.find( 'input[name="multi_number"]' ).val( widgetNumber ); } widgetId = $control.find( '[name="widget-id"]' ).val(); $control.hide(); // to be slid-down below settingId = 'widget_' + widget.get( 'id_base' ); if ( widget.get( 'is_multi' ) ) { settingId += '[' + widgetNumber + ']'; } $control.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) ); this.container.after( $control ); // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget) isExistingWidget = api.has( settingId ); if ( ! isExistingWidget ) { settingArgs = { transport: 'refresh', previewer: this.setting.previewer }; api.create( settingId, settingId, {}, settingArgs ); } controlConstructor = api.controlConstructor[controlType]; widgetFormControl = new controlConstructor( settingId, { params: { settings: { 'default': settingId }, sidebar_id: self.params.sidebar_id, widget_id: widgetId, widget_id_base: widget.get( 'id_base' ), type: controlType, is_new: ! isExistingWidget, width: widget.get( 'width' ), height: widget.get( 'height' ), is_wide: widget.get( 'is_wide' ) }, previewer: self.setting.previewer } ); api.control.add( settingId, widgetFormControl ); // Make sure widget is removed from the other sidebars api.each( function( otherSetting ) { if ( otherSetting.id === self.setting.id ) { return; } if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) { return; } var otherSidebarWidgets = otherSetting().slice(), i = _.indexOf( otherSidebarWidgets, widgetId ); if ( -1 !== i ) { otherSidebarWidgets.splice( i ); otherSetting( otherSidebarWidgets ); } } ); // Add widget to this sidebar sidebarWidgets = this.setting().slice(); if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) { sidebarWidgets.push( widgetId ); this.setting( sidebarWidgets ); } $control.slideDown( function() { if ( isExistingWidget ) { widgetFormControl.expandForm(); widgetFormControl.updateWidget( { instance: widgetFormControl.setting(), complete: function( error ) { if ( error ) { throw error; } widgetFormControl.focus(); } } ); } else { widgetFormControl.focus(); } } ); $( document ).trigger( 'widget-added', [ $widget ] ); return widgetFormControl; } } ); /** * Extends wp.customizer.controlConstructor with control constructor for * widget_form and sidebar_widgets. */ $.extend( api.controlConstructor, { widget_form: api.Widgets.WidgetControl, sidebar_widgets: api.Widgets.SidebarControl }); /** * Capture the instance of the Previewer since it is private */ OldPreviewer = api.Previewer; api.Previewer = OldPreviewer.extend({ initialize: function( params, options ) { api.Widgets.Previewer = this; OldPreviewer.prototype.initialize.call( this, params, options ); this.bind( 'refresh', this.refresh ); } } ); /** * Init Customizer for widgets. */ api.bind( 'ready', function() { // Set up the widgets panel api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({ collection: api.Widgets.availableWidgets }); // Highlight widget control api.Widgets.Previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl ); // Open and focus widget control api.Widgets.Previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl ); } ); /** * Highlight a widget control. * * @param {string} widgetId */ api.Widgets.highlightWidgetFormControl = function( widgetId ) { var control = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( control ) { control.highlightSectionAndControl(); } }, /** * Focus a widget control. * * @param {string} widgetId */ api.Widgets.focusWidgetFormControl = function( widgetId ) { var control = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( control ) { control.focus(); } }, /** * Given a widget control, find the sidebar widgets control that contains it. * @param {string} widgetId * @return {object|null} */ api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) { var foundControl = null; // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl() api.control.each( function( control ) { if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) { foundControl = control; } } ); return foundControl; }; /** * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it. * * @param {string} widgetId * @return {object|null} */ api.Widgets.getWidgetFormControlForWidget = function( widgetId ) { var foundControl = null; // @todo We can just use widgetIdToSettingId() here api.control.each( function( control ) { if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) { foundControl = control; } } ); return foundControl; }; /** * @param {String} widgetId * @returns {Object} */ function parseWidgetId( widgetId ) { var matches, parsed = { number: null, id_base: null }; matches = widgetId.match( /^(.+)-(\d+)$/ ); if ( matches ) { parsed.id_base = matches[1]; parsed.number = parseInt( matches[2], 10 ); } else { // likely an old single widget parsed.id_base = widgetId; } return parsed; } /** * @param {String} widgetId * @returns {String} settingId */ function widgetIdToSettingId( widgetId ) { var parsed = parseWidgetId( widgetId ), settingId; settingId = 'widget_' + parsed.id_base; if ( parsed.number ) { settingId += '[' + parsed.number + ']'; } return settingId; } })( window.wp, jQuery );
JavaScript
/* global postboxes:true, commentL10n:true */ jQuery(document).ready( function($) { postboxes.add_postbox_toggles('comment'); var stamp = $('#timestamp').html(); $('.edit-timestamp').click(function () { if ($('#timestampdiv').is(':hidden')) { $('#timestampdiv').slideDown('normal'); $('.edit-timestamp').hide(); } return false; }); $('.cancel-timestamp').click(function() { $('#timestampdiv').slideUp('normal'); $('#mm').val($('#hidden_mm').val()); $('#jj').val($('#hidden_jj').val()); $('#aa').val($('#hidden_aa').val()); $('#hh').val($('#hidden_hh').val()); $('#mn').val($('#hidden_mn').val()); $('#timestamp').html(stamp); $('.edit-timestamp').show(); return false; }); $('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(), newD = new Date( aa, mm - 1, jj, hh, mn ); if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) { $('.timestamp-wrap', '#timestampdiv').addClass('form-invalid'); return false; } else { $('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid'); } $('#timestampdiv').slideUp('normal'); $('.edit-timestamp').show(); $('#timestamp').html( commentL10n.submittedOn + ' <b>' + $( '#mm option[value="' + mm + '"]' ).text() + ' ' + jj + ', ' + aa + ' @ ' + hh + ':' + mn + '</b> ' ); return false; }); });
JavaScript
/* global postboxes, deleteUserSetting, setUserSetting, getUserSetting */ jQuery(document).ready( function($) { var newCat, noSyncChecks = false, syncChecks, catAddAfter; $('#link_name').focus(); // postboxes postboxes.add_postbox_toggles('link'); // category tabs $('#category-tabs a').click(function(){ var t = $(this).attr('href'); $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); $('.tabs-panel').hide(); $(t).show(); if ( '#categories-all' == t ) deleteUserSetting('cats'); else setUserSetting('cats','pop'); return false; }); if ( getUserSetting('cats') ) $('#category-tabs a[href="#categories-pop"]').click(); // Ajax Cat newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ); } ); $('#link-category-add-submit').click( function() { newCat.focus(); } ); syncChecks = function() { if ( noSyncChecks ) return; noSyncChecks = true; var th = $(this), c = th.is(':checked'), id = th.val().toString(); $('#in-link-category-' + id + ', #in-popular-link_category-' + id).prop( 'checked', c ); noSyncChecks = false; }; catAddAfter = function( r, s ) { $(s.what + ' response_data', r).each( function() { var t = $($(this).text()); t.find( 'label' ).each( function() { var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o; $('#' + id).change( syncChecks ); o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name ); } ); } ); }; $('#categorychecklist').wpList( { alt: '', what: 'link-category', response: 'category-ajax-response', addAfter: catAddAfter } ); $('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');}); $('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');}); if ( 'pop' == getUserSetting('cats') ) $('a[href="#categories-pop"]').click(); $('#category-add-toggle').click( function() { $(this).parents('div:first').toggleClass( 'wp-hidden-children' ); $('#category-tabs a[href="#categories-all"]').click(); $('#newcategory').focus(); return false; } ); $('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change(); });
JavaScript
/* global ajaxurl, attachMediaBoxL10n */ var findPosts; ( function( $ ){ findPosts = { open: function( af_name, af_val ) { var overlay = $( '.ui-find-overlay' ); if ( overlay.length === 0 ) { $( 'body' ).append( '<div class="ui-find-overlay"></div>' ); findPosts.overlay(); } overlay.show(); if ( af_name && af_val ) { $( '#affected' ).attr( 'name', af_name ).val( af_val ); } $( '#find-posts' ).show(); $('#find-posts-input').focus().keyup( function( event ){ if ( event.which == 27 ) { findPosts.close(); } // close on Escape }); // Pull some results up by default findPosts.send(); return false; }, close: function() { $('#find-posts-response').html(''); $('#find-posts').hide(); $( '.ui-find-overlay' ).hide(); }, overlay: function() { $( '.ui-find-overlay' ).on( 'click', function () { findPosts.close(); }); }, send: function() { var post = { ps: $( '#find-posts-input' ).val(), action: 'find_posts', _ajax_nonce: $('#_ajax_nonce').val() }, spinner = $( '.find-box-search .spinner' ); spinner.show(); $.ajax( ajaxurl, { type: 'POST', data: post, dataType: 'json' }).always( function() { spinner.hide(); }).done( function( x ) { if ( ! x.success ) { $( '#find-posts-response' ).text( attachMediaBoxL10n.error ); } $( '#find-posts-response' ).html( x.data ); }).fail( function() { $( '#find-posts-response' ).text( attachMediaBoxL10n.error ); }); } }; $( document ).ready( function() { $( '#find-posts-submit' ).click( function( event ) { if ( ! $( '#find-posts-response input[type="radio"]:checked' ).length ) event.preventDefault(); }); $( '#find-posts .find-box-search :input' ).keypress( function( event ) { if ( 13 == event.which ) { findPosts.send(); return false; } }); $( '#find-posts-search' ).click( findPosts.send ); $( '#find-posts-close' ).click( findPosts.close ); $( '#doaction, #doaction2' ).click( function( event ) { $( 'select[name^="action"]' ).each( function() { if ( $(this).val() === 'attach' ) { event.preventDefault(); findPosts.open(); } }); }); // Enable whole row to be clicked $( '.find-box-inside' ).on( 'click', 'tr', function() { $( this ).find( '.found-radio input' ).prop( 'checked', true ); }); }); })( jQuery );
JavaScript
/* global ajaxurl */ (function($) { $(document).ready(function() { var frame, bgImage = $( '#custom-background-image' ); $('#background-color').wpColorPicker({ change: function( event, ui ) { bgImage.css('background-color', ui.color.toString()); }, clear: function() { bgImage.css('background-color', ''); } }); $('input[name="background-position-x"]').change(function() { bgImage.css('background-position', $(this).val() + ' top'); }); $('input[name="background-repeat"]').change(function() { bgImage.css('background-repeat', $(this).val()); }); $('#choose-from-library-link').click( function( event ) { var $el = $(this); event.preventDefault(); // If the media frame already exists, reopen it. if ( frame ) { frame.open(); return; } // Create the media frame. frame = wp.media.frames.customBackground = wp.media({ // Set the title of the modal. title: $el.data('choose'), // Tell the modal to show only images. library: { type: 'image' }, // Customize the submit button. button: { // Set the text of the button. text: $el.data('update'), // Tell the button not to close the modal, since we're // going to refresh the page when the image is selected. close: false } }); // When an image is selected, run a callback. frame.on( 'select', function() { // Grab the selected attachment. var attachment = frame.state().get('selection').first(); // Run an AJAX request to set the background image. $.post( ajaxurl, { action: 'set-background-image', attachment_id: attachment.id, size: 'full' }).done( function() { // When the request completes, reload the window. window.location.reload(); }); }); // Finally, open the modal. frame.open(); }); }); })(jQuery);
JavaScript
/* global inlineEditL10n, ajaxurl, typenow */ var inlineEditPost; (function($) { inlineEditPost = { init : function(){ var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit'); t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post'; t.what = '#post-'; // prepare the edit rows qeRow.keyup(function(e){ if ( e.which === 27 ) { return inlineEditPost.revert(); } }); bulkRow.keyup(function(e){ if ( e.which === 27 ) { return inlineEditPost.revert(); } }); $('a.cancel', qeRow).click(function(){ return inlineEditPost.revert(); }); $('a.save', qeRow).click(function(){ return inlineEditPost.save(this); }); $('td', qeRow).keydown(function(e){ if ( e.which === 13 ) { return inlineEditPost.save(this); } }); $('a.cancel', bulkRow).click(function(){ return inlineEditPost.revert(); }); $('#inline-edit .inline-edit-private input[value="private"]').click( function(){ var pw = $('input.inline-edit-password-input'); if ( $(this).prop('checked') ) { pw.val('').prop('disabled', true); } else { pw.prop('disabled', false); } }); // add events $('#the-list').on('click', 'a.editinline', function(){ inlineEditPost.edit(this); return false; }); $('#bulk-title-div').parents('fieldset').after( $('#inline-edit fieldset.inline-edit-categories').clone() ).siblings( 'fieldset:last' ).prepend( $('#inline-edit label.inline-edit-tags').clone() ); $('select[name="_status"] option[value="future"]', bulkRow).remove(); $('#doaction, #doaction2').click(function(e){ var n = $(this).attr('id').substr(2); if ( 'edit' === $( 'select[name="' + n + '"]' ).val() ) { e.preventDefault(); t.setBulk(); } else if ( $('form#posts-filter tr.inline-editor').length > 0 ) { t.revert(); } }); }, toggle : function(el){ var t = this; $( t.what + t.getId( el ) ).css( 'display' ) === 'none' ? t.revert() : t.edit( el ); }, setBulk : function(){ var te = '', type = this.type, tax, c = true; this.revert(); $('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length); $('table.widefat tbody').prepend( $('#bulk-edit') ); $('#bulk-edit').addClass('inline-editor').show(); $( 'tbody th.check-column input[type="checkbox"]' ).each( function() { if ( $(this).prop('checked') ) { c = false; var id = $(this).val(), theTitle; theTitle = $('#inline_'+id+' .post_title').html() || inlineEditL10n.notitle; te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>'; } }); if ( c ) { return this.revert(); } $('#bulk-titles').html(te); $('#bulk-titles a').click(function(){ var id = $(this).attr('id').substr(1); $('table.widefat input[value="' + id + '"]').prop('checked', false); $('#ttle'+id).remove(); }); // enable autocomplete for tags if ( 'post' === type ) { // support multi taxonomies? tax = 'post_tag'; $('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } ); } $('html, body').animate( { scrollTop: 0 }, 'fast' ); }, edit : function(id) { var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f; t.revert(); if ( typeof(id) === 'object' ) { id = t.getId(id); } fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order']; if ( t.type === 'page' ) { fields.push('post_parent', 'page_template'); } // add the new blank row editRow = $('#inline-edit').clone(true); $('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length); if ( $( t.what + id ).hasClass( 'alternate' ) ) { $(editRow).addClass('alternate'); } $(t.what+id).hide().after(editRow); // populate the data rowData = $('#inline_'+id); if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) { // author no longer has edit caps, so we need to add them to the list of authors $(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>'); } if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) { $('label.inline-edit-author', editRow).hide(); } // hide unsupported formats, but leave the current format alone cur_format = $('.post_format', rowData).text(); $('option.unsupported', editRow).each(function() { var $this = $(this); if ( $this.val() !== cur_format ) { $this.remove(); } }); for ( f = 0; f < fields.length; f++ ) { $(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() ); } if ( $( '.comment_status', rowData ).text() === 'open' ) { $( 'input[name="comment_status"]', editRow ).prop( 'checked', true ); } if ( $( '.ping_status', rowData ).text() === 'open' ) { $( 'input[name="ping_status"]', editRow ).prop( 'checked', true ); } if ( $( '.sticky', rowData ).text() === 'sticky' ) { $( 'input[name="sticky"]', editRow ).prop( 'checked', true ); } // hierarchical taxonomies $('.post_category', rowData).each(function(){ var taxname, term_ids = $(this).text(); if ( term_ids ) { taxname = $(this).attr('id').replace('_'+id, ''); $('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(',')); } }); //flat taxonomies $('.tags_input', rowData).each(function(){ var terms = $(this).text(), taxname = $(this).attr('id').replace('_' + id, ''), textarea = $('textarea.tax_input_' + taxname, editRow), comma = inlineEditL10n.comma; if ( terms ) { if ( ',' !== comma ) { terms = terms.replace(/,/g, comma); } textarea.val(terms); } textarea.suggest( ajaxurl + '?action=ajax-tag-search&tax=' + taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } ); }); // handle the post status status = $('._status', rowData).text(); if ( 'future' !== status ) { $('select[name="_status"] option[value="future"]', editRow).remove(); } if ( 'private' === status ) { $('input[name="keep_private"]', editRow).prop('checked', true); $('input.inline-edit-password-input').val('').prop('disabled', true); } // remove the current page and children from the parent dropdown pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow); if ( pageOpt.length > 0 ) { pageLevel = pageOpt[0].className.split('-')[1]; nextPage = pageOpt; while ( pageLoop ) { nextPage = nextPage.next('option'); if ( nextPage.length === 0 ) { break; } nextLevel = nextPage[0].className.split('-')[1]; if ( nextLevel <= pageLevel ) { pageLoop = false; } else { nextPage.remove(); nextPage = pageOpt; } } pageOpt.remove(); } $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); $('.ptitle', editRow).focus(); return false; }, save : function(id) { var params, fields, page = $('.post_status_page').val() || ''; if ( typeof(id) === 'object' ) { id = this.getId(id); } $('table.widefat .spinner').show(); params = { action: 'inline-save', post_type: typenow, post_ID: id, edit_date: 'true', post_status: page }; fields = $('#edit-'+id).find(':input').serialize(); params = fields + '&' + $.param(params); // make ajax request $.post( ajaxurl, params, function(r) { $('table.widefat .spinner').hide(); if (r) { if ( -1 !== r.indexOf( '<tr' ) ) { $(inlineEditPost.what+id).remove(); $('#edit-'+id).before(r).remove(); $(inlineEditPost.what+id).hide().fadeIn(); } else { r = r.replace( /<.[^<>]*?>/g, '' ); $('#edit-'+id+' .inline-edit-save .error').html(r).show(); } } else { $('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show(); } if ( $('#post-'+id).prev().hasClass('alternate') ) { $('#post-'+id).removeClass('alternate'); } }, 'html'); return false; }, revert : function(){ var id = $('table.widefat tr.inline-editor').attr('id'); if ( id ) { $('table.widefat .spinner').hide(); if ( 'bulk-edit' === id ) { $('table.widefat #bulk-edit').removeClass('inline-editor').hide(); $('#bulk-titles').html(''); $('#inlineedit').append( $('#bulk-edit') ); } else { $('#'+id).remove(); id = id.substr( id.lastIndexOf('-') + 1 ); $(this.what+id).show(); } } return false; }, getId : function(o) { var id = $(o).closest('tr').attr('id'), parts = id.split('-'); return parts[parts.length - 1]; } }; $( document ).ready( function(){ inlineEditPost.init(); } ); // Show/hide locks on posts $( document ).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) { var locked = data['wp-check-locked-posts'] || {}; $('#the-list tr').each( function(i, el) { var key = el.id, row = $(el), lock_data, avatar; if ( locked.hasOwnProperty( key ) ) { if ( ! row.hasClass('wp-locked') ) { lock_data = locked[key]; row.find('.column-title .locked-text').text( lock_data.text ); row.find('.check-column checkbox').prop('checked', false); if ( lock_data.avatar_src ) { avatar = $('<img class="avatar avatar-18 photo" width="18" height="18" />').attr( 'src', lock_data.avatar_src.replace(/&amp;/g, '&') ); row.find('.column-title .locked-avatar').empty().append( avatar ); } row.addClass('wp-locked'); } } else if ( row.hasClass('wp-locked') ) { // Make room for the CSS animation row.removeClass('wp-locked').delay(1000).find('.locked-info span').empty(); } }); }).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) { var check = []; $('#the-list tr').each( function(i, el) { if ( el.id ) { check.push( el.id ); } }); if ( check.length ) { data['wp-check-locked-posts'] = check; } }).ready( function() { // Set the heartbeat interval to 15 sec. if ( typeof wp !== 'undefined' && wp.heartbeat ) { wp.heartbeat.interval( 15 ); } }); }(jQuery));
JavaScript
/* global unescape, getUserSetting, setUserSetting */ jQuery(document).ready(function($) { var gallerySortable, gallerySortableInit, sortIt, clearAll, w, desc = false; gallerySortableInit = function() { gallerySortable = $('#media-items').sortable( { items: 'div.media-item', placeholder: 'sorthelper', axis: 'y', distance: 2, handle: 'div.filename', stop: function() { // When an update has occurred, adjust the order for each item var all = $('#media-items').sortable('toArray'), len = all.length; $.each(all, function(i, id) { var order = desc ? (len - i) : (1 + i); $('#' + id + ' .menu_order input').val(order); }); } } ); }; sortIt = function() { var all = $('.menu_order_input'), len = all.length; all.each(function(i){ var order = desc ? (len - i) : (1 + i); $(this).val(order); }); }; clearAll = function(c) { c = c || 0; $('.menu_order_input').each( function() { if ( this.value === '0' || c ) { this.value = ''; } }); }; $('#asc').click( function() { desc = false; sortIt(); return false; }); $('#desc').click( function() { desc = true; sortIt(); return false; }); $('#clear').click( function() { clearAll(1); return false; }); $('#showall').click( function() { $('#sort-buttons span a').toggle(); $('a.describe-toggle-on').hide(); $('a.describe-toggle-off, table.slidetoggle').show(); $('img.pinkynail').toggle(false); return false; }); $('#hideall').click( function() { $('#sort-buttons span a').toggle(); $('a.describe-toggle-on').show(); $('a.describe-toggle-off, table.slidetoggle').hide(); $('img.pinkynail').toggle(true); return false; }); // initialize sortable gallerySortableInit(); clearAll(); if ( $('#media-items>*').length > 1 ) { w = wpgallery.getWin(); $('#save-all, #gallery-settings').show(); if ( typeof w.tinyMCE !== 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) { wpgallery.mcemode = true; wpgallery.init(); } else { $('#insert-gallery').show(); } } }); jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup /* gallery settings */ var tinymce = null, tinyMCE, wpgallery; wpgallery = { mcemode : false, editor : {}, dom : {}, is_update : false, el : {}, I : function(e) { return document.getElementById(e); }, init: function() { var t = this, li, q, i, it, w = t.getWin(); if ( ! t.mcemode ) { return; } li = ('' + document.location.search).replace(/^\?/, '').split('&'); q = {}; for (i=0; i<li.length; i++) { it = li[i].split('='); q[unescape(it[0])] = unescape(it[1]); } if ( q.mce_rdomain ) { document.domain = q.mce_rdomain; } // Find window & API tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.setup(); }, getWin : function() { return window.dialogArguments || opener || parent || top; }, setup : function() { var t = this, a, ed = t.editor, g, columns, link, order, orderby; if ( ! t.mcemode ) { return; } t.el = ed.selection.getNode(); if ( t.el.nodeName !== 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) { if ( ( g = ed.dom.select('img.wpGallery') ) && g[0] ) { t.el = g[0]; } else { if ( getUserSetting('galfile') === '1' ) { t.I('linkto-file').checked = 'checked'; } if ( getUserSetting('galdesc') === '1' ) { t.I('order-desc').checked = 'checked'; } if ( getUserSetting('galcols') ) { t.I('columns').value = getUserSetting('galcols'); } if ( getUserSetting('galord') ) { t.I('orderby').value = getUserSetting('galord'); } jQuery('#insert-gallery').show(); return; } } a = ed.dom.getAttrib(t.el, 'title'); a = ed.dom.decode(a); if ( a ) { jQuery('#update-gallery').show(); t.is_update = true; columns = a.match(/columns=['"]([0-9]+)['"]/); link = a.match(/link=['"]([^'"]+)['"]/i); order = a.match(/order=['"]([^'"]+)['"]/i); orderby = a.match(/orderby=['"]([^'"]+)['"]/i); if ( link && link[1] ) { t.I('linkto-file').checked = 'checked'; } if ( order && order[1] ) { t.I('order-desc').checked = 'checked'; } if ( columns && columns[1] ) { t.I('columns').value = '' + columns[1]; } if ( orderby && orderby[1] ) { t.I('orderby').value = orderby[1]; } } else { jQuery('#insert-gallery').show(); } }, update : function() { var t = this, ed = t.editor, all = '', s; if ( ! t.mcemode || ! t.is_update ) { s = '[gallery' + t.getSettings() + ']'; t.getWin().send_to_editor(s); return; } if ( t.el.nodeName !== 'IMG' ) { return; } all = ed.dom.decode( ed.dom.getAttrib( t.el, 'title' ) ); all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, ''); all += t.getSettings(); ed.dom.setAttrib(t.el, 'title', all); t.getWin().tb_remove(); }, getSettings : function() { var I = this.I, s = ''; if ( I('linkto-file').checked ) { s += ' link="file"'; setUserSetting('galfile', '1'); } if ( I('order-desc').checked ) { s += ' order="DESC"'; setUserSetting('galdesc', '1'); } if ( I('columns').value !== 3 ) { s += ' columns="' + I('columns').value + '"'; setUserSetting('galcols', I('columns').value); } if ( I('orderby').value !== 'menu_order' ) { s += ' orderby="' + I('orderby').value + '"'; setUserSetting('galord', I('orderby').value); } return s; } };
JavaScript
/* global _wpThemeSettings, confirm */ window.wp = window.wp || {}; ( function($) { // Set up our namespace... var themes, l10n; themes = wp.themes = wp.themes || {}; // Store the theme data and settings for organized and quick access // themes.data.settings, themes.data.themes, themes.data.l10n themes.data = _wpThemeSettings; l10n = themes.data.l10n; // Shortcut for isInstall check themes.isInstall = !! themes.data.settings.isInstall; // Setup app structure _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template }); themes.Model = Backbone.Model.extend({ // Adds attributes to the default data coming through the .org themes api // Map `id` to `slug` for shared code initialize: function() { var description; // If theme is already installed, set an attribute. if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) { this.set({ installed: true }); } // Set the attributes this.set({ // slug is for installation, id is for existing. id: this.get( 'slug' ) || this.get( 'id' ) }); // Map `section.description` to `description` // as the API sometimes returns it differently if ( this.has( 'sections' ) ) { description = this.get( 'sections' ).description; this.set({ description: description }); } } }); // Main view controller for themes.php // Unifies and renders all available views themes.view.Appearance = wp.Backbone.View.extend({ el: '#wpbody-content .wrap .theme-browser', window: $( window ), // Pagination instance page: 0, // Sets up a throttler for binding to 'scroll' initialize: function( options ) { // Scroller checks how far the scroll position is _.bindAll( this, 'scroller' ); this.SearchView = options.SearchView ? options.SearchView : themes.view.Search; // Bind to the scroll event and throttle // the results from this.scroller this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) ); }, // Main render control render: function() { // Setup the main theme view // with the current theme collection this.view = new themes.view.Themes({ collection: this.collection, parent: this }); // Render search form. this.search(); // Render and append this.view.render(); this.$el.empty().append( this.view.el ).addClass('rendered'); this.$el.append( '<br class="clear"/>' ); }, // Defines search element container searchContainer: $( '#wpbody h2:first' ), // Search input and view // for current theme collection search: function() { var view, self = this; // Don't render the search if there is only one theme if ( themes.data.themes.length === 1 ) { return; } view = new this.SearchView({ collection: self.collection, parent: this }); // Render and append after screen title view.render(); this.searchContainer .append( $.parseHTML( '<label class="screen-reader-text" for="theme-search-input">' + l10n.search + '</label>' ) ) .append( view.el ); }, // Checks when the user gets close to the bottom // of the mage and triggers a theme:scroll event scroller: function() { var self = this, bottom, threshold; bottom = this.window.scrollTop() + self.window.height(); threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height(); threshold = Math.round( threshold * 0.9 ); if ( bottom > threshold ) { this.trigger( 'theme:scroll' ); } } }); // Set up the Collection for our theme data // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ... themes.Collection = Backbone.Collection.extend({ model: themes.Model, // Search terms terms: '', // Controls searching on the current theme collection // and triggers an update event doSearch: function( value ) { // Don't do anything if we've already done this search // Useful because the Search handler fires multiple times per keystroke if ( this.terms === value ) { return; } // Updates terms with the value passed this.terms = value; // If we have terms, run a search... if ( this.terms.length > 0 ) { this.search( this.terms ); } // If search is blank, show all themes // Useful for resetting the views when you clean the input if ( this.terms === '' ) { this.reset( themes.data.themes ); } // Trigger an 'update' event this.trigger( 'update' ); }, // Performs a search within the collection // @uses RegExp search: function( term ) { var match, results, haystack; // Start with a full collection this.reset( themes.data.themes, { silent: true } ); // Escape the term string for RegExp meta characters term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' ); // Consider spaces as word delimiters and match the whole string // so matching terms can be combined term = term.replace( / /g, ')(?=.*' ); match = new RegExp( '^(?=.*' + term + ').+', 'i' ); // Find results // _.filter and .test results = this.filter( function( data ) { haystack = _.union( data.get( 'name' ), data.get( 'id' ), data.get( 'description' ), data.get( 'author' ), data.get( 'tags' ) ); if ( match.test( data.get( 'author' ) ) && term.length > 2 ) { data.set( 'displayAuthor', true ); } return match.test( haystack ); }); this.reset( results ); }, // Paginates the collection with a helper method // that slices the collection paginate: function( instance ) { var collection = this; instance = instance || 0; // Themes per instance are set at 20 collection = _( collection.rest( 20 * instance ) ); collection = _( collection.first( 20 ) ); return collection; }, count: false, // Handles requests for more themes // and caches results // // When we are missing a cache object we fire an apiCall() // which triggers events of `query:success` or `query:fail` query: function( request ) { /** * @static * @type Array */ var queries = this.queries, self = this, query, isPaginated, count; // Store current query request args // for later use with the event `theme:end` this.currentQuery.request = request; // Search the query cache for matches. query = _.find( queries, function( query ) { return _.isEqual( query.request, request ); }); // If the request matches the stored currentQuery.request // it means we have a paginated request. isPaginated = _.has( request, 'page' ); // Reset the internal api page counter for non paginated queries. if ( ! isPaginated ) { this.currentQuery.page = 1; } // Otherwise, send a new API call and add it to the cache. if ( ! query && ! isPaginated ) { query = this.apiCall( request ).done( function( data ) { // Update the collection with the queried data. if ( data.themes ) { self.reset( data.themes ); count = data.info.results; // Store the results and the query request queries.push( { themes: data.themes, request: request, total: count } ); } // Trigger a collection refresh event // and a `query:success` event with a `count` argument. self.trigger( 'update' ); self.trigger( 'query:success', count ); if ( data.themes && data.themes.length === 0 ) { self.trigger( 'query:empty' ); } }).fail( function() { self.trigger( 'query:fail' ); }); } else { // If it's a paginated request we need to fetch more themes... if ( isPaginated ) { return this.apiCall( request, isPaginated ).done( function( data ) { // Add the new themes to the current collection // @todo update counter self.add( data.themes ); self.trigger( 'query:success' ); // We are done loading themes for now. self.loadingThemes = false; }).fail( function() { self.trigger( 'query:fail' ); }); } if ( query.themes.length === 0 ) { self.trigger( 'query:empty' ); } else { $( 'body' ).removeClass( 'no-results' ); } // Only trigger an update event since we already have the themes // on our cached object if ( _.isNumber( query.total ) ) { this.count = query.total; } this.reset( query.themes ); if ( ! query.total ) { this.count = this.length; } this.trigger( 'update' ); this.trigger( 'query:success', this.count ); } }, // Local cache array for API queries queries: [], // Keep track of current query so we can handle pagination currentQuery: { page: 1, request: {} }, // Send request to api.wordpress.org/themes apiCall: function( request, paginated ) { return wp.ajax.send( 'query-themes', { data: { // Request data request: _.extend({ per_page: 100, fields: { description: true, tested: true, requires: true, rating: true, downloaded: true, downloadLink: true, last_updated: true, homepage: true, num_ratings: true } }, request) }, beforeSend: function() { if ( ! paginated ) { // Spin it $( 'body' ).addClass( 'loading-themes' ).removeClass( 'no-results' ); } } }); }, // Static status controller for when we are loading themes. loadingThemes: false }); // This is the view that controls each theme item // that will be displayed on the screen themes.view.Theme = wp.Backbone.View.extend({ // Wrap theme data on a div.theme element className: 'theme', // Reflects which theme view we have // 'grid' (default) or 'detail' state: 'grid', // The HTML template for each element to be rendered html: themes.template( 'theme' ), events: { 'click': themes.isInstall ? 'preview': 'expand', 'click .preview': 'preview', 'keydown': themes.isInstall ? 'preview': 'expand', 'touchend': themes.isInstall ? 'preview': 'expand', 'keyup': 'addFocus', 'touchmove': 'preventExpand' }, touchDrag: false, render: function() { var data = this.model.toJSON(); // Render themes using the html template this.$el.html( this.html( data ) ).attr({ tabindex: 0, 'aria-describedby' : data.id + '-action ' + data.id + '-name' }); // Renders active theme styles this.activeTheme(); if ( this.model.get( 'displayAuthor' ) ) { this.$el.addClass( 'display-author' ); } if ( this.model.get( 'installed' ) ) { this.$el.addClass( 'is-installed' ); } }, // Adds a class to the currently active theme // and to the overlay in detailed view mode activeTheme: function() { if ( this.model.get( 'active' ) ) { this.$el.addClass( 'active' ); } }, // Add class of focus to the theme we are focused on. addFocus: function() { var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme'); $('.theme.focus').removeClass('focus'); $themeToFocus.addClass('focus'); }, // Single theme overlay screen // It's shown when clicking a theme expand: function( event ) { var self = this; event = event || window.event; // 'enter' and 'space' keys expand the details view when a theme is :focused if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) { return; } // Bail if the user scrolled on a touch device if ( this.touchDrag === true ) { return this.touchDrag = false; } // Prevent the modal from showing when the user clicks // one of the direct action buttons if ( $( event.target ).is( '.theme-actions a' ) ) { return; } // Set focused theme to current element themes.focusedTheme = this.$el; this.trigger( 'theme:expand', self.model.cid ); }, preventExpand: function() { this.touchDrag = true; }, preview: function( event ) { var self = this, current, preview; // Bail if the user scrolled on a touch device if ( this.touchDrag === true ) { return this.touchDrag = false; } // Allow direct link path to installing a theme. if ( $( event.target ).hasClass( 'button-primary' ) ) { return; } // 'enter' and 'space' keys expand the details view when a theme is :focused if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) { return; } // pressing enter while focused on the buttons shouldn't open the preview if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) { return; } event.preventDefault(); event = event || window.event; // Set focus to current theme. themes.focusedTheme = this.$el; // Construct a new Preview view. preview = new themes.view.Preview({ model: this.model }); // Render the view and append it. preview.render(); this.setNavButtonsState(); // Hide previous/next navigation if there is only one theme if ( this.model.collection.length === 1 ) { preview.$el.addClass( 'no-navigation' ); } else { preview.$el.removeClass( 'no-navigation' ); } // Apend preview $( 'div.wrap' ).append( preview.el ); // Listen to our preview object // for `theme:next` and `theme:previous` events. this.listenTo( preview, 'theme:next', function() { // Keep local track of current theme model. current = self.model; // If we have ventured away from current model update the current model position. if ( ! _.isUndefined( self.current ) ) { current = self.current; } // Get previous theme model. self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 ); // If we have no more themes, bail. if ( _.isUndefined( self.current ) ) { self.options.parent.parent.trigger( 'theme:end' ); return self.current = current; } // Construct a new Preview view. preview = new themes.view.Preview({ model: self.current }); // Render and append. preview.render(); this.setNavButtonsState(); $( 'div.wrap' ).append( preview.el ); $( '.next-theme' ).focus(); }) .listenTo( preview, 'theme:previous', function() { // Keep track of current theme model. current = self.model; // Bail early if we are at the beginning of the collection if ( self.model.collection.indexOf( self.current ) === 0 ) { return; } // If we have ventured away from current model update the current model position. if ( ! _.isUndefined( self.current ) ) { current = self.current; } // Get previous theme model. self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 ); // If we have no more themes, bail. if ( _.isUndefined( self.current ) ) { return; } // Construct a new Preview view. preview = new themes.view.Preview({ model: self.current }); // Render and append. preview.render(); this.setNavButtonsState(); $( 'div.wrap' ).append( preview.el ); $( '.previous-theme' ).focus(); }); this.listenTo( preview, 'preview:close', function() { self.current = self.model; }); }, // Handles .disabled classes for previous/next buttons in theme installer preview setNavButtonsState: function() { var $themeInstaller = $( '.theme-install-overlay' ), current = _.isUndefined( this.current ) ? this.model : this.current; // Disable previous at the zero position if ( 0 === this.model.collection.indexOf( current ) ) { $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' ); } // Disable next if the next model is undefined if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) { $themeInstaller.find( '.next-theme' ).addClass( 'disabled' ); } } }); // Theme Details view // Set ups a modal overlay with the expanded theme data themes.view.Details = wp.Backbone.View.extend({ // Wrap theme data on a div.theme element className: 'theme-overlay', events: { 'click': 'collapse', 'click .delete-theme': 'deleteTheme', 'click .left': 'previousTheme', 'click .right': 'nextTheme' }, // The HTML template for the theme overlay html: themes.template( 'theme-single' ), render: function() { var data = this.model.toJSON(); this.$el.html( this.html( data ) ); // Renders active theme styles this.activeTheme(); // Set up navigation events this.navigation(); // Checks screenshot size this.screenshotCheck( this.$el ); // Contain "tabbing" inside the overlay this.containFocus( this.$el ); }, // Adds a class to the currently active theme // and to the overlay in detailed view mode activeTheme: function() { // Check the model has the active property this.$el.toggleClass( 'active', this.model.get( 'active' ) ); }, // Keeps :focus within the theme details elements containFocus: function( $el ) { var $target; // Move focus to the primary action _.delay( function() { $( '.theme-wrap a.button-primary:visible' ).focus(); }, 500 ); $el.on( 'keydown.wp-themes', function( event ) { // Tab key if ( event.which === 9 ) { $target = $( event.target ); // Keep focus within the overlay by making the last link on theme actions // switch focus to button.left on tabbing and vice versa if ( $target.is( 'button.left' ) && event.shiftKey ) { $el.find( '.theme-actions a:last-child' ).focus(); event.preventDefault(); } else if ( $target.is( '.theme-actions a:last-child' ) ) { $el.find( 'button.left' ).focus(); event.preventDefault(); } } }); }, // Single theme overlay screen // It's shown when clicking a theme collapse: function( event ) { var self = this, scroll; event = event || window.event; // Prevent collapsing detailed view when there is only one theme available if ( themes.data.themes.length === 1 ) { return; } // Detect if the click is inside the overlay // and don't close it unless the target was // the div.back button if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) { // Add a temporary closing class while overlay fades out $( 'body' ).addClass( 'closing-overlay' ); // With a quick fade out animation this.$el.fadeOut( 130, function() { // Clicking outside the modal box closes the overlay $( 'body' ).removeClass( 'closing-overlay' ); // Handle event cleanup self.closeOverlay(); // Get scroll position to avoid jumping to the top scroll = document.body.scrollTop; // Clean the url structure themes.router.navigate( themes.router.baseUrl( '' ) ); // Restore scroll position document.body.scrollTop = scroll; // Return focus to the theme div if ( themes.focusedTheme ) { themes.focusedTheme.focus(); } }); } }, // Handles .disabled classes for next/previous buttons navigation: function() { // Disable Left/Right when at the start or end of the collection if ( this.model.cid === this.model.collection.at(0).cid ) { this.$el.find( '.left' ).addClass( 'disabled' ); } if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) { this.$el.find( '.right' ).addClass( 'disabled' ); } }, // Performs the actions to effectively close // the theme details overlay closeOverlay: function() { $( 'body' ).removeClass( 'theme-overlay-open' ); this.remove(); this.unbind(); this.trigger( 'theme:collapse' ); }, // Confirmation dialog for deleting a theme deleteTheme: function() { return confirm( themes.data.settings.confirmDelete ); }, nextTheme: function() { var self = this; self.trigger( 'theme:next', self.model.cid ); return false; }, previousTheme: function() { var self = this; self.trigger( 'theme:previous', self.model.cid ); return false; }, // Checks if the theme screenshot is the old 300px width version // and adds a corresponding class if it's true screenshotCheck: function( el ) { var screenshot, image; screenshot = el.find( '.screenshot img' ); image = new Image(); image.src = screenshot.attr( 'src' ); // Width check if ( image.width && image.width <= 300 ) { el.addClass( 'small-screenshot' ); } } }); // Theme Preview view // Set ups a modal overlay with the expanded theme data themes.view.Preview = themes.view.Details.extend({ className: 'wp-full-overlay expanded', el: '.theme-install-overlay', events: { 'click .close-full-overlay': 'close', 'click .collapse-sidebar': 'collapse', 'click .previous-theme': 'previousTheme', 'click .next-theme': 'nextTheme', 'keyup': 'keyEvent' }, // The HTML template for the theme preview html: themes.template( 'theme-preview' ), render: function() { var data = this.model.toJSON(); this.$el.html( this.html( data ) ); themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.get( 'id' ) ), { replace: true } ); this.$el.fadeIn( 200, function() { $( 'body' ).addClass( 'theme-installer-active full-overlay-active' ); $( '.close-full-overlay' ).focus(); }); }, close: function() { this.$el.fadeOut( 200, function() { $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' ); // Return focus to the theme div if ( themes.focusedTheme ) { themes.focusedTheme.focus(); } }); themes.router.navigate( themes.router.baseUrl( '' ) ); this.trigger( 'preview:close' ); this.unbind(); return false; }, collapse: function() { this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' ); return false; }, keyEvent: function( event ) { // The escape key closes the preview if ( event.keyCode === 27 ) { this.undelegateEvents(); this.close(); } // The right arrow key, next theme if ( event.keyCode === 39 ) { _.once( this.nextTheme() ); } // The left arrow key, previous theme if ( event.keyCode === 37 ) { this.previousTheme(); } } }); // Controls the rendering of div.themes, // a wrapper that will hold all the theme elements themes.view.Themes = wp.Backbone.View.extend({ className: 'themes', $overlay: $( 'div.theme-overlay' ), // Number to keep track of scroll position // while in theme-overlay mode index: 0, // The theme count element count: $( '.theme-count' ), initialize: function( options ) { var self = this; // Set up parent this.parent = options.parent; // Set current view to [grid] this.setView( 'grid' ); // Move the active theme to the beginning of the collection self.currentTheme(); // When the collection is updated by user input... this.listenTo( self.collection, 'update', function() { self.parent.page = 0; self.currentTheme(); self.render( this ); }); // Update theme count to full result set when available. this.listenTo( self.collection, 'query:success', function( count ) { if ( _.isNumber( count ) ) { self.count.text( count ); } else { self.count.text( self.collection.length ); } }); this.listenTo( self.collection, 'query:empty', function() { $( 'body' ).addClass( 'no-results' ); }); this.listenTo( this.parent, 'theme:scroll', function() { self.renderThemes( self.parent.page ); }); this.listenTo( this.parent, 'theme:close', function() { if ( self.overlay ) { self.overlay.closeOverlay(); } } ); // Bind keyboard events. $( 'body' ).on( 'keyup', function( event ) { if ( ! self.overlay ) { return; } // Pressing the right arrow key fires a theme:next event if ( event.keyCode === 39 ) { self.overlay.nextTheme(); } // Pressing the left arrow key fires a theme:previous event if ( event.keyCode === 37 ) { self.overlay.previousTheme(); } // Pressing the escape key fires a theme:collapse event if ( event.keyCode === 27 ) { self.overlay.collapse( event ); } }); }, // Manages rendering of theme pages // and keeping theme count in sync render: function() { // Clear the DOM, please this.$el.html( '' ); // If the user doesn't have switch capabilities // or there is only one theme in the collection // render the detailed view of the active theme if ( themes.data.themes.length === 1 ) { // Constructs the view this.singleTheme = new themes.view.Details({ model: this.collection.models[0] }); // Render and apply a 'single-theme' class to our container this.singleTheme.render(); this.$el.addClass( 'single-theme' ); this.$el.append( this.singleTheme.el ); } // Generate the themes // Using page instance // While checking the collection has items if ( this.options.collection.size() > 0 ) { this.renderThemes( this.parent.page ); } // Display a live theme count for the collection this.count.text( this.collection.count ? this.collection.count : this.collection.length ); }, // Iterates through each instance of the collection // and renders each theme module renderThemes: function( page ) { var self = this; self.instance = self.collection.paginate( page ); // If we have no more themes bail if ( self.instance.size() === 0 ) { // Fire a no-more-themes event. this.parent.trigger( 'theme:end' ); return; } // Make sure the add-new stays at the end if ( page >= 1 ) { $( '.add-new-theme' ).remove(); } // Loop through the themes and setup each theme view self.instance.each( function( theme ) { self.theme = new themes.view.Theme({ model: theme, parent: self }); // Render the views... self.theme.render(); // and append them to div.themes self.$el.append( self.theme.el ); // Binds to theme:expand to show the modal box // with the theme details self.listenTo( self.theme, 'theme:expand', self.expand, self ); }); // 'Add new theme' element shown at the end of the grid if ( themes.data.settings.canInstall ) { this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h3 class="theme-name">' + l10n.addNew + '</h3></a></div>' ); } this.parent.page++; }, // Grabs current theme and puts it at the beginning of the collection currentTheme: function() { var self = this, current; current = self.collection.findWhere({ active: true }); // Move the active theme to the beginning of the collection if ( current ) { self.collection.remove( current ); self.collection.add( current, { at:0 } ); } }, // Sets current view setView: function( view ) { return view; }, // Renders the overlay with the ThemeDetails view // Uses the current model data expand: function( id ) { var self = this; // Set the current theme model this.model = self.collection.get( id ); // Trigger a route update for the current model themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.id ) ); // Sets this.view to 'detail' this.setView( 'detail' ); $( 'body' ).addClass( 'theme-overlay-open' ); // Set up the theme details view this.overlay = new themes.view.Details({ model: self.model }); this.overlay.render(); this.$overlay.html( this.overlay.el ); // Bind to theme:next and theme:previous // triggered by the arrow keys // // Keep track of the current model so we // can infer an index position this.listenTo( this.overlay, 'theme:next', function() { // Renders the next theme on the overlay self.next( [ self.model.cid ] ); }) .listenTo( this.overlay, 'theme:previous', function() { // Renders the previous theme on the overlay self.previous( [ self.model.cid ] ); }); }, // This method renders the next theme on the overlay modal // based on the current position in the collection // @params [model cid] next: function( args ) { var self = this, model, nextModel; // Get the current theme model = self.collection.get( args[0] ); // Find the next model within the collection nextModel = self.collection.at( self.collection.indexOf( model ) + 1 ); // Sanity check which also serves as a boundary test if ( nextModel !== undefined ) { // We have a new theme... // Close the overlay this.overlay.closeOverlay(); // Trigger a route update for the current model self.theme.trigger( 'theme:expand', nextModel.cid ); } }, // This method renders the previous theme on the overlay modal // based on the current position in the collection // @params [model cid] previous: function( args ) { var self = this, model, previousModel; // Get the current theme model = self.collection.get( args[0] ); // Find the previous model within the collection previousModel = self.collection.at( self.collection.indexOf( model ) - 1 ); if ( previousModel !== undefined ) { // We have a new theme... // Close the overlay this.overlay.closeOverlay(); // Trigger a route update for the current model self.theme.trigger( 'theme:expand', previousModel.cid ); } } }); // Search input view controller. themes.view.Search = wp.Backbone.View.extend({ tagName: 'input', className: 'theme-search', id: 'theme-search-input', searching: false, attributes: { placeholder: l10n.searchPlaceholder, type: 'search' }, events: { 'input': 'search', 'keyup': 'search', 'change': 'search', 'search': 'search', 'blur': 'pushState' }, initialize: function( options ) { this.parent = options.parent; this.listenTo( this.parent, 'theme:close', function() { this.searching = false; } ); }, // Runs a search on the theme collection. search: function( event ) { var options = {}; // Clear on escape. if ( event.type === 'keyup' && event.which === 27 ) { event.target.value = ''; } // Lose input focus when pressing enter if ( event.which === 13 ) { this.$el.trigger( 'blur' ); } this.collection.doSearch( event.target.value ); // if search is initiated and key is not return if ( this.searching && event.which !== 13 ) { options.replace = true; } else { this.searching = true; } // Update the URL hash if ( event.target.value ) { themes.router.navigate( themes.router.baseUrl( '?search=' + event.target.value ), options ); } else { themes.router.navigate( themes.router.baseUrl( '' ) ); } }, pushState: function( event ) { var url = themes.router.baseUrl( '' ); if ( event.target.value ) { url = themes.router.baseUrl( '?search=' + event.target.value ); } this.searching = false; themes.router.navigate( url ); } }); // Sets up the routes events for relevant url queries // Listens to [theme] and [search] params themes.Router = Backbone.Router.extend({ routes: { 'themes.php?theme=:slug': 'theme', 'themes.php?search=:query': 'search', 'themes.php?s=:query': 'search', 'themes.php': 'themes', '': 'themes' }, baseUrl: function( url ) { return 'themes.php' + url; }, search: function( query ) { $( '.theme-search' ).val( query ); }, themes: function() { $( '.theme-search' ).val( '' ); }, navigate: function() { if ( Backbone.history._hasPushState ) { Backbone.Router.prototype.navigate.apply( this, arguments ); } } }); // Execute and setup the application themes.Run = { init: function() { // Initializes the blog's theme library view // Create a new collection with data this.themes = new themes.Collection( themes.data.themes ); // Set up the view this.view = new themes.view.Appearance({ collection: this.themes }); this.render(); }, render: function() { // Render results this.view.render(); this.routes(); Backbone.history.start({ root: themes.data.settings.adminUrl, pushState: true, hashChange: false }); }, routes: function() { var self = this; // Bind to our global thx object // so that the object is available to sub-views themes.router = new themes.Router(); // Handles theme details route event themes.router.on( 'route:theme', function( slug ) { self.view.view.expand( slug ); }); themes.router.on( 'route:themes', function() { self.themes.doSearch( '' ); self.view.trigger( 'theme:close' ); }); // Handles search route event themes.router.on( 'route:search', function() { $( '.theme-search' ).trigger( 'keyup' ); }); this.extraRoutes(); }, extraRoutes: function() { return false; } }; // Extend the main Search view themes.view.InstallerSearch = themes.view.Search.extend({ events: { 'keyup': 'search' }, // Handles Ajax request for searching through themes in public repo search: function( event ) { // Tabbing or reverse tabbing into the search input shouldn't trigger a search if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) { return; } this.collection = this.options.parent.view.collection; // Clear on escape. if ( event.type === 'keyup' && event.which === 27 ) { event.target.value = ''; } _.debounce( _.bind( this.doSearch, this ), 300 )( event.target.value ); }, doSearch: _.debounce( function( value ) { var request = {}; request.search = value; // Intercept an [author] search. // // If input value starts with `author:` send a request // for `author` instead of a regular `search` if ( value.substring( 0, 7 ) === 'author:' ) { request.search = ''; request.author = value.slice( 7 ); } // Intercept a [tag] search. // // If input value starts with `tag:` send a request // for `tag` instead of a regular `search` if ( value.substring( 0, 4 ) === 'tag:' ) { request.search = ''; request.tag = [ value.slice( 4 ) ]; } $( '.theme-section.current' ).removeClass( 'current' ); $( 'body' ).removeClass( 'more-filters-opened filters-applied' ); // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache this.collection.query( request ); // Set route themes.router.navigate( themes.router.baseUrl( '?search=' + value ), { replace: true } ); }, 300 ) }); themes.view.Installer = themes.view.Appearance.extend({ el: '#wpbody-content .wrap', // Register events for sorting and filters in theme-navigation events: { 'click .theme-section': 'onSort', 'click .theme-filter': 'onFilter', 'click .more-filters': 'moreFilters', 'click .apply-filters': 'applyFilters', 'click [type="checkbox"]': 'addFilter', 'click .clear-filters': 'clearFilters', 'click .feature-name': 'filterSection', 'click .filtering-by a': 'backToFilters' }, // Initial render method render: function() { var self = this; this.search(); this.uploader(); this.collection = new themes.Collection(); // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page. this.listenTo( this, 'theme:end', function() { // Make sure we are not already loading if ( self.collection.loadingThemes ) { return; } // Set loadingThemes to true and bump page instance of currentQuery. self.collection.loadingThemes = true; self.collection.currentQuery.page++; // Use currentQuery.page to build the themes request. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } ); self.collection.query( self.collection.currentQuery.request ); }); this.listenTo( this.collection, 'query:success', function() { $( 'body' ).removeClass( 'loading-themes' ); $( '.theme-browser' ).find( 'div.error' ).remove(); }); this.listenTo( this.collection, 'query:fail', function() { $( 'body' ).removeClass( 'loading-themes' ); $( '.theme-browser' ).find( 'div.error' ).remove(); $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' ); }); if ( this.view ) { this.view.remove(); } // Set ups the view and passes the section argument this.view = new themes.view.Themes({ collection: this.collection, parent: this }); // Reset pagination every time the install view handler is run this.page = 0; // Render and append this.$el.find( '.themes' ).remove(); this.view.render(); this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' ); }, // Handles all the rendering of the public theme directory browse: function( section ) { // Create a new collection with the proper theme data // for each section this.collection.query( { browse: section } ); }, // Sorting navigation onSort: function( event ) { var $el = $( event.target ), sort = $el.data( 'sort' ); event.preventDefault(); $( 'body' ).removeClass( 'filters-applied more-filters-opened' ); // Bail if this is already active if ( $el.hasClass( this.activeClass ) ) { return; } this.sort( sort ); // Trigger a router.naviagte update themes.router.navigate( themes.router.baseUrl( '?browse=' + sort ) ); }, sort: function( sort ) { this.clearSearch(); $( '.theme-section, .theme-filter' ).removeClass( this.activeClass ); $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass ); this.browse( sort ); }, // Filters and Tags onFilter: function( event ) { var request, $el = $( event.target ), filter = $el.data( 'filter' ); // Bail if this is already active if ( $el.hasClass( this.activeClass ) ) { return; } $( '.theme-filter, .theme-section' ).removeClass( this.activeClass ); $el.addClass( this.activeClass ); if ( ! filter ) { return; } // Construct the filter request // using the default values filter = _.union( filter, this.filtersChecked() ); request = { tag: [ filter ] }; // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache this.collection.query( request ); }, // Clicking on a checkbox to add another filter to the request addFilter: function() { this.filtersChecked(); }, // Applying filters triggers a tag request applyFilters: function( event ) { var name, tags = this.filtersChecked(), request = { tag: tags }, filteringBy = $( '.filtering-by .tags' ); if ( event ) { event.preventDefault(); } $( 'body' ).addClass( 'filters-applied' ); $( '.theme-section.current' ).removeClass( 'current' ); filteringBy.empty(); _.each( tags, function( tag ) { name = $( 'label[for="feature-id-' + tag + '"]' ).text(); filteringBy.append( '<span class="tag">' + name + '</span>' ); }); // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache this.collection.query( request ); }, // Get the checked filters // @return {array} of tags or false filtersChecked: function() { var items = $( '.feature-group' ).find( ':checkbox' ), tags = []; _.each( items.filter( ':checked' ), function( item ) { tags.push( $( item ).prop( 'value' ) ); }); // When no filters are checked, restore initial state and return if ( tags.length === 0 ) { $( '.apply-filters' ).find( 'span' ).text( '' ); $( '.clear-filters' ).hide(); $( 'body' ).removeClass( 'filters-applied' ); return false; } $( '.apply-filters' ).find( 'span' ).text( tags.length ); $( '.clear-filters' ).css( 'display', 'inline-block' ); return tags; }, activeClass: 'current', // Overwrite search container class to append search // in new location searchContainer: $( '.theme-navigation' ), uploader: function() { $( 'a.upload' ).on( 'click', function( event ) { event.preventDefault(); $( 'body' ).addClass( 'show-upload-theme' ); themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } ); }); $( 'a.browse-themes' ).on( 'click', function( event ) { event.preventDefault(); $( 'body' ).removeClass( 'show-upload-theme' ); themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } ); }); }, // Toggle the full filters navigation moreFilters: function( event ) { event.preventDefault(); if ( $( 'body' ).hasClass( 'filters-applied' ) ) { return this.backToFilters(); } // If the filters section is opened and filters are checked // run the relevant query collapsing to filtered-by state if ( $( 'body' ).hasClass( 'more-filters-opened' ) && this.filtersChecked() ) { return this.addFilter(); } this.clearSearch(); themes.router.navigate( themes.router.baseUrl( '' ) ); $( 'body' ).toggleClass( 'more-filters-opened' ); }, // Expand/collapse each individual filter section filterSection: function() { $( event.target ).parent().toggleClass( 'open' ); }, // Clears all the checked filters // @uses filtersChecked() clearFilters: function( event ) { var items = $( '.feature-group' ).find( ':checkbox' ), self = this; event.preventDefault(); _.each( items.filter( ':checked' ), function( item ) { $( item ).prop( 'checked', false ); return self.filtersChecked(); }); }, backToFilters: function( event ) { if ( event ) { event.preventDefault(); } $( 'body' ).removeClass( 'filters-applied' ); }, clearSearch: function() { $( '#theme-search-input').val( '' ); } }); themes.InstallerRouter = Backbone.Router.extend({ routes: { 'theme-install.php?theme=:slug': 'preview', 'theme-install.php?browse=:sort': 'sort', 'theme-install.php?upload': 'upload', 'theme-install.php?search=:query': 'search', 'theme-install.php': 'sort' }, baseUrl: function( url ) { return 'theme-install.php' + url; }, search: function( query ) { $( '.theme-search' ).val( query ); }, navigate: function() { if ( Backbone.history._hasPushState ) { Backbone.Router.prototype.navigate.apply( this, arguments ); } } }); themes.RunInstaller = { init: function() { // Set up the view // Passes the default 'section' as an option this.view = new themes.view.Installer({ section: 'featured', SearchView: themes.view.InstallerSearch }); // Render results this.render(); }, render: function() { // Render results this.view.render(); this.routes(); Backbone.history.start({ root: themes.data.settings.adminUrl, pushState: true, hashChange: false }); }, routes: function() { var self = this, request = {}; // Bind to our global `wp.themes` object // so that the router is available to sub-views themes.router = new themes.InstallerRouter(); // Handles `theme` route event // Queries the API for the passed theme slug themes.router.on( 'route:preview', function( slug ) { request.theme = slug; self.view.collection.query( request ); }); // Handles sorting / browsing routes // Also handles the root URL triggering a sort request // for `featured`, the default view themes.router.on( 'route:sort', function( sort ) { if ( ! sort ) { sort = 'featured'; } self.view.sort( sort ); self.view.trigger( 'theme:close' ); }); // Support the `upload` route by going straight to upload section themes.router.on( 'route:upload', function() { $( 'a.upload' ).trigger( 'click' ); }); // The `search` route event. The router populates the input field. themes.router.on( 'route:search', function() { $( '.theme-search' ).focus().trigger( 'keyup' ); }); this.extraRoutes(); }, extraRoutes: function() { return false; } }; // Ready... $( document ).ready(function() { if ( themes.isInstall ) { themes.RunInstaller.init(); } else { themes.Run.init(); } }); })( jQuery ); // Align theme browser thickbox var tb_position; jQuery(document).ready( function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 1040 < width ) ? 1040 : width, adminbar_height = 0; if ( $('#wpadminbar').length ) { adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 ); } if ( tbWindow.size() ) { tbWindow.width( W - 50 ).height( H - 45 - adminbar_height ); $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height ); tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'}); if ( typeof document.body.style.maxWidth !== 'undefined' ) { tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'}); } } }; $(window).resize(function(){ tb_position(); }); });
JavaScript
/* global ajaxurl, wpAjax, tagsl10n, showNotice, validateForm */ jQuery(document).ready(function($) { $( '#the-list' ).on( 'click', '.delete-tag', function() { var t = $(this), tr = t.parents('tr'), r = true, data; if ( 'undefined' != showNotice ) r = showNotice.warn(); if ( r ) { data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag'); $.post(ajaxurl, data, function(r){ if ( '1' == r ) { $('#ajax-response').empty(); tr.fadeOut('normal', function(){ tr.remove(); }); // Remove the term from the parent box and tag cloud $('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove(); $('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove(); } else if ( '-1' == r ) { $('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>'); tr.children().css('backgroundColor', ''); } else { $('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>'); tr.children().css('backgroundColor', ''); } }); tr.children().css('backgroundColor', '#f33'); } return false; }); $('#submit').click(function(){ var form = $(this).parents('form'); if ( ! validateForm( form ) ) return false; $.post(ajaxurl, $('#addtag').serialize(), function(r){ var res, parent, term, indent, i; $('#ajax-response').empty(); res = wpAjax.parseAjaxResponse( r, 'ajax-response' ); if ( ! res || res.errors ) return; parent = form.find( 'select#parent' ).val(); if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list. $( '.tags #tag-' + parent ).after( res.responses[0].supplemental.noparents ); // As the parent exists, Insert the version with - - - prefixed else $( '.tags' ).prepend( res.responses[0].supplemental.parents ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm $('.tags .no-items').remove(); if ( form.find('select#parent') ) { // Parents field exists, Add new term to the list. term = res.responses[1].supplemental; // Create an indent for the Parent field indent = ''; for ( i = 0; i < res.responses[1].position; i++ ) indent += '&nbsp;&nbsp;&nbsp;'; form.find( 'select#parent option:selected' ).after( '<option value="' + term.term_id + '">' + indent + term.name + '</option>' ); } $('input[type="text"]:visible, textarea:visible', form).val(''); }); return false; }); });
JavaScript
/* global tinymce, tinyMCEPreInit, QTags, setUserSetting */ window.switchEditors = { switchto: function( el ) { var aid = el.id, l = aid.length, id = aid.substr( 0, l - 5 ), mode = aid.substr( l - 4 ); this.go( id, mode ); }, // mode can be 'html', 'tmce', or 'toggle'; 'html' is used for the 'Text' editor tab. go: function( id, mode ) { var t = this, ed, wrap_id, txtarea_el, iframe, editorHeight, toolbarHeight, DOM = tinymce.DOM; //DOMUtils outside the editor iframe id = id || 'content'; mode = mode || 'toggle'; ed = tinymce.get( id ); wrap_id = 'wp-' + id + '-wrap'; txtarea_el = DOM.get( id ); if ( 'toggle' === mode ) { if ( ed && ! ed.isHidden() ) { mode = 'html'; } else { mode = 'tmce'; } } function getToolbarHeight() { var node = DOM.select( '.mce-toolbar-grp', ed.getContainer() )[0], height = node && node.clientHeight; if ( height && height > 10 && height < 200 ) { return parseInt( height, 10 ); } return 30; } if ( 'tmce' === mode || 'tinymce' === mode ) { if ( ed && ! ed.isHidden() ) { return false; } if ( typeof( QTags ) !== 'undefined' ) { QTags.closeAllTags( id ); } editorHeight = txtarea_el ? parseInt( txtarea_el.style.height, 10 ) : 0; if ( tinyMCEPreInit.mceInit[ id ] && tinyMCEPreInit.mceInit[ id ].wpautop ) { txtarea_el.value = t.wpautop( txtarea_el.value ); } if ( ed ) { ed.show(); if ( editorHeight ) { toolbarHeight = getToolbarHeight(); editorHeight = editorHeight - toolbarHeight + 14; // height cannot be under 50 or over 5000 if ( editorHeight > 50 && editorHeight < 5000 ) { ed.theme.resizeTo( null, editorHeight ); } } } else { tinymce.init( tinyMCEPreInit.mceInit[id] ); } DOM.removeClass( wrap_id, 'html-active' ); DOM.addClass( wrap_id, 'tmce-active' ); setUserSetting( 'editor', 'tinymce' ); } else if ( 'html' === mode ) { if ( ed && ed.isHidden() ) { return false; } if ( ed ) { iframe = DOM.get( id + '_ifr' ); editorHeight = iframe ? parseInt( iframe.style.height, 10 ) : 0; if ( editorHeight ) { toolbarHeight = getToolbarHeight(); editorHeight = editorHeight + toolbarHeight - 14; // height cannot be under 50 or over 5000 if ( editorHeight > 50 && editorHeight < 5000 ) { txtarea_el.style.height = editorHeight + 'px'; } } ed.hide(); } else { // The TinyMCE instance doesn't exist, run the content through 'pre_wpautop()' and show the textarea if ( tinyMCEPreInit.mceInit[ id ] && tinyMCEPreInit.mceInit[ id ].wpautop ) { txtarea_el.value = t.pre_wpautop( txtarea_el.value ); } DOM.setStyles( txtarea_el, {'display': '', 'visibility': ''} ); } DOM.removeClass( wrap_id, 'tmce-active' ); DOM.addClass( wrap_id, 'html-active' ); setUserSetting( 'editor', 'html' ); } return false; }, _wp_Nop: function( content ) { var blocklist1, blocklist2, preserve_linebreaks = false, preserve_br = false; // Protect pre|script tags if ( content.indexOf( '<pre' ) !== -1 || content.indexOf( '<script' ) !== -1 ) { preserve_linebreaks = true; content = content.replace( /<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function( a ) { a = a.replace( /<br ?\/?>(\r\n|\n)?/g, '<wp-line-break>' ); a = a.replace( /<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>' ); return a.replace( /\r?\n/g, '<wp-line-break>' ); }); } // keep <br> tags inside captions and remove line breaks if ( content.indexOf( '[caption' ) !== -1 ) { preserve_br = true; content = content.replace( /\[caption[\s\S]+?\[\/caption\]/g, function( a ) { return a.replace( /<br([^>]*)>/g, '<wp-temp-br$1>' ).replace( /[\r\n\t]+/, '' ); }); } // Pretty it up for the source editor blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset'; content = content.replace( new RegExp( '\\s*</(' + blocklist1 + ')>\\s*', 'g' ), '</$1>\n' ); content = content.replace( new RegExp( '\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g' ), '\n<$1>' ); // Mark </p> if it has any attributes. content = content.replace( /(<p [^>]+>.*?)<\/p>/g, '$1</p#>' ); // Separate <div> containing <p> content = content.replace( /<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n' ); // Remove <p> and <br /> content = content.replace( /\s*<p>/gi, '' ); content = content.replace( /\s*<\/p>\s*/gi, '\n\n' ); content = content.replace( /\n[\s\u00a0]+\n/g, '\n\n' ); content = content.replace( /\s*<br ?\/?>\s*/gi, '\n' ); // Fix some block element newline issues content = content.replace( /\s*<div/g, '\n<div' ); content = content.replace( /<\/div>\s*/g, '</div>\n' ); content = content.replace( /\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n' ); content = content.replace( /caption\]\n\n+\[caption/g, 'caption]\n\n[caption' ); blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset'; content = content.replace( new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g' ), '\n<$1>' ); content = content.replace( new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g' ), '</$1>\n' ); content = content.replace( /<li([^>]*)>/g, '\t<li$1>' ); if ( content.indexOf( '<hr' ) !== -1 ) { content = content.replace( /\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n' ); } if ( content.indexOf( '<object' ) !== -1 ) { content = content.replace( /<object[\s\S]+?<\/object>/g, function( a ) { return a.replace( /[\r\n]+/g, '' ); }); } // Unmark special paragraph closing tags content = content.replace( /<\/p#>/g, '</p>\n' ); content = content.replace( /\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1' ); // Trim whitespace content = content.replace( /^\s+/, '' ); content = content.replace( /[\s\u00a0]+$/, '' ); // put back the line breaks in pre|script if ( preserve_linebreaks ) { content = content.replace( /<wp-line-break>/g, '\n' ); } // and the <br> tags in captions if ( preserve_br ) { content = content.replace( /<wp-temp-br([^>]*)>/g, '<br$1>' ); } return content; }, _wp_Autop: function(pee) { var preserve_linebreaks = false, preserve_br = false, blocklist = 'table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre' + '|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section' + '|article|aside|hgroup|header|footer|nav|figure|details|menu|summary'; if ( pee.indexOf( '<object' ) !== -1 ) { pee = pee.replace( /<object[\s\S]+?<\/object>/g, function( a ) { return a.replace( /[\r\n]+/g, '' ); }); } pee = pee.replace( /<[^<>]+>/g, function( a ){ return a.replace( /[\r\n]+/g, ' ' ); }); // Protect pre|script tags if ( pee.indexOf( '<pre' ) !== -1 || pee.indexOf( '<script' ) !== -1 ) { preserve_linebreaks = true; pee = pee.replace( /<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function( a ) { return a.replace( /(\r\n|\n)/g, '<wp-line-break>' ); }); } // keep <br> tags inside captions and convert line breaks if ( pee.indexOf( '[caption' ) !== -1 ) { preserve_br = true; pee = pee.replace( /\[caption[\s\S]+?\[\/caption\]/g, function( a ) { // keep existing <br> a = a.replace( /<br([^>]*)>/g, '<wp-temp-br$1>' ); // no line breaks inside HTML tags a = a.replace( /<[a-zA-Z0-9]+( [^<>]+)?>/g, function( b ) { return b.replace( /[\r\n\t]+/, ' ' ); }); // convert remaining line breaks to <br> return a.replace( /\s*\n\s*/g, '<wp-temp-br />' ); }); } pee = pee + '\n\n'; pee = pee.replace( /<br \/>\s*<br \/>/gi, '\n\n' ); pee = pee.replace( new RegExp( '(<(?:' + blocklist + ')(?: [^>]*)?>)', 'gi' ), '\n$1' ); pee = pee.replace( new RegExp( '(</(?:' + blocklist + ')>)', 'gi' ), '$1\n\n' ); pee = pee.replace( /<hr( [^>]*)?>/gi, '<hr$1>\n\n' ); // hr is self closing block element pee = pee.replace( /\r\n|\r/g, '\n' ); pee = pee.replace( /\n\s*\n+/g, '\n\n' ); pee = pee.replace( /([\s\S]+?)\n\n/g, '<p>$1</p>\n' ); pee = pee.replace( /<p>\s*?<\/p>/gi, ''); pee = pee.replace( new RegExp( '<p>\\s*(</?(?:' + blocklist + ')(?: [^>]*)?>)\\s*</p>', 'gi' ), '$1' ); pee = pee.replace( /<p>(<li.+?)<\/p>/gi, '$1'); pee = pee.replace( /<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>'); pee = pee.replace( /<\/blockquote>\s*<\/p>/gi, '</p></blockquote>'); pee = pee.replace( new RegExp( '<p>\\s*(</?(?:' + blocklist + ')(?: [^>]*)?>)', 'gi' ), '$1' ); pee = pee.replace( new RegExp( '(</?(?:' + blocklist + ')(?: [^>]*)?>)\\s*</p>', 'gi' ), '$1' ); pee = pee.replace( /\s*\n/gi, '<br />\n'); pee = pee.replace( new RegExp( '(</?(?:' + blocklist + ')[^>]*>)\\s*<br />', 'gi' ), '$1' ); pee = pee.replace( /<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1' ); pee = pee.replace( /(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]' ); pee = pee.replace( /(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function( a, b, c ) { if ( c.match( /<p( [^>]*)?>/ ) ) { return a; } return b + '<p>' + c + '</p>'; }); // put back the line breaks in pre|script if ( preserve_linebreaks ) { pee = pee.replace( /<wp-line-break>/g, '\n' ); } if ( preserve_br ) { pee = pee.replace( /<wp-temp-br([^>]*)>/g, '<br$1>' ); } return pee; }, pre_wpautop: function( content ) { var t = this, o = { o: t, data: content, unfiltered: content }, q = typeof( jQuery ) !== 'undefined'; if ( q ) { jQuery( 'body' ).trigger( 'beforePreWpautop', [ o ] ); } o.data = t._wp_Nop( o.data ); if ( q ) { jQuery('body').trigger('afterPreWpautop', [ o ] ); } return o.data; }, wpautop: function( pee ) { var t = this, o = { o: t, data: pee, unfiltered: pee }, q = typeof( jQuery ) !== 'undefined'; if ( q ) { jQuery( 'body' ).trigger('beforeWpautop', [ o ] ); } o.data = t._wp_Autop( o.data ); if ( q ) { jQuery( 'body' ).trigger('afterWpautop', [ o ] ); } return o.data; } };
JavaScript
/* global adminCommentsL10n, thousandsSeparator, list_args, QTags, ajaxurl, wpAjax */ var setCommentsList, theList, theExtraList, commentReply; (function($) { var getCount, updateCount, updatePending; setCommentsList = function() { var totalInput, perPageInput, pageInput, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList, diff, lastConfidentTime = 0; totalInput = $('input[name="_total"]', '#comments-form'); perPageInput = $('input[name="_per_page"]', '#comments-form'); pageInput = $('input[name="_page"]', '#comments-form'); dimAfter = function( r, settings ) { var editRow, replyID, replyButton, c = $( '#' + settings.element ); editRow = $('#replyrow'); replyID = $('#comment_ID', editRow).val(); replyButton = $('#replybtn', editRow); if ( c.is('.unapproved') ) { if ( settings.data.id == replyID ) replyButton.text(adminCommentsL10n.replyApprove); c.find('div.comment_status').html('0'); } else { if ( settings.data.id == replyID ) replyButton.text(adminCommentsL10n.reply); c.find('div.comment_status').html('1'); } diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1; updatePending( diff ); }; // Send current total, page, per_page and url delBefore = function( settings, list ) { var note, id, el, n, h, a, author, action = false, wpListsData = $( settings.target ).attr( 'data-wp-lists' ); settings.data._total = totalInput.val() || 0; settings.data._per_page = perPageInput.val() || 0; settings.data._page = pageInput.val() || 0; settings.data._url = document.location.href; settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val(); if ( wpListsData.indexOf(':trash=1') != -1 ) action = 'trash'; else if ( wpListsData.indexOf(':spam=1') != -1 ) action = 'spam'; if ( action ) { id = wpListsData.replace(/.*?comment-([0-9]+).*/, '$1'); el = $('#comment-' + id); note = $('#' + action + '-undo-holder').html(); el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits. if ( el.siblings('#replyrow').length && commentReply.cid == id ) commentReply.close(); if ( el.is('tr') ) { n = el.children(':visible').length; author = $('.author strong', el).text(); h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>'); } else { author = $('.comment-author', el).text(); h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>'); } el.before(h); $('strong', '#undo-' + id).text(author); a = $('.undo a', '#undo-' + id); a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce); a.attr('data-wp-lists', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1'); a.attr('class', 'vim-z vim-destructive'); $('.avatar', el).first().clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside'); a.click(function(){ list.wpList.del(this); $('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){ $(this).remove(); $('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show(); }); }); return false; }); } return settings; }; // Updates the current total (stored in the _total input) updateTotalCount = function( total, time, setConfidentTime ) { if ( time < lastConfidentTime ) return; if ( setConfidentTime ) lastConfidentTime = time; totalInput.val( total.toString() ); }; getCount = function(el) { var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 ); if ( isNaN(n) ) return 0; return n; }; updateCount = function(el, n) { var n1 = ''; if ( isNaN(n) ) return; n = n < 1 ? '0' : n.toString(); if ( n.length > 3 ) { while ( n.length > 3 ) { n1 = thousandsSeparator + n.substr(n.length - 3) + n1; n = n.substr(0, n.length - 3); } n = n + n1; } el.html(n); }; updatePending = function( diff ) { $('span.pending-count').each(function() { var a = $(this), n = getCount(a) + diff; if ( n < 1 ) n = 0; a.closest('.awaiting-mod')[ 0 === n ? 'addClass' : 'removeClass' ]('count-0'); updateCount( a, n ); }); }; // In admin-ajax.php, we send back the unix time stamp instead of 1 on success delAfter = function( r, settings ) { var total_items_i18n, total, spam, trash, pending, untrash = $(settings.target).parent().is('span.untrash'), unspam = $(settings.target).parent().is('span.unspam'), unapproved = $('#' + settings.element).is('.unapproved'); function getUpdate(s) { if ( $(settings.target).parent().is('span.' + s) ) return 1; else if ( $('#' + settings.element).is('.' + s) ) return -1; return 0; } if ( untrash ) trash = -1; else trash = getUpdate('trash'); if ( unspam ) spam = -1; else spam = getUpdate('spam'); if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) { // a comment was 'deleted' from another list (e.g. approved, spam, trash) and moved to pending, // or a trash/spam of a pending comment was undone pending = 1; } else if ( unapproved ) { // a pending comment was trashed/spammed/approved pending = -1; } if ( pending ) updatePending(pending); $('span.spam-count').each( function() { var a = $(this), n = getCount(a) + spam; updateCount(a, n); }); $('span.trash-count').each( function() { var a = $(this), n = getCount(a) + trash; updateCount(a, n); }); if ( ! $('#dashboard_right_now').length ) { total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0; if ( $(settings.target).parent().is('span.undo') ) total++; else total--; if ( total < 0 ) total = 0; if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) { total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || ''; if ( total_items_i18n ) { $('.displaying-num').text( total_items_i18n ); $('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n ); $('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val()); } updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true ); } else { updateTotalCount( total, r, false ); } } if ( ! theExtraList || theExtraList.size() === 0 || theExtraList.children().size() === 0 || untrash || unspam ) { return; } theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() ); refillTheExtraList(); }; refillTheExtraList = function(ev) { var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val(); if (! args.paged) args.paged = 1; if (args.paged > total_pages) { return; } if (ev) { theExtraList.empty(); args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php } else { args.number = 1; args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list } args.no_placeholder = true; args.paged ++; // $.query.get() needs some correction to be sent into an ajax request if ( true === args.comment_type ) args.comment_type = ''; args = $.extend(args, { 'action': 'fetch-list', 'list_args': list_args, '_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val() }); $.ajax({ url: ajaxurl, global: false, dataType: 'json', data: args, success: function(response) { theExtraList.get(0).wpList.add( response.rows ); } }); }; theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } ); theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } ) .bind('wpListDelEnd', function(e, s){ var wpListsData = $(s.target).attr('data-wp-lists'), id = s.element.replace(/[^0-9]+/g, ''); if ( wpListsData.indexOf(':trash=1') != -1 || wpListsData.indexOf(':spam=1') != -1 ) $('#undo-' + id).fadeIn(300, function(){ $(this).show(); }); }); }; commentReply = { cid : '', act : '', init : function() { var row = $('#replyrow'); $('a.cancel', row).click(function() { return commentReply.revert(); }); $('a.save', row).click(function() { return commentReply.send(); }); $('input#author, input#author-email, input#author-url', row).keypress(function(e){ if ( e.which == 13 ) { commentReply.send(); e.preventDefault(); return false; } }); // add events $('#the-comment-list .column-comment > p').dblclick(function(){ commentReply.toggle($(this).parent()); }); $('#doaction, #doaction2, #post-query-submit').click(function(){ if ( $('#the-comment-list #replyrow').length > 0 ) commentReply.close(); }); this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || ''; /* $(listTable).bind('beforeChangePage', function(){ commentReply.close(); }); */ }, addEvents : function(r) { r.each(function() { $(this).find('.column-comment > p').dblclick(function(){ commentReply.toggle($(this).parent()); }); }); }, toggle : function(el) { if ( $(el).css('display') != 'none' ) $(el).find('a.vim-q').click(); }, revert : function() { if ( $('#the-comment-list #replyrow').length < 1 ) return false; $('#replyrow').fadeOut('fast', function(){ commentReply.close(); }); return false; }, close : function() { var c, replyrow = $('#replyrow'); // replyrow is not showing? if ( replyrow.parent().is('#com-reply') ) return; if ( this.cid && this.act == 'edit-comment' ) { c = $('#comment-' + this.cid); c.fadeIn(300, function(){ c.show(); }).css('backgroundColor', ''); } // reset the Quicktags buttons if ( typeof QTags != 'undefined' ) QTags.closeAllTags('replycontent'); $('#add-new-comment').css('display', ''); replyrow.hide(); $('#com-reply').append( replyrow ); $('#replycontent').css('height', '').val(''); $('#edithead input').val(''); $('.error', replyrow).html('').hide(); $('.spinner', replyrow).hide(); this.cid = ''; }, open : function(comment_id, post_id, action) { var editRow, rowData, act, replyButton, editHeight, t = this, c = $('#comment-' + comment_id), h = c.height(); t.close(); t.cid = comment_id; editRow = $('#replyrow'); rowData = $('#inline-'+comment_id); action = action || 'replyto'; act = 'edit' == action ? 'edit' : 'replyto'; act = t.act = act + '-comment'; $('#action', editRow).val(act); $('#comment_post_ID', editRow).val(post_id); $('#comment_ID', editRow).val(comment_id); if ( action == 'edit' ) { $('#author', editRow).val( $('div.author', rowData).text() ); $('#author-email', editRow).val( $('div.author-email', rowData).text() ); $('#author-url', editRow).val( $('div.author-url', rowData).text() ); $('#status', editRow).val( $('div.comment_status', rowData).text() ); $('#replycontent', editRow).val( $('textarea.comment', rowData).val() ); $('#edithead, #savebtn', editRow).show(); $('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide(); if ( h > 120 ) { // Limit the maximum height when editing very long comments to make it more manageable. // The textarea is resizable in most browsers, so the user can adjust it if needed. editHeight = h > 500 ? 500 : h; $('#replycontent', editRow).css('height', editHeight + 'px'); } c.after( editRow ).fadeOut('fast', function(){ $('#replyrow').fadeIn(300, function(){ $(this).show(); }); }); } else if ( action == 'add' ) { $('#addhead, #addbtn', editRow).show(); $('#replyhead, #replybtn, #edithead, #editbtn', editRow).hide(); $('#the-comment-list').prepend(editRow); $('#replyrow').fadeIn(300); } else { replyButton = $('#replybtn', editRow); $('#edithead, #savebtn, #addhead, #addbtn', editRow).hide(); $('#replyhead, #replybtn', editRow).show(); c.after(editRow); if ( c.hasClass('unapproved') ) { replyButton.text(adminCommentsL10n.replyApprove); } else { replyButton.text(adminCommentsL10n.reply); } $('#replyrow').fadeIn(300, function(){ $(this).show(); }); } setTimeout(function() { var rtop, rbottom, scrollTop, vp, scrollBottom; rtop = $('#replyrow').offset().top; rbottom = rtop + $('#replyrow').height(); scrollTop = window.pageYOffset || document.documentElement.scrollTop; vp = document.documentElement.clientHeight || window.innerHeight || 0; scrollBottom = scrollTop + vp; if ( scrollBottom - 20 < rbottom ) window.scroll(0, rbottom - vp + 35); else if ( rtop - 20 < scrollTop ) window.scroll(0, rtop - 35); $('#replycontent').focus().keyup(function(e){ if ( e.which == 27 ) commentReply.revert(); // close on Escape }); }, 600); return false; }, send : function() { var post = {}; $('#replysubmit .error').hide(); $('#replysubmit .spinner').show(); $('#replyrow input').not(':button').each(function() { var t = $(this); post[ t.attr('name') ] = t.val(); }); post.content = $('#replycontent').val(); post.id = post.comment_post_ID; post.comments_listing = this.comments_listing; post.p = $('[name="p"]').val(); if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') ) post.approve_parent = 1; $.ajax({ type : 'POST', url : ajaxurl, data : post, success : function(x) { commentReply.show(x); }, error : function(r) { commentReply.error(r); } }); return false; }, show : function(xml) { var t = this, r, c, id, bg, pid; if ( typeof(xml) == 'string' ) { t.error({'responseText': xml}); return false; } r = wpAjax.parseAjaxResponse(xml); if ( r.errors ) { t.error({'responseText': wpAjax.broken}); return false; } t.revert(); r = r.responses[0]; id = '#comment-' + r.id; if ( 'edit-comment' == t.act ) $(id).remove(); if ( r.supplemental.parent_approved ) { pid = $('#comment-' + r.supplemental.parent_approved); updatePending( -1 ); if ( this.comments_listing == 'moderated' ) { pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){ pid.fadeOut(); }); return; } } c = $.trim(r.data); // Trim leading whitespaces $(c).hide(); $('#replyrow').after(c); id = $(id); t.addEvents(id); bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor'); id.animate( { 'backgroundColor':'#CCEEBB' }, 300 ) .animate( { 'backgroundColor': bg }, 300, function() { if ( pid && pid.length ) { pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 ) .animate( { 'backgroundColor': bg }, 300 ) .removeClass('unapproved').addClass('approved') .find('div.comment_status').html('1'); } }); }, error : function(r) { var er = r.statusText; $('#replysubmit .spinner').hide(); if ( r.responseText ) er = r.responseText.replace( /<.[^<>]*?>/g, '' ); if ( er ) $('#replysubmit .error').html(er).show(); }, addcomment: function(post_id) { var t = this; $('#add-new-comment').fadeOut(200, function(){ t.open(0, post_id, 'add'); $('table.comments-box').css('display', ''); $('#no-comments').remove(); }); } }; $(document).ready(function(){ var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk; setCommentsList(); commentReply.init(); $(document).delegate('span.delete a.delete', 'click', function(){return false;}); if ( typeof $.table_hotkeys != 'undefined' ) { make_hotkeys_redirect = function(which) { return function() { var first_last, l; first_last = 'next' == which? 'first' : 'last'; l = $('.tablenav-pages .'+which+'-page:not(.disabled)'); if (l.length) window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1'; }; }; edit_comment = function(event, current_row) { window.location = $('span.edit a', current_row).attr('href'); }; toggle_all = function() { $('#cb-select-all-1').data( 'wp-toggle', 1 ).trigger( 'click' ).removeData( 'wp-toggle' ); }; make_bulk = function(value) { return function() { var scope = $('select[name="action"]'); $('option[value="' + value + '"]', scope).prop('selected', true); $('#doaction').click(); }; }; $.table_hotkeys( $('table.widefat'), [ 'a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all], ['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')], ['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')], ['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')] ], { highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last, prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next'), hotkeys_opts: { disableInInput: true, type: 'keypress', noDisable: '.check-column input[type="checkbox"]' } } ); } }); })(jQuery);
JavaScript
/** * Attempt to re-color SVG icons used in the admin menu or the toolbar * */ window.wp = window.wp || {}; wp.svgPainter = ( function( $, window, document, undefined ) { 'use strict'; var selector, base64, painter, colorscheme = {}, elements = []; $(document).ready( function() { // detection for browser SVG capability if ( document.implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#Image', '1.1' ) ) { $( document.body ).removeClass( 'no-svg' ).addClass( 'svg' ); wp.svgPainter.init(); } }); /** * Needed only for IE9 * * Based on jquery.base64.js 0.0.3 - https://github.com/yckart/jquery.base64.js * * Based on: https://gist.github.com/Yaffle/1284012 * * Copyright (c) 2012 Yannick Albert (http://yckart.com) * Licensed under the MIT license * http://www.opensource.org/licenses/mit-license.php */ base64 = ( function() { var c, b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', a256 = '', r64 = [256], r256 = [256], i = 0; function init() { while( i < 256 ) { c = String.fromCharCode(i); a256 += c; r256[i] = i; r64[i] = b64.indexOf(c); ++i; } } function code( s, discard, alpha, beta, w1, w2 ) { var tmp, length, buffer = 0, i = 0, result = '', bitsInBuffer = 0; s = String(s); length = s.length; while( i < length ) { c = s.charCodeAt(i); c = c < 256 ? alpha[c] : -1; buffer = ( buffer << w1 ) + c; bitsInBuffer += w1; while( bitsInBuffer >= w2 ) { bitsInBuffer -= w2; tmp = buffer >> bitsInBuffer; result += beta.charAt(tmp); buffer ^= tmp << bitsInBuffer; } ++i; } if ( ! discard && bitsInBuffer > 0 ) { result += beta.charAt( buffer << ( w2 - bitsInBuffer ) ); } return result; } function btoa( plain ) { if ( ! c ) { init(); } plain = code( plain, false, r256, b64, 8, 6 ); return plain + '===='.slice( ( plain.length % 4 ) || 4 ); } function atob( coded ) { var i; if ( ! c ) { init(); } coded = coded.replace( /[^A-Za-z0-9\+\/\=]/g, '' ); coded = String(coded).split('='); i = coded.length; do { --i; coded[i] = code( coded[i], true, r64, a256, 6, 8 ); } while ( i > 0 ); coded = coded.join(''); return coded; } return { atob: atob, btoa: btoa }; })(); return { init: function() { painter = this; selector = $( '#adminmenu .wp-menu-image, #wpadminbar .ab-item' ); this.setColors(); this.findElements(); this.paint(); }, setColors: function( colors ) { if ( typeof colors === 'undefined' && typeof window._wpColorScheme !== 'undefined' ) { colors = window._wpColorScheme; } if ( colors && colors.icons && colors.icons.base && colors.icons.current && colors.icons.focus ) { colorscheme = colors.icons; } }, findElements: function() { selector.each( function() { var $this = $(this), bgImage = $this.css( 'background-image' ); if ( bgImage && bgImage.indexOf( 'data:image/svg+xml;base64' ) != -1 ) { elements.push( $this ); } }); }, paint: function() { // loop through all elements $.each( elements, function( index, $element ) { var $menuitem = $element.parent().parent(); if ( $menuitem.hasClass( 'current' ) || $menuitem.hasClass( 'wp-has-current-submenu' ) ) { // paint icon in 'current' color painter.paintElement( $element, 'current' ); } else { // paint icon in base color painter.paintElement( $element, 'base' ); // set hover callbacks $menuitem.hover( function() { painter.paintElement( $element, 'focus' ); }, function() { // Match the delay from hoverIntent window.setTimeout( function() { painter.paintElement( $element, 'base' ); }, 100 ); } ); } }); }, paintElement: function( $element, colorType ) { var xml, encoded, color; if ( ! colorType || ! colorscheme.hasOwnProperty( colorType ) ) { return; } color = colorscheme[ colorType ]; // only accept hex colors: #101 or #101010 if ( ! color.match( /^(#[0-9a-f]{3}|#[0-9a-f]{6})$/i ) ) { return; } xml = $element.data( 'wp-ui-svg-' + color ); if ( xml === 'none' ) { return; } if ( ! xml ) { encoded = $element.css( 'background-image' ).match( /.+data:image\/svg\+xml;base64,([A-Za-z0-9\+\/\=]+)/ ); if ( ! encoded || ! encoded[1] ) { $element.data( 'wp-ui-svg-' + color, 'none' ); return; } try { if ( 'atob' in window ) { xml = window.atob( encoded[1] ); } else { xml = base64.atob( encoded[1] ); } } catch ( error ) {} if ( xml ) { // replace `fill` attributes xml = xml.replace( /fill="(.+?)"/g, 'fill="' + color + '"'); // replace `style` attributes xml = xml.replace( /style="(.+?)"/g, 'style="fill:' + color + '"'); // replace `fill` properties in `<style>` tags xml = xml.replace( /fill:.*?;/g, 'fill: ' + color + ';'); if ( 'btoa' in window ) { xml = window.btoa( xml ); } else { xml = base64.btoa( xml ); } $element.data( 'wp-ui-svg-' + color, xml ); } else { $element.data( 'wp-ui-svg-' + color, 'none' ); return; } } $element.attr( 'style', 'background-image: url("data:image/svg+xml;base64,' + xml + '") !important;' ); } }; })( jQuery, window, document );
JavaScript
jQuery( document ).ready(function( $ ) { $( '#link_rel' ).prop( 'readonly', true ); $( '#linkxfndiv input' ).bind( 'click keyup', function() { var isMe = $( '#me' ).is( ':checked' ), inputs = ''; $( 'input.valinp' ).each( function() { if ( isMe ) { $( this ).prop( 'disabled', true ).parent().addClass( 'disabled' ); } else { $( this ).removeAttr( 'disabled' ).parent().removeClass( 'disabled' ); if ( $( this ).is( ':checked' ) && $( this ).val() !== '') { inputs += $( this ).val() + ' '; } } }); $( '#link_rel' ).val( ( isMe ) ? 'me' : inputs.substr( 0,inputs.length - 1 ) ); }); });
JavaScript
/* globals _wpCustomizeHeader, _wpMediaViewsL10n */ (function( exports, $ ){ var api = wp.customize; /** * @param options * - previewer - The Previewer instance to sync with. * - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'. */ api.Setting = api.Value.extend({ initialize: function( id, value, options ) { api.Value.prototype.initialize.call( this, value, options ); this.id = id; this.transport = this.transport || 'refresh'; this.bind( this.preview ); }, preview: function() { switch ( this.transport ) { case 'refresh': return this.previewer.refresh(); case 'postMessage': return this.previewer.send( 'setting', [ this.id, this() ] ); } } }); api.Control = api.Class.extend({ initialize: function( id, options ) { var control = this, nodes, radios, settings; this.params = {}; $.extend( this, options || {} ); this.id = id; this.selector = '#customize-control-' + id.replace( /\]/g, '' ).replace( /\[/g, '-' ); this.container = $( this.selector ); settings = $.map( this.params.settings, function( value ) { return value; }); api.apply( api, settings.concat( function() { var key; control.settings = {}; for ( key in control.params.settings ) { control.settings[ key ] = api( control.params.settings[ key ] ); } control.setting = control.settings['default'] || null; control.ready(); }) ); control.elements = []; nodes = this.container.find('[data-customize-setting-link]'); radios = {}; nodes.each( function() { var node = $(this), name; if ( node.is(':radio') ) { name = node.prop('name'); if ( radios[ name ] ) return; radios[ name ] = true; node = nodes.filter( '[name="' + name + '"]' ); } api( node.data('customizeSettingLink'), function( setting ) { var element = new api.Element( node ); control.elements.push( element ); element.sync( setting ); element.set( setting() ); }); }); }, ready: function() {}, dropdownInit: function() { var control = this, statuses = this.container.find('.dropdown-status'), params = this.params, toggleFreeze = false, update = function( to ) { if ( typeof to === 'string' && params.statuses && params.statuses[ to ] ) statuses.html( params.statuses[ to ] ).show(); else statuses.hide(); }; // Support the .dropdown class to open/close complex elements this.container.on( 'click keydown', '.dropdown', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; event.preventDefault(); if (!toggleFreeze) control.container.toggleClass('open'); if ( control.container.hasClass('open') ) control.container.parent().parent().find('li.library-selected').focus(); // Don't want to fire focus and click at same time toggleFreeze = true; setTimeout(function () { toggleFreeze = false; }, 400); }); this.setting.bind( update ); update( this.setting() ); } }); api.ColorControl = api.Control.extend({ ready: function() { var control = this, picker = this.container.find('.color-picker-hex'); picker.val( control.setting() ).wpColorPicker({ change: function() { control.setting.set( picker.wpColorPicker('color') ); }, clear: function() { control.setting.set( false ); } }); } }); api.UploadControl = api.Control.extend({ ready: function() { var control = this; this.params.removed = this.params.removed || ''; this.success = $.proxy( this.success, this ); this.uploader = $.extend({ container: this.container, browser: this.container.find('.upload'), dropzone: this.container.find('.upload-dropzone'), success: this.success, plupload: {}, params: {} }, this.uploader || {} ); if ( control.params.extensions ) { control.uploader.plupload.filters = [{ title: api.l10n.allowedFiles, extensions: control.params.extensions }]; } if ( control.params.context ) control.uploader.params['post_data[context]'] = this.params.context; if ( api.settings.theme.stylesheet ) control.uploader.params['post_data[theme]'] = api.settings.theme.stylesheet; this.uploader = new wp.Uploader( this.uploader ); this.remover = this.container.find('.remove'); this.remover.on( 'click keydown', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; control.setting.set( control.params.removed ); event.preventDefault(); }); this.removerVisibility = $.proxy( this.removerVisibility, this ); this.setting.bind( this.removerVisibility ); this.removerVisibility( this.setting.get() ); }, success: function( attachment ) { this.setting.set( attachment.get('url') ); }, removerVisibility: function( to ) { this.remover.toggle( to != this.params.removed ); } }); api.ImageControl = api.UploadControl.extend({ ready: function() { var control = this, panels; this.uploader = { init: function() { var fallback, button; if ( this.supports.dragdrop ) return; // Maintain references while wrapping the fallback button. fallback = control.container.find( '.upload-fallback' ); button = fallback.children().detach(); this.browser.detach().empty().append( button ); fallback.append( this.browser ).show(); } }; api.UploadControl.prototype.ready.call( this ); this.thumbnail = this.container.find('.preview-thumbnail img'); this.thumbnailSrc = $.proxy( this.thumbnailSrc, this ); this.setting.bind( this.thumbnailSrc ); this.library = this.container.find('.library'); // Generate tab objects this.tabs = {}; panels = this.library.find('.library-content'); this.library.children('ul').children('li').each( function() { var link = $(this), id = link.data('customizeTab'), panel = panels.filter('[data-customize-tab="' + id + '"]'); control.tabs[ id ] = { both: link.add( panel ), link: link, panel: panel }; }); // Bind tab switch events this.library.children('ul').on( 'click keydown', 'li', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; var id = $(this).data('customizeTab'), tab = control.tabs[ id ]; event.preventDefault(); if ( tab.link.hasClass('library-selected') ) return; control.selected.both.removeClass('library-selected'); control.selected = tab; control.selected.both.addClass('library-selected'); }); // Bind events to switch image urls. this.library.on( 'click keydown', 'a', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; var value = $(this).data('customizeImageValue'); if ( value ) { control.setting.set( value ); event.preventDefault(); } }); if ( this.tabs.uploaded ) { this.tabs.uploaded.target = this.library.find('.uploaded-target'); if ( ! this.tabs.uploaded.panel.find('.thumbnail').length ) this.tabs.uploaded.both.addClass('hidden'); } // Select a tab panels.each( function() { var tab = control.tabs[ $(this).data('customizeTab') ]; // Select the first visible tab. if ( ! tab.link.hasClass('hidden') ) { control.selected = tab; tab.both.addClass('library-selected'); return false; } }); this.dropdownInit(); }, success: function( attachment ) { api.UploadControl.prototype.success.call( this, attachment ); // Add the uploaded image to the uploaded tab. if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) { this.tabs.uploaded.both.removeClass('hidden'); // @todo: Do NOT store this on the attachment model. That is bad. attachment.element = $( '<a href="#" class="thumbnail"></a>' ) .data( 'customizeImageValue', attachment.get('url') ) .append( '<img src="' + attachment.get('url')+ '" />' ) .appendTo( this.tabs.uploaded.target ); } }, thumbnailSrc: function( to ) { if ( /^(https?:)?\/\//.test( to ) ) this.thumbnail.prop( 'src', to ).show(); else this.thumbnail.hide(); } }); api.HeaderControl = api.Control.extend({ ready: function() { this.btnRemove = $('.actions .remove'); this.btnNew = $('.actions .new'); _.bindAll(this, 'openMedia', 'removeImage'); this.btnNew.on( 'click', this.openMedia ); this.btnRemove.on( 'click', this.removeImage ); api.HeaderTool.currentHeader = new api.HeaderTool.ImageModel(); new api.HeaderTool.CurrentView({ model: api.HeaderTool.currentHeader, el: '.current .container' }); new api.HeaderTool.ChoiceListView({ collection: api.HeaderTool.UploadsList = new api.HeaderTool.ChoiceList(), el: '.choices .uploaded .list' }); new api.HeaderTool.ChoiceListView({ collection: api.HeaderTool.DefaultsList = new api.HeaderTool.DefaultsList(), el: '.choices .default .list' }); api.HeaderTool.combinedList = api.HeaderTool.CombinedList = new api.HeaderTool.CombinedList([ api.HeaderTool.UploadsList, api.HeaderTool.DefaultsList ]); }, /** * Returns a set of options, computed from the attached image data and * theme-specific data, to be fed to the imgAreaSelect plugin in * wp.media.view.Cropper. * * @param {wp.media.model.Attachment} attachment * @param {wp.media.controller.Cropper} controller * @returns {Object} Options */ calculateImageSelectOptions: function(attachment, controller) { var xInit = parseInt(_wpCustomizeHeader.data.width, 10), yInit = parseInt(_wpCustomizeHeader.data.height, 10), flexWidth = !! parseInt(_wpCustomizeHeader.data['flex-width'], 10), flexHeight = !! parseInt(_wpCustomizeHeader.data['flex-height'], 10), ratio, xImg, yImg, realHeight, realWidth, imgSelectOptions; realWidth = attachment.get('width'); realHeight = attachment.get('height'); this.headerImage = new api.HeaderTool.ImageModel(); this.headerImage.set({ themeWidth: xInit, themeHeight: yInit, themeFlexWidth: flexWidth, themeFlexHeight: flexHeight, imageWidth: realWidth, imageHeight: realHeight }); controller.set( 'canSkipCrop', ! this.headerImage.shouldBeCropped() ); ratio = xInit / yInit; xImg = realWidth; yImg = realHeight; if ( xImg / yImg > ratio ) { yInit = yImg; xInit = yInit * ratio; } else { xInit = xImg; yInit = xInit / ratio; } imgSelectOptions = { handles: true, keys: true, instance: true, persistent: true, imageWidth: realWidth, imageHeight: realHeight, x1: 0, y1: 0, x2: xInit, y2: yInit }; if (flexHeight === false && flexWidth === false) { imgSelectOptions.aspectRatio = xInit + ':' + yInit; } if (flexHeight === false ) { imgSelectOptions.maxHeight = yInit; } if (flexWidth === false ) { imgSelectOptions.maxWidth = xInit; } return imgSelectOptions; }, /** * Sets up and opens the Media Manager in order to select an image. * Depending on both the size of the image and the properties of the * current theme, a cropping step after selection may be required or * skippable. * * @param {event} event */ openMedia: function(event) { var l10n = _wpMediaViewsL10n; event.preventDefault(); this.frame = wp.media({ button: { text: l10n.selectAndCrop, close: false }, states: [ new wp.media.controller.Library({ title: l10n.chooseImage, library: wp.media.query({ type: 'image' }), multiple: false, priority: 20, suggestedWidth: _wpCustomizeHeader.data.width, suggestedHeight: _wpCustomizeHeader.data.height }), new wp.media.controller.Cropper({ imgSelectOptions: this.calculateImageSelectOptions }) ] }); this.frame.on('select', this.onSelect, this); this.frame.on('cropped', this.onCropped, this); this.frame.on('skippedcrop', this.onSkippedCrop, this); this.frame.open(); }, onSelect: function() { this.frame.setState('cropper'); }, onCropped: function(croppedImage) { var url = croppedImage.post_content, attachmentId = croppedImage.attachment_id, w = croppedImage.width, h = croppedImage.height; this.setImageFromURL(url, attachmentId, w, h); }, onSkippedCrop: function(selection) { var url = selection.get('url'), w = selection.get('width'), h = selection.get('height'); this.setImageFromURL(url, selection.id, w, h); }, /** * Creates a new wp.customize.HeaderTool.ImageModel from provided * header image data and inserts it into the user-uploaded headers * collection. * * @param {String} url * @param {Number} attachmentId * @param {Number} width * @param {Number} height */ setImageFromURL: function(url, attachmentId, width, height) { var choice, data = {}; data.url = url; data.thumbnail_url = url; data.timestamp = _.now(); if (attachmentId) { data.attachment_id = attachmentId; } if (width) { data.width = width; } if (height) { data.height = height; } choice = new api.HeaderTool.ImageModel({ header: data, choice: url.split('/').pop() }); api.HeaderTool.UploadsList.add(choice); api.HeaderTool.currentHeader.set(choice.toJSON()); choice.save(); choice.importImage(); }, /** * Triggers the necessary events to deselect an image which was set as * the currently selected one. */ removeImage: function() { api.HeaderTool.currentHeader.trigger('hide'); api.HeaderTool.CombinedList.trigger('control:removeImage'); } }); // Change objects contained within the main customize object to Settings. api.defaultConstructor = api.Setting; // Create the collection of Control objects. api.control = new api.Values({ defaultConstructor: api.Control }); api.PreviewFrame = api.Messenger.extend({ sensitivity: 2000, initialize: function( params, options ) { var deferred = $.Deferred(); // This is the promise object. deferred.promise( this ); this.container = params.container; this.signature = params.signature; $.extend( params, { channel: api.PreviewFrame.uuid() }); api.Messenger.prototype.initialize.call( this, params, options ); this.add( 'previewUrl', params.previewUrl ); this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() }); this.run( deferred ); }, run: function( deferred ) { var self = this, loaded = false, ready = false; if ( this._ready ) this.unbind( 'ready', this._ready ); this._ready = function() { ready = true; if ( loaded ) deferred.resolveWith( self ); }; this.bind( 'ready', this._ready ); this.request = $.ajax( this.previewUrl(), { type: 'POST', data: this.query, xhrFields: { withCredentials: true } } ); this.request.fail( function() { deferred.rejectWith( self, [ 'request failure' ] ); }); this.request.done( function( response ) { var location = self.request.getResponseHeader('Location'), signature = self.signature, index; // Check if the location response header differs from the current URL. // If so, the request was redirected; try loading the requested page. if ( location && location != self.previewUrl() ) { deferred.rejectWith( self, [ 'redirect', location ] ); return; } // Check if the user is not logged in. if ( '0' === response ) { self.login( deferred ); return; } // Check for cheaters. if ( '-1' === response ) { deferred.rejectWith( self, [ 'cheatin' ] ); return; } // Check for a signature in the request. index = response.lastIndexOf( signature ); if ( -1 === index || index < response.lastIndexOf('</html>') ) { deferred.rejectWith( self, [ 'unsigned' ] ); return; } // Strip the signature from the request. response = response.slice( 0, index ) + response.slice( index + signature.length ); // Create the iframe and inject the html content. self.iframe = $('<iframe />').appendTo( self.container ); // Bind load event after the iframe has been added to the page; // otherwise it will fire when injected into the DOM. self.iframe.one( 'load', function() { loaded = true; if ( ready ) { deferred.resolveWith( self ); } else { setTimeout( function() { deferred.rejectWith( self, [ 'ready timeout' ] ); }, self.sensitivity ); } }); self.targetWindow( self.iframe[0].contentWindow ); self.targetWindow().document.open(); self.targetWindow().document.write( response ); self.targetWindow().document.close(); }); }, login: function( deferred ) { var self = this, reject; reject = function() { deferred.rejectWith( self, [ 'logged out' ] ); }; if ( this.triedLogin ) return reject(); // Check if we have an admin cookie. $.get( api.settings.url.ajax, { action: 'logged-in' }).fail( reject ).done( function( response ) { var iframe; if ( '1' !== response ) reject(); iframe = $('<iframe src="' + self.previewUrl() + '" />').hide(); iframe.appendTo( self.container ); iframe.load( function() { self.triedLogin = true; iframe.remove(); self.run( deferred ); }); }); }, destroy: function() { api.Messenger.prototype.destroy.call( this ); this.request.abort(); if ( this.iframe ) this.iframe.remove(); delete this.request; delete this.iframe; delete this.targetWindow; } }); (function(){ var uuid = 0; api.PreviewFrame.uuid = function() { return 'preview-' + uuid++; }; }()); api.Previewer = api.Messenger.extend({ refreshBuffer: 250, /** * Requires params: * - container - a selector or jQuery element * - previewUrl - the URL of preview frame */ initialize: function( params, options ) { var self = this, rscheme = /^https?/; $.extend( this, options || {} ); /* * Wrap this.refresh to prevent it from hammering the servers: * * If refresh is called once and no other refresh requests are * loading, trigger the request immediately. * * If refresh is called while another refresh request is loading, * debounce the refresh requests: * 1. Stop the loading request (as it is instantly outdated). * 2. Trigger the new request once refresh hasn't been called for * self.refreshBuffer milliseconds. */ this.refresh = (function( self ) { var refresh = self.refresh, callback = function() { timeout = null; refresh.call( self ); }, timeout; return function() { if ( typeof timeout !== 'number' ) { if ( self.loading ) { self.abort(); } else { return callback(); } } clearTimeout( timeout ); timeout = setTimeout( callback, self.refreshBuffer ); }; })( this ); this.container = api.ensure( params.container ); this.allowedUrls = params.allowedUrls; this.signature = params.signature; params.url = window.location.href; api.Messenger.prototype.initialize.call( this, params ); this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) { var match = to.match( rscheme ); return match ? match[0] : ''; }); // Limit the URL to internal, front-end links. // // If the frontend and the admin are served from the same domain, load the // preview over ssl if the customizer is being loaded over ssl. This avoids // insecure content warnings. This is not attempted if the admin and frontend // are on different domains to avoid the case where the frontend doesn't have // ssl certs. this.add( 'previewUrl', params.previewUrl ).setter( function( to ) { var result; // Check for URLs that include "/wp-admin/" or end in "/wp-admin". // Strip hashes and query strings before testing. if ( /\/wp-admin(\/|$)/.test( to.replace( /[#?].*$/, '' ) ) ) return null; // Attempt to match the URL to the control frame's scheme // and check if it's allowed. If not, try the original URL. $.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) { $.each( self.allowedUrls, function( i, allowed ) { var path; allowed = allowed.replace( /\/+$/, '' ); path = url.replace( allowed, '' ); if ( 0 === url.indexOf( allowed ) && /^([/#?]|$)/.test( path ) ) { result = url; return false; } }); if ( result ) return false; }); // If we found a matching result, return it. If not, bail. return result ? result : null; }); // Refresh the preview when the URL is changed (but not yet). this.previewUrl.bind( this.refresh ); this.scroll = 0; this.bind( 'scroll', function( distance ) { this.scroll = distance; }); // Update the URL when the iframe sends a URL message. this.bind( 'url', this.previewUrl ); }, query: function() {}, abort: function() { if ( this.loading ) { this.loading.destroy(); delete this.loading; } }, refresh: function() { var self = this; this.abort(); this.loading = new api.PreviewFrame({ url: this.url(), previewUrl: this.previewUrl(), query: this.query() || {}, container: this.container, signature: this.signature }); this.loading.done( function() { // 'this' is the loading frame this.bind( 'synced', function() { if ( self.preview ) self.preview.destroy(); self.preview = this; delete self.loading; self.targetWindow( this.targetWindow() ); self.channel( this.channel() ); self.send( 'active' ); }); this.send( 'sync', { scroll: self.scroll, settings: api.get() }); }); this.loading.fail( function( reason, location ) { if ( 'redirect' === reason && location ) self.previewUrl( location ); if ( 'logged out' === reason ) { if ( self.preview ) { self.preview.destroy(); delete self.preview; } self.login().done( self.refresh ); } if ( 'cheatin' === reason ) self.cheatin(); }); }, login: function() { var previewer = this, deferred, messenger, iframe; if ( this._login ) return this._login; deferred = $.Deferred(); this._login = deferred.promise(); messenger = new api.Messenger({ channel: 'login', url: api.settings.url.login }); iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container ); messenger.targetWindow( iframe[0].contentWindow ); messenger.bind( 'login', function() { iframe.remove(); messenger.destroy(); delete previewer._login; deferred.resolve(); }); return this._login; }, cheatin: function() { $( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' ); } }); /* ===================================================================== * Ready. * ===================================================================== */ api.controlConstructor = { color: api.ColorControl, upload: api.UploadControl, image: api.ImageControl, header: api.HeaderControl }; $( function() { api.settings = window._wpCustomizeSettings; api.l10n = window._wpCustomizeControlsL10n; // Check if we can run the customizer. if ( ! api.settings ) return; // Redirect to the fallback preview if any incompatibilities are found. if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) ) return window.location = api.settings.url.fallback; var previewer, parent, topFocus, body = $( document.body ), overlay = body.children('.wp-full-overlay'); // Prevent the form from saving when enter is pressed on an input or select element. $('#customize-controls').on( 'keydown', function( e ) { var isEnter = ( 13 === e.which ), $el = $( e.target ); if ( isEnter && ( $el.is( 'input:not([type=button])' ) || $el.is( 'select' ) ) ) { e.preventDefault(); } }); // Initialize Previewer previewer = new api.Previewer({ container: '#customize-preview', form: '#customize-controls', previewUrl: api.settings.url.preview, allowedUrls: api.settings.url.allowed, signature: 'WP_CUSTOMIZER_SIGNATURE' }, { nonce: api.settings.nonce, query: function() { return { wp_customize: 'on', theme: api.settings.theme.stylesheet, customized: JSON.stringify( api.get() ), nonce: this.nonce.preview }; }, save: function() { var self = this, query = $.extend( this.query(), { action: 'customize_save', nonce: this.nonce.save } ), processing = api.state( 'processing' ), submitWhenDoneProcessing, submit; body.addClass( 'saving' ); submit = function () { var request = $.post( api.settings.url.ajax, query ); api.trigger( 'save', request ); request.always( function () { body.removeClass( 'saving' ); } ); request.done( function( response ) { // Check if the user is logged out. if ( '0' === response ) { self.preview.iframe.hide(); self.login().done( function() { self.save(); self.preview.iframe.show(); } ); return; } // Check for cheaters. if ( '-1' === response ) { self.cheatin(); return; } api.trigger( 'saved' ); } ); }; if ( 0 === processing() ) { submit(); } else { submitWhenDoneProcessing = function () { if ( 0 === processing() ) { api.state.unbind( 'change', submitWhenDoneProcessing ); submit(); } }; api.state.bind( 'change', submitWhenDoneProcessing ); } } }); // Refresh the nonces if the preview sends updated nonces over. previewer.bind( 'nonce', function( nonce ) { $.extend( this.nonce, nonce ); }); $.each( api.settings.settings, function( id, data ) { api.create( id, id, data.value, { transport: data.transport, previewer: previewer } ); }); $.each( api.settings.controls, function( id, data ) { var constructor = api.controlConstructor[ data.type ] || api.Control, control; control = api.control.add( id, new constructor( id, { params: data, previewer: previewer } ) ); }); // Check if preview url is valid and load the preview frame. if ( previewer.previewUrl() ) previewer.refresh(); else previewer.previewUrl( api.settings.url.home ); // Save and activated states (function() { var state = new api.Values(), saved = state.create( 'saved' ), activated = state.create( 'activated' ), processing = state.create( 'processing' ); state.bind( 'change', function() { var save = $('#save'), back = $('.back'); if ( ! activated() ) { save.val( api.l10n.activate ).prop( 'disabled', false ); back.text( api.l10n.cancel ); } else if ( saved() ) { save.val( api.l10n.saved ).prop( 'disabled', true ); back.text( api.l10n.close ); } else { save.val( api.l10n.save ).prop( 'disabled', false ); back.text( api.l10n.cancel ); } }); // Set default states. saved( true ); activated( api.settings.theme.active ); processing( 0 ); api.bind( 'change', function() { state('saved').set( false ); }); api.bind( 'saved', function() { state('saved').set( true ); state('activated').set( true ); }); activated.bind( function( to ) { if ( to ) api.trigger( 'activated' ); }); // Expose states to the API. api.state = state; }()); // Button bindings. $('#save').click( function( event ) { previewer.save(); event.preventDefault(); }).keydown( function( event ) { if ( 9 === event.which ) // tab return; if ( 13 === event.which ) // enter previewer.save(); event.preventDefault(); }); $('.back').keydown( function( event ) { if ( 9 === event.which ) // tab return; if ( 13 === event.which ) // enter this.click(); event.preventDefault(); }); $('.upload-dropzone a.upload').keydown( function( event ) { if ( 13 === event.which ) // enter this.click(); }); $('.collapse-sidebar').on( 'click keydown', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' ); event.preventDefault(); }); // Create a potential postMessage connection with the parent frame. parent = new api.Messenger({ url: api.settings.url.parent, channel: 'loader' }); // If we receive a 'back' event, we're inside an iframe. // Send any clicks to the 'Return' link to the parent page. parent.bind( 'back', function() { $('.back').on( 'click.back', function( event ) { event.preventDefault(); parent.send( 'close' ); }); }); // Pass events through to the parent. api.bind( 'saved', function() { parent.send( 'saved' ); }); // When activated, let the loader handle redirecting the page. // If no loader exists, redirect the page ourselves (if a url exists). api.bind( 'activated', function() { if ( parent.targetWindow() ) parent.send( 'activated', api.settings.url.activated ); else if ( api.settings.url.activated ) window.location = api.settings.url.activated; }); // Initialize the connection with the parent frame. parent.send( 'ready' ); // Control visibility for default controls $.each({ 'background_image': { controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ], callback: function( to ) { return !! to; } }, 'show_on_front': { controls: [ 'page_on_front', 'page_for_posts' ], callback: function( to ) { return 'page' === to; } }, 'header_textcolor': { controls: [ 'header_textcolor' ], callback: function( to ) { return 'blank' !== to; } } }, function( settingId, o ) { api( settingId, function( setting ) { $.each( o.controls, function( i, controlId ) { api.control( controlId, function( control ) { var visibility = function( to ) { control.container.toggle( o.callback( to ) ); }; visibility( setting.get() ); setting.bind( visibility ); }); }); }); }); // Juggle the two controls that use header_textcolor api.control( 'display_header_text', function( control ) { var last = ''; control.elements[0].unsync( api( 'header_textcolor' ) ); control.element = new api.Element( control.container.find('input') ); control.element.set( 'blank' !== control.setting() ); control.element.bind( function( to ) { if ( ! to ) last = api( 'header_textcolor' ).get(); control.setting.set( to ? last : 'blank' ); }); control.setting.bind( function( to ) { control.element.set( 'blank' !== to ); }); }); api.trigger( 'ready' ); // Make sure left column gets focus topFocus = $('.back'); topFocus.focus(); setTimeout(function () { topFocus.focus(); }, 200); }); })( wp, jQuery );
JavaScript
( function( $ ){ $( document ).ready( function () { // Expand/Collapse on click $( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) { if ( e.type === 'keydown' && 13 !== e.which ) // "return" key return; e.preventDefault(); // Keep this AFTER the key filter above accordionSwitch( $( this ) ); }); // Re-initialize accordion when screen options are toggled $( '.hide-postbox-tog' ).click( function () { accordionInit(); }); }); var accordionOptions = $( '.accordion-container li.accordion-section' ), sectionContent = $( '.accordion-section-content' ); function accordionInit () { // Rounded corners accordionOptions.removeClass( 'top bottom' ); accordionOptions.filter( ':visible' ).first().addClass( 'top' ); accordionOptions.filter( ':visible' ).last().addClass( 'bottom' ).find( sectionContent ).addClass( 'bottom' ); } function accordionSwitch ( el ) { var section = el.closest( '.accordion-section' ), siblings = section.closest( '.accordion-container' ).find( '.open' ), content = section.find( sectionContent ); if ( section.hasClass( 'cannot-expand' ) ) return; if ( section.hasClass( 'open' ) ) { section.toggleClass( 'open' ); content.toggle( true ).slideToggle( 150 ); } else { siblings.removeClass( 'open' ); siblings.find( sectionContent ).show().slideUp( 150 ); content.toggle( false ).slideToggle( 150 ); section.toggleClass( 'open' ); } accordionInit(); } // Initialize the accordion (currently just corner fixes) accordionInit(); })(jQuery);
JavaScript
/* global setPostThumbnailL10n, ajaxurl, post_id, alert */ /* exported WPSetAsThumbnail */ function WPSetAsThumbnail( id, nonce ) { var $link = jQuery('a#wp-post-thumbnail-' + id); $link.text( setPostThumbnailL10n.saving ); jQuery.post(ajaxurl, { action: 'set-post-thumbnail', post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie ) }, function(str){ var win = window.dialogArguments || opener || parent || top; $link.text( setPostThumbnailL10n.setThumbnail ); if ( str == '0' ) { alert( setPostThumbnailL10n.error ); } else { jQuery('a.wp-post-thumbnail').show(); $link.text( setPostThumbnailL10n.done ); $link.fadeOut( 2000 ); win.WPSetThumbnailID(id); win.WPSetThumbnailHTML(str); } } ); }
JavaScript
/* global wordCountL10n */ var wpWordCount; (function($,undefined) { wpWordCount = { settings : { strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc. w : /\S\s+/g, // word-counting regexp c : /\S/g // char-counting regexp for asian languages }, block : 0, wc : function(tx, type) { var t = this, w = $('.word-count'), tc = 0; if ( type === undefined ) type = wordCountL10n.type; if ( type !== 'w' && type !== 'c' ) type = 'w'; if ( t.block ) return; t.block = 1; setTimeout( function() { if ( tx ) { tx = tx.replace( t.settings.strip, ' ' ).replace( /&nbsp;|&#160;/gi, ' ' ); tx = tx.replace( t.settings.clean, '' ); tx.replace( t.settings[type], function(){tc++;} ); } w.html(tc.toString()); setTimeout( function() { t.block = 0; }, 2000 ); }, 1 ); } }; $(document).bind( 'wpcountwords', function(e, txt) { wpWordCount.wc(txt); }); }(jQuery));
JavaScript
/* global wpColorPickerL10n:true */ ( function( $, undef ){ var ColorPicker, // html stuff _before = '<a tabindex="0" class="wp-color-result" />', _after = '<div class="wp-picker-holder" />', _wrap = '<div class="wp-picker-container" />', _button = '<input type="button" class="button button-small hidden" />'; // jQuery UI Widget constructor ColorPicker = { options: { defaultColor: false, change: false, clear: false, hide: true, palettes: true }, _create: function() { // bail early for unsupported Iris. if ( ! $.support.iris ) return; var self = this, el = self.element; $.extend( self.options, el.data() ); self.initialValue = el.val(); // Set up HTML structure, hide things el.addClass( 'wp-color-picker' ).hide().wrap( _wrap ); self.wrap = el.parent(); self.toggler = $( _before ).insertBefore( el ).css( { backgroundColor: self.initialValue } ).attr( 'title', wpColorPickerL10n.pick ).attr( 'data-current', wpColorPickerL10n.current ); self.pickerContainer = $( _after ).insertAfter( el ); self.button = $( _button ); if ( self.options.defaultColor ) self.button.addClass( 'wp-picker-default' ).val( wpColorPickerL10n.defaultString ); else self.button.addClass( 'wp-picker-clear' ).val( wpColorPickerL10n.clear ); el.wrap('<span class="wp-picker-input-wrap" />').after(self.button); el.iris( { target: self.pickerContainer, hide: true, width: 255, mode: 'hsv', palettes: self.options.palettes, change: function( event, ui ) { self.toggler.css( { backgroundColor: ui.color.toString() } ); // check for a custom cb if ( $.isFunction( self.options.change ) ) self.options.change.call( this, event, ui ); } } ); el.val( self.initialValue ); self._addListeners(); if ( ! self.options.hide ) self.toggler.click(); }, _addListeners: function() { var self = this; self.toggler.click( function( event ){ event.stopPropagation(); self.element.toggle().iris( 'toggle' ); self.button.toggleClass('hidden'); self.toggler.toggleClass( 'wp-picker-open' ); // close picker when you click outside it if ( self.toggler.hasClass( 'wp-picker-open' ) ) $( 'body' ).on( 'click', { wrap: self.wrap, toggler: self.toggler }, self._bodyListener ); else $( 'body' ).off( 'click', self._bodyListener ); }); self.element.change(function( event ) { var me = $(this), val = me.val(); // Empty = clear if ( val === '' || val === '#' ) { self.toggler.css('backgroundColor', ''); // fire clear callback if we have one if ( $.isFunction( self.options.clear ) ) self.options.clear.call( this, event ); } }); // open a keyboard-focused closed picker with space or enter self.toggler.on('keyup', function( e ) { if ( e.keyCode === 13 || e.keyCode === 32 ) { e.preventDefault(); self.toggler.trigger('click').next().focus(); } }); self.button.click( function( event ) { var me = $(this); if ( me.hasClass( 'wp-picker-clear' ) ) { self.element.val( '' ); self.toggler.css('backgroundColor', ''); if ( $.isFunction( self.options.clear ) ) self.options.clear.call( this, event ); } else if ( me.hasClass( 'wp-picker-default' ) ) { self.element.val( self.options.defaultColor ).change(); } }); }, _bodyListener: function( event ) { if ( ! event.data.wrap.find( event.target ).length ) event.data.toggler.click(); }, // $("#input").wpColorPicker('color') returns the current color // $("#input").wpColorPicker('color', '#bada55') to set color: function( newColor ) { if ( newColor === undef ) return this.element.iris( 'option', 'color' ); this.element.iris( 'option', 'color', newColor ); }, //$("#input").wpColorPicker('defaultColor') returns the current default color //$("#input").wpColorPicker('defaultColor', newDefaultColor) to set defaultColor: function( newDefaultColor ) { if ( newDefaultColor === undef ) return this.options.defaultColor; this.options.defaultColor = newDefaultColor; } }; $.widget( 'wp.wpColorPicker', ColorPicker ); }( jQuery ) );
JavaScript
/* global imageEditL10n, ajaxurl, confirm */ (function($) { var imageEdit = window.imageEdit = { iasapi : {}, hold : {}, postid : '', _view : false, intval : function(f) { return f | 0; }, setDisabled : function(el, s) { if ( s ) { el.removeClass('disabled'); $('input', el).removeAttr('disabled'); } else { el.addClass('disabled'); $('input', el).prop('disabled', true); } }, init : function(postid) { var t = this, old = $('#image-editor-' + t.postid), x = t.intval( $('#imgedit-x-' + postid).val() ), y = t.intval( $('#imgedit-y-' + postid).val() ); if ( t.postid !== postid && old.length ) { t.close(t.postid); } t.hold.w = t.hold.ow = x; t.hold.h = t.hold.oh = y; t.hold.xy_ratio = x / y; t.hold.sizer = parseFloat( $('#imgedit-sizer-' + postid).val() ); t.postid = postid; $('#imgedit-response-' + postid).empty(); $('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) { var k = e.keyCode; if ( 36 < k && k < 41 ) { $(this).blur(); } if ( 13 === k ) { e.preventDefault(); e.stopPropagation(); return false; } }); }, toggleEditor : function(postid, toggle) { var wait = $('#imgedit-wait-' + postid); if ( toggle ) { wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast'); } else { wait.fadeOut('fast'); } }, toggleHelp : function(el) { $( el ).parents( '.imgedit-group-top' ).toggleClass( 'imgedit-help-toggled' ).find( '.imgedit-help' ).slideToggle( 'fast' ); return false; }, getTarget : function(postid) { return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full'; }, scaleChanged : function(postid, x) { var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid), warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = ''; if ( x ) { h1 = ( w.val() !== '' ) ? Math.round( w.val() / this.hold.xy_ratio ) : ''; h.val( h1 ); } else { w1 = ( h.val() !== '' ) ? Math.round( h.val() * this.hold.xy_ratio ) : ''; w.val( w1 ); } if ( ( h1 && h1 > this.hold.oh ) || ( w1 && w1 > this.hold.ow ) ) { warn.css('visibility', 'visible'); } else { warn.css('visibility', 'hidden'); } }, getSelRatio : function(postid) { var x = this.hold.w, y = this.hold.h, X = this.intval( $('#imgedit-crop-width-' + postid).val() ), Y = this.intval( $('#imgedit-crop-height-' + postid).val() ); if ( X && Y ) { return X + ':' + Y; } if ( x && y ) { return x + ':' + y; } return '1:1'; }, filterHistory : function(postid, setSize) { // apply undo state to history var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = []; if ( history !== '' ) { history = JSON.parse(history); pop = this.intval( $('#imgedit-undone-' + postid).val() ); if ( pop > 0 ) { while ( pop > 0 ) { history.pop(); pop--; } } if ( setSize ) { if ( !history.length ) { this.hold.w = this.hold.ow; this.hold.h = this.hold.oh; return ''; } // restore o = history[history.length - 1]; o = o.c || o.r || o.f || false; if ( o ) { this.hold.w = o.fw; this.hold.h = o.fh; } } // filter the values for ( n in history ) { i = history[n]; if ( i.hasOwnProperty('c') ) { op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } }; } else if ( i.hasOwnProperty('r') ) { op[n] = { 'r': i.r.r }; } else if ( i.hasOwnProperty('f') ) { op[n] = { 'f': i.f.f }; } } return JSON.stringify(op); } return ''; }, refreshEditor : function(postid, nonce, callback) { var t = this, data, img; t.toggleEditor(postid, 1); data = { 'action': 'imgedit-preview', '_ajax_nonce': nonce, 'postid': postid, 'history': t.filterHistory(postid, 1), 'rand': t.intval(Math.random() * 1000000) }; img = $('<img id="image-preview-' + postid + '" />') .on('load', function() { var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit; parent.empty().append(img); // w, h are the new full size dims max1 = Math.max( t.hold.w, t.hold.h ); max2 = Math.max( $(img).width(), $(img).height() ); t.hold.sizer = max1 > max2 ? max2 / max1 : 1; t.initCrop(postid, img, parent); t.setCropSelection(postid, 0); if ( (typeof callback !== 'undefined') && callback !== null ) { callback(); } if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() === '0' ) { $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled'); } else { $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true); } t.toggleEditor(postid, 0); }) .on('error', function() { $('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>'); t.toggleEditor(postid, 0); }) .attr('src', ajaxurl + '?' + $.param(data)); }, action : function(postid, nonce, action) { var t = this, data, w, h, fw, fh; if ( t.notsaved(postid) ) { return false; } data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid }; if ( 'scale' === action ) { w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid), fw = t.intval(w.val()), fh = t.intval(h.val()); if ( fw < 1 ) { w.focus(); return false; } else if ( fh < 1 ) { h.focus(); return false; } if ( fw === t.hold.ow || fh === t.hold.oh ) { return false; } data['do'] = 'scale'; data.fwidth = fw; data.fheight = fh; } else if ( 'restore' === action ) { data['do'] = 'restore'; } else { return false; } t.toggleEditor(postid, 1); $.post(ajaxurl, data, function(r) { $('#image-editor-' + postid).empty().append(r); t.toggleEditor(postid, 0); // refresh the attachment model so that changes propagate if ( t._view ) { t._view.refresh(); } }); }, save : function(postid, nonce) { var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0), self = this; if ( '' === history ) { return false; } this.toggleEditor(postid, 1); data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid, 'history': history, 'target': target, 'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null, 'do': 'save' }; $.post(ajaxurl, data, function(r) { var ret = JSON.parse(r); if ( ret.error ) { $('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>'); imageEdit.close(postid); return; } if ( ret.fw && ret.fh ) { $('#media-dims-' + postid).html( ret.fw + ' &times; ' + ret.fh ); } if ( ret.thumbnail ) { $('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail); } if ( ret.msg ) { $('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>'); } if ( self._view ) { self._view.save(); } else { imageEdit.close(postid); } }); }, open : function( postid, nonce, view ) { this._view = view; var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid), btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner'); btn.prop('disabled', true); spin.show(); data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid, 'do': 'open' }; elem.load(ajaxurl, data, function() { elem.fadeIn('fast'); head.fadeOut('fast', function(){ btn.removeAttr('disabled'); spin.hide(); }); }); }, imgLoaded : function(postid) { var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid); this.initCrop(postid, img, parent); this.setCropSelection(postid, 0); this.toggleEditor(postid, 0); }, initCrop : function(postid, image, parent) { var t = this, selW = $('#imgedit-sel-width-' + postid), selH = $('#imgedit-sel-height-' + postid), $img; t.iasapi = $(image).imgAreaSelect({ parent: parent, instance: true, handles: true, keys: true, minWidth: 3, minHeight: 3, onInit: function( img ) { // Ensure that the imgareaselect wrapper elements are position:absolute // (even if we're in a position:fixed modal) $img = $( img ); $img.next().css( 'position', 'absolute' ) .nextAll( '.imgareaselect-outer' ).css( 'position', 'absolute' ); parent.children().mousedown(function(e){ var ratio = false, sel, defRatio; if ( e.shiftKey ) { sel = t.iasapi.getSelection(); defRatio = t.getSelRatio(postid); ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio; } t.iasapi.setOptions({ aspectRatio: ratio }); }); }, onSelectStart: function() { imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1); }, onSelectEnd: function(img, c) { imageEdit.setCropSelection(postid, c); }, onSelectChange: function(img, c) { var sizer = imageEdit.hold.sizer; selW.val( imageEdit.round(c.width / sizer) ); selH.val( imageEdit.round(c.height / sizer) ); } }); }, setCropSelection : function(postid, c) { var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128', sizer = this.hold.sizer; min = min.split(':'); c = c || 0; if ( !c || ( c.width < 3 && c.height < 3 ) ) { this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0); this.setDisabled($('#imgedit-crop-sel-' + postid), 0); $('#imgedit-sel-width-' + postid).val(''); $('#imgedit-sel-height-' + postid).val(''); $('#imgedit-selection-' + postid).val(''); return false; } if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) { this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0); $('#imgedit-selection-' + postid).val(''); return false; } sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height }; this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1); $('#imgedit-selection-' + postid).val( JSON.stringify(sel) ); }, close : function(postid, warn) { warn = warn || false; if ( warn && this.notsaved(postid) ) { return false; } this.iasapi = {}; this.hold = {}; // If we've loaded the editor in the context of a Media Modal, then switch to the previous view, // whatever that might have been. if ( this._view ){ this._view.back(); } // In case we are not accessing the image editor in the context of a View, close the editor the old-skool way else { $('#image-editor-' + postid).fadeOut('fast', function() { $('#media-head-' + postid).fadeIn('fast'); $(this).empty(); }); } }, notsaved : function(postid) { var h = $('#imgedit-history-' + postid).val(), history = ( h !== '' ) ? JSON.parse(h) : [], pop = this.intval( $('#imgedit-undone-' + postid).val() ); if ( pop < history.length ) { if ( confirm( $('#imgedit-leaving-' + postid).html() ) ) { return false; } return true; } return false; }, addStep : function(op, postid, nonce) { var t = this, elem = $('#imgedit-history-' + postid), history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [], undone = $('#imgedit-undone-' + postid), pop = t.intval(undone.val()); while ( pop > 0 ) { history.pop(); pop--; } undone.val(0); // reset history.push(op); elem.val( JSON.stringify(history) ); t.refreshEditor(postid, nonce, function() { t.setDisabled($('#image-undo-' + postid), true); t.setDisabled($('#image-redo-' + postid), false); }); }, rotate : function(angle, postid, nonce, t) { if ( $(t).hasClass('disabled') ) { return false; } this.addStep({ 'r': { 'r': angle, 'fw': this.hold.h, 'fh': this.hold.w }}, postid, nonce); }, flip : function (axis, postid, nonce, t) { if ( $(t).hasClass('disabled') ) { return false; } this.addStep({ 'f': { 'f': axis, 'fw': this.hold.w, 'fh': this.hold.h }}, postid, nonce); }, crop : function (postid, nonce, t) { var sel = $('#imgedit-selection-' + postid).val(), w = this.intval( $('#imgedit-sel-width-' + postid).val() ), h = this.intval( $('#imgedit-sel-height-' + postid).val() ); if ( $(t).hasClass('disabled') || sel === '' ) { return false; } sel = JSON.parse(sel); if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) { sel.fw = w; sel.fh = h; this.addStep({ 'c': sel }, postid, nonce); } }, undo : function (postid, nonce) { var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid), pop = t.intval( elem.val() ) + 1; if ( button.hasClass('disabled') ) { return; } elem.val(pop); t.refreshEditor(postid, nonce, function() { var elem = $('#imgedit-history-' + postid), history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : []; t.setDisabled($('#image-redo-' + postid), true); t.setDisabled(button, pop < history.length); }); }, redo : function(postid, nonce) { var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid), pop = t.intval( elem.val() ) - 1; if ( button.hasClass('disabled') ) { return; } elem.val(pop); t.refreshEditor(postid, nonce, function() { t.setDisabled($('#image-undo-' + postid), true); t.setDisabled(button, pop > 0); }); }, setNumSelection : function(postid) { var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid), x = this.intval( elX.val() ), y = this.intval( elY.val() ), img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(), sizer = this.hold.sizer, x1, y1, x2, y2, ias = this.iasapi; if ( x < 1 ) { elX.val(''); return false; } if ( y < 1 ) { elY.val(''); return false; } if ( x && y && ( sel = ias.getSelection() ) ) { x2 = sel.x1 + Math.round( x * sizer ); y2 = sel.y1 + Math.round( y * sizer ); x1 = sel.x1; y1 = sel.y1; if ( x2 > imgw ) { x1 = 0; x2 = imgw; elX.val( Math.round( x2 / sizer ) ); } if ( y2 > imgh ) { y1 = 0; y2 = imgh; elY.val( Math.round( y2 / sizer ) ); } ias.setSelection( x1, y1, x2, y2 ); ias.update(); this.setCropSelection(postid, ias.getSelection()); } }, round : function(num) { var s; num = Math.round(num); if ( this.hold.sizer > 0.6 ) { return num; } s = num.toString().slice(-1); if ( '1' === s ) { return num - 1; } else if ( '9' === s ) { return num + 1; } return num; }, setRatioSelection : function(postid, n, el) { var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ), y = this.intval( $('#imgedit-crop-height-' + postid).val() ), h = $('#image-preview-' + postid).height(); if ( !this.intval( $(el).val() ) ) { $(el).val(''); return; } if ( x && y ) { this.iasapi.setOptions({ aspectRatio: x + ':' + y }); if ( sel = this.iasapi.getSelection(true) ) { r = Math.ceil( sel.y1 + ( ( sel.x2 - sel.x1 ) / ( x / y ) ) ); if ( r > h ) { r = h; if ( n ) { $('#imgedit-crop-height-' + postid).val(''); } else { $('#imgedit-crop-width-' + postid).val(''); } } this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r ); this.iasapi.update(); } } } }; })(jQuery);
JavaScript
/* global ajaxurl */ jQuery(function($){ $( 'body' ).bind( 'click.wp-gallery', function(e){ var target = $( e.target ), id, img_size; if ( target.hasClass( 'wp-set-header' ) ) { ( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' ); e.preventDefault(); } else if ( target.hasClass( 'wp-set-background' ) ) { id = target.data( 'attachment-id' ); img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val(); jQuery.post(ajaxurl, { action: 'set-background-image', attachment_id: id, size: img_size }, function(){ var win = window.dialogArguments || opener || parent || top; win.tb_remove(); win.location.reload(); }); e.preventDefault(); } }); });
JavaScript
/* global ajaxurl, pwsL10n */ (function($){ function check_pass_strength() { var pass1 = $('#pass1').val(), pass2 = $('#pass2').val(), strength; $('#pass-strength-result').removeClass('short bad good strong'); if ( ! pass1 ) { $('#pass-strength-result').html( pwsL10n.empty ); return; } strength = wp.passwordStrength.meter( pass1, wp.passwordStrength.userInputBlacklist(), pass2 ); switch ( strength ) { case 2: $('#pass-strength-result').addClass('bad').html( pwsL10n.bad ); break; case 3: $('#pass-strength-result').addClass('good').html( pwsL10n.good ); break; case 4: $('#pass-strength-result').addClass('strong').html( pwsL10n.strong ); break; case 5: $('#pass-strength-result').addClass('short').html( pwsL10n.mismatch ); break; default: $('#pass-strength-result').addClass('short').html( pwsL10n['short'] ); } } $(document).ready( function() { var $colorpicker, $stylesheet, user_id, current_user_id, select = $( '#display_name' ); $('#pass1').val('').keyup( check_pass_strength ); $('#pass2').val('').keyup( check_pass_strength ); $('#pass-strength-result').show(); $('.color-palette').click( function() { $(this).siblings('input[name="admin_color"]').prop('checked', true); }); if ( select.length ) { $('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() { var dub = [], inputs = { display_nickname : $('#nickname').val() || '', display_username : $('#user_login').val() || '', display_firstname : $('#first_name').val() || '', display_lastname : $('#last_name').val() || '' }; if ( inputs.display_firstname && inputs.display_lastname ) { inputs.display_firstlast = inputs.display_firstname + ' ' + inputs.display_lastname; inputs.display_lastfirst = inputs.display_lastname + ' ' + inputs.display_firstname; } $.each( $('option', select), function( i, el ){ dub.push( el.value ); }); $.each(inputs, function( id, value ) { if ( ! value ) { return; } var val = value.replace(/<\/?[a-z][^>]*>/gi, ''); if ( inputs[id].length && $.inArray( val, dub ) === -1 ) { dub.push(val); $('<option />', { 'text': val }).appendTo( select ); } }); }); } $colorpicker = $( '#color-picker' ); $stylesheet = $( '#colors-css' ); user_id = $( 'input#user_id' ).val(); current_user_id = $( 'input[name="checkuser_id"]' ).val(); $colorpicker.on( 'click.colorpicker', '.color-option', function() { var colors, $this = $(this); if ( $this.hasClass( 'selected' ) ) { return; } $this.siblings( '.selected' ).removeClass( 'selected' ); $this.addClass( 'selected' ).find( 'input[type="radio"]' ).prop( 'checked', true ); // Set color scheme if ( user_id === current_user_id ) { // Load the colors stylesheet. // The default color scheme won't have one, so we'll need to create an element. if ( 0 === $stylesheet.length ) { $stylesheet = $( '<link rel="stylesheet" />' ).appendTo( 'head' ); } $stylesheet.attr( 'href', $this.children( '.css_url' ).val() ); // repaint icons if ( typeof wp !== 'undefined' && wp.svgPainter ) { try { colors = $.parseJSON( $this.children( '.icon_colors' ).val() ); } catch ( error ) {} if ( colors ) { wp.svgPainter.setColors( colors ); wp.svgPainter.paint(); } } // update user option $.post( ajaxurl, { action: 'save-user-color-scheme', color_scheme: $this.children( 'input[name="admin_color"]' ).val(), nonce: $('#color-nonce').val() }); } }); }); })(jQuery);
JavaScript
/* global plugininstallL10n, tb_click, confirm */ /* Plugin Browser Thickbox related JS*/ var tb_position; jQuery( document ).ready( function( $ ) { tb_position = function() { var tbWindow = $( '#TB_window' ), width = $( window ).width(), H = $( window ).height() - ( ( 850 < width ) ? 60 : 20 ), W = ( 850 < width ) ? 830 : width - 20; if ( tbWindow.size() ) { tbWindow.width( W ).height( H ); $( '#TB_iframeContent' ).width( W ).height( H ); tbWindow.css({ 'margin-left': '-' + parseInt( ( W / 2 ), 10 ) + 'px' }); if ( typeof document.body.style.maxWidth !== 'undefined' ) { tbWindow.css({ 'top': ( ( 850 < width ) ? 30 : 10 ) + 'px', 'margin-top': '0' }); } } return $( 'a.thickbox' ).each( function() { var href = $( this ).attr( 'href' ); if ( ! href ) { return; } href = href.replace( /&width=[0-9]+/g, '' ); href = href.replace( /&height=[0-9]+/g, '' ); $(this).attr( 'href', href + '&width=' + W + '&height=' + ( H ) ); }); }; $( window ).resize( function() { tb_position(); }); $('.plugins').on( 'click', 'a.thickbox', function() { tb_click.call(this); $('#TB_title').css({'background-color':'#222','color':'#cfcfcf'}); $('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong>&nbsp;' + $(this).attr('title') ); return false; }); /* Plugin install related JS*/ $( '#plugin-information-tabs a' ).click( function( event ) { var tab = $( this ).attr( 'name' ); event.preventDefault(); //Flip the tab $( '#plugin-information-tabs a.current' ).removeClass( 'current' ); $( this ).addClass( 'current' ); //Flip the content. $( '#section-holder div.section' ).hide(); //Hide 'em all $( '#section-' + tab ).show(); }); $( 'a.install-now' ).click( function() { return confirm( plugininstallL10n.ays ); }); });
JavaScript
/* global deleteUserSetting, setUserSetting, switchEditors, tinymce, tinyMCEPreInit */ /** * Distraction Free Writing * (wp-fullscreen) * * Access the API globally using the window.wp.editor.fullscreen variable. */ ( function( $, window ) { var api, ps, s, toggleUI, uiTimer, PubSub, uiScrollTop = 0, transitionend = 'transitionend webkitTransitionEnd', $body = $( document.body ), $document = $( document ); /** * PubSub * * A lightweight publish/subscribe implementation. * * @access private */ PubSub = function() { this.topics = {}; this.subscribe = function( topic, callback ) { if ( ! this.topics[ topic ] ) this.topics[ topic ] = []; this.topics[ topic ].push( callback ); return callback; }; this.unsubscribe = function( topic, callback ) { var i, l, topics = this.topics[ topic ]; if ( ! topics ) return callback || []; // Clear matching callbacks if ( callback ) { for ( i = 0, l = topics.length; i < l; i++ ) { if ( callback == topics[i] ) topics.splice( i, 1 ); } return callback; // Clear all callbacks } else { this.topics[ topic ] = []; return topics; } }; this.publish = function( topic, args ) { var i, l, broken, topics = this.topics[ topic ]; if ( ! topics ) return; args = args || []; for ( i = 0, l = topics.length; i < l; i++ ) { broken = ( topics[i].apply( null, args ) === false || broken ); } return ! broken; }; }; // Initialize the fullscreen/api object api = {}; // Create the PubSub (publish/subscribe) interface. ps = api.pubsub = new PubSub(); s = api.settings = { // Settings visible: false, mode: 'tinymce', id: '', title_id: '', timer: 0, toolbar_shown: false }; function _hideUI() { $body.removeClass('wp-dfw-show-ui'); } /** * toggleUI * * Toggle the CSS class to show/hide the toolbar, borders and statusbar. */ toggleUI = api.toggleUI = function( show ) { clearTimeout( uiTimer ); if ( ! $body.hasClass('wp-dfw-show-ui') || show === 'show' ) { $body.addClass('wp-dfw-show-ui'); } else if ( show !== 'autohide' ) { $body.removeClass('wp-dfw-show-ui'); } if ( show === 'autohide' ) { uiTimer = setTimeout( _hideUI, 2000 ); } }; function resetCssPosition( add ) { s.$dfwWrap.parents().each( function( i, parent ) { var cssPosition, $parent = $(parent); if ( add ) { if ( parent.style.position ) { $parent.data( 'wp-dfw-css-position', parent.style.position ); } $parent.css( 'position', 'static' ); } else { cssPosition = $parent.data( 'wp-dfw-css-position' ); cssPosition = cssPosition || ''; $parent.css( 'position', cssPosition ); } if ( parent.nodeName === 'BODY' ) { return false; } }); } /** * on() * * Turns fullscreen on. * * @param string mode Optional. Switch to the given mode before opening. */ api.on = function() { var id, $dfwWrap, titleId; if ( s.visible ) { return; } if ( ! s.$fullscreenFader ) { api.ui.init(); } // Settings can be added or changed by defining "wp_fullscreen_settings" JS object. if ( typeof window.wp_fullscreen_settings === 'object' ) $.extend( s, window.wp_fullscreen_settings ); id = s.id || window.wpActiveEditor; if ( ! id ) { if ( s.hasTinymce ) { id = tinymce.activeEditor.id; } else { return; } } s.id = id; $dfwWrap = s.$dfwWrap = $( '#wp-' + id + '-wrap' ); if ( ! $dfwWrap.length ) { return; } s.$dfwTextarea = $( '#' + id ); s.$editorContainer = $dfwWrap.find( '.wp-editor-container' ); uiScrollTop = $document.scrollTop(); if ( s.hasTinymce ) { s.editor = tinymce.get( id ); } if ( s.editor && ! s.editor.isHidden() ) { s.origHeight = $( '#' + id + '_ifr' ).height(); s.mode = 'tinymce'; } else { s.origHeight = s.$dfwTextarea.height(); s.mode = 'html'; } // Try to find title field if ( typeof window.adminpage !== 'undefined' && ( window.adminpage === 'post-php' || window.adminpage === 'post-new-php' ) ) { titleId = 'title'; } else { titleId = id + '-title'; } s.$dfwTitle = $( '#' + titleId ); if ( ! s.$dfwTitle.length ) { s.$dfwTitle = null; } api.ui.fade( 'show', 'showing', 'shown' ); }; /** * off() * * Turns fullscreen off. */ api.off = function() { if ( ! s.visible ) return; api.ui.fade( 'hide', 'hiding', 'hidden' ); }; /** * switchmode() * * @return string - The current mode. * * @param string to - The fullscreen mode to switch to. * @event switchMode * @eventparam string to - The new mode. * @eventparam string from - The old mode. */ api.switchmode = function( to ) { var from = s.mode; if ( ! to || ! s.visible || ! s.hasTinymce || typeof switchEditors === 'undefined' ) { return from; } // Don't switch if the mode is the same. if ( from == to ) return from; if ( to === 'tinymce' && ! s.editor ) { s.editor = tinymce.get( s.id ); if ( ! s.editor && typeof tinyMCEPreInit !== 'undefined' && tinyMCEPreInit.mceInit && tinyMCEPreInit.mceInit[ s.id ] ) { // If the TinyMCE instance hasn't been created, set the "wp_fulscreen" flag on creating it tinyMCEPreInit.mceInit[ s.id ].wp_fullscreen = true; } } s.mode = to; switchEditors.go( s.id, to ); api.refreshButtons( true ); if ( to === 'html' ) { setTimeout( api.resizeTextarea, 200 ); } return to; }; /** * General */ api.save = function() { var $hidden = $('#hiddenaction'), oldVal = $hidden.val(), $spinner = $('#wp-fullscreen-save .spinner'), $saveMessage = $('#wp-fullscreen-save .wp-fullscreen-saved-message'), $errorMessage = $('#wp-fullscreen-save .wp-fullscreen-error-message'); $spinner.show(); $errorMessage.hide(); $saveMessage.hide(); $hidden.val('wp-fullscreen-save-post'); if ( s.editor && ! s.editor.isHidden() ) { s.editor.save(); } $.ajax({ url: window.ajaxurl, type: 'post', data: $('form#post').serialize(), dataType: 'json' }).done( function( response ) { $spinner.hide(); if ( response && response.success ) { $saveMessage.show(); setTimeout( function() { $saveMessage.fadeOut(300); }, 3000 ); if ( response.data && response.data.last_edited ) { $('#wp-fullscreen-save input').attr( 'title', response.data.last_edited ); } } else { $errorMessage.show(); } }).fail( function() { $spinner.hide(); $errorMessage.show(); }); $hidden.val( oldVal ); }; api.dfwWidth = function( pixels, total ) { var width; if ( pixels && pixels.toString().indexOf('%') !== -1 ) { s.$editorContainer.css( 'width', pixels ); s.$statusbar.css( 'width', pixels ); if ( s.$dfwTitle ) { s.$dfwTitle.css( 'width', pixels ); } return; } if ( ! pixels ) { // Reset to theme width width = $('#wp-fullscreen-body').data('theme-width') || 800; s.$editorContainer.width( width ); s.$statusbar.width( width ); if ( s.$dfwTitle ) { s.$dfwTitle.width( width - 16 ); } deleteUserSetting('dfw_width'); return; } if ( total ) { width = pixels; } else { width = s.$editorContainer.width(); width += pixels; } if ( width < 200 || width > 1200 ) { // sanity check return; } s.$editorContainer.width( width ); s.$statusbar.width( width ); if ( s.$dfwTitle ) { s.$dfwTitle.width( width - 16 ); } setUserSetting( 'dfw_width', width ); }; // This event occurs before the overlay blocks the UI. ps.subscribe( 'show', function() { var title = $('#last-edit').text(); if ( title ) { $('#wp-fullscreen-save input').attr( 'title', title ); } }); // This event occurs while the overlay blocks the UI. ps.subscribe( 'showing', function() { $body.addClass( 'wp-fullscreen-active' ); s.$dfwWrap.addClass( 'wp-fullscreen-wrap' ); if ( s.$dfwTitle ) { s.$dfwTitle.after( '<span id="wp-fullscreen-title-placeholder">' ); s.$dfwWrap.prepend( s.$dfwTitle.addClass('wp-fullscreen-title') ); } api.refreshButtons(); resetCssPosition( true ); $('#wpadminbar').hide(); // Show the UI for 2 sec. when opening toggleUI('autohide'); api.bind_resize(); if ( s.editor ) { s.editor.execCommand( 'wpFullScreenOn' ); } if ( 'ontouchstart' in window ) { api.dfwWidth( '90%' ); } else { api.dfwWidth( $( '#wp-fullscreen-body' ).data('dfw-width') || 800, true ); } // scroll to top so the user is not disoriented scrollTo(0, 0); }); // This event occurs after the overlay unblocks the UI ps.subscribe( 'shown', function() { s.visible = true; if ( s.editor && ! s.editor.isHidden() ) { s.editor.execCommand( 'wpAutoResize' ); } else { api.resizeTextarea( 'force' ); } }); ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW. $document.unbind( '.fullscreen' ); s.$dfwTextarea.unbind('.wp-dfw-resize'); }); ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI. $body.removeClass( 'wp-fullscreen-active' ); if ( s.$dfwTitle ) { $( '#wp-fullscreen-title-placeholder' ).before( s.$dfwTitle.removeClass('wp-fullscreen-title').css( 'width', '' ) ).remove(); } s.$dfwWrap.removeClass( 'wp-fullscreen-wrap' ); s.$editorContainer.css( 'width', '' ); s.$dfwTextarea.add( '#' + s.id + '_ifr' ).height( s.origHeight ); if ( s.editor ) { s.editor.execCommand( 'wpFullScreenOff' ); } resetCssPosition( false ); window.scrollTo( 0, uiScrollTop ); $('#wpadminbar').show(); }); // This event occurs after DFW is removed. ps.subscribe( 'hidden', function() { s.visible = false; }); api.refreshButtons = function( fade ) { if ( s.mode === 'html' ) { $('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode') .find('a').removeClass( 'active' ).filter('.wp-fullscreen-mode-html').addClass( 'active' ); if ( fade ) { $('#wp-fullscreen-button-bar').fadeOut( 150, function(){ $(this).addClass('wp-html-mode').fadeIn( 150 ); }); } else { $('#wp-fullscreen-button-bar').addClass('wp-html-mode'); } } else if ( s.mode === 'tinymce' ) { $('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode') .find('a').removeClass( 'active' ).filter('.wp-fullscreen-mode-tinymce').addClass( 'active' ); if ( fade ) { $('#wp-fullscreen-button-bar').fadeOut( 150, function(){ $(this).removeClass('wp-html-mode').fadeIn( 150 ); }); } else { $('#wp-fullscreen-button-bar').removeClass('wp-html-mode'); } } }; /** * UI Elements * * Used for transitioning between states. */ api.ui = { init: function() { var toolbar; s.toolbar = toolbar = $('#fullscreen-topbar'); s.$fullscreenFader = $('#fullscreen-fader'); s.$statusbar = $('#wp-fullscreen-status'); s.hasTinymce = typeof tinymce !== 'undefined'; if ( ! s.hasTinymce ) $('#wp-fullscreen-mode-bar').hide(); $document.keyup( function(e) { var c = e.keyCode || e.charCode, modKey; if ( ! s.visible ) { return; } if ( navigator.platform && navigator.platform.indexOf('Mac') !== -1 ) { modKey = e.ctrlKey; // Ctrl key for Mac } else { modKey = e.altKey; // Alt key for Win & Linux } if ( modKey && ( 61 === c || 107 === c || 187 === c ) ) { // + api.dfwWidth( 25 ); e.preventDefault(); } if ( modKey && ( 45 === c || 109 === c || 189 === c ) ) { // - api.dfwWidth( -25 ); e.preventDefault(); } if ( modKey && 48 === c ) { // 0 api.dfwWidth( 0 ); e.preventDefault(); } }); $document.on( 'keydown.wp-fullscreen', function( event ) { if ( 27 === event.which && s.visible ) { // Esc api.off(); event.stopImmediatePropagation(); } }); if ( 'ontouchstart' in window ) { $body.addClass('wp-dfw-touch'); } toolbar.on( 'mouseenter', function() { toggleUI('show'); }).on( 'mouseleave', function() { toggleUI('autohide'); }); // Bind buttons $('#wp-fullscreen-buttons').on( 'click.wp-fullscreen', 'button', function( event ) { var command = event.currentTarget.id ? event.currentTarget.id.substr(6) : null; if ( s.editor && 'tinymce' === s.mode ) { switch( command ) { case 'bold': s.editor.execCommand('Bold'); break; case 'italic': s.editor.execCommand('Italic'); break; case 'bullist': s.editor.execCommand('InsertUnorderedList'); break; case 'numlist': s.editor.execCommand('InsertOrderedList'); break; case 'link': s.editor.execCommand('WP_Link'); break; case 'unlink': s.editor.execCommand('unlink'); break; case 'help': s.editor.execCommand('WP_Help'); break; case 'blockquote': s.editor.execCommand('mceBlockQuote'); break; } } else if ( command === 'link' && window.wpLink ) { window.wpLink.open(); } if ( command === 'wp-media-library' && typeof wp !== 'undefined' && wp.media && wp.media.editor ) { wp.media.editor.open( s.id ); } }); }, fade: function( before, during, after ) { if ( ! s.$fullscreenFader ) { api.ui.init(); } // If any callback bound to before returns false, bail. if ( before && ! ps.publish( before ) ) { return; } api.fade.In( s.$fullscreenFader, 200, function() { if ( during ) { ps.publish( during ); } api.fade.Out( s.$fullscreenFader, 200, function() { if ( after ) { ps.publish( after ); } }); }); } }; api.fade = { // Sensitivity to allow browsers to render the blank element before animating. sensitivity: 100, In: function( element, speed, callback, stop ) { callback = callback || $.noop; speed = speed || 400; stop = stop || false; if ( api.fade.transitions ) { if ( element.is(':visible') ) { element.addClass( 'fade-trigger' ); return element; } element.show(); element.first().one( transitionend, function() { callback(); }); setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity ); } else { if ( stop ) { element.stop(); } element.css( 'opacity', 1 ); element.first().fadeIn( speed, callback ); if ( element.length > 1 ) { element.not(':first').fadeIn( speed ); } } return element; }, Out: function( element, speed, callback, stop ) { callback = callback || $.noop; speed = speed || 400; stop = stop || false; if ( ! element.is(':visible') ) { return element; } if ( api.fade.transitions ) { element.first().one( transitionend, function() { if ( element.hasClass('fade-trigger') ) { return; } element.hide(); callback(); }); setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity ); } else { if ( stop ) { element.stop(); } element.first().fadeOut( speed, callback ); if ( element.length > 1 ) { element.not(':first').fadeOut( speed ); } } return element; }, // Check if the browser supports CSS 3.0 transitions transitions: ( function() { var style = document.documentElement.style; return ( typeof style.WebkitTransition === 'string' || typeof style.MozTransition === 'string' || typeof style.OTransition === 'string' || typeof style.transition === 'string' ); })() }; /** * Resize API * * Automatically updates textarea height. */ api.bind_resize = function() { s.$dfwTextarea.on( 'keydown.wp-dfw-resize click.wp-dfw-resize paste.wp-dfw-resize', function() { api.resizeTextarea(); }); }; api.resizeTextarea = function() { var node = s.$dfwTextarea[0]; if ( node.scrollHeight > node.clientHeight ) { node.style.height = node.scrollHeight + 50 + 'px'; } }; // Export window.wp = window.wp || {}; window.wp.editor = window.wp.editor || {}; window.wp.editor.fullscreen = api; })( jQuery, window );
JavaScript
/* global tinymce, QTags */ // send html to the post editor var wpActiveEditor, send_to_editor; send_to_editor = function( html ) { var editor, hasTinymce = typeof tinymce !== 'undefined', hasQuicktags = typeof QTags !== 'undefined'; if ( ! wpActiveEditor ) { if ( hasTinymce && tinymce.activeEditor ) { editor = tinymce.activeEditor; wpActiveEditor = editor.id; } else if ( ! hasQuicktags ) { return false; } } else if ( hasTinymce ) { editor = tinymce.get( wpActiveEditor ); } if ( editor && ! editor.isHidden() ) { editor.execCommand( 'mceInsertContent', false, html ); } else if ( hasQuicktags ) { QTags.insertContent( html ); } else { document.getElementById( wpActiveEditor ).value += html; } // If the old thickbox remove function exists, call it if ( window.tb_remove ) { try { window.tb_remove(); } catch( e ) {} } }; // thickbox settings var tb_position; (function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0; if ( $('#wpadminbar').length ) { adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 ); } if ( tbWindow.size() ) { tbWindow.width( W - 50 ).height( H - 45 - adminbar_height ); $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height ); tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'}); if ( typeof document.body.style.maxWidth !== 'undefined' ) tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'}); } return $('a.thickbox').each( function() { var href = $(this).attr('href'); if ( ! href ) return; href = href.replace(/&width=[0-9]+/g, ''); href = href.replace(/&height=[0-9]+/g, ''); $(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) ); }); }; $(window).resize(function(){ tb_position(); }); })(jQuery);
JavaScript
window.wp = window.wp || {}; (function( $, wp ) { wp.updates = {}; /** * Decrement update counts throughout the various menus * * @param {string} updateType */ wp.updates.decrementCount = function( upgradeType ) { var count, pluginCount, $elem; $elem = $( '#wp-admin-bar-updates .ab-label' ); count = $elem.text(); count = parseInt( count, 10 ) - 1; if ( count < 0 ) { return; } $( '#wp-admin-bar-updates .ab-item' ).removeAttr( 'title' ); $elem.text( count ); $elem = $( 'a[href="update-core.php"] .update-plugins' ); $elem.each( function( index, elem ) { elem.className = elem.className.replace( /count-\d+/, 'count-' + count ); } ); $elem.removeAttr( 'title' ); $elem.find( '.update-count' ).text( count ); if ( 'plugin' === upgradeType ) { $elem = $( '#menu-plugins' ); pluginCount = $elem.find( '.plugin-count' ).eq(0).text(); pluginCount = parseInt( pluginCount, 10 ) - 1; if ( count < 0 ) { return; } $elem.find( '.plugin-count' ).text( pluginCount ); $elem.find( '.update-plugins' ).each( function( index, elem ) { elem.className = elem.className.replace( /count-\d+/, 'count-' + pluginCount ); } ); } }; $( window ).on( 'message', function( e ) { var event = e.originalEvent, message, loc = document.location, expectedOrigin = loc.protocol + '//' + loc.hostname; if ( event.origin !== expectedOrigin ) { return; } message = $.parseJSON( event.data ); if ( typeof message.action === 'undefined' || message.action !== 'decrementUpdateCount' ) { return; } wp.updates.decrementCount( message.upgradeType ); } ); })( jQuery, window.wp );
JavaScript
/* global setUserSetting, ajaxurl, commonL10n, alert, confirm, pagenow */ var showNotice, adminMenu, columns, validateForm, screenMeta; ( function( $, window, undefined ) { // Removed in 3.3. // (perhaps) needed for back-compat adminMenu = { init : function() {}, fold : function() {}, restoreMenuState : function() {}, toggle : function() {}, favorites : function() {} }; // show/hide/save table columns columns = { init : function() { var that = this; $('.hide-column-tog', '#adv-settings').click( function() { var $t = $(this), column = $t.val(); if ( $t.prop('checked') ) that.checked(column); else that.unchecked(column); columns.saveManageColumnsState(); }); }, saveManageColumnsState : function() { var hidden = this.hidden(); $.post(ajaxurl, { action: 'hidden-columns', hidden: hidden, screenoptionnonce: $('#screenoptionnonce').val(), page: pagenow }); }, checked : function(column) { $('.column-' + column).show(); this.colSpanChange(+1); }, unchecked : function(column) { $('.column-' + column).hide(); this.colSpanChange(-1); }, hidden : function() { return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(','); }, useCheckboxesForHidden : function() { this.hidden = function(){ return $('.hide-column-tog').not(':checked').map(function() { var id = this.id; return id.substring( id, id.length - 5 ); }).get().join(','); }; }, colSpanChange : function(diff) { var $t = $('table').find('.colspanchange'), n; if ( !$t.length ) return; n = parseInt( $t.attr('colspan'), 10 ) + diff; $t.attr('colspan', n.toString()); } }; $(document).ready(function(){columns.init();}); validateForm = function( form ) { return !$( form ) .find( '.form-required' ) .filter( function() { return $( 'input:visible', this ).val() === ''; } ) .addClass( 'form-invalid' ) .find( 'input:visible' ) .change( function() { $( this ).closest( '.form-invalid' ).removeClass( 'form-invalid' ); } ) .size(); }; // stub for doing better warnings showNotice = { warn : function() { var msg = commonL10n.warnDelete || ''; if ( confirm(msg) ) { return true; } return false; }, note : function(text) { alert(text); } }; screenMeta = { element: null, // #screen-meta toggles: null, // .screen-meta-toggle page: null, // #wpcontent init: function() { this.element = $('#screen-meta'); this.toggles = $('.screen-meta-toggle a'); this.page = $('#wpcontent'); this.toggles.click( this.toggleEvent ); }, toggleEvent: function( e ) { var panel = $( this.href.replace(/.+#/, '#') ); e.preventDefault(); if ( !panel.length ) return; if ( panel.is(':visible') ) screenMeta.close( panel, $(this) ); else screenMeta.open( panel, $(this) ); }, open: function( panel, link ) { $('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden'); panel.parent().show(); panel.slideDown( 'fast', function() { panel.focus(); link.addClass('screen-meta-active').attr('aria-expanded', true); }); }, close: function( panel, link ) { panel.slideUp( 'fast', function() { link.removeClass('screen-meta-active').attr('aria-expanded', false); $('.screen-meta-toggle').css('visibility', ''); panel.parent().hide(); }); } }; /** * Help tabs. */ $('.contextual-help-tabs').delegate('a', 'click focus', function(e) { var link = $(this), panel; e.preventDefault(); // Don't do anything if the click is for the tab already showing. if ( link.is('.active a') ) return false; // Links $('.contextual-help-tabs .active').removeClass('active'); link.parent('li').addClass('active'); panel = $( link.attr('href') ); // Panels $('.help-tab-content').not( panel ).removeClass('active').hide(); panel.addClass('active').show(); }); $(document).ready( function() { var checks, first, last, checked, sliced, mobileEvent, transitionTimeout, focusedRowActions, lastClicked = false, menu = $('#adminmenu'), pageInput = $('input.current-page'), currentPage = pageInput.val(); // when the menu is folded, make the fly-out submenu header clickable menu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){ $(e.target).parent().siblings('a').get(0).click(); }); $('#collapse-menu').on('click.collapse-menu', function() { var body = $( document.body ), respWidth; // reset any compensation for submenus near the bottom of the screen $('#adminmenu div.wp-submenu').css('margin-top', ''); if ( window.innerWidth ) { // window.innerWidth is affected by zooming on phones respWidth = Math.max( window.innerWidth, document.documentElement.clientWidth ); } else { // IE < 9 doesn't support @media CSS rules respWidth = 901; } if ( respWidth && respWidth < 900 ) { if ( body.hasClass('auto-fold') ) { body.removeClass('auto-fold').removeClass('folded'); setUserSetting('unfold', 1); setUserSetting('mfold', 'o'); } else { body.addClass('auto-fold'); setUserSetting('unfold', 0); } } else { if ( body.hasClass('folded') ) { body.removeClass('folded'); setUserSetting('mfold', 'o'); } else { body.addClass('folded'); setUserSetting('mfold', 'f'); } } }); if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device // iOS Safari works with touchstart, the rest work with click mobileEvent = /Mobile\/.+Safari/.test(navigator.userAgent) ? 'touchstart' : 'click'; // close any open submenus when touch/click is not on the menu $(document.body).on( mobileEvent+'.wp-mobile-hover', function(e) { if ( menu.data('wp-responsive') ) { return; } if ( ! $(e.target).closest('#adminmenu').length ) { menu.find('li.wp-has-submenu.opensub').removeClass('opensub'); } }); menu.find('a.wp-has-submenu').on( mobileEvent+'.wp-mobile-hover', function(e) { var b, h, o, f, menutop, wintop, maxtop, el = $(this), parent = el.parent(), m = parent.find('.wp-submenu'); if ( menu.data('wp-responsive') ) { return; } // Show the sub instead of following the link if: // - the submenu is not open // - the submenu is not shown inline or the menu is not folded if ( !parent.hasClass('opensub') && ( !parent.hasClass('wp-menu-open') || parent.width() < 40 ) ) { e.preventDefault(); menutop = parent.offset().top; wintop = $(window).scrollTop(); maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar b = menutop + m.height() + 1; // Bottom offset of the menu h = $('#wpwrap').height(); // Height of the entire page o = 60 + b - h; f = $(window).height() + wintop - 50; // The fold if ( f < (b - o) ) { o = b - f; } if ( o > maxtop ) { o = maxtop; } if ( o > 1 ) { m.css('margin-top', '-'+o+'px'); } else { m.css('margin-top', ''); } menu.find('li.opensub').removeClass('opensub'); parent.addClass('opensub'); } }); } menu.find('li.wp-has-submenu').hoverIntent({ over: function() { var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop, top = parseInt( m.css('top'), 10 ); if ( isNaN(top) || top > -5 ) { // meaning the submenu is visible return; } if ( menu.data('wp-responsive') ) { // The menu is in responsive mode, bail return; } menutop = $(this).offset().top; wintop = $(window).scrollTop(); maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar b = menutop + m.height() + 1; // Bottom offset of the menu h = $('#wpwrap').height(); // Height of the entire page o = 60 + b - h; f = $(window).height() + wintop - 15; // The fold if ( f < (b - o) ) { o = b - f; } if ( o > maxtop ) { o = maxtop; } if ( o > 1 ) { m.css('margin-top', '-'+o+'px'); } else { m.css('margin-top', ''); } menu.find('li.menu-top').removeClass('opensub'); $(this).addClass('opensub'); }, out: function(){ if ( menu.data('wp-responsive') ) { // The menu is in responsive mode, bail return; } $(this).removeClass('opensub').find('.wp-submenu').css('margin-top', ''); }, timeout: 200, sensitivity: 7, interval: 90 }); menu.on('focus.adminmenu', '.wp-submenu a', function(e){ if ( menu.data('wp-responsive') ) { // The menu is in responsive mode, bail return; } $(e.target).closest('li.menu-top').addClass('opensub'); }).on('blur.adminmenu', '.wp-submenu a', function(e){ if ( menu.data('wp-responsive') ) { // The menu is in responsive mode, bail return; } $(e.target).closest('li.menu-top').removeClass('opensub'); }); // Move .updated and .error alert boxes. Don't move boxes designed to be inline. $('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2'); $('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') ); // Init screen meta screenMeta.init(); // check all checkboxes $('tbody').children().children('.check-column').find(':checkbox').click( function(e) { if ( 'undefined' == e.shiftKey ) { return true; } if ( e.shiftKey ) { if ( !lastClicked ) { return true; } checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' ); first = checks.index( lastClicked ); last = checks.index( this ); checked = $(this).prop('checked'); if ( 0 < first && 0 < last && first != last ) { sliced = ( last > first ) ? checks.slice( first, last ) : checks.slice( last, first ); sliced.prop( 'checked', function() { if ( $(this).closest('tr').is(':visible') ) return checked; return false; }); } } lastClicked = this; // toggle "check all" checkboxes var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible').not(':checked'); $(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() { return ( 0 === unchecked.length ); }); return true; }); $('thead, tfoot').find('.check-column :checkbox').on( 'click.wp-toggle-checkboxes', function( event ) { var $this = $(this), $table = $this.closest( 'table' ), controlChecked = $this.prop('checked'), toggle = event.shiftKey || $this.data('wp-toggle'); $table.children( 'tbody' ).filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( $(this).is(':hidden') ) { return false; } if ( toggle ) { return ! $(this).prop( 'checked' ); } else if ( controlChecked ) { return true; } return false; }); $table.children('thead, tfoot').filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( toggle ) { return false; } else if ( controlChecked ) { return true; } return false; }); }); // Show row actions on keyboard focus of its parent container element or any other elements contained within $( 'td.post-title, td.title, td.comment, .bookmarks td.column-name, td.blogname, td.username, .dashboard-comment-wrap' ).focusin(function(){ clearTimeout( transitionTimeout ); focusedRowActions = $(this).find( '.row-actions' ); focusedRowActions.addClass( 'visible' ); }).focusout(function(){ // Tabbing between post title and .row-actions links needs a brief pause, otherwise // the .row-actions div gets hidden in transit in some browsers (ahem, Firefox). transitionTimeout = setTimeout(function(){ focusedRowActions.removeClass( 'visible' ); }, 30); }); $('#default-password-nag-no').click( function() { setUserSetting('default_password_nag', 'hide'); $('div.default-password-nag').hide(); return false; }); // tab in textareas $('#newcontent').bind('keydown.wpevent_InsertTab', function(e) { var el = e.target, selStart, selEnd, val, scroll, sel; if ( e.keyCode == 27 ) { // escape key $(el).data('tab-out', true); return; } if ( e.keyCode != 9 || e.ctrlKey || e.altKey || e.shiftKey ) // tab key return; if ( $(el).data('tab-out') ) { $(el).data('tab-out', false); return; } selStart = el.selectionStart; selEnd = el.selectionEnd; val = el.value; try { this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below. } catch(err) {} if ( document.selection ) { el.focus(); sel = document.selection.createRange(); sel.text = '\t'; } else if ( selStart >= 0 ) { scroll = this.scrollTop; el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) ); el.selectionStart = el.selectionEnd = selStart + 1; this.scrollTop = scroll; } if ( e.stopPropagation ) e.stopPropagation(); if ( e.preventDefault ) e.preventDefault(); }); $('#newcontent').bind('blur.wpevent_InsertTab', function() { if ( this.lastKey && 9 == this.lastKey ) this.focus(); }); if ( pageInput.length ) { pageInput.closest('form').submit( function() { // Reset paging var for new filters/searches but not for bulk actions. See #17685. if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage ) pageInput.val('1'); }); } $('.search-box input[type="search"], .search-box input[type="submit"]').mousedown(function () { $('select[name^="action"]').val('-1'); }); // Scroll into view when focused $('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){ if ( e.target.scrollIntoView ) e.target.scrollIntoView(false); }); // Disable upload buttons until files are selected (function(){ var button, input, form = $('form.wp-upload-form'); if ( ! form.length ) return; button = form.find('input[type="submit"]'); input = form.find('input[type="file"]'); function toggleUploadButton() { button.prop('disabled', '' === input.map( function() { return $(this).val(); }).get().join('')); } toggleUploadButton(); input.on('change', toggleUploadButton); })(); }); // Fire a custom jQuery event at the end of window resize ( function() { var timeout; function triggerEvent() { $(document).trigger( 'wp-window-resized' ); } function fireOnce() { window.clearTimeout( timeout ); timeout = window.setTimeout( triggerEvent, 200 ); } $(window).on( 'resize.wp-fire-once', fireOnce ); }()); $(document).ready( function() { var $document = $( document ), $window = $( window ), $body = $( document.body ), $adminMenuWrap = $( '#adminmenuwrap' ), $collapseMenu = $( '#collapse-menu' ), $wpwrap = $( '#wpwrap' ), $adminmenu = $( '#adminmenu' ), $overlay = $( '#wp-responsive-overlay' ), $toolbar = $( '#wp-toolbar' ), $toolbarPopups = $toolbar.find( 'a[aria-haspopup="true"]' ), $sortables = $('.meta-box-sortables'), stickyMenuActive = false, wpResponsiveActive = false; window.stickyMenu = { enable: function() { if ( ! stickyMenuActive ) { $document.on( 'wp-window-resized.sticky-menu', $.proxy( this.update, this ) ); $collapseMenu.on( 'click.sticky-menu', $.proxy( this.update, this ) ); this.update(); stickyMenuActive = true; } }, disable: function() { if ( stickyMenuActive ) { $window.off( 'resize.sticky-menu' ); $collapseMenu.off( 'click.sticky-menu' ); $body.removeClass( 'sticky-menu' ); stickyMenuActive = false; } }, update: function() { // Make the admin menu sticky if the viewport is taller than it if ( $window.height() > $adminMenuWrap.height() + 32 ) { if ( ! $body.hasClass( 'sticky-menu' ) ) { $body.addClass( 'sticky-menu' ); } } else { if ( $body.hasClass( 'sticky-menu' ) ) { $body.removeClass( 'sticky-menu' ); } } } }; window.wpResponsive = { init: function() { var self = this, scrollStart = 0; // Modify functionality based on custom activate/deactivate event $document.on( 'wp-responsive-activate.wp-responsive', function() { self.activate(); }).on( 'wp-responsive-deactivate.wp-responsive', function() { self.deactivate(); }); $( '#wp-admin-bar-menu-toggle a' ).attr( 'aria-expanded', 'false' ); // Toggle sidebar when toggle is clicked $( '#wp-admin-bar-menu-toggle' ).on( 'click.wp-responsive', function( event ) { event.preventDefault(); $wpwrap.toggleClass( 'wp-responsive-open' ); if ( $wpwrap.hasClass( 'wp-responsive-open' ) ) { $(this).find('a').attr( 'aria-expanded', 'true' ); $( '#adminmenu a:first' ).focus(); } else { $(this).find('a').attr( 'aria-expanded', 'false' ); } } ); // Add menu events $adminmenu.on( 'touchstart.wp-responsive', 'li.wp-has-submenu > a', function() { scrollStart = $window.scrollTop(); }).on( 'touchend.wp-responsive click.wp-responsive', 'li.wp-has-submenu > a', function( event ) { if ( ! $adminmenu.data('wp-responsive') || ( event.type === 'touchend' && $window.scrollTop() !== scrollStart ) ) { return; } $( this ).parent( 'li' ).toggleClass( 'selected' ); event.preventDefault(); }); self.trigger(); $document.on( 'wp-window-resized.wp-responsive', $.proxy( this.trigger, this ) ); // This needs to run later as UI Sortable may be initialized later on $(document).ready() $window.on( 'load.wp-responsive', function() { var width = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $window.width() : window.innerWidth; if ( width <= 782 ) { self.disableSortables(); } }); }, activate: function() { window.stickyMenu.disable(); if ( ! $body.hasClass( 'auto-fold' ) ) { $body.addClass( 'auto-fold' ); } $adminmenu.data( 'wp-responsive', 1 ); this.disableSortables(); }, deactivate: function() { window.stickyMenu.enable(); $adminmenu.removeData('wp-responsive'); this.enableSortables(); }, trigger: function() { var width; if ( window.innerWidth ) { // window.innerWidth is affected by zooming on phones width = Math.max( window.innerWidth, document.documentElement.clientWidth ); } else { // Exclude IE < 9, it doesn't support @media CSS rules return; } if ( width <= 782 ) { if ( ! wpResponsiveActive ) { $document.trigger( 'wp-responsive-activate' ); wpResponsiveActive = true; } } else { if ( wpResponsiveActive ) { $document.trigger( 'wp-responsive-deactivate' ); wpResponsiveActive = false; } } if ( width <= 480 ) { this.enableOverlay(); } else { this.disableOverlay(); } }, enableOverlay: function() { if ( $overlay.length === 0 ) { $overlay = $( '<div id="wp-responsive-overlay"></div>' ) .insertAfter( '#wpcontent' ) .hide() .on( 'click.wp-responsive', function() { $toolbar.find( '.menupop.hover' ).removeClass( 'hover' ); $( this ).hide(); }); } $toolbarPopups.on( 'click.wp-responsive', function() { $overlay.show(); }); }, disableOverlay: function() { $toolbarPopups.off( 'click.wp-responsive' ); $overlay.hide(); }, disableSortables: function() { if ( $sortables.length ) { try { $sortables.sortable('disable'); } catch(e) {} } }, enableSortables: function() { if ( $sortables.length ) { try { $sortables.sortable('enable'); } catch(e) {} } } }; window.stickyMenu.enable(); window.wpResponsive.init(); }); // make Windows 8 devices playing along nicely (function(){ if ( '-ms-user-select' in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/) ) { var msViewportStyle = document.createElement( 'style' ); msViewportStyle.appendChild( document.createTextNode( '@-ms-viewport{width:auto!important}' ) ); document.getElementsByTagName( 'head' )[0].appendChild( msViewportStyle ); } })(); }( jQuery, window ));
JavaScript
/*! * Farbtastic: jQuery color picker plug-in v1.3u * * Licensed under the GPL license: * http://www.gnu.org/licenses/gpl.html */ (function($) { $.fn.farbtastic = function (options) { $.farbtastic(this, options); return this; }; $.farbtastic = function (container, callback) { var container = $(container).get(0); return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback)); }; $._farbtastic = function (container, callback) { // Store farbtastic object var fb = this; // Insert markup $(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>'); var e = $('.farbtastic', container); fb.wheel = $('.wheel', container).get(0); // Dimensions fb.radius = 84; fb.square = 100; fb.width = 194; // Fix background PNGs in IE6 if (navigator.appVersion.match(/MSIE [0-6]\./)) { $('*', e).each(function () { if (this.currentStyle.backgroundImage != 'none') { var image = this.currentStyle.backgroundImage; image = this.currentStyle.backgroundImage.substring(5, image.length - 2); $(this).css({ 'backgroundImage': 'none', 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" }); } }); } /** * Link to the given element(s) or callback. */ fb.linkTo = function (callback) { // Unbind previous nodes if (typeof fb.callback == 'object') { $(fb.callback).unbind('keyup', fb.updateValue); } // Reset color fb.color = null; // Bind callback or elements if (typeof callback == 'function') { fb.callback = callback; } else if (typeof callback == 'object' || typeof callback == 'string') { fb.callback = $(callback); fb.callback.bind('keyup', fb.updateValue); if (fb.callback.get(0).value) { fb.setColor(fb.callback.get(0).value); } } return this; }; fb.updateValue = function (event) { if (this.value && this.value != fb.color) { fb.setColor(this.value); } }; /** * Change color with HTML syntax #123456 */ fb.setColor = function (color) { var unpack = fb.unpack(color); if (fb.color != color && unpack) { fb.color = color; fb.rgb = unpack; fb.hsl = fb.RGBToHSL(fb.rgb); fb.updateDisplay(); } return this; }; /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ fb.setHSL = function (hsl) { fb.hsl = hsl; fb.rgb = fb.HSLToRGB(hsl); fb.color = fb.pack(fb.rgb); fb.updateDisplay(); return this; }; ///////////////////////////////////////////////////// /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ fb.widgetCoords = function (event) { var offset = $(fb.wheel).offset(); return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 }; }; /** * Mousedown handler */ fb.mousedown = function (event) { // Capture mouse if (!document.dragging) { $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); document.dragging = true; } // Check which area is being dragged var pos = fb.widgetCoords(event); fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; // Process fb.mousemove(event); return false; }; /** * Mousemove handler */ fb.mousemove = function (event) { // Get coordinates relative to color picker center var pos = fb.widgetCoords(event); // Set new HSL parameters if (fb.circleDrag) { var hue = Math.atan2(pos.x, -pos.y) / 6.28; if (hue < 0) hue += 1; fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); } else { var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); fb.setHSL([fb.hsl[0], sat, lum]); } return false; }; /** * Mouseup handler */ fb.mouseup = function () { // Uncapture mouse $(document).unbind('mousemove', fb.mousemove); $(document).unbind('mouseup', fb.mouseup); document.dragging = false; }; /** * Update the markers and styles */ fb.updateDisplay = function () { // Markers var angle = fb.hsl[0] * 6.28; $('.h-marker', e).css({ left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' }); $('.sl-marker', e).css({ left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' }); // Saturation/Luminance gradient $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); // Linked elements or callback if (typeof fb.callback == 'object') { // Set background/foreground color $(fb.callback).css({ backgroundColor: fb.color, color: fb.hsl[2] > 0.5 ? '#000' : '#fff' }); // Change linked value $(fb.callback).each(function() { if (this.value && this.value != fb.color) { this.value = fb.color; } }); } else if (typeof fb.callback == 'function') { fb.callback.call(fb, fb.color); } }; /* Various color utility functions */ fb.pack = function (rgb) { var r = Math.round(rgb[0] * 255); var g = Math.round(rgb[1] * 255); var b = Math.round(rgb[2] * 255); return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '') + g.toString(16) + (b < 16 ? '0' : '') + b.toString(16); }; fb.unpack = function (color) { if (color.length == 7) { return [parseInt('0x' + color.substring(1, 3)) / 255, parseInt('0x' + color.substring(3, 5)) / 255, parseInt('0x' + color.substring(5, 7)) / 255]; } else if (color.length == 4) { return [parseInt('0x' + color.substring(1, 2)) / 15, parseInt('0x' + color.substring(2, 3)) / 15, parseInt('0x' + color.substring(3, 4)) / 15]; } }; fb.HSLToRGB = function (hsl) { var m1, m2, r, g, b; var h = hsl[0], s = hsl[1], l = hsl[2]; m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; m1 = l * 2 - m2; return [this.hueToRGB(m1, m2, h+0.33333), this.hueToRGB(m1, m2, h), this.hueToRGB(m1, m2, h-0.33333)]; }; fb.hueToRGB = function (m1, m2, h) { h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; if (h * 2 < 1) return m2; if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; return m1; }; fb.RGBToHSL = function (rgb) { var min, max, delta, h, s, l; var r = rgb[0], g = rgb[1], b = rgb[2]; min = Math.min(r, Math.min(g, b)); max = Math.max(r, Math.max(g, b)); delta = max - min; l = (min + max) / 2; s = 0; if (l > 0 && l < 1) { s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); } h = 0; if (delta > 0) { if (max == r && max != g) h += (g - b) / delta; if (max == g && max != b) h += (2 + (b - r) / delta); if (max == b && max != r) h += (4 + (r - g) / delta); h /= 6; } return [h, s, l]; }; // Install mousedown handler (the others are set on the document on-demand) $('*', e).mousedown(fb.mousedown); // Init color fb.setColor('#000000'); // Set linked elements/callback if (callback) { fb.linkTo(callback); } }; })(jQuery);
JavaScript
/* global zxcvbn */ window.wp = window.wp || {}; var passwordStrength; (function($){ wp.passwordStrength = { /** * Determine the strength of a given password * * @param string password1 The password * @param array blacklist An array of words that will lower the entropy of the password * @param string password2 The confirmed password */ meter : function( password1, blacklist, password2 ) { if ( ! $.isArray( blacklist ) ) blacklist = [ blacklist.toString() ]; if (password1 != password2 && password2 && password2.length > 0) return 5; var result = zxcvbn( password1, blacklist ); return result.score; }, /** * Builds an array of data that should be penalized, because it would lower the entropy of a password if it were used * * @return array The array of data to be blacklisted */ userInputBlacklist : function() { var i, userInputFieldsLength, rawValuesLength, currentField, rawValues = [], blacklist = [], userInputFields = [ 'user_login', 'first_name', 'last_name', 'nickname', 'display_name', 'email', 'url', 'description', 'weblog_title', 'admin_email' ]; // Collect all the strings we want to blacklist rawValues.push( document.title ); rawValues.push( document.URL ); userInputFieldsLength = userInputFields.length; for ( i = 0; i < userInputFieldsLength; i++ ) { currentField = $( '#' + userInputFields[ i ] ); if ( 0 === currentField.length ) { continue; } rawValues.push( currentField[0].defaultValue ); rawValues.push( currentField.val() ); } // Strip out non-alphanumeric characters and convert each word to an individual entry rawValuesLength = rawValues.length; for ( i = 0; i < rawValuesLength; i++ ) { if ( rawValues[ i ] ) { blacklist = blacklist.concat( rawValues[ i ].replace( /\W/g, ' ' ).split( ' ' ) ); } } // Remove empty values, short words, and duplicates. Short words are likely to cause many false positives. blacklist = $.grep( blacklist, function( value, key ) { if ( '' === value || 4 > value.length ) { return false; } return $.inArray( value, blacklist ) === key; }); return blacklist; } }; // Backwards compatibility. passwordStrength = wp.passwordStrength.meter; })(jQuery);
JavaScript
/* global pagenow, ajaxurl, postboxes, wpActiveEditor:true */ var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad; jQuery(document).ready( function($) { var welcomePanel = $( '#welcome-panel' ), welcomePanelHide = $('#wp_welcome_panel-hide'), updateWelcomePanel; updateWelcomePanel = function( visible ) { $.post( ajaxurl, { action: 'update-welcome-panel', visible: visible, welcomepanelnonce: $( '#welcomepanelnonce' ).val() }); }; if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') ) { welcomePanel.removeClass('hidden'); } $('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) { e.preventDefault(); welcomePanel.addClass('hidden'); updateWelcomePanel( 0 ); $('#wp_welcome_panel-hide').prop('checked', false); }); welcomePanelHide.click( function() { welcomePanel.toggleClass('hidden', ! this.checked ); updateWelcomePanel( this.checked ? 1 : 0 ); }); // These widgets are sometimes populated via ajax ajaxWidgets = ['dashboard_primary']; ajaxPopulateWidgets = function(el) { function show(i, id) { var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading'); if ( e.length ) { p = e.parent(); setTimeout( function(){ p.load( ajaxurl + '?action=dashboard-widgets&widget=' + id + '&pagenow=' + pagenow, '', function() { p.hide().slideDown('normal', function(){ $(this).css('display', ''); }); }); }, i * 500 ); } } if ( el ) { el = el.toString(); if ( $.inArray(el, ajaxWidgets) !== -1 ) { show(0, el); } } else { $.each( ajaxWidgets, show ); } }; ajaxPopulateWidgets(); postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } ); /* QuickPress */ quickPressLoad = function() { var act = $('#quickpost-action'), t; t = $('#quick-press').submit( function() { $('#dashboard_quick_press #publishing-action .spinner').show(); $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true); $.post( t.attr( 'action' ), t.serializeArray(), function( data ) { // Replace the form, and prepend the published post. $('#dashboard_quick_press .inside').html( data ); $('#quick-press').removeClass('initial-form'); quickPressLoad(); highlightLatestPost(); $('#title').focus(); }); function highlightLatestPost () { var latestPost = $('.drafts ul li').first(); latestPost.css('background', '#fffbe5'); setTimeout(function () { latestPost.css('background', 'none'); }, 1000); } return false; } ); $('#publish').click( function() { act.val( 'post-quickpress-publish' ); } ); $('#title, #tags-input, #content').each( function() { var input = $(this), prompt = $('#' + this.id + '-prompt-text'); if ( '' === this.value ) { prompt.removeClass('screen-reader-text'); } prompt.click( function() { $(this).addClass('screen-reader-text'); input.focus(); }); input.blur( function() { if ( '' === this.value ) { prompt.removeClass('screen-reader-text'); } }); input.focus( function() { prompt.addClass('screen-reader-text'); }); }); $('#quick-press').on( 'click focusin', function() { wpActiveEditor = 'content'; }); autoResizeTextarea(); }; quickPressLoad(); $( '.meta-box-sortables' ).sortable( 'option', 'containment', 'document' ); function autoResizeTextarea() { if ( document.documentMode && document.documentMode < 9 ) { return; } // Add a hidden div. We'll copy over the text from the textarea to measure its height. $('body').append( '<div class="quick-draft-textarea-clone" style="display: none;"></div>' ); var clone = $('.quick-draft-textarea-clone'), editor = $('#content'), editorHeight = editor.height(), // 100px roughly accounts for browser chrome and allows the // save draft button to show on-screen at the same time. editorMaxHeight = $(window).height() - 100; // Match up textarea and clone div as much as possible. // Padding cannot be reliably retrieved using shorthand in all browsers. clone.css({ 'font-family': editor.css('font-family'), 'font-size': editor.css('font-size'), 'line-height': editor.css('line-height'), 'padding-bottom': editor.css('paddingBottom'), 'padding-left': editor.css('paddingLeft'), 'padding-right': editor.css('paddingRight'), 'padding-top': editor.css('paddingTop'), 'white-space': 'pre-wrap', 'word-wrap': 'break-word', 'display': 'none' }); // propertychange is for IE < 9 editor.on('focus input propertychange', function() { var $this = $(this), // &nbsp; is to ensure that the height of a final trailing newline is included. textareaContent = $this.val() + '&nbsp;', // 2px is for border-top & border-bottom cloneHeight = clone.css('width', $this.css('width')).text(textareaContent).outerHeight() + 2; // Default to having scrollbars editor.css('overflow-y', 'auto'); // Only change the height if it has indeed changed and both heights are below the max. if ( cloneHeight === editorHeight || ( cloneHeight >= editorMaxHeight && editorHeight >= editorMaxHeight ) ) { return; } // Don't allow editor to exceed height of window. // This is also bound in CSS to a max-height of 1300px to be extra safe. if ( cloneHeight > editorMaxHeight ) { editorHeight = editorMaxHeight; } else { editorHeight = cloneHeight; } // No scrollbars as we change height, not for IE < 9 editor.css('overflow', 'hidden'); $this.css('height', editorHeight + 'px'); }); } } );
JavaScript
/* global ajaxurl, current_site_id, isRtl */ (function( $ ) { var id = ( typeof current_site_id !== 'undefined' ) ? '&site_id=' + current_site_id : ''; $(document).ready( function() { var position = { offset: '0, -1' }; if ( typeof isRtl !== 'undefined' && isRtl ) { position.my = 'right top'; position.at = 'right bottom'; } $( '.wp-suggest-user' ).each( function(){ var $this = $( this ), autocompleteType = ( typeof $this.data( 'autocompleteType' ) !== 'undefined' ) ? $this.data( 'autocompleteType' ) : 'add', autocompleteField = ( typeof $this.data( 'autocompleteField' ) !== 'undefined' ) ? $this.data( 'autocompleteField' ) : 'user_login'; $this.autocomplete({ source: ajaxurl + '?action=autocomplete-user&autocomplete_type=' + autocompleteType + '&autocomplete_field=' + autocompleteField + id, delay: 500, minLength: 2, position: position, open: function() { $( this ).addClass( 'open' ); }, close: function() { $( this ).removeClass( 'open' ); } }); }); }); })( jQuery );
JavaScript
/* global _wpRevisionsSettings, isRtl */ window.wp = window.wp || {}; (function($) { var revisions; revisions = wp.revisions = { model: {}, view: {}, controller: {} }; // Link settings. revisions.settings = _.isUndefined( _wpRevisionsSettings ) ? {} : _wpRevisionsSettings; // For debugging revisions.debug = false; revisions.log = function() { if ( window.console && revisions.debug ) { window.console.log.apply( window.console, arguments ); } }; // Handy functions to help with positioning $.fn.allOffsets = function() { var offset = this.offset() || {top: 0, left: 0}, win = $(window); return _.extend( offset, { right: win.width() - offset.left - this.outerWidth(), bottom: win.height() - offset.top - this.outerHeight() }); }; $.fn.allPositions = function() { var position = this.position() || {top: 0, left: 0}, parent = this.parent(); return _.extend( position, { right: parent.outerWidth() - position.left - this.outerWidth(), bottom: parent.outerHeight() - position.top - this.outerHeight() }); }; // wp_localize_script transforms top-level numbers into strings. Undo that. if ( revisions.settings.to ) { revisions.settings.to = parseInt( revisions.settings.to, 10 ); } if ( revisions.settings.from ) { revisions.settings.from = parseInt( revisions.settings.from, 10 ); } // wp_localize_script does not allow for top-level booleans. Fix that. if ( revisions.settings.compareTwoMode ) { revisions.settings.compareTwoMode = revisions.settings.compareTwoMode === '1'; } /** * ======================================================================== * MODELS * ======================================================================== */ revisions.model.Slider = Backbone.Model.extend({ defaults: { value: null, values: null, min: 0, max: 1, step: 1, range: false, compareTwoMode: false }, initialize: function( options ) { this.frame = options.frame; this.revisions = options.revisions; // Listen for changes to the revisions or mode from outside this.listenTo( this.frame, 'update:revisions', this.receiveRevisions ); this.listenTo( this.frame, 'change:compareTwoMode', this.updateMode ); // Listen for internal changes this.listenTo( this, 'change:from', this.handleLocalChanges ); this.listenTo( this, 'change:to', this.handleLocalChanges ); this.listenTo( this, 'change:compareTwoMode', this.updateSliderSettings ); this.listenTo( this, 'update:revisions', this.updateSliderSettings ); // Listen for changes to the hovered revision this.listenTo( this, 'change:hoveredRevision', this.hoverRevision ); this.set({ max: this.revisions.length - 1, compareTwoMode: this.frame.get('compareTwoMode'), from: this.frame.get('from'), to: this.frame.get('to') }); this.updateSliderSettings(); }, getSliderValue: function( a, b ) { return isRtl ? this.revisions.length - this.revisions.indexOf( this.get(a) ) - 1 : this.revisions.indexOf( this.get(b) ); }, updateSliderSettings: function() { if ( this.get('compareTwoMode') ) { this.set({ values: [ this.getSliderValue( 'to', 'from' ), this.getSliderValue( 'from', 'to' ) ], value: null, range: true // ensures handles cannot cross }); } else { this.set({ value: this.getSliderValue( 'to', 'to' ), values: null, range: false }); } this.trigger( 'update:slider' ); }, // Called when a revision is hovered hoverRevision: function( model, value ) { this.trigger( 'hovered:revision', value ); }, // Called when `compareTwoMode` changes updateMode: function( model, value ) { this.set({ compareTwoMode: value }); }, // Called when `from` or `to` changes in the local model handleLocalChanges: function() { this.frame.set({ from: this.get('from'), to: this.get('to') }); }, // Receives revisions changes from outside the model receiveRevisions: function( from, to ) { // Bail if nothing changed if ( this.get('from') === from && this.get('to') === to ) { return; } this.set({ from: from, to: to }, { silent: true }); this.trigger( 'update:revisions', from, to ); } }); revisions.model.Tooltip = Backbone.Model.extend({ defaults: { revision: null, offset: {}, hovering: false, // Whether the mouse is hovering scrubbing: false // Whether the mouse is scrubbing }, initialize: function( options ) { this.frame = options.frame; this.revisions = options.revisions; this.slider = options.slider; this.listenTo( this.slider, 'hovered:revision', this.updateRevision ); this.listenTo( this.slider, 'change:hovering', this.setHovering ); this.listenTo( this.slider, 'change:scrubbing', this.setScrubbing ); }, updateRevision: function( revision ) { this.set({ revision: revision }); }, setHovering: function( model, value ) { this.set({ hovering: value }); }, setScrubbing: function( model, value ) { this.set({ scrubbing: value }); } }); revisions.model.Revision = Backbone.Model.extend({}); revisions.model.Revisions = Backbone.Collection.extend({ model: revisions.model.Revision, initialize: function() { _.bindAll( this, 'next', 'prev' ); }, next: function( revision ) { var index = this.indexOf( revision ); if ( index !== -1 && index !== this.length - 1 ) { return this.at( index + 1 ); } }, prev: function( revision ) { var index = this.indexOf( revision ); if ( index !== -1 && index !== 0 ) { return this.at( index - 1 ); } } }); revisions.model.Field = Backbone.Model.extend({}); revisions.model.Fields = Backbone.Collection.extend({ model: revisions.model.Field }); revisions.model.Diff = Backbone.Model.extend({ initialize: function() { var fields = this.get('fields'); this.unset('fields'); this.fields = new revisions.model.Fields( fields ); } }); revisions.model.Diffs = Backbone.Collection.extend({ initialize: function( models, options ) { _.bindAll( this, 'getClosestUnloaded' ); this.loadAll = _.once( this._loadAll ); this.revisions = options.revisions; this.requests = {}; }, model: revisions.model.Diff, ensure: function( id, context ) { var diff = this.get( id ), request = this.requests[ id ], deferred = $.Deferred(), ids = {}, from = id.split(':')[0], to = id.split(':')[1]; ids[id] = true; wp.revisions.log( 'ensure', id ); this.trigger( 'ensure', ids, from, to, deferred.promise() ); if ( diff ) { deferred.resolveWith( context, [ diff ] ); } else { this.trigger( 'ensure:load', ids, from, to, deferred.promise() ); _.each( ids, _.bind( function( id ) { // Remove anything that has an ongoing request if ( this.requests[ id ] ) { delete ids[ id ]; } // Remove anything we already have if ( this.get( id ) ) { delete ids[ id ]; } }, this ) ); if ( ! request ) { // Always include the ID that started this ensure ids[ id ] = true; request = this.load( _.keys( ids ) ); } request.done( _.bind( function() { deferred.resolveWith( context, [ this.get( id ) ] ); }, this ) ).fail( _.bind( function() { deferred.reject(); }) ); } return deferred.promise(); }, // Returns an array of proximal diffs getClosestUnloaded: function( ids, centerId ) { var self = this; return _.chain([0].concat( ids )).initial().zip( ids ).sortBy( function( pair ) { return Math.abs( centerId - pair[1] ); }).map( function( pair ) { return pair.join(':'); }).filter( function( diffId ) { return _.isUndefined( self.get( diffId ) ) && ! self.requests[ diffId ]; }).value(); }, _loadAll: function( allRevisionIds, centerId, num ) { var self = this, deferred = $.Deferred(), diffs = _.first( this.getClosestUnloaded( allRevisionIds, centerId ), num ); if ( _.size( diffs ) > 0 ) { this.load( diffs ).done( function() { self._loadAll( allRevisionIds, centerId, num ).done( function() { deferred.resolve(); }); }).fail( function() { if ( 1 === num ) { // Already tried 1. This just isn't working. Give up. deferred.reject(); } else { // Request fewer diffs this time self._loadAll( allRevisionIds, centerId, Math.ceil( num / 2 ) ).done( function() { deferred.resolve(); }); } }); } else { deferred.resolve(); } return deferred; }, load: function( comparisons ) { wp.revisions.log( 'load', comparisons ); // Our collection should only ever grow, never shrink, so remove: false return this.fetch({ data: { compare: comparisons }, remove: false }).done( function() { wp.revisions.log( 'load:complete', comparisons ); }); }, sync: function( method, model, options ) { if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'get-revision-diffs', post_id: revisions.settings.postId }); var deferred = wp.ajax.send( options ), requests = this.requests; // Record that we're requesting each diff. if ( options.data.compare ) { _.each( options.data.compare, function( id ) { requests[ id ] = deferred; }); } // When the request completes, clear the stored request. deferred.always( function() { if ( options.data.compare ) { _.each( options.data.compare, function( id ) { delete requests[ id ]; }); } }); return deferred; // Otherwise, fall back to `Backbone.sync()`. } else { return Backbone.Model.prototype.sync.apply( this, arguments ); } } }); revisions.model.FrameState = Backbone.Model.extend({ defaults: { loading: false, error: false, compareTwoMode: false }, initialize: function( attributes, options ) { var properties = {}; _.bindAll( this, 'receiveDiff' ); this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 ); this.revisions = options.revisions; this.diffs = new revisions.model.Diffs( [], { revisions: this.revisions }); // Set the initial diffs collection provided through the settings this.diffs.set( revisions.settings.diffData ); // Set up internal listeners this.listenTo( this, 'change:from', this.changeRevisionHandler ); this.listenTo( this, 'change:to', this.changeRevisionHandler ); this.listenTo( this, 'change:compareTwoMode', this.changeMode ); this.listenTo( this, 'update:revisions', this.updatedRevisions ); this.listenTo( this.diffs, 'ensure:load', this.updateLoadingStatus ); this.listenTo( this, 'update:diff', this.updateLoadingStatus ); // Set the initial revisions, baseUrl, and mode as provided through settings properties.to = this.revisions.get( revisions.settings.to ); properties.from = this.revisions.get( revisions.settings.from ); properties.compareTwoMode = revisions.settings.compareTwoMode; properties.baseUrl = revisions.settings.baseUrl; this.set( properties ); // Start the router if browser supports History API if ( window.history && window.history.pushState ) { this.router = new revisions.Router({ model: this }); Backbone.history.start({ pushState: true }); } }, updateLoadingStatus: function() { this.set( 'error', false ); this.set( 'loading', ! this.diff() ); }, changeMode: function( model, value ) { // If we were on the first revision before switching, we have to bump them over one if ( value && 0 === this.revisions.indexOf( this.get('to') ) ) { this.set({ from: this.revisions.at(0), to: this.revisions.at(1) }); } }, updatedRevisions: function( from, to ) { if ( this.get( 'compareTwoMode' ) ) { // TODO: compare-two loading strategy } else { this.diffs.loadAll( this.revisions.pluck('id'), to.id, 40 ); } }, // Fetch the currently loaded diff. diff: function() { return this.diffs.get( this._diffId ); }, // So long as `from` and `to` are changed at the same time, the diff // will only be updated once. This is because Backbone updates all of // the changed attributes in `set`, and then fires the `change` events. updateDiff: function( options ) { var from, to, diffId, diff; options = options || {}; from = this.get('from'); to = this.get('to'); diffId = ( from ? from.id : 0 ) + ':' + to.id; // Check if we're actually changing the diff id. if ( this._diffId === diffId ) { return $.Deferred().reject().promise(); } this._diffId = diffId; this.trigger( 'update:revisions', from, to ); diff = this.diffs.get( diffId ); // If we already have the diff, then immediately trigger the update. if ( diff ) { this.receiveDiff( diff ); return $.Deferred().resolve().promise(); // Otherwise, fetch the diff. } else { if ( options.immediate ) { return this._ensureDiff(); } else { this._debouncedEnsureDiff(); return $.Deferred().reject().promise(); } } }, // A simple wrapper around `updateDiff` to prevent the change event's // parameters from being passed through. changeRevisionHandler: function() { this.updateDiff(); }, receiveDiff: function( diff ) { // Did we actually get a diff? if ( _.isUndefined( diff ) || _.isUndefined( diff.id ) ) { this.set({ loading: false, error: true }); } else if ( this._diffId === diff.id ) { // Make sure the current diff didn't change this.trigger( 'update:diff', diff ); } }, _ensureDiff: function() { return this.diffs.ensure( this._diffId, this ).always( this.receiveDiff ); } }); /** * ======================================================================== * VIEWS * ======================================================================== */ // The frame view. This contains the entire page. revisions.view.Frame = wp.Backbone.View.extend({ className: 'revisions', template: wp.template('revisions-frame'), initialize: function() { this.listenTo( this.model, 'update:diff', this.renderDiff ); this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode ); this.listenTo( this.model, 'change:loading', this.updateLoadingStatus ); this.listenTo( this.model, 'change:error', this.updateErrorStatus ); this.views.set( '.revisions-control-frame', new revisions.view.Controls({ model: this.model }) ); }, render: function() { wp.Backbone.View.prototype.render.apply( this, arguments ); $('html').css( 'overflow-y', 'scroll' ); $('#wpbody-content .wrap').append( this.el ); this.updateCompareTwoMode(); this.renderDiff( this.model.diff() ); this.views.ready(); return this; }, renderDiff: function( diff ) { this.views.set( '.revisions-diff-frame', new revisions.view.Diff({ model: diff }) ); }, updateLoadingStatus: function() { this.$el.toggleClass( 'loading', this.model.get('loading') ); }, updateErrorStatus: function() { this.$el.toggleClass( 'diff-error', this.model.get('error') ); }, updateCompareTwoMode: function() { this.$el.toggleClass( 'comparing-two-revisions', this.model.get('compareTwoMode') ); } }); // The control view. // This contains the revision slider, previous/next buttons, the meta info and the compare checkbox. revisions.view.Controls = wp.Backbone.View.extend({ className: 'revisions-controls', initialize: function() { _.bindAll( this, 'setWidth' ); // Add the button view this.views.add( new revisions.view.Buttons({ model: this.model }) ); // Add the checkbox view this.views.add( new revisions.view.Checkbox({ model: this.model }) ); // Prep the slider model var slider = new revisions.model.Slider({ frame: this.model, revisions: this.model.revisions }), // Prep the tooltip model tooltip = new revisions.model.Tooltip({ frame: this.model, revisions: this.model.revisions, slider: slider }); // Add the tooltip view this.views.add( new revisions.view.Tooltip({ model: tooltip }) ); // Add the tickmarks view this.views.add( new revisions.view.Tickmarks({ model: tooltip }) ); // Add the slider view this.views.add( new revisions.view.Slider({ model: slider }) ); // Add the Metabox view this.views.add( new revisions.view.Metabox({ model: this.model }) ); }, ready: function() { this.top = this.$el.offset().top; this.window = $(window); this.window.on( 'scroll.wp.revisions', {controls: this}, function(e) { var controls = e.data.controls, container = controls.$el.parent(), scrolled = controls.window.scrollTop(), frame = controls.views.parent; if ( scrolled >= controls.top ) { if ( ! frame.$el.hasClass('pinned') ) { controls.setWidth(); container.css('height', container.height() + 'px' ); controls.window.on('resize.wp.revisions.pinning click.wp.revisions.pinning', {controls: controls}, function(e) { e.data.controls.setWidth(); }); } frame.$el.addClass('pinned'); } else if ( frame.$el.hasClass('pinned') ) { controls.window.off('.wp.revisions.pinning'); controls.$el.css('width', 'auto'); frame.$el.removeClass('pinned'); container.css('height', 'auto'); controls.top = controls.$el.offset().top; } else { controls.top = controls.$el.offset().top; } }); }, setWidth: function() { this.$el.css('width', this.$el.parent().width() + 'px'); } }); // The tickmarks view revisions.view.Tickmarks = wp.Backbone.View.extend({ className: 'revisions-tickmarks', direction: isRtl ? 'right' : 'left', initialize: function() { this.listenTo( this.model, 'change:revision', this.reportTickPosition ); }, reportTickPosition: function( model, revision ) { var offset, thisOffset, parentOffset, tick, index = this.model.revisions.indexOf( revision ); thisOffset = this.$el.allOffsets(); parentOffset = this.$el.parent().allOffsets(); if ( index === this.model.revisions.length - 1 ) { // Last one offset = { rightPlusWidth: thisOffset.left - parentOffset.left + 1, leftPlusWidth: thisOffset.right - parentOffset.right + 1 }; } else { // Normal tick tick = this.$('div:nth-of-type(' + (index + 1) + ')'); offset = tick.allPositions(); _.extend( offset, { left: offset.left + thisOffset.left - parentOffset.left, right: offset.right + thisOffset.right - parentOffset.right }); _.extend( offset, { leftPlusWidth: offset.left + tick.outerWidth(), rightPlusWidth: offset.right + tick.outerWidth() }); } this.model.set({ offset: offset }); }, ready: function() { var tickCount, tickWidth; tickCount = this.model.revisions.length - 1; tickWidth = 1 / tickCount; this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px'); _(tickCount).times( function( index ){ this.$el.append( '<div style="' + this.direction + ': ' + ( 100 * tickWidth * index ) + '%"></div>' ); }, this ); } }); // The metabox view revisions.view.Metabox = wp.Backbone.View.extend({ className: 'revisions-meta', initialize: function() { // Add the 'from' view this.views.add( new revisions.view.MetaFrom({ model: this.model, className: 'diff-meta diff-meta-from' }) ); // Add the 'to' view this.views.add( new revisions.view.MetaTo({ model: this.model }) ); } }); // The revision meta view (to be extended) revisions.view.Meta = wp.Backbone.View.extend({ template: wp.template('revisions-meta'), events: { 'click .restore-revision': 'restoreRevision' }, initialize: function() { this.listenTo( this.model, 'update:revisions', this.render ); }, prepare: function() { return _.extend( this.model.toJSON()[this.type] || {}, { type: this.type }); }, restoreRevision: function() { document.location = this.model.get('to').attributes.restoreUrl; } }); // The revision meta 'from' view revisions.view.MetaFrom = revisions.view.Meta.extend({ className: 'diff-meta diff-meta-from', type: 'from' }); // The revision meta 'to' view revisions.view.MetaTo = revisions.view.Meta.extend({ className: 'diff-meta diff-meta-to', type: 'to' }); // The checkbox view. revisions.view.Checkbox = wp.Backbone.View.extend({ className: 'revisions-checkbox', template: wp.template('revisions-checkbox'), events: { 'click .compare-two-revisions': 'compareTwoToggle' }, initialize: function() { this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode ); }, ready: function() { if ( this.model.revisions.length < 3 ) { $('.revision-toggle-compare-mode').hide(); } }, updateCompareTwoMode: function() { this.$('.compare-two-revisions').prop( 'checked', this.model.get('compareTwoMode') ); }, // Toggle the compare two mode feature when the compare two checkbox is checked. compareTwoToggle: function() { // Activate compare two mode? this.model.set({ compareTwoMode: $('.compare-two-revisions').prop('checked') }); } }); // The tooltip view. // Encapsulates the tooltip. revisions.view.Tooltip = wp.Backbone.View.extend({ className: 'revisions-tooltip', template: wp.template('revisions-meta'), initialize: function() { this.listenTo( this.model, 'change:offset', this.render ); this.listenTo( this.model, 'change:hovering', this.toggleVisibility ); this.listenTo( this.model, 'change:scrubbing', this.toggleVisibility ); }, prepare: function() { if ( _.isNull( this.model.get('revision') ) ) { return; } else { return _.extend( { type: 'tooltip' }, { attributes: this.model.get('revision').toJSON() }); } }, render: function() { var otherDirection, direction, directionVal, flipped, css = {}, position = this.model.revisions.indexOf( this.model.get('revision') ) + 1; flipped = ( position / this.model.revisions.length ) > 0.5; if ( isRtl ) { direction = flipped ? 'left' : 'right'; directionVal = flipped ? 'leftPlusWidth' : direction; } else { direction = flipped ? 'right' : 'left'; directionVal = flipped ? 'rightPlusWidth' : direction; } otherDirection = 'right' === direction ? 'left': 'right'; wp.Backbone.View.prototype.render.apply( this, arguments ); css[direction] = this.model.get('offset')[directionVal] + 'px'; css[otherDirection] = ''; this.$el.toggleClass( 'flipped', flipped ).css( css ); }, visible: function() { return this.model.get( 'scrubbing' ) || this.model.get( 'hovering' ); }, toggleVisibility: function() { if ( this.visible() ) { this.$el.stop().show().fadeTo( 100 - this.el.style.opacity * 100, 1 ); } else { this.$el.stop().fadeTo( this.el.style.opacity * 300, 0, function(){ $(this).hide(); } ); } return; } }); // The buttons view. // Encapsulates all of the configuration for the previous/next buttons. revisions.view.Buttons = wp.Backbone.View.extend({ className: 'revisions-buttons', template: wp.template('revisions-buttons'), events: { 'click .revisions-next .button': 'nextRevision', 'click .revisions-previous .button': 'previousRevision' }, initialize: function() { this.listenTo( this.model, 'update:revisions', this.disabledButtonCheck ); }, ready: function() { this.disabledButtonCheck(); }, // Go to a specific model index gotoModel: function( toIndex ) { var attributes = { to: this.model.revisions.at( toIndex ) }; // If we're at the first revision, unset 'from'. if ( toIndex ) { attributes.from = this.model.revisions.at( toIndex - 1 ); } else { this.model.unset('from', { silent: true }); } this.model.set( attributes ); }, // Go to the 'next' revision nextRevision: function() { var toIndex = this.model.revisions.indexOf( this.model.get('to') ) + 1; this.gotoModel( toIndex ); }, // Go to the 'previous' revision previousRevision: function() { var toIndex = this.model.revisions.indexOf( this.model.get('to') ) - 1; this.gotoModel( toIndex ); }, // Check to see if the Previous or Next buttons need to be disabled or enabled. disabledButtonCheck: function() { var maxVal = this.model.revisions.length - 1, minVal = 0, next = $('.revisions-next .button'), previous = $('.revisions-previous .button'), val = this.model.revisions.indexOf( this.model.get('to') ); // Disable "Next" button if you're on the last node. next.prop( 'disabled', ( maxVal === val ) ); // Disable "Previous" button if you're on the first node. previous.prop( 'disabled', ( minVal === val ) ); } }); // The slider view. revisions.view.Slider = wp.Backbone.View.extend({ className: 'wp-slider', direction: isRtl ? 'right' : 'left', events: { 'mousemove' : 'mouseMove' }, initialize: function() { _.bindAll( this, 'start', 'slide', 'stop', 'mouseMove', 'mouseEnter', 'mouseLeave' ); this.listenTo( this.model, 'update:slider', this.applySliderSettings ); }, ready: function() { this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px'); this.$el.slider( _.extend( this.model.toJSON(), { start: this.start, slide: this.slide, stop: this.stop }) ); this.$el.hoverIntent({ over: this.mouseEnter, out: this.mouseLeave, timeout: 800 }); this.applySliderSettings(); }, mouseMove: function( e ) { var zoneCount = this.model.revisions.length - 1, // One fewer zone than models sliderFrom = this.$el.allOffsets()[this.direction], // "From" edge of slider sliderWidth = this.$el.width(), // Width of slider tickWidth = sliderWidth / zoneCount, // Calculated width of zone actualX = ( isRtl ? $(window).width() - e.pageX : e.pageX ) - sliderFrom, // Flipped for RTL - sliderFrom; currentModelIndex = Math.floor( ( actualX + ( tickWidth / 2 ) ) / tickWidth ); // Calculate the model index // Ensure sane value for currentModelIndex. if ( currentModelIndex < 0 ) { currentModelIndex = 0; } else if ( currentModelIndex >= this.model.revisions.length ) { currentModelIndex = this.model.revisions.length - 1; } // Update the tooltip mode this.model.set({ hoveredRevision: this.model.revisions.at( currentModelIndex ) }); }, mouseLeave: function() { this.model.set({ hovering: false }); }, mouseEnter: function() { this.model.set({ hovering: true }); }, applySliderSettings: function() { this.$el.slider( _.pick( this.model.toJSON(), 'value', 'values', 'range' ) ); var handles = this.$('a.ui-slider-handle'); if ( this.model.get('compareTwoMode') ) { // in RTL mode the 'left handle' is the second in the slider, 'right' is first handles.first() .toggleClass( 'to-handle', !! isRtl ) .toggleClass( 'from-handle', ! isRtl ); handles.last() .toggleClass( 'from-handle', !! isRtl ) .toggleClass( 'to-handle', ! isRtl ); } else { handles.removeClass('from-handle to-handle'); } }, start: function( event, ui ) { this.model.set({ scrubbing: true }); // Track the mouse position to enable smooth dragging, // overrides default jQuery UI step behavior. $( window ).on( 'mousemove.wp.revisions', { view: this }, function( e ) { var handles, view = e.data.view, leftDragBoundary = view.$el.offset().left, sliderOffset = leftDragBoundary, sliderRightEdge = leftDragBoundary + view.$el.width(), rightDragBoundary = sliderRightEdge, leftDragReset = '0', rightDragReset = '100%', handle = $( ui.handle ); // In two handle mode, ensure handles can't be dragged past each other. // Adjust left/right boundaries and reset points. if ( view.model.get('compareTwoMode') ) { handles = handle.parent().find('.ui-slider-handle'); if ( handle.is( handles.first() ) ) { // We're the left handle rightDragBoundary = handles.last().offset().left; rightDragReset = rightDragBoundary - sliderOffset; } else { // We're the right handle leftDragBoundary = handles.first().offset().left + handles.first().width(); leftDragReset = leftDragBoundary - sliderOffset; } } // Follow mouse movements, as long as handle remains inside slider. if ( e.pageX < leftDragBoundary ) { handle.css( 'left', leftDragReset ); // Mouse to left of slider. } else if ( e.pageX > rightDragBoundary ) { handle.css( 'left', rightDragReset ); // Mouse to right of slider. } else { handle.css( 'left', e.pageX - sliderOffset ); // Mouse in slider. } } ); }, getPosition: function( position ) { return isRtl ? this.model.revisions.length - position - 1: position; }, // Responds to slide events slide: function( event, ui ) { var attributes, movedRevision; // Compare two revisions mode if ( this.model.get('compareTwoMode') ) { // Prevent sliders from occupying same spot if ( ui.values[1] === ui.values[0] ) { return false; } if ( isRtl ) { ui.values.reverse(); } attributes = { from: this.model.revisions.at( this.getPosition( ui.values[0] ) ), to: this.model.revisions.at( this.getPosition( ui.values[1] ) ) }; } else { attributes = { to: this.model.revisions.at( this.getPosition( ui.value ) ) }; // If we're at the first revision, unset 'from'. if ( this.getPosition( ui.value ) > 0 ) { attributes.from = this.model.revisions.at( this.getPosition( ui.value ) - 1 ); } else { attributes.from = undefined; } } movedRevision = this.model.revisions.at( this.getPosition( ui.value ) ); // If we are scrubbing, a scrub to a revision is considered a hover if ( this.model.get('scrubbing') ) { attributes.hoveredRevision = movedRevision; } this.model.set( attributes ); }, stop: function() { $( window ).off('mousemove.wp.revisions'); this.model.updateSliderSettings(); // To snap us back to a tick mark this.model.set({ scrubbing: false }); } }); // The diff view. // This is the view for the current active diff. revisions.view.Diff = wp.Backbone.View.extend({ className: 'revisions-diff', template: wp.template('revisions-diff'), // Generate the options to be passed to the template. prepare: function() { return _.extend({ fields: this.model.fields.toJSON() }, this.options ); } }); // The revisions router. // Maintains the URL routes so browser URL matches state. revisions.Router = Backbone.Router.extend({ initialize: function( options ) { this.model = options.model; // Maintain state and history when navigating this.listenTo( this.model, 'update:diff', _.debounce( this.updateUrl, 250 ) ); this.listenTo( this.model, 'change:compareTwoMode', this.updateUrl ); }, baseUrl: function( url ) { return this.model.get('baseUrl') + url; }, updateUrl: function() { var from = this.model.has('from') ? this.model.get('from').id : 0, to = this.model.get('to').id; if ( this.model.get('compareTwoMode' ) ) { this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ), { replace: true } ); } else { this.navigate( this.baseUrl( '?revision=' + to ), { replace: true } ); } }, handleRoute: function( a, b ) { var compareTwo = _.isUndefined( b ); if ( ! compareTwo ) { b = this.model.revisions.get( a ); a = this.model.revisions.prev( b ); b = b ? b.id : 0; a = a ? a.id : 0; } } }); // Initialize the revisions UI. revisions.init = function() { revisions.view.frame = new revisions.view.Frame({ model: new revisions.model.FrameState({}, { revisions: new revisions.model.Revisions( revisions.settings.revisionData ) }) }).render(); }; $( revisions.init ); }(jQuery));
JavaScript
/* global postL10n, ajaxurl, wpAjax, setPostThumbnailL10n, postboxes, pagenow, tinymce, alert, deleteUserSetting */ /* global theList:true, theExtraList:true, getUserSetting, setUserSetting */ var tagBox, commentsBox, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint, makeSlugeditClickable, editPermalink; // Back-compat: prevent fatal errors makeSlugeditClickable = editPermalink = function(){}; window.wp = window.wp || {}; // return an array with any duplicate, whitespace or values removed function array_unique_noempty(a) { var out = []; jQuery.each( a, function(key, val) { val = jQuery.trim(val); if ( val && jQuery.inArray(val, out) == -1 ) out.push(val); } ); return out; } ( function($) { var titleHasFocus = false; tagBox = { clean : function(tags) { var comma = postL10n.comma; if ( ',' !== comma ) tags = tags.replace(new RegExp(comma, 'g'), ','); tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, ''); if ( ',' !== comma ) tags = tags.replace(/,/g, comma); return tags; }, parseTags : function(el) { var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'), thetags = taxbox.find('.the-tags'), comma = postL10n.comma, current_tags = thetags.val().split(comma), new_tags = []; delete current_tags[num]; $.each( current_tags, function(key, val) { val = $.trim(val); if ( val ) { new_tags.push(val); } }); thetags.val( this.clean( new_tags.join(comma) ) ); this.quickClicks(taxbox); return false; }, quickClicks : function(el) { var thetags = $('.the-tags', el), tagchecklist = $('.tagchecklist', el), id = $(el).attr('id'), current_tags, disabled; if ( !thetags.length ) return; disabled = thetags.prop('disabled'); current_tags = thetags.val().split(postL10n.comma); tagchecklist.empty(); $.each( current_tags, function( key, val ) { var span, xbutton; val = $.trim( val ); if ( ! val ) return; // Create a new span, and ensure the text is properly escaped. span = $('<span />').text( val ); // If tags editing isn't disabled, create the X button. if ( ! disabled ) { xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' ); xbutton.click( function(){ tagBox.parseTags(this); }); span.prepend('&nbsp;').prepend( xbutton ); } // Append the span to the tag list. tagchecklist.append( span ); }); }, flushTags : function(el, a, f) { var tagsval, newtags, text, tags = $('.the-tags', el), newtag = $('input.newtag', el), comma = postL10n.comma; a = a || false; text = a ? $(a).text() : newtag.val(); tagsval = tags.val(); newtags = tagsval ? tagsval + comma + text : text; newtags = this.clean( newtags ); newtags = array_unique_noempty( newtags.split(comma) ).join(comma); tags.val(newtags); this.quickClicks(el); if ( !a ) newtag.val(''); if ( 'undefined' == typeof(f) ) newtag.focus(); return false; }, get : function(id) { var tax = id.substr(id.indexOf('-')+1); $.post(ajaxurl, {'action':'get-tagcloud', 'tax':tax}, function(r, stat) { if ( 0 === r || 'success' != stat ) r = wpAjax.broken; r = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>'); $('a', r).click(function(){ tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this); return false; }); $('#'+id).after(r); }); }, init : function() { var t = this, ajaxtag = $('div.ajaxtag'); $('.tagsdiv').each( function() { tagBox.quickClicks(this); }); $('input.tagadd', ajaxtag).click(function(){ t.flushTags( $(this).closest('.tagsdiv') ); }); $('div.taghint', ajaxtag).click(function(){ $(this).css('visibility', 'hidden').parent().siblings('.newtag').focus(); }); $('input.newtag', ajaxtag).blur(function() { if ( '' === this.value ) $(this).parent().siblings('.taghint').css('visibility', ''); }).focus(function(){ $(this).parent().siblings('.taghint').css('visibility', 'hidden'); }).keyup(function(e){ if ( 13 == e.which ) { tagBox.flushTags( $(this).closest('.tagsdiv') ); return false; } }).keypress(function(e){ if ( 13 == e.which ) { e.preventDefault(); return false; } }).each(function(){ var tax = $(this).closest('div.tagsdiv').attr('id'); $(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: postL10n.comma + ' ' } ); }); // save tags on post save/publish $('#post').submit(function(){ $('div.tagsdiv').each( function() { tagBox.flushTags(this, false, 1); }); }); // tag cloud $('a.tagcloud-link').click(function(){ tagBox.get( $(this).attr('id') ); $(this).unbind().click(function(){ $(this).siblings('.the-tagcloud').toggle(); return false; }); return false; }); } }; commentsBox = { st : 0, get : function(total, num) { var st = this.st, data; if ( ! num ) num = 20; this.st += num; this.total = total; $('#commentsdiv .spinner').show(); data = { 'action' : 'get-comments', 'mode' : 'single', '_ajax_nonce' : $('#add_comment_nonce').val(), 'p' : $('#post_ID').val(), 'start' : st, 'number' : num }; $.post(ajaxurl, data, function(r) { r = wpAjax.parseAjaxResponse(r); $('#commentsdiv .widefat').show(); $('#commentsdiv .spinner').hide(); if ( 'object' == typeof r && r.responses[0] ) { $('#the-comment-list').append( r.responses[0].data ); theList = theExtraList = null; $( 'a[className*=\':\']' ).unbind(); if ( commentsBox.st > commentsBox.total ) $('#show-comments').hide(); else $('#show-comments').show().children('a').html(postL10n.showcomm); return; } else if ( 1 == r ) { $('#show-comments').html(postL10n.endcomm); return; } $('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>'); } ); return false; } }; WPSetThumbnailHTML = function(html){ $('.inside', '#postimagediv').html(html); }; WPSetThumbnailID = function(id){ var field = $('input[value="_thumbnail_id"]', '#list-table'); if ( field.size() > 0 ) { $('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id); } }; WPRemoveThumbnail = function(nonce){ $.post(ajaxurl, { action: 'set-post-thumbnail', post_id: $( '#post_ID' ).val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie ) }, function(str){ if ( str == '0' ) { alert( setPostThumbnailL10n.error ); } else { WPSetThumbnailHTML(str); } } ); }; $(document).on( 'heartbeat-send.refresh-lock', function( e, data ) { var lock = $('#active_post_lock').val(), post_id = $('#post_ID').val(), send = {}; if ( ! post_id || ! $('#post-lock-dialog').length ) return; send.post_id = post_id; if ( lock ) send.lock = lock; data['wp-refresh-post-lock'] = send; }).on( 'heartbeat-tick.refresh-lock', function( e, data ) { // Post locks: update the lock string or show the dialog if somebody has taken over editing var received, wrap, avatar; if ( data['wp-refresh-post-lock'] ) { received = data['wp-refresh-post-lock']; if ( received.lock_error ) { // show "editing taken over" message wrap = $('#post-lock-dialog'); if ( wrap.length && ! wrap.is(':visible') ) { if ( wp.autosave ) { // Save the latest changes and disable $(document).one( 'heartbeat-tick', function() { wp.autosave.server.suspend(); wrap.removeClass('saving').addClass('saved'); $(window).off( 'beforeunload.edit-post' ); }); wrap.addClass('saving'); wp.autosave.server.triggerSave(); } if ( received.lock_error.avatar_src ) { avatar = $('<img class="avatar avatar-64 photo" width="64" height="64" />').attr( 'src', received.lock_error.avatar_src.replace(/&amp;/g, '&') ); wrap.find('div.post-locked-avatar').empty().append( avatar ); } wrap.show().find('.currently-editing').text( received.lock_error.text ); wrap.find('.wp-tab-first').focus(); } } else if ( received.new_lock ) { $('#active_post_lock').val( received.new_lock ); } } }).on( 'before-autosave.update-post-slug', function() { titleHasFocus = document.activeElement && document.activeElement.id === 'title'; }).on( 'after-autosave.update-post-slug', function() { // Create slug area only if not already there // and the title field was not focused (user was not typing a title) when autosave ran if ( ! $('#edit-slug-box > *').length && ! titleHasFocus ) { $.post( ajaxurl, { action: 'sample-permalink', post_id: $('#post_ID').val(), new_title: $('#title').val(), samplepermalinknonce: $('#samplepermalinknonce').val() }, function( data ) { if ( data != '-1' ) { $('#edit-slug-box').html(data); } } ); } }); }(jQuery)); (function($) { var check, timeout; function schedule() { check = false; window.clearTimeout( timeout ); timeout = window.setTimeout( function(){ check = true; }, 300000 ); } $(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) { var nonce, post_id; if ( check ) { if ( ( post_id = $('#post_ID').val() ) && ( nonce = $('#_wpnonce').val() ) ) { data['wp-refresh-post-nonces'] = { post_id: post_id, post_nonce: nonce }; } } }).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) { var nonces = data['wp-refresh-post-nonces']; if ( nonces ) { schedule(); if ( nonces.replace ) { $.each( nonces.replace, function( selector, value ) { $( '#' + selector ).val( value ); }); } if ( nonces.heartbeatNonce ) window.heartbeatSettings.nonce = nonces.heartbeatNonce; } }).ready( function() { schedule(); }); }(jQuery)); jQuery(document).ready( function($) { var stamp, visibility, $submitButtons, updateVisibility, updateText, sticky = '', last = 0, co = $('#content'), $document = $(document), $editSlugWrap = $('#edit-slug-box'), postId = $('#post_ID').val() || 0, $submitpost = $('#submitpost'), releaseLock = true, $postVisibilitySelect = $('#post-visibility-select'), $timestampdiv = $('#timestampdiv'), $postStatusSelect = $('#post-status-select'); postboxes.add_postbox_toggles(pagenow); // Clear the window name. Otherwise if this is a former preview window where the user navigated to edit another post, // and the first post is still being edited, clicking Preview there will use this window to show the preview. window.name = ''; // Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item. $('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) { if ( e.which != 9 ) return; var target = $(e.target); if ( target.hasClass('wp-tab-first') && e.shiftKey ) { $(this).find('.wp-tab-last').focus(); e.preventDefault(); } else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) { $(this).find('.wp-tab-first').focus(); e.preventDefault(); } }).filter(':visible').find('.wp-tab-first').focus(); // Set the heartbeat interval to 15 sec. if post lock dialogs are enabled if ( wp.heartbeat && $('#post-lock-dialog').length ) { wp.heartbeat.interval( 15 ); } // The form is being submitted by the user $submitButtons = $submitpost.find( ':button, :submit, a.submitdelete, #post-preview' ).on( 'click.edit-post', function( event ) { var $button = $(this); if ( $button.hasClass('disabled') ) { event.preventDefault(); return; } if ( $button.hasClass('submitdelete') || $button.is( '#post-preview' ) ) { return; } // The form submission can be blocked from JS or by using HTML 5.0 validation on some fields. // Run this only on an actual 'submit'. $('form#post').off( 'submit.edit-post' ).on( 'submit.edit-post', function( event ) { if ( event.isDefaultPrevented() ) { return; } // Stop autosave if ( wp.autosave ) { wp.autosave.server.suspend(); } releaseLock = false; $(window).off( 'beforeunload.edit-post' ); $submitButtons.addClass( 'disabled' ); if ( $button.attr('id') === 'publish' ) { $submitpost.find('#major-publishing-actions .spinner').show(); } else { $submitpost.find('#minor-publishing .spinner').show(); } }); }); // Submit the form saving a draft or an autosave, and show a preview in a new tab $('#post-preview').on( 'click.post-preview', function( event ) { var $this = $(this), $form = $('form#post'), $previewField = $('input#wp-preview'), target = $this.attr('target') || 'wp-preview', ua = navigator.userAgent.toLowerCase(); event.preventDefault(); if ( $this.hasClass('disabled') ) { return; } if ( wp.autosave ) { wp.autosave.server.tempBlockSave(); } $previewField.val('dopreview'); $form.attr( 'target', target ).submit().attr( 'target', '' ); // Workaround for WebKit bug preventing a form submitting twice to the same action. // https://bugs.webkit.org/show_bug.cgi?id=28633 if ( ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 ) { $form.attr( 'action', function( index, value ) { return value + '?t=' + ( new Date() ).getTime(); }); } $previewField.val(''); }); // This code is meant to allow tabbing from Title to Post content. $('#title').on( 'keydown.editor-focus', function( event ) { var editor, $textarea; if ( event.keyCode === 9 && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) { editor = typeof tinymce != 'undefined' && tinymce.get('content'); $textarea = $('#content'); if ( editor && ! editor.isHidden() ) { editor.focus(); } else if ( $textarea.length ) { $textarea.focus(); } else { return; } event.preventDefault(); } }); // Autosave new posts after a title is typed if ( $( '#auto_draft' ).val() ) { $( '#title' ).blur( function() { var cancel; if ( ! this.value || $('#edit-slug-box > *').length ) { return; } // Cancel the autosave when the blur was triggered by the user submitting the form $('form#post').one( 'submit', function() { cancel = true; }); window.setTimeout( function() { if ( ! cancel && wp.autosave ) { wp.autosave.server.triggerSave(); } }, 200 ); }); } $document.on( 'autosave-disable-buttons.edit-post', function() { $submitButtons.addClass( 'disabled' ); }).on( 'autosave-enable-buttons.edit-post', function() { if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) { $submitButtons.removeClass( 'disabled' ); } }).on( 'before-autosave.edit-post', function() { $( '.autosave-message' ).text( postL10n.savingText ); }).on( 'after-autosave.edit-post', function( event, data ) { $( '.autosave-message' ).text( data.message ); }); $(window).on( 'beforeunload.edit-post', function() { var editor = typeof tinymce !== 'undefined' && tinymce.get('content'); if ( ( editor && ! editor.isHidden() && editor.isDirty() ) || ( wp.autosave && wp.autosave.server.postChanged() ) ) { return postL10n.saveAlert; } }).on( 'unload.edit-post', function( event ) { if ( ! releaseLock ) { return; } // Unload is triggered (by hand) on removing the Thickbox iframe. // Make sure we process only the main document unload. if ( event.target && event.target.nodeName != '#document' ) { return; } $.ajax({ type: 'POST', url: ajaxurl, async: false, data: { action: 'wp-remove-post-lock', _wpnonce: $('#_wpnonce').val(), post_ID: $('#post_ID').val(), active_post_lock: $('#active_post_lock').val() } }); }); // multi-taxonomies if ( $('#tagsdiv-post_tag').length ) { tagBox.init(); } else { $('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){ if ( this.id.indexOf('tagsdiv-') === 0 ) { tagBox.init(); return false; } }); } // categories $('.categorydiv').each( function(){ var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName; taxonomyParts = this_id.split('-'); taxonomyParts.shift(); taxonomy = taxonomyParts.join('-'); settingName = taxonomy + '_tab'; if ( taxonomy == 'category' ) settingName = 'cats'; // TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js $('a', '#' + taxonomy + '-tabs').click( function(){ var t = $(this).attr('href'); $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); $('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide(); $(t).show(); if ( '#' + taxonomy + '-all' == t ) deleteUserSetting( settingName ); else setUserSetting( settingName, 'pop' ); return false; }); if ( getUserSetting( settingName ) ) $('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click(); // Ajax Cat $( '#new' + taxonomy ).one( 'focus', function() { $( this ).val( '' ).removeClass( 'form-input-tip' ); } ); $('#new' + taxonomy).keypress( function(event){ if( 13 === event.keyCode ) { event.preventDefault(); $('#' + taxonomy + '-add-submit').click(); } }); $('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); }); catAddBefore = function( s ) { if ( !$('#new'+taxonomy).val() ) return false; s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize(); $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true ); return s; }; catAddAfter = function( r, s ) { var sup, drop = $('#new'+taxonomy+'_parent'); $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false ); if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) { drop.before(sup); drop.remove(); } }; $('#' + taxonomy + 'checklist').wpList({ alt: '', response: taxonomy + '-ajax-response', addBefore: catAddBefore, addAfter: catAddAfter }); $('#' + taxonomy + '-add-toggle').click( function() { $('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' ); $('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click(); $('#new'+taxonomy).focus(); return false; }); $('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', function() { var t = $(this), c = t.is(':checked'), id = t.val(); if ( id && t.parents('#taxonomy-'+taxonomy).length ) $('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c ); }); }); // end cats // Custom Fields if ( $('#postcustom').length ) { $( '#the-list' ).wpList( { addAfter: function() { $('table#list-table').show(); }, addBefore: function( s ) { s.data += '&post_id=' + $('#post_ID').val(); return s; } }); } // submitdiv if ( $('#submitdiv').length ) { stamp = $('#timestamp').html(); visibility = $('#post-visibility-display').html(); updateVisibility = function() { if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) { $('#sticky').prop('checked', false); $('#sticky-span').hide(); } else { $('#sticky-span').show(); } if ( $postVisibilitySelect.find('input:radio:checked').val() != 'password' ) { $('#password-span').hide(); } else { $('#password-span').show(); } }; updateText = function() { if ( ! $timestampdiv.length ) return true; var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'), optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(); attemptedDate = new Date( aa, mm - 1, jj, hh, mn ); originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() ); currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() ); if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) { $timestampdiv.find('.timestamp-wrap').addClass('form-invalid'); return false; } else { $timestampdiv.find('.timestamp-wrap').removeClass('form-invalid'); } if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) { publishOn = postL10n.publishOnFuture; $('#publish').val( postL10n.schedule ); } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) { publishOn = postL10n.publishOn; $('#publish').val( postL10n.publish ); } else { publishOn = postL10n.publishOnPast; $('#publish').val( postL10n.update ); } if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack $('#timestamp').html(stamp); } else { $('#timestamp').html( publishOn + ' <b>' + postL10n.dateFormat.replace( '%1$s', $('option[value="' + $('#mm').val() + '"]', '#mm').text() ) .replace( '%2$s', jj ) .replace( '%3$s', aa ) .replace( '%4$s', hh ) .replace( '%5$s', mn ) + '</b> ' ); } if ( $postVisibilitySelect.find('input:radio:checked').val() == 'private' ) { $('#publish').val( postL10n.update ); if ( 0 === optPublish.length ) { postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>'); } else { optPublish.html( postL10n.privatelyPublished ); } $('option[value="publish"]', postStatus).prop('selected', true); $('#misc-publishing-actions .edit-post-status').hide(); } else { if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) { if ( optPublish.length ) { optPublish.remove(); postStatus.val($('#hidden_post_status').val()); } } else { optPublish.html( postL10n.published ); } if ( postStatus.is(':hidden') ) $('#misc-publishing-actions .edit-post-status').show(); } $('#post-status-display').html($('option:selected', postStatus).text()); if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) { $('#save-post').hide(); } else { $('#save-post').show(); if ( $('option:selected', postStatus).val() == 'pending' ) { $('#save-post').show().val( postL10n.savePending ); } else { $('#save-post').show().val( postL10n.saveDraft ); } } return true; }; $( '#visibility .edit-visibility').click( function () { if ( $postVisibilitySelect.is(':hidden') ) { updateVisibility(); $postVisibilitySelect.slideDown('fast').find('input[type="radio"]').first().focus(); $(this).hide(); } return false; }); $postVisibilitySelect.find('.cancel-post-visibility').click( function( event ) { $postVisibilitySelect.slideUp('fast'); $('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true); $('#post_password').val($('#hidden-post-password').val()); $('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked')); $('#post-visibility-display').html(visibility); $('#visibility .edit-visibility').show().focus(); updateText(); event.preventDefault(); }); $postVisibilitySelect.find('.save-post-visibility').click( function( event ) { // crazyhorse - multiple ok cancels $postVisibilitySelect.slideUp('fast'); $('#visibility .edit-visibility').show(); updateText(); if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) { $('#sticky').prop('checked', false); } // WEAPON LOCKED if ( $('#sticky').prop('checked') ) { sticky = 'Sticky'; } else { sticky = ''; } $('#post-visibility-display').html( postL10n[ $postVisibilitySelect.find('input:radio:checked').val() + sticky ] ); event.preventDefault(); }); $postVisibilitySelect.find('input:radio').change( function() { updateVisibility(); }); $timestampdiv.siblings('a.edit-timestamp').click( function( event ) { if ( $timestampdiv.is( ':hidden' ) ) { $timestampdiv.slideDown('fast'); $('#mm').focus(); $(this).hide(); } event.preventDefault(); }); $timestampdiv.find('.cancel-timestamp').click( function( event ) { $timestampdiv.slideUp('fast').siblings('a.edit-timestamp').show().focus(); $('#mm').val($('#hidden_mm').val()); $('#jj').val($('#hidden_jj').val()); $('#aa').val($('#hidden_aa').val()); $('#hh').val($('#hidden_hh').val()); $('#mn').val($('#hidden_mn').val()); updateText(); event.preventDefault(); }); $timestampdiv.find('.save-timestamp').click( function( event ) { // crazyhorse - multiple ok cancels if ( updateText() ) { $timestampdiv.slideUp('fast'); $timestampdiv.siblings('a.edit-timestamp').show(); } event.preventDefault(); }); $('#post').on( 'submit', function( event ) { if ( ! updateText() ) { event.preventDefault(); $timestampdiv.show(); if ( wp.autosave ) { wp.autosave.enableButtons(); } $('#publishing-action .spinner').hide(); } }); $postStatusSelect.siblings('a.edit-post-status').click( function( event ) { if ( $postStatusSelect.is( ':hidden' ) ) { $postStatusSelect.slideDown('fast').find('select').focus(); $(this).hide(); } event.preventDefault(); }); $postStatusSelect.find('.save-post-status').click( function( event ) { $postStatusSelect.slideUp('fast').siblings('a.edit-post-status').show(); updateText(); event.preventDefault(); }); $postStatusSelect.find('.cancel-post-status').click( function( event ) { $('#post-status-select').slideUp('fast').siblings( 'a.edit-post-status' ).show().focus(); $('#post_status').val( $('#hidden_post_status').val() ); updateText(); event.preventDefault(); }); } // end submitdiv // permalink function editPermalink() { var i, slug_value, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html(); $('#view-post-btn').hide(); b.html('<a href="#" class="save button button-small">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>'); b.children('.save').click(function() { var new_slug = e.children('input').val(); if ( new_slug == $('#editable-post-name-full').text() ) { return $('#edit-slug-buttons .cancel').click(); } $.post(ajaxurl, { action: 'sample-permalink', post_id: postId, new_slug: new_slug, new_title: $('#title').val(), samplepermalinknonce: $('#samplepermalinknonce').val() }, function(data) { var box = $('#edit-slug-box'); box.html(data); if (box.hasClass('hidden')) { box.fadeIn('fast', function () { box.removeClass('hidden'); }); } b.html(revert_b); real_slug.val(new_slug); $('#view-post-btn').show(); }); return false; }); $('#edit-slug-buttons .cancel').click(function() { $('#view-post-btn').show(); e.html(revert_e); b.html(revert_b); real_slug.val(revert_slug); return false; }); for ( i = 0; i < full.length; ++i ) { if ( '%' == full.charAt(i) ) c++; } slug_value = ( c > full.length / 4 ) ? '' : full; e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e) { var key = e.keyCode || 0; // on enter, just save the new slug, don't save the post if ( 13 == key ) { b.children('.save').click(); return false; } if ( 27 == key ) { b.children('.cancel').click(); return false; } } ).keyup( function() { real_slug.val(this.value); }).focus(); } if ( $editSlugWrap.length ) { $editSlugWrap.on( 'click', function( event ) { var $target = $( event.target ); if ( $target.is('#editable-post-name') || $target.hasClass('edit-slug') ) { editPermalink(); } }); } // word count if ( typeof(wpWordCount) != 'undefined' ) { $document.triggerHandler('wpcountwords', [ co.val() ]); co.keyup( function(e) { var k = e.keyCode || e.charCode; if ( k == last ) return true; if ( 13 == k || 8 == last || 46 == last ) $document.triggerHandler('wpcountwords', [ co.val() ]); last = k; return true; }); } wptitlehint = function(id) { id = id || 'title'; var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text'); if ( '' === title.val() ) titleprompt.removeClass('screen-reader-text'); titleprompt.click(function(){ $(this).addClass('screen-reader-text'); title.focus(); }); title.blur(function(){ if ( '' === this.value ) titleprompt.removeClass('screen-reader-text'); }).focus(function(){ titleprompt.addClass('screen-reader-text'); }).keydown(function(e){ titleprompt.addClass('screen-reader-text'); $(this).unbind(e); }); }; wptitlehint(); // Resize the visual and text editors ( function() { var editor, offset, mce, $textarea = $('textarea#content'), $handle = $('#post-status-info'); // No point for touch devices if ( ! $textarea.length || 'ontouchstart' in window ) { return; } function dragging( event ) { if ( mce ) { editor.theme.resizeTo( null, offset + event.pageY ); } else { $textarea.height( Math.max( 50, offset + event.pageY ) ); } event.preventDefault(); } function endDrag() { var height, toolbarHeight; if ( mce ) { editor.focus(); toolbarHeight = $( '#wp-content-editor-container .mce-toolbar-grp' ).height(); if ( toolbarHeight < 10 || toolbarHeight > 200 ) { toolbarHeight = 30; } height = parseInt( $('#content_ifr').css('height'), 10 ) + toolbarHeight - 28; } else { $textarea.focus(); height = parseInt( $textarea.css('height'), 10 ); } $document.off( '.wp-editor-resize' ); // sanity check if ( height && height > 50 && height < 5000 ) { setUserSetting( 'ed_size', height ); } } $textarea.css( 'resize', 'none' ); $handle.on( 'mousedown.wp-editor-resize', function( event ) { if ( typeof tinymce !== 'undefined' ) { editor = tinymce.get('content'); } if ( editor && ! editor.isHidden() ) { mce = true; offset = $('#content_ifr').height() - event.pageY; } else { mce = false; offset = $textarea.height() - event.pageY; $textarea.blur(); } $document.on( 'mousemove.wp-editor-resize', dragging ) .on( 'mouseup.wp-editor-resize mouseleave.wp-editor-resize', endDrag ); event.preventDefault(); }).on( 'mouseup.wp-editor-resize', endDrag ); })(); if ( typeof tinymce !== 'undefined' ) { // When changing post formats, change the editor body class $( '#post-formats-select input.post-format' ).on( 'change.set-editor-class', function() { var editor, body, format = this.id; if ( format && $( this ).prop('checked') ) { editor = tinymce.get( 'content' ); if ( editor ) { body = editor.getBody(); body.className = body.className.replace( /\bpost-format-[^ ]+/, '' ); editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format ); } } }); } });
JavaScript
/** * WordPress Administration Navigation Menu * Interface JS functions * * @version 2.0.0 * * @package WordPress * @subpackage Administration */ /* global menus, postboxes, columns, isRtl, navMenuL10n, ajaxurl */ var wpNavMenu; (function($) { var api; api = wpNavMenu = { options : { menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead. globalMaxDepth : 11 }, menuList : undefined, // Set in init. targetList : undefined, // Set in init. menusChanged : false, isRTL: !! ( 'undefined' != typeof isRtl && isRtl ), negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1, // Functions that run on init. init : function() { api.menuList = $('#menu-to-edit'); api.targetList = api.menuList; this.jQueryExtensions(); this.attachMenuEditListeners(); this.setupInputWithDefaultTitle(); this.attachQuickSearchListeners(); this.attachThemeLocationsListeners(); this.attachTabsPanelListeners(); this.attachUnsavedChangesListener(); if ( api.menuList.length ) this.initSortables(); if ( menus.oneThemeLocationNoMenus ) $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom ); this.initManageLocations(); this.initAccessibility(); this.initToggles(); }, jQueryExtensions : function() { // jQuery extensions $.fn.extend({ menuItemDepth : function() { var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left'); return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 ); }, updateDepthClass : function(current, prev) { return this.each(function(){ var t = $(this); prev = prev || t.menuItemDepth(); $(this).removeClass('menu-item-depth-'+ prev ) .addClass('menu-item-depth-'+ current ); }); }, shiftDepthClass : function(change) { return this.each(function(){ var t = $(this), depth = t.menuItemDepth(); $(this).removeClass('menu-item-depth-'+ depth ) .addClass('menu-item-depth-'+ (depth + change) ); }); }, childMenuItems : function() { var result = $(); this.each(function(){ var t = $(this), depth = t.menuItemDepth(), next = t.next(); while( next.length && next.menuItemDepth() > depth ) { result = result.add( next ); next = next.next(); } }); return result; }, shiftHorizontally : function( dir ) { return this.each(function(){ var t = $(this), depth = t.menuItemDepth(), newDepth = depth + dir; // Change .menu-item-depth-n class t.moveHorizontally( newDepth, depth ); }); }, moveHorizontally : function( newDepth, depth ) { return this.each(function(){ var t = $(this), children = t.childMenuItems(), diff = newDepth - depth, subItemText = t.find('.is-submenu'); // Change .menu-item-depth-n class t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId(); // If it has children, move those too if ( children ) { children.each(function() { var t = $(this), thisDepth = t.menuItemDepth(), newDepth = thisDepth + diff; t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId(); }); } // Show "Sub item" helper text if (0 === newDepth) subItemText.hide(); else subItemText.show(); }); }, updateParentMenuItemDBId : function() { return this.each(function(){ var item = $(this), input = item.find( '.menu-item-data-parent-id' ), depth = parseInt( item.menuItemDepth(), 10 ), parentDepth = depth - 1, parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first(); if ( 0 === depth ) { // Item is on the top level, has no parent input.val(0); } else { // Find the parent item, and retrieve its object id. input.val( parent.find( '.menu-item-data-db-id' ).val() ); } }); }, hideAdvancedMenuItemFields : function() { return this.each(function(){ var that = $(this); $('.hide-column-tog').not(':checked').each(function(){ that.find('.field-' + $(this).val() ).addClass('hidden-field'); }); }); }, /** * Adds selected menu items to the menu. * * @param jQuery metabox The metabox jQuery object. */ addSelectedToMenu : function(processMethod) { if ( 0 === $('#menu-to-edit').length ) { return false; } return this.each(function() { var t = $(this), menuItems = {}, checkboxes = ( menus.oneThemeLocationNoMenus && 0 === t.find( '.tabs-panel-active .categorychecklist li input:checked' ).length ) ? t.find( '#page-all li input[type="checkbox"]' ) : t.find( '.tabs-panel-active .categorychecklist li input:checked' ), re = /menu-item\[([^\]]*)/; processMethod = processMethod || api.addMenuItemToBottom; // If no items are checked, bail. if ( !checkboxes.length ) return false; // Show the ajax spinner t.find('.spinner').show(); // Retrieve menu item data $(checkboxes).each(function(){ var t = $(this), listItemDBIDMatch = re.exec( t.attr('name') ), listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10); if ( this.className && -1 != this.className.indexOf('add-to-top') ) processMethod = api.addMenuItemToTop; menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID ); }); // Add the items api.addItemToMenu(menuItems, processMethod, function(){ // Deselect the items and hide the ajax spinner checkboxes.removeAttr('checked'); t.find('.spinner').hide(); }); }); }, getItemData : function( itemType, id ) { itemType = itemType || 'menu-item'; var itemData = {}, i, fields = [ 'menu-item-db-id', 'menu-item-object-id', 'menu-item-object', 'menu-item-parent-id', 'menu-item-position', 'menu-item-type', 'menu-item-title', 'menu-item-url', 'menu-item-description', 'menu-item-attr-title', 'menu-item-target', 'menu-item-classes', 'menu-item-xfn' ]; if( !id && itemType == 'menu-item' ) { id = this.find('.menu-item-data-db-id').val(); } if( !id ) return itemData; this.find('input').each(function() { var field; i = fields.length; while ( i-- ) { if( itemType == 'menu-item' ) field = fields[i] + '[' + id + ']'; else if( itemType == 'add-menu-item' ) field = 'menu-item[' + id + '][' + fields[i] + ']'; if ( this.name && field == this.name ) { itemData[fields[i]] = this.value; } } }); return itemData; }, setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id. itemType = itemType || 'menu-item'; if( !id && itemType == 'menu-item' ) { id = $('.menu-item-data-db-id', this).val(); } if( !id ) return this; this.find('input').each(function() { var t = $(this), field; $.each( itemData, function( attr, val ) { if( itemType == 'menu-item' ) field = attr + '[' + id + ']'; else if( itemType == 'add-menu-item' ) field = 'menu-item[' + id + '][' + attr + ']'; if ( field == t.attr('name') ) { t.val( val ); } }); }); return this; } }); }, countMenuItems : function( depth ) { return $( '.menu-item-depth-' + depth ).length; }, moveMenuItem : function( $this, dir ) { var items, newItemPosition, newDepth, menuItems = $( '#menu-to-edit li' ), menuItemsCount = menuItems.length, thisItem = $this.parents( 'li.menu-item' ), thisItemChildren = thisItem.childMenuItems(), thisItemData = thisItem.getItemData(), thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ), thisItemPosition = parseInt( thisItem.index(), 10 ), nextItem = thisItem.next(), nextItemChildren = nextItem.childMenuItems(), nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1, prevItem = thisItem.prev(), prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ), prevItemId = prevItem.getItemData()['menu-item-db-id']; switch ( dir ) { case 'up': newItemPosition = thisItemPosition - 1; // Already at top if ( 0 === thisItemPosition ) break; // If a sub item is moved to top, shift it to 0 depth if ( 0 === newItemPosition && 0 !== thisItemDepth ) thisItem.moveHorizontally( 0, thisItemDepth ); // If prev item is sub item, shift to match depth if ( 0 !== prevItemDepth ) thisItem.moveHorizontally( prevItemDepth, thisItemDepth ); // Does this item have sub items? if ( thisItemChildren ) { items = thisItem.add( thisItemChildren ); // Move the entire block items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId(); } else { thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId(); } break; case 'down': // Does this item have sub items? if ( thisItemChildren ) { items = thisItem.add( thisItemChildren ), nextItem = menuItems.eq( items.length + thisItemPosition ), nextItemChildren = 0 !== nextItem.childMenuItems().length; if ( nextItemChildren ) { newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1; thisItem.moveHorizontally( newDepth, thisItemDepth ); } // Have we reached the bottom? if ( menuItemsCount === thisItemPosition + items.length ) break; items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId(); } else { // If next item has sub items, shift depth if ( 0 !== nextItemChildren.length ) thisItem.moveHorizontally( nextItemDepth, thisItemDepth ); // Have we reached the bottom if ( menuItemsCount === thisItemPosition + 1 ) break; thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId(); } break; case 'top': // Already at top if ( 0 === thisItemPosition ) break; // Does this item have sub items? if ( thisItemChildren ) { items = thisItem.add( thisItemChildren ); // Move the entire block items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId(); } else { thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId(); } break; case 'left': // As far left as possible if ( 0 === thisItemDepth ) break; thisItem.shiftHorizontally( -1 ); break; case 'right': // Can't be sub item at top if ( 0 === thisItemPosition ) break; // Already sub item of prevItem if ( thisItemData['menu-item-parent-id'] === prevItemId ) break; thisItem.shiftHorizontally( 1 ); break; } $this.focus(); api.registerChange(); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, initAccessibility : function() { var menu = $( '#menu-to-edit' ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); // Events menu.on( 'click', '.menus-move-up', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'up' ); e.preventDefault(); }); menu.on( 'click', '.menus-move-down', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'down' ); e.preventDefault(); }); menu.on( 'click', '.menus-move-top', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'top' ); e.preventDefault(); }); menu.on( 'click', '.menus-move-left', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'left' ); e.preventDefault(); }); menu.on( 'click', '.menus-move-right', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'right' ); e.preventDefault(); }); }, refreshAdvancedAccessibility : function() { // Hide all links by default $( '.menu-item-settings .field-move a' ).css( 'display', 'none' ); $( '.item-edit' ).each( function() { var thisLink, thisLinkText, primaryItems, itemPosition, title, parentItem, parentItemId, parentItemName, subItems, $this = $(this), menuItem = $this.closest( 'li.menu-item' ).first(), depth = menuItem.menuItemDepth(), isPrimaryMenuItem = ( 0 === depth ), itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(), position = parseInt( menuItem.index(), 10 ), prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ), prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(), prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(), totalMenuItems = $('#menu-to-edit li').length, hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length; // Where can they move this menu item? if ( 0 !== position ) { thisLink = menuItem.find( '.menus-move-up' ); thisLink.prop( 'title', menus.moveUp ).css( 'display', 'inline' ); } if ( 0 !== position && isPrimaryMenuItem ) { thisLink = menuItem.find( '.menus-move-top' ); thisLink.prop( 'title', menus.moveToTop ).css( 'display', 'inline' ); } if ( position + 1 !== totalMenuItems && 0 !== position ) { thisLink = menuItem.find( '.menus-move-down' ); thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' ); } if ( 0 === position && 0 !== hasSameDepthSibling ) { thisLink = menuItem.find( '.menus-move-down' ); thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' ); } if ( ! isPrimaryMenuItem ) { thisLink = menuItem.find( '.menus-move-left' ), thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft ); thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).html( thisLinkText ).css( 'display', 'inline' ); } if ( 0 !== position ) { if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) { thisLink = menuItem.find( '.menus-move-right' ), thisLinkText = menus.under.replace( '%s', prevItemNameRight ); thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).html( thisLinkText ).css( 'display', 'inline' ); } } if ( isPrimaryMenuItem ) { primaryItems = $( '.menu-item-depth-0' ), itemPosition = primaryItems.index( menuItem ) + 1, totalMenuItems = primaryItems.length, // String together help text for primary menu items title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems ); } else { parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(), parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(), parentItemName = parentItem.find( '.menu-item-title' ).text(), subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ), itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1; // String together help text for sub menu items title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName ); } $this.prop('title', title).html( title ); }); }, refreshKeyboardAccessibility : function() { $( '.item-edit' ).off( 'focus' ).on( 'focus', function(){ $(this).off( 'keydown' ).on( 'keydown', function(e){ var arrows, $this = $( this ), thisItem = $this.parents( 'li.menu-item' ), thisItemData = thisItem.getItemData(); // Bail if it's not an arrow key if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which ) return; // Avoid multiple keydown events $this.off('keydown'); // Bail if there is only one menu item if ( 1 === $('#menu-to-edit li').length ) return; // If RTL, swap left/right arrows arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' }; if ( $('body').hasClass('rtl') ) arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' }; switch ( arrows[e.which] ) { case 'up': api.moveMenuItem( $this, 'up' ); break; case 'down': api.moveMenuItem( $this, 'down' ); break; case 'left': api.moveMenuItem( $this, 'left' ); break; case 'right': api.moveMenuItem( $this, 'right' ); break; } // Put focus back on same menu item $( '#edit-' + thisItemData['menu-item-db-id'] ).focus(); return false; }); }); }, initToggles : function() { // init postboxes postboxes.add_postbox_toggles('nav-menus'); // adjust columns functions for menus UI columns.useCheckboxesForHidden(); columns.checked = function(field) { $('.field-' + field).removeClass('hidden-field'); }; columns.unchecked = function(field) { $('.field-' + field).addClass('hidden-field'); }; // hide fields api.menuList.hideAdvancedMenuItemFields(); $('.hide-postbox-tog').click(function () { var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(','); $.post(ajaxurl, { action: 'closed-postboxes', hidden: hidden, closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(), page: 'nav-menus' }); }); }, initSortables : function() { var currentDepth = 0, originalDepth, minDepth, maxDepth, prev, next, prevBottom, nextThreshold, helperHeight, transport, menuEdge = api.menuList.offset().left, body = $('body'), maxChildDepth, menuMaxDepth = initialMenuMaxDepth(); if( 0 !== $( '#menu-to-edit li' ).length ) $( '.drag-instructions' ).show(); // Use the right edge if RTL. menuEdge += api.isRTL ? api.menuList.width() : 0; api.menuList.sortable({ handle: '.menu-item-handle', placeholder: 'sortable-placeholder', start: function(e, ui) { var height, width, parent, children, tempHolder; // handle placement for rtl orientation if ( api.isRTL ) ui.item[0].style.right = 'auto'; transport = ui.item.children('.menu-item-transport'); // Set depths. currentDepth must be set before children are located. originalDepth = ui.item.menuItemDepth(); updateCurrentDepth(ui, originalDepth); // Attach child elements to parent // Skip the placeholder parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item; children = parent.childMenuItems(); transport.append( children ); // Update the height of the placeholder to match the moving item. height = transport.outerHeight(); // If there are children, account for distance between top of children and parent height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0; height += ui.helper.outerHeight(); helperHeight = height; height -= 2; // Subtract 2 for borders ui.placeholder.height(height); // Update the width of the placeholder to match the moving item. maxChildDepth = originalDepth; children.each(function(){ var depth = $(this).menuItemDepth(); maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth; }); width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width width += api.depthToPx(maxChildDepth - originalDepth); // Account for children width -= 2; // Subtract 2 for borders ui.placeholder.width(width); // Update the list of menu items. tempHolder = ui.placeholder.next(); tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item $(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know. ui.item.after( ui.placeholder ); // reattach the placeholder. tempHolder.css('margin-top', 0); // reset the margin // Now that the element is complete, we can update... updateSharedVars(ui); }, stop: function(e, ui) { var children, subMenuTitle, depthChange = currentDepth - originalDepth; // Return child elements to the list children = transport.children().insertAfter(ui.item); // Add "sub menu" description subMenuTitle = ui.item.find( '.item-title .is-submenu' ); if ( 0 < currentDepth ) subMenuTitle.show(); else subMenuTitle.hide(); // Update depth classes if ( 0 !== depthChange ) { ui.item.updateDepthClass( currentDepth ); children.shiftDepthClass( depthChange ); updateMenuMaxDepth( depthChange ); } // Register a change api.registerChange(); // Update the item data. ui.item.updateParentMenuItemDBId(); // address sortable's incorrectly-calculated top in opera ui.item[0].style.top = 0; // handle drop placement for rtl orientation if ( api.isRTL ) { ui.item[0].style.left = 'auto'; ui.item[0].style.right = 0; } api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, change: function(e, ui) { // Make sure the placeholder is inside the menu. // Otherwise fix it, or we're in trouble. if( ! ui.placeholder.parent().hasClass('menu') ) (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder ); updateSharedVars(ui); }, sort: function(e, ui) { var offset = ui.helper.offset(), edge = api.isRTL ? offset.left + ui.helper.width() : offset.left, depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge ); // Check and correct if depth is not within range. // Also, if the dragged element is dragged upwards over // an item, shift the placeholder to a child position. if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth; else if ( depth < minDepth ) depth = minDepth; if( depth != currentDepth ) updateCurrentDepth(ui, depth); // If we overlap the next element, manually shift downwards if( nextThreshold && offset.top + helperHeight > nextThreshold ) { next.after( ui.placeholder ); updateSharedVars( ui ); $( this ).sortable( 'refreshPositions' ); } } }); function updateSharedVars(ui) { var depth; prev = ui.placeholder.prev(); next = ui.placeholder.next(); // Make sure we don't select the moving item. if( prev[0] == ui.item[0] ) prev = prev.prev(); if( next[0] == ui.item[0] ) next = next.next(); prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0; nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0; minDepth = (next.length) ? next.menuItemDepth() : 0; if( prev.length ) maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth; else maxDepth = 0; } function updateCurrentDepth(ui, depth) { ui.placeholder.updateDepthClass( depth, currentDepth ); currentDepth = depth; } function initialMenuMaxDepth() { if( ! body[0].className ) return 0; var match = body[0].className.match(/menu-max-depth-(\d+)/); return match && match[1] ? parseInt( match[1], 10 ) : 0; } function updateMenuMaxDepth( depthChange ) { var depth, newDepth = menuMaxDepth; if ( depthChange === 0 ) { return; } else if ( depthChange > 0 ) { depth = maxChildDepth + depthChange; if( depth > menuMaxDepth ) newDepth = depth; } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) { while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 ) newDepth--; } // Update the depth class. body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth ); menuMaxDepth = newDepth; } }, initManageLocations : function () { $('#menu-locations-wrap form').submit(function(){ window.onbeforeunload = null; }); $('.menu-location-menus select').on('change', function () { var editLink = $(this).closest('tr').find('.locations-edit-menu-link'); if ($(this).find('option:selected').data('orig')) editLink.show(); else editLink.hide(); }); }, attachMenuEditListeners : function() { var that = this; $('#update-nav-menu').bind('click', function(e) { if ( e.target && e.target.className ) { if ( -1 != e.target.className.indexOf('item-edit') ) { return that.eventOnClickEditLink(e.target); } else if ( -1 != e.target.className.indexOf('menu-save') ) { return that.eventOnClickMenuSave(e.target); } else if ( -1 != e.target.className.indexOf('menu-delete') ) { return that.eventOnClickMenuDelete(e.target); } else if ( -1 != e.target.className.indexOf('item-delete') ) { return that.eventOnClickMenuItemDelete(e.target); } else if ( -1 != e.target.className.indexOf('item-cancel') ) { return that.eventOnClickCancelLink(e.target); } } }); $('#add-custom-links input[type="text"]').keypress(function(e){ if ( e.keyCode === 13 ) { e.preventDefault(); $( '#submit-customlinkdiv' ).click(); } }); }, /** * An interface for managing default values for input elements * that is both JS and accessibility-friendly. * * Input elements that add the class 'input-with-default-title' * will have their values set to the provided HTML title when empty. */ setupInputWithDefaultTitle : function() { var name = 'input-with-default-title'; $('.' + name).each( function(){ var $t = $(this), title = $t.attr('title'), val = $t.val(); $t.data( name, title ); if( '' === val ) $t.val( title ); else if ( title == val ) return; else $t.removeClass( name ); }).focus( function(){ var $t = $(this); if( $t.val() == $t.data(name) ) $t.val('').removeClass( name ); }).blur( function(){ var $t = $(this); if( '' === $t.val() ) $t.addClass( name ).val( $t.data(name) ); }); $( '.blank-slate .input-with-default-title' ).focus(); }, attachThemeLocationsListeners : function() { var loc = $('#nav-menu-theme-locations'), params = {}; params.action = 'menu-locations-save'; params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val(); loc.find('input[type="submit"]').click(function() { loc.find('select').each(function() { params[this.name] = $(this).val(); }); loc.find('.spinner').show(); $.post( ajaxurl, params, function() { loc.find('.spinner').hide(); }); return false; }); }, attachQuickSearchListeners : function() { var searchTimer; $('.quick-search').keypress(function(e){ var t = $(this); if( 13 == e.which ) { api.updateQuickSearchResults( t ); return false; } if( searchTimer ) clearTimeout(searchTimer); searchTimer = setTimeout(function(){ api.updateQuickSearchResults( t ); }, 400); }).attr('autocomplete','off'); }, updateQuickSearchResults : function(input) { var panel, params, minSearchLength = 2, q = input.val(); if( q.length < minSearchLength ) return; panel = input.parents('.tabs-panel'); params = { 'action': 'menu-quick-search', 'response-format': 'markup', 'menu': $('#menu').val(), 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(), 'q': q, 'type': input.attr('name') }; $('.spinner', panel).show(); $.post( ajaxurl, params, function(menuMarkup) { api.processQuickSearchQueryResponse(menuMarkup, params, panel); }); }, addCustomLink : function( processMethod ) { var url = $('#custom-menu-item-url').val(), label = $('#custom-menu-item-name').val(); processMethod = processMethod || api.addMenuItemToBottom; if ( '' === url || 'http://' == url ) return false; // Show the ajax spinner $('.customlinkdiv .spinner').show(); this.addLinkToMenu( url, label, processMethod, function() { // Remove the ajax spinner $('.customlinkdiv .spinner').hide(); // Set custom link form back to defaults $('#custom-menu-item-name').val('').blur(); $('#custom-menu-item-url').val('http://'); }); }, addLinkToMenu : function(url, label, processMethod, callback) { processMethod = processMethod || api.addMenuItemToBottom; callback = callback || function(){}; api.addItemToMenu({ '-1': { 'menu-item-type': 'custom', 'menu-item-url': url, 'menu-item-title': label } }, processMethod, callback); }, addItemToMenu : function(menuItem, processMethod, callback) { var menu = $('#menu').val(), nonce = $('#menu-settings-column-nonce').val(), params; processMethod = processMethod || function(){}; callback = callback || function(){}; params = { 'action': 'add-menu-item', 'menu': menu, 'menu-settings-column-nonce': nonce, 'menu-item': menuItem }; $.post( ajaxurl, params, function(menuMarkup) { var ins = $('#menu-instructions'); menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces processMethod(menuMarkup, params); // Make it stand out a bit more visually, by adding a fadeIn $( 'li.pending' ).hide().fadeIn('slow'); $( '.drag-instructions' ).show(); if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length ) ins.addClass( 'menu-instructions-inactive' ); callback(); }); }, /** * Process the add menu item request response into menu list item. * * @param string menuMarkup The text server response of menu item markup. * @param object req The request arguments. */ addMenuItemToBottom : function( menuMarkup ) { $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, addMenuItemToTop : function( menuMarkup ) { $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, attachUnsavedChangesListener : function() { $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){ api.registerChange(); }); if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) { window.onbeforeunload = function(){ if ( api.menusChanged ) return navMenuL10n.saveAlert; }; } else { // Make the post boxes read-only, as they can't be used yet $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' ); } }, registerChange : function() { api.menusChanged = true; }, attachTabsPanelListeners : function() { $('#menu-settings-column').bind('click', function(e) { var selectAreaMatch, panelId, wrapper, items, target = $(e.target); if ( target.hasClass('nav-tab-link') ) { panelId = target.data( 'type' ); wrapper = target.parents('.accordion-section-content').first(); // upon changing tabs, we want to uncheck all checkboxes $('input', wrapper).removeAttr('checked'); $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive'); $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active'); $('.tabs', wrapper).removeClass('tabs'); target.parent().addClass('tabs'); // select the search bar $('.quick-search', wrapper).focus(); e.preventDefault(); } else if ( target.hasClass('select-all') ) { selectAreaMatch = /#(.*)$/.exec(e.target.href); if ( selectAreaMatch && selectAreaMatch[1] ) { items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input'); if( items.length === items.filter(':checked').length ) items.removeAttr('checked'); else items.prop('checked', true); return false; } } else if ( target.hasClass('submit-add-to-menu') ) { api.registerChange(); if ( e.target.id && 'submit-customlinkdiv' == e.target.id ) api.addCustomLink( api.addMenuItemToBottom ); else if ( e.target.id && -1 != e.target.id.indexOf('submit-') ) $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom ); return false; } else if ( target.hasClass('page-numbers') ) { $.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox', function( resp ) { if ( -1 == resp.indexOf('replace-id') ) return; var metaBoxData = $.parseJSON(resp), toReplace = document.getElementById(metaBoxData['replace-id']), placeholder = document.createElement('div'), wrap = document.createElement('div'); if ( ! metaBoxData.markup || ! toReplace ) return; wrap.innerHTML = metaBoxData.markup ? metaBoxData.markup : ''; toReplace.parentNode.insertBefore( placeholder, toReplace ); placeholder.parentNode.removeChild( toReplace ); placeholder.parentNode.insertBefore( wrap, placeholder ); placeholder.parentNode.removeChild( placeholder ); } ); return false; } }); }, eventOnClickEditLink : function(clickedEl) { var settings, item, matchedSection = /#(.*)$/.exec(clickedEl.href); if ( matchedSection && matchedSection[1] ) { settings = $('#'+matchedSection[1]); item = settings.parent(); if( 0 !== item.length ) { if( item.hasClass('menu-item-edit-inactive') ) { if( ! settings.data('menu-item-data') ) { settings.data( 'menu-item-data', settings.getItemData() ); } settings.slideDown('fast'); item.removeClass('menu-item-edit-inactive') .addClass('menu-item-edit-active'); } else { settings.slideUp('fast'); item.removeClass('menu-item-edit-active') .addClass('menu-item-edit-inactive'); } return false; } } }, eventOnClickCancelLink : function(clickedEl) { var settings = $( clickedEl ).closest( '.menu-item-settings' ), thisMenuItem = $( clickedEl ).closest( '.menu-item' ); thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive'); settings.setItemData( settings.data('menu-item-data') ).hide(); return false; }, eventOnClickMenuSave : function() { var locs = '', menuName = $('#menu-name'), menuNameVal = menuName.val(); // Cancel and warn if invalid menu name if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) { menuName.parent().addClass('form-invalid'); return false; } // Copy menu theme locations $('#nav-menu-theme-locations select').each(function() { locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />'; }); $('#update-nav-menu').append( locs ); // Update menu item position data api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } ); window.onbeforeunload = null; return true; }, eventOnClickMenuDelete : function() { // Delete warning AYS if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) { window.onbeforeunload = null; return true; } return false; }, eventOnClickMenuItemDelete : function(clickedEl) { var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10); api.removeMenuItem( $('#menu-item-' + itemID) ); api.registerChange(); return false; }, /** * Process the quick search response into a search result * * @param string resp The server response to the query. * @param object req The request arguments. * @param jQuery panel The tabs panel we're searching in. */ processQuickSearchQueryResponse : function(resp, req, panel) { var matched, newID, takenIDs = {}, form = document.getElementById('nav-menu-meta'), pattern = /menu-item[(\[^]\]*/, $items = $('<div>').html(resp).find('li'), $item; if( ! $items.length ) { $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' ); $('.spinner', panel).hide(); return; } $items.each(function(){ $item = $(this); // make a unique DB ID number matched = pattern.exec($item.html()); if ( matched && matched[1] ) { newID = matched[1]; while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) { newID--; } takenIDs[newID] = true; if ( newID != matched[1] ) { $item.html( $item.html().replace(new RegExp( 'menu-item\\[' + matched[1] + '\\]', 'g'), 'menu-item[' + newID + ']' ) ); } } }); $('.categorychecklist', panel).html( $items ); $('.spinner', panel).hide(); }, removeMenuItem : function(el) { var children = el.childMenuItems(); el.addClass('deleting').animate({ opacity : 0, height: 0 }, 350, function() { var ins = $('#menu-instructions'); el.remove(); children.shiftDepthClass( -1 ).updateParentMenuItemDBId(); if ( 0 === $( '#menu-to-edit li' ).length ) { $( '.drag-instructions' ).hide(); ins.removeClass( 'menu-instructions-inactive' ); } }); }, depthToPx : function(depth) { return depth * api.options.menuItemDepthPerLevel; }, pxToDepth : function(px) { return Math.floor(px / api.options.menuItemDepthPerLevel); } }; $(document).ready(function(){ wpNavMenu.init(); }); })(jQuery);
JavaScript