code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 FCKURLParams object that is used to get all parameters * passed by the URL QueryString (after the "?"). */ // #### URLParams: holds all URL passed parameters (like ?Param1=Value1&Param2=Value2) var FCKURLParams = new Object() ; (function() { var aParams = document.location.search.substr(1).split('&') ; for ( var i = 0 ; i < aParams.length ; i++ ) { var aParam = aParams[i].split('=') ; var sParamName = decodeURIComponent( aParam[0] ) ; var sParamValue = decodeURIComponent( aParam[1] ) ; FCKURLParams[ sParamName ] = sParamValue ; } })();
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Debug window control and operations. */ // Public function defined here must be declared in fckdebug_empty.js. var FCKDebug = { Output : function( message, color, noParse ) { if ( ! FCKConfig.Debug ) return ; try { this._GetWindow().Output( message, color, noParse ) ; } catch ( e ) {} // Ignore errors }, OutputObject : function( anyObject, color ) { if ( ! FCKConfig.Debug ) return ; try { this._GetWindow().OutputObject( anyObject, color ) ; } catch ( e ) {} // Ignore errors }, _GetWindow : function() { if ( !this.DebugWindow || this.DebugWindow.closed ) this.DebugWindow = window.open( FCKConfig.BasePath + 'fckdebug.html', 'FCKeditorDebug', 'menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=600,height=500', true ) ; return this.DebugWindow ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Contains browser detection information. */ var s = navigator.userAgent.toLowerCase() ; var FCKBrowserInfo = { IsIE : /*@cc_on!@*/false, IsIE7 : /*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/ )[1], 10 ) >= 7 ), IsIE6 : /*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/ )[1], 10 ) >= 6 ), IsSafari : s.Contains(' applewebkit/'), // Read "IsWebKit" IsOpera : !!window.opera, IsAIR : s.Contains(' adobeair/'), IsMac : s.Contains('macintosh') } ; // Completes the browser info with further Gecko information. (function( browserInfo ) { browserInfo.IsGecko = ( navigator.product == 'Gecko' ) && !browserInfo.IsSafari && !browserInfo.IsOpera ; browserInfo.IsGeckoLike = ( browserInfo.IsGecko || browserInfo.IsSafari || browserInfo.IsOpera ) ; if ( browserInfo.IsGecko ) { var geckoMatch = s.match( /rv:(\d+\.\d+)/ ) ; var geckoVersion = geckoMatch && parseFloat( geckoMatch[1] ) ; // Actually "10" refers to Gecko versions before Firefox 1.5, when // Gecko 1.8 (build 20051111) has been released. // Some browser (like Mozilla 1.7.13) may have a Gecko build greater // than 20051111, so we must also check for the revision number not to // be 1.7 (we are assuming that rv < 1.7 will not have build > 20051111). if ( geckoVersion ) { browserInfo.IsGecko10 = ( geckoVersion < 1.8 ) ; browserInfo.IsGecko19 = ( geckoVersion > 1.8 ) ; } } if ( browserInfo.IsSafari ) browserInfo.IsSafari3 = ( parseFloat( s.match( / applewebkit\/(\d+)/ )[1] ) < 526 ) ; })(FCKBrowserInfo) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Active selection functions. (IE specific implementation) */ // Get the selection type. FCKSelection.GetType = function() { // It is possible that we can still get a text range object even when type=='None' is returned by IE. // So we'd better check the object returned by createRange() rather than by looking at the type. try { var ieType = FCKSelection.GetSelection().type ; if ( ieType == 'Control' || ieType == 'Text' ) return ieType ; if ( this.GetSelection().createRange().parentElement ) return 'Text' ; } catch(e) { // Nothing to do, it will return None properly. } return 'None' ; } ; // Retrieves the selected element (if any), just in the case that a single // element (object like and image or a table) is selected. FCKSelection.GetSelectedElement = function() { if ( this.GetType() == 'Control' ) { var oRange = this.GetSelection().createRange() ; if ( oRange && oRange.item ) return this.GetSelection().createRange().item(0) ; } return null ; } ; FCKSelection.GetParentElement = function() { switch ( this.GetType() ) { case 'Control' : var el = FCKSelection.GetSelectedElement() ; return el ? el.parentElement : null ; case 'None' : return null ; default : return this.GetSelection().createRange().parentElement() ; } } ; FCKSelection.GetBoundaryParentElement = function( startBoundary ) { switch ( this.GetType() ) { case 'Control' : var el = FCKSelection.GetSelectedElement() ; return el ? el.parentElement : null ; case 'None' : return null ; default : var doc = FCK.EditorDocument ; var range = doc.selection.createRange() ; range.collapse( startBoundary !== false ) ; var el = range.parentElement() ; // It may happen that range is comming from outside "doc", so we // must check it (#1204). return FCKTools.GetElementDocument( el ) == doc ? el : null ; } } ; FCKSelection.SelectNode = function( node ) { FCK.Focus() ; this.GetSelection().empty() ; var oRange ; try { // Try to select the node as a control. oRange = FCK.EditorDocument.body.createControlRange() ; oRange.addElement( node ) ; oRange.select() ; } catch(e) { // If failed, select it as a text range. oRange = FCK.EditorDocument.body.createTextRange() ; oRange.moveToElementText( node ) ; oRange.select() ; } } ; FCKSelection.Collapse = function( toStart ) { FCK.Focus() ; if ( this.GetType() == 'Text' ) { var oRange = this.GetSelection().createRange() ; oRange.collapse( toStart == null || toStart === true ) ; oRange.select() ; } } ; // The "nodeTagName" parameter must be Upper Case. FCKSelection.HasAncestorNode = function( nodeTagName ) { var oContainer ; if ( this.GetSelection().type == "Control" ) { oContainer = this.GetSelectedElement() ; } else { var oRange = this.GetSelection().createRange() ; oContainer = oRange.parentElement() ; } while ( oContainer ) { if ( oContainer.nodeName.IEquals( nodeTagName ) ) return true ; oContainer = oContainer.parentNode ; } return false ; } ; // The "nodeTagName" parameter must be UPPER CASE. // It can be also an array of names FCKSelection.MoveToAncestorNode = function( nodeTagName ) { var oNode, oRange ; if ( ! FCK.EditorDocument ) return null ; if ( this.GetSelection().type == "Control" ) { oRange = this.GetSelection().createRange() ; for ( i = 0 ; i < oRange.length ; i++ ) { if (oRange(i).parentNode) { oNode = oRange(i).parentNode ; break ; } } } else { oRange = this.GetSelection().createRange() ; oNode = oRange.parentElement() ; } while ( oNode && !oNode.nodeName.Equals( nodeTagName ) ) oNode = oNode.parentNode ; return oNode ; } ; FCKSelection.Delete = function() { // Gets the actual selection. var oSel = this.GetSelection() ; // Deletes the actual selection contents. if ( oSel.type.toLowerCase() != "none" ) { oSel.clear() ; } return oSel ; } ; /** * Returns the native selection object. */ FCKSelection.GetSelection = function() { this.Restore() ; return FCK.EditorDocument.selection ; } FCKSelection.Save = function( lock ) { var editorDocument = FCK.EditorDocument ; if ( !editorDocument ) return ; // Avoid saving again a selection while a dialog is open #2616 if ( this.locked ) return ; this.locked = !!lock ; var selection = editorDocument.selection ; var range ; if ( selection ) { // The call might fail if the document doesn't have the focus (#1801), // but we don't want to modify the current selection (#2495) with a call to FCK.Focus() ; try { range = selection.createRange() ; } catch(e) {} // Ensure that the range comes from the editor document. if ( range ) { if ( range.parentElement && FCKTools.GetElementDocument( range.parentElement() ) != editorDocument ) range = null ; else if ( range.item && FCKTools.GetElementDocument( range.item(0) )!= editorDocument ) range = null ; } } this.SelectionData = range ; } FCKSelection._GetSelectionDocument = function( selection ) { var range = selection.createRange() ; if ( !range ) return null; else if ( range.item ) return FCKTools.GetElementDocument( range.item( 0 ) ) ; else return FCKTools.GetElementDocument( range.parentElement() ) ; } FCKSelection.Restore = function() { if ( this.SelectionData ) { FCK.IsSelectionChangeLocked = true ; try { // Don't repeat the restore process if the editor document is already selected. if ( String( this._GetSelectionDocument( FCK.EditorDocument.selection ).body.contentEditable ) == 'true' ) { FCK.IsSelectionChangeLocked = false ; return ; } this.SelectionData.select() ; } catch ( e ) {} FCK.IsSelectionChangeLocked = false ; } } FCKSelection.Release = function() { this.locked = false ; delete this.SelectionData ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Manage table operations. */ var FCKTableHandler = new Object() ; FCKTableHandler.InsertRow = function( insertBefore ) { // Get the row where the selection is placed in. var oRow = FCKSelection.MoveToAncestorNode( 'TR' ) ; if ( !oRow ) return ; // Create a clone of the row. var oNewRow = oRow.cloneNode( true ) ; // Insert the new row (copy) before of it. oRow.parentNode.insertBefore( oNewRow, oRow ) ; // Clean one of the rows to produce the illusion of inserting an empty row before or after. FCKTableHandler.ClearRow( insertBefore ? oNewRow : oRow ) ; } FCKTableHandler.DeleteRows = function( row ) { // If no row has been passed as a parameter, // then get the row( s ) containing the cells where the selection is placed in. // If user selected multiple rows ( by selecting multiple cells ), walk // the selected cell list and delete the rows containing the selected cells if ( ! row ) { var aCells = FCKTableHandler.GetSelectedCells() ; var aRowsToDelete = new Array() ; //queue up the rows -- it's possible ( and likely ) that we may get duplicates for ( var i = 0; i < aCells.length; i++ ) { var oRow = aCells[i].parentNode ; aRowsToDelete[oRow.rowIndex] = oRow ; } for ( var i = aRowsToDelete.length; i >= 0; i-- ) { if ( aRowsToDelete[i] ) FCKTableHandler.DeleteRows( aRowsToDelete[i] ); } return ; } // Get the row's table. var oTable = FCKTools.GetElementAscensor( row, 'TABLE' ) ; // If just one row is available then delete the entire table. if ( oTable.rows.length == 1 ) { FCKTableHandler.DeleteTable( oTable ) ; return ; } // Delete the row. row.parentNode.removeChild( row ) ; } FCKTableHandler.DeleteTable = function( table ) { // If no table has been passed as a parameter, // then get the table where the selection is placed in. if ( !table ) { table = FCKSelection.GetSelectedElement() ; if ( !table || table.tagName != 'TABLE' ) table = FCKSelection.MoveToAncestorNode( 'TABLE' ) ; } if ( !table ) return ; // Delete the table. FCKSelection.SelectNode( table ) ; FCKSelection.Collapse(); // if the table is wrapped with a singleton <p> ( or something similar ), remove // the surrounding tag -- which likely won't show after deletion anyway if ( table.parentNode.childNodes.length == 1 ) table.parentNode.parentNode.removeChild( table.parentNode ); else table.parentNode.removeChild( table ) ; } FCKTableHandler.InsertColumn = function( insertBefore ) { // Get the cell where the selection is placed in. var oCell = null ; var nodes = this.GetSelectedCells() ; if ( nodes && nodes.length ) oCell = nodes[ insertBefore ? 0 : ( nodes.length - 1 ) ] ; if ( ! oCell ) return ; // Get the cell's table. var oTable = FCKTools.GetElementAscensor( oCell, 'TABLE' ) ; var iIndex = oCell.cellIndex ; // Loop through all rows available in the table. for ( var i = 0 ; i < oTable.rows.length ; i++ ) { // Get the row. var oRow = oTable.rows[i] ; // If the row doesn't have enough cells, ignore it. if ( oRow.cells.length < ( iIndex + 1 ) ) continue ; oCell = oRow.cells[iIndex].cloneNode(false) ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( oCell ) ; // Get back the currently selected cell. var oBaseCell = oRow.cells[iIndex] ; oRow.insertBefore( oCell, ( insertBefore ? oBaseCell : oBaseCell.nextSibling ) ) ; } } FCKTableHandler.DeleteColumns = function( oCell ) { // if user selected multiple cols ( by selecting multiple cells ), walk // the selected cell list and delete the rows containing the selected cells if ( !oCell ) { var aColsToDelete = FCKTableHandler.GetSelectedCells(); for ( var i = aColsToDelete.length; i >= 0; i-- ) { if ( aColsToDelete[i] ) FCKTableHandler.DeleteColumns( aColsToDelete[i] ); } return; } if ( !oCell ) return ; // Get the cell's table. var oTable = FCKTools.GetElementAscensor( oCell, 'TABLE' ) ; // Get the cell index. var iIndex = oCell.cellIndex ; // Loop throw all rows (from down to up, because it's possible that some // rows will be deleted). for ( var i = oTable.rows.length - 1 ; i >= 0 ; i-- ) { // Get the row. var oRow = oTable.rows[i] ; // If the cell to be removed is the first one and the row has just one cell. if ( iIndex == 0 && oRow.cells.length == 1 ) { // Remove the entire row. FCKTableHandler.DeleteRows( oRow ) ; continue ; } // If the cell to be removed exists the delete it. if ( oRow.cells[iIndex] ) oRow.removeChild( oRow.cells[iIndex] ) ; } } FCKTableHandler.InsertCell = function( cell, insertBefore ) { // Get the cell where the selection is placed in. var oCell = null ; var nodes = this.GetSelectedCells() ; if ( nodes && nodes.length ) oCell = nodes[ insertBefore ? 0 : ( nodes.length - 1 ) ] ; if ( ! oCell ) return null ; // Create the new cell element to be added. var oNewCell = FCK.EditorDocument.createElement( 'TD' ) ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( oNewCell ) ; if ( !insertBefore && oCell.cellIndex == oCell.parentNode.cells.length - 1 ) oCell.parentNode.appendChild( oNewCell ) ; else oCell.parentNode.insertBefore( oNewCell, insertBefore ? oCell : oCell.nextSibling ) ; return oNewCell ; } FCKTableHandler.DeleteCell = function( cell ) { // If this is the last cell in the row. if ( cell.parentNode.cells.length == 1 ) { // Delete the entire row. FCKTableHandler.DeleteRows( cell.parentNode ) ; return ; } // Delete the cell from the row. cell.parentNode.removeChild( cell ) ; } FCKTableHandler.DeleteCells = function() { var aCells = FCKTableHandler.GetSelectedCells() ; for ( var i = aCells.length - 1 ; i >= 0 ; i-- ) { FCKTableHandler.DeleteCell( aCells[i] ) ; } } FCKTableHandler._MarkCells = function( cells, label ) { for ( var i = 0 ; i < cells.length ; i++ ) cells[i][label] = true ; } FCKTableHandler._UnmarkCells = function( cells, label ) { for ( var i = 0 ; i < cells.length ; i++ ) { FCKDomTools.ClearElementJSProperty(cells[i], label ) ; } } FCKTableHandler._ReplaceCellsByMarker = function( tableMap, marker, substitute ) { for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { if ( tableMap[i][j][marker] ) tableMap[i][j] = substitute ; } } } FCKTableHandler._GetMarkerGeometry = function( tableMap, rowIdx, colIdx, markerName ) { var selectionWidth = 0 ; var selectionHeight = 0 ; var cellsLeft = 0 ; var cellsUp = 0 ; for ( var i = colIdx ; tableMap[rowIdx][i] && tableMap[rowIdx][i][markerName] ; i++ ) selectionWidth++ ; for ( var i = colIdx - 1 ; tableMap[rowIdx][i] && tableMap[rowIdx][i][markerName] ; i-- ) { selectionWidth++ ; cellsLeft++ ; } for ( var i = rowIdx ; tableMap[i] && tableMap[i][colIdx] && tableMap[i][colIdx][markerName] ; i++ ) selectionHeight++ ; for ( var i = rowIdx - 1 ; tableMap[i] && tableMap[i][colIdx] && tableMap[i][colIdx][markerName] ; i-- ) { selectionHeight++ ; cellsUp++ ; } return { 'width' : selectionWidth, 'height' : selectionHeight, 'x' : cellsLeft, 'y' : cellsUp } ; } FCKTableHandler.CheckIsSelectionRectangular = function() { // If every row and column in an area on a plane are of the same width and height, // Then the area is a rectangle. var cells = FCKTableHandler.GetSelectedCells() ; if ( cells.length < 1 ) return false ; // Check if the selected cells are all in the same table section (thead, tfoot or tbody) for (var i = 0; i < cells.length; i++) { if ( cells[i].parentNode.parentNode != cells[0].parentNode.parentNode ) return false ; } this._MarkCells( cells, '_CellSelected' ) ; var tableMap = this._CreateTableMap( cells[0] ) ; var rowIdx = cells[0].parentNode.rowIndex ; var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, cells[0] ) ; var geometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ; var baseColIdx = colIdx - geometry.x ; var baseRowIdx = rowIdx - geometry.y ; if ( geometry.width >= geometry.height ) { for ( colIdx = baseColIdx ; colIdx < baseColIdx + geometry.width ; colIdx++ ) { rowIdx = baseRowIdx + ( colIdx - baseColIdx ) % geometry.height ; if ( ! tableMap[rowIdx] || ! tableMap[rowIdx][colIdx] ) { this._UnmarkCells( cells, '_CellSelected' ) ; return false ; } var g = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ; if ( g.width != geometry.width || g.height != geometry.height ) { this._UnmarkCells( cells, '_CellSelected' ) ; return false ; } } } else { for ( rowIdx = baseRowIdx ; rowIdx < baseRowIdx + geometry.height ; rowIdx++ ) { colIdx = baseColIdx + ( rowIdx - baseRowIdx ) % geometry.width ; if ( ! tableMap[rowIdx] || ! tableMap[rowIdx][colIdx] ) { this._UnmarkCells( cells, '_CellSelected' ) ; return false ; } var g = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ; if ( g.width != geometry.width || g.height != geometry.height ) { this._UnmarkCells( cells, '_CellSelected' ) ; return false ; } } } this._UnmarkCells( cells, '_CellSelected' ) ; return true ; } FCKTableHandler.MergeCells = function() { // Get all selected cells. var cells = this.GetSelectedCells() ; if ( cells.length < 2 ) return ; // Assume the selected cells are already in a rectangular geometry. // Because the checking is already done by FCKTableCommand. var refCell = cells[0] ; var tableMap = this._CreateTableMap( refCell ) ; var rowIdx = refCell.parentNode.rowIndex ; var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ; this._MarkCells( cells, '_SelectedCells' ) ; var selectionGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SelectedCells' ) ; var baseColIdx = colIdx - selectionGeometry.x ; var baseRowIdx = rowIdx - selectionGeometry.y ; var cellContents = FCKTools.GetElementDocument( refCell ).createDocumentFragment() ; for ( var i = 0 ; i < selectionGeometry.height ; i++ ) { var rowChildNodesCount = 0 ; for ( var j = 0 ; j < selectionGeometry.width ; j++ ) { var currentCell = tableMap[baseRowIdx + i][baseColIdx + j] ; while ( currentCell.childNodes.length > 0 ) { var node = currentCell.removeChild( currentCell.firstChild ) ; if ( node.nodeType != 1 || ( node.getAttribute( 'type', 2 ) != '_moz' && node.getAttribute( '_moz_dirty' ) != null ) ) { cellContents.appendChild( node ) ; rowChildNodesCount++ ; } } } if ( rowChildNodesCount > 0 ) cellContents.appendChild( FCK.EditorDocument.createElement( 'br' ) ) ; } this._ReplaceCellsByMarker( tableMap, '_SelectedCells', refCell ) ; this._UnmarkCells( cells, '_SelectedCells' ) ; this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ; refCell.appendChild( cellContents ) ; if ( FCKBrowserInfo.IsGeckoLike && ( ! refCell.firstChild ) ) FCKTools.AppendBogusBr( refCell ) ; this._MoveCaretToCell( refCell, false ) ; } FCKTableHandler.MergeRight = function() { var target = this.GetMergeRightTarget() ; if ( target == null ) return ; var refCell = target.refCell ; var tableMap = target.tableMap ; var nextCell = target.nextCell ; var cellContents = FCK.EditorDocument.createDocumentFragment() ; while ( nextCell && nextCell.childNodes && nextCell.childNodes.length > 0 ) cellContents.appendChild( nextCell.removeChild( nextCell.firstChild ) ) ; nextCell.parentNode.removeChild( nextCell ) ; refCell.appendChild( cellContents ) ; this._MarkCells( [nextCell], '_Replace' ) ; this._ReplaceCellsByMarker( tableMap, '_Replace', refCell ) ; this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ; this._MoveCaretToCell( refCell, false ) ; } FCKTableHandler.MergeDown = function() { var target = this.GetMergeDownTarget() ; if ( target == null ) return ; var refCell = target.refCell ; var tableMap = target.tableMap ; var nextCell = target.nextCell ; var cellContents = FCKTools.GetElementDocument( refCell ).createDocumentFragment() ; while ( nextCell && nextCell.childNodes && nextCell.childNodes.length > 0 ) cellContents.appendChild( nextCell.removeChild( nextCell.firstChild ) ) ; if ( cellContents.firstChild ) cellContents.insertBefore( FCK.EditorDocument.createElement( 'br' ), cellContents.firstChild ) ; refCell.appendChild( cellContents ) ; this._MarkCells( [nextCell], '_Replace' ) ; this._ReplaceCellsByMarker( tableMap, '_Replace', refCell ) ; this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ; this._MoveCaretToCell( refCell, false ) ; } FCKTableHandler.HorizontalSplitCell = function() { var cells = FCKTableHandler.GetSelectedCells() ; if ( cells.length != 1 ) return ; var refCell = cells[0] ; var tableMap = this._CreateTableMap( refCell ) ; var rowIdx = refCell.parentNode.rowIndex ; var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, refCell ) ; var cellSpan = isNaN( refCell.colSpan ) ? 1 : refCell.colSpan ; if ( cellSpan > 1 ) { // Splitting a multi-column cell - original cell gets ceil(colSpan/2) columns, // new cell gets floor(colSpan/2). var newCellSpan = Math.ceil( cellSpan / 2 ) ; var newCell = FCK.EditorDocument.createElement( refCell.nodeName ) ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( newCell ) ; var startIdx = colIdx + newCellSpan ; var endIdx = colIdx + cellSpan ; var rowSpan = isNaN( refCell.rowSpan ) ? 1 : refCell.rowSpan ; for ( var r = rowIdx ; r < rowIdx + rowSpan ; r++ ) { for ( var i = startIdx ; i < endIdx ; i++ ) tableMap[r][i] = newCell ; } } else { // Splitting a single-column cell - add a new cell, and expand // cells crossing the same column. var newTableMap = [] ; for ( var i = 0 ; i < tableMap.length ; i++ ) { var newRow = tableMap[i].slice( 0, colIdx ) ; if ( tableMap[i].length <= colIdx ) { newTableMap.push( newRow ) ; continue ; } if ( tableMap[i][colIdx] == refCell ) { newRow.push( refCell ) ; newRow.push( FCK.EditorDocument.createElement( refCell.nodeName ) ) ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( newRow[newRow.length - 1] ) ; } else { newRow.push( tableMap[i][colIdx] ) ; newRow.push( tableMap[i][colIdx] ) ; } for ( var j = colIdx + 1 ; j < tableMap[i].length ; j++ ) newRow.push( tableMap[i][j] ) ; newTableMap.push( newRow ) ; } tableMap = newTableMap ; } this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ; } FCKTableHandler.VerticalSplitCell = function() { var cells = FCKTableHandler.GetSelectedCells() ; if ( cells.length != 1 ) return ; var currentCell = cells[0] ; var tableMap = this._CreateTableMap( currentCell ) ; var currentRowIndex = currentCell.parentNode.rowIndex ; var cellIndex = FCKTableHandler._GetCellIndexSpan( tableMap, currentRowIndex, currentCell ) ; // Save current cell colSpan var currentColSpan = isNaN( currentCell.colSpan ) ? 1 : currentCell.colSpan ; var currentRowSpan = currentCell.rowSpan ; if ( isNaN( currentRowSpan ) ) currentRowSpan = 1 ; if ( currentRowSpan > 1 ) { // 1. Set the current cell's rowSpan to 1. currentCell.rowSpan = Math.ceil( currentRowSpan / 2 ) ; // 2. Find the appropriate place to insert a new cell at the next row. var newCellRowIndex = currentRowIndex + Math.ceil( currentRowSpan / 2 ) ; var oRow = tableMap[newCellRowIndex] ; var insertMarker = null ; for ( var i = cellIndex+1 ; i < oRow.length ; i++ ) { if ( oRow[i].parentNode.rowIndex == newCellRowIndex ) { insertMarker = oRow[i] ; break ; } } // 3. Insert the new cell to the indicated place, with the appropriate rowSpan and colSpan, next row. var newCell = FCK.EditorDocument.createElement( currentCell.nodeName ) ; newCell.rowSpan = Math.floor( currentRowSpan / 2 ) ; if ( currentColSpan > 1 ) newCell.colSpan = currentColSpan ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( newCell ) ; currentCell.parentNode.parentNode.parentNode.rows[newCellRowIndex].insertBefore( newCell, insertMarker ) ; } else { // 1. Insert a new row. var newSectionRowIdx = currentCell.parentNode.sectionRowIndex + 1 ; var newRow = FCK.EditorDocument.createElement( 'tr' ) ; var tSection = currentCell.parentNode.parentNode ; if ( tSection.rows.length > newSectionRowIdx ) tSection.insertBefore( newRow, tSection.rows[newSectionRowIdx] ) ; else tSection.appendChild( newRow ) ; // 2. +1 to rowSpan for all cells crossing currentCell's row. for ( var i = 0 ; i < tableMap[currentRowIndex].length ; ) { var colSpan = tableMap[currentRowIndex][i].colSpan ; if ( isNaN( colSpan ) || colSpan < 1 ) colSpan = 1 ; if ( i == cellIndex ) { i += colSpan ; continue ; } var rowSpan = tableMap[currentRowIndex][i].rowSpan ; if ( isNaN( rowSpan ) ) rowSpan = 1 ; tableMap[currentRowIndex][i].rowSpan = rowSpan + 1 ; i += colSpan ; } // 3. Insert a new cell to new row. Set colSpan on the new cell. var newCell = FCK.EditorDocument.createElement( currentCell.nodeName ) ; if ( currentColSpan > 1 ) newCell.colSpan = currentColSpan ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( newCell ) ; newRow.appendChild( newCell ) ; } } // Get the cell index from a TableMap. FCKTableHandler._GetCellIndexSpan = function( tableMap, rowIndex, cell ) { if ( tableMap.length < rowIndex + 1 ) return null ; var oRow = tableMap[ rowIndex ] ; for ( var c = 0 ; c < oRow.length ; c++ ) { if ( oRow[c] == cell ) return c ; } return null ; } // Get the cell location from a TableMap. Returns an array with an [x,y] location FCKTableHandler._GetCellLocation = function( tableMap, cell ) { for ( var i = 0 ; i < tableMap.length; i++ ) { for ( var c = 0 ; c < tableMap[i].length ; c++ ) { if ( tableMap[i][c] == cell ) return [i,c]; } } return null ; } // This function is quite hard to explain. It creates a matrix representing all cells in a table. // The difference here is that the "spanned" cells (colSpan and rowSpan) are duplicated on the matrix // cells that are "spanned". For example, a row with 3 cells where the second cell has colSpan=2 and rowSpan=3 // will produce a bi-dimensional matrix with the following values (representing the cells): // Cell1, Cell2, Cell2, Cell3 // Cell4, Cell2, Cell2, Cell5 // Cell6, Cell2, Cell2, Cell7 FCKTableHandler._CreateTableMap = function( refCell ) { var table = (refCell.nodeName == 'TABLE' ? refCell : refCell.parentNode.parentNode.parentNode ) ; var aRows = table.rows ; // Row and Column counters. var r = -1 ; var aMap = new Array() ; for ( var i = 0 ; i < aRows.length ; i++ ) { r++ ; if ( !aMap[r] ) aMap[r] = new Array() ; var c = -1 ; for ( var j = 0 ; j < aRows[i].cells.length ; j++ ) { var oCell = aRows[i].cells[j] ; c++ ; while ( aMap[r][c] ) c++ ; var iColSpan = isNaN( oCell.colSpan ) ? 1 : oCell.colSpan ; var iRowSpan = isNaN( oCell.rowSpan ) ? 1 : oCell.rowSpan ; for ( var rs = 0 ; rs < iRowSpan ; rs++ ) { if ( !aMap[r + rs] ) aMap[r + rs] = new Array() ; for ( var cs = 0 ; cs < iColSpan ; cs++ ) { aMap[r + rs][c + cs] = aRows[i].cells[j] ; } } c += iColSpan - 1 ; } } return aMap ; } // This function is the inverse of _CreateTableMap - it takes in a table map and converts it to an HTML table. FCKTableHandler._InstallTableMap = function( tableMap, table ) { // Workaround for #1917 : MSIE will always report a cell's rowSpan as 1 as long // as the cell is not attached to a row. So we'll need an alternative attribute // for storing the calculated rowSpan in IE. var rowSpanAttr = FCKBrowserInfo.IsIE ? "_fckrowspan" : "rowSpan" ; // Disconnect all the cells in tableMap from their parents, set all colSpan and rowSpan attributes to 1. for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; if ( cell.parentNode ) cell.parentNode.removeChild( cell ) ; cell.colSpan = cell[rowSpanAttr] = 1 ; } } // Scan by rows and set colSpan. var maxCol = 0 ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; if ( ! cell) continue ; if ( j > maxCol ) maxCol = j ; if ( cell._colScanned === true ) continue ; if ( tableMap[i][j-1] == cell ) cell.colSpan++ ; if ( tableMap[i][j+1] != cell ) cell._colScanned = true ; } } // Scan by columns and set rowSpan. for ( var i = 0 ; i <= maxCol ; i++ ) { for ( var j = 0 ; j < tableMap.length ; j++ ) { if ( ! tableMap[j] ) continue ; var cell = tableMap[j][i] ; if ( ! cell || cell._rowScanned === true ) continue ; if ( tableMap[j-1] && tableMap[j-1][i] == cell ) cell[rowSpanAttr]++ ; if ( ! tableMap[j+1] || tableMap[j+1][i] != cell ) cell._rowScanned = true ; } } // Clear all temporary flags. for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++) { var cell = tableMap[i][j] ; FCKDomTools.ClearElementJSProperty(cell, '_colScanned' ) ; FCKDomTools.ClearElementJSProperty(cell, '_rowScanned' ) ; } } // Insert physical rows and columns to the table. for ( var i = 0 ; i < tableMap.length ; i++ ) { var rowObj = FCK.EditorDocument.createElement( 'tr' ) ; for ( var j = 0 ; j < tableMap[i].length ; ) { var cell = tableMap[i][j] ; if ( tableMap[i-1] && tableMap[i-1][j] == cell ) { j += cell.colSpan ; continue ; } rowObj.appendChild( cell ) ; if ( rowSpanAttr != 'rowSpan' ) { cell.rowSpan = cell[rowSpanAttr] ; cell.removeAttribute( rowSpanAttr ) ; } j += cell.colSpan ; if ( cell.colSpan == 1 ) cell.removeAttribute( 'colspan' ) ; if ( cell.rowSpan == 1 ) cell.removeAttribute( 'rowspan' ) ; } if ( FCKBrowserInfo.IsIE ) { table.rows[i].replaceNode( rowObj ) ; } else { table.rows[i].innerHTML = '' ; FCKDomTools.MoveChildren( rowObj, table.rows[i] ) ; } } } FCKTableHandler._MoveCaretToCell = function ( refCell, toStart ) { var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToNodeContents( refCell ) ; range.Collapse( toStart ) ; range.Select() ; } FCKTableHandler.ClearRow = function( tr ) { // Get the array of row's cells. var aCells = tr.cells ; // Replace the contents of each cell with "nothing". for ( var i = 0 ; i < aCells.length ; i++ ) { aCells[i].innerHTML = '' ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( aCells[i] ) ; } } FCKTableHandler.GetMergeRightTarget = function() { var cells = this.GetSelectedCells() ; if ( cells.length != 1 ) return null ; var refCell = cells[0] ; var tableMap = this._CreateTableMap( refCell ) ; var rowIdx = refCell.parentNode.rowIndex ; var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ; var nextColIdx = colIdx + ( isNaN( refCell.colSpan ) ? 1 : refCell.colSpan ) ; var nextCell = tableMap[rowIdx][nextColIdx] ; if ( ! nextCell ) return null ; // The two cells must have the same vertical geometry, otherwise merging does not make sense. this._MarkCells( [refCell, nextCell], '_SizeTest' ) ; var refGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SizeTest' ) ; var nextGeometry = this._GetMarkerGeometry( tableMap, rowIdx, nextColIdx, '_SizeTest' ) ; this._UnmarkCells( [refCell, nextCell], '_SizeTest' ) ; if ( refGeometry.height != nextGeometry.height || refGeometry.y != nextGeometry.y ) return null ; return { 'refCell' : refCell, 'nextCell' : nextCell, 'tableMap' : tableMap } ; } FCKTableHandler.GetMergeDownTarget = function() { var cells = this.GetSelectedCells() ; if ( cells.length != 1 ) return null ; var refCell = cells[0] ; var tableMap = this._CreateTableMap( refCell ) ; var rowIdx = refCell.parentNode.rowIndex ; var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ; var newRowIdx = rowIdx + ( isNaN( refCell.rowSpan ) ? 1 : refCell.rowSpan ) ; if ( ! tableMap[newRowIdx] ) return null ; var nextCell = tableMap[newRowIdx][colIdx] ; if ( ! nextCell ) return null ; // Check if the selected cells are both in the same table section (thead, tfoot or tbody). if ( refCell.parentNode.parentNode != nextCell.parentNode.parentNode ) return null ; // The two cells must have the same horizontal geometry, otherwise merging does not makes sense. this._MarkCells( [refCell, nextCell], '_SizeTest' ) ; var refGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SizeTest' ) ; var nextGeometry = this._GetMarkerGeometry( tableMap, newRowIdx, colIdx, '_SizeTest' ) ; this._UnmarkCells( [refCell, nextCell], '_SizeTest' ) ; if ( refGeometry.width != nextGeometry.width || refGeometry.x != nextGeometry.x ) return null ; return { 'refCell' : refCell, 'nextCell' : nextCell, 'tableMap' : tableMap } ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Dialog windows operations. */ var FCKDialog = ( function() { var topDialog ; var baseZIndex ; var cover ; // The document that holds the dialog. var topWindow = window.parent ; while ( topWindow.parent && topWindow.parent != topWindow ) { try { if ( topWindow.parent.document.domain != document.domain ) break ; if ( topWindow.parent.document.getElementsByTagName( 'frameset' ).length > 0 ) break ; } catch ( e ) { break ; } topWindow = topWindow.parent ; } var topDocument = topWindow.document ; var getZIndex = function() { if ( !baseZIndex ) baseZIndex = FCKConfig.FloatingPanelsZIndex + 999 ; return ++baseZIndex ; } // TODO : This logic is not actually working when reducing the window, only // when enlarging it. var resizeHandler = function() { if ( !cover ) return ; var relElement = FCKTools.IsStrictMode( topDocument ) ? topDocument.documentElement : topDocument.body ; FCKDomTools.SetElementStyles( cover, { 'width' : Math.max( relElement.scrollWidth, relElement.clientWidth, topDocument.scrollWidth || 0 ) - 1 + 'px', 'height' : Math.max( relElement.scrollHeight, relElement.clientHeight, topDocument.scrollHeight || 0 ) - 1 + 'px' } ) ; } return { /** * Opens a dialog window using the standard dialog template. */ OpenDialog : function( dialogName, dialogTitle, dialogPage, width, height, customValue, resizable ) { if ( !topDialog ) this.DisplayMainCover() ; // Setup the dialog info to be passed to the dialog. var dialogInfo = { Title : dialogTitle, Page : dialogPage, Editor : window, CustomValue : customValue, // Optional TopWindow : topWindow } FCK.ToolbarSet.CurrentInstance.Selection.Save( true ) ; // Calculate the dialog position, centering it on the screen. var viewSize = FCKTools.GetViewPaneSize( topWindow ) ; var scrollPosition = { 'X' : 0, 'Y' : 0 } ; var useAbsolutePosition = FCKBrowserInfo.IsIE && ( !FCKBrowserInfo.IsIE7 || !FCKTools.IsStrictMode( topWindow.document ) ) ; if ( useAbsolutePosition ) scrollPosition = FCKTools.GetScrollPosition( topWindow ) ; var iTop = Math.max( scrollPosition.Y + ( viewSize.Height - height - 20 ) / 2, 0 ) ; var iLeft = Math.max( scrollPosition.X + ( viewSize.Width - width - 20 ) / 2, 0 ) ; // Setup the IFRAME that will hold the dialog. var dialog = topDocument.createElement( 'iframe' ) ; FCKTools.ResetStyles( dialog ) ; dialog.src = FCKConfig.BasePath + 'fckdialog.html' ; // Dummy URL for testing whether the code in fckdialog.js alone leaks memory. // dialog.src = 'about:blank'; dialog.frameBorder = 0 ; dialog.allowTransparency = true ; FCKDomTools.SetElementStyles( dialog, { 'position' : ( useAbsolutePosition ) ? 'absolute' : 'fixed', 'top' : iTop + 'px', 'left' : iLeft + 'px', 'width' : width + 'px', 'height' : height + 'px', 'zIndex' : getZIndex() } ) ; // Save the dialog info to be used by the dialog page once loaded. dialog._DialogArguments = dialogInfo ; // Append the IFRAME to the target document. topDocument.body.appendChild( dialog ) ; // Keep record of the dialog's parent/child relationships. dialog._ParentDialog = topDialog ; topDialog = dialog ; }, /** * (For internal use) * Called when the top dialog is closed. */ OnDialogClose : function( dialogWindow ) { var dialog = dialogWindow.frameElement ; FCKDomTools.RemoveNode( dialog ) ; if ( dialog._ParentDialog ) // Nested Dialog. { topDialog = dialog._ParentDialog ; dialog._ParentDialog.contentWindow.SetEnabled( true ) ; } else // First Dialog. { // Set the Focus in the browser, so the "OnBlur" event is not // fired. In IE, there is no need to do that because the dialog // already moved the selection to the editing area before // closing (EnsureSelection). Also, the Focus() call here // causes memory leak on IE7 (weird). if ( !FCKBrowserInfo.IsIE ) FCK.Focus() ; this.HideMainCover() ; // Bug #1918: Assigning topDialog = null directly causes IE6 to crash. setTimeout( function(){ topDialog = null ; }, 0 ) ; // Release the previously saved selection. FCK.ToolbarSet.CurrentInstance.Selection.Release() ; } }, DisplayMainCover : function() { // Setup the DIV that will be used to cover. cover = topDocument.createElement( 'div' ) ; FCKTools.ResetStyles( cover ) ; FCKDomTools.SetElementStyles( cover, { 'position' : 'absolute', 'zIndex' : getZIndex(), 'top' : '0px', 'left' : '0px', 'backgroundColor' : FCKConfig.BackgroundBlockerColor } ) ; FCKDomTools.SetOpacity( cover, FCKConfig.BackgroundBlockerOpacity ) ; // For IE6-, we need to fill the cover with a transparent IFRAME, // to properly block <select> fields. if ( FCKBrowserInfo.IsIE && !FCKBrowserInfo.IsIE7 ) { var iframe = topDocument.createElement( 'iframe' ) ; FCKTools.ResetStyles( iframe ) ; iframe.hideFocus = true ; iframe.frameBorder = 0 ; iframe.src = FCKTools.GetVoidUrl() ; FCKDomTools.SetElementStyles( iframe, { 'width' : '100%', 'height' : '100%', 'position' : 'absolute', 'left' : '0px', 'top' : '0px', 'filter' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)' } ) ; cover.appendChild( iframe ) ; } // We need to manually adjust the cover size on resize. FCKTools.AddEventListener( topWindow, 'resize', resizeHandler ) ; resizeHandler() ; topDocument.body.appendChild( cover ) ; FCKFocusManager.Lock() ; // Prevent the user from refocusing the disabled // editing window by pressing Tab. (Bug #2065) var el = FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'frameElement' ) ; el._fck_originalTabIndex = el.tabIndex ; el.tabIndex = -1 ; }, HideMainCover : function() { FCKDomTools.RemoveNode( cover ) ; FCKFocusManager.Unlock() ; // Revert the tab index hack. (Bug #2065) var el = FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'frameElement' ) ; el.tabIndex = el._fck_originalTabIndex ; FCKDomTools.ClearElementJSProperty( el, '_fck_originalTabIndex' ) ; }, GetCover : function() { return cover ; } } ; } )() ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Creation and initialization of the "FCK" object. This is the main object * that represents an editor instance. */ // FCK represents the active editor instance. var FCK = { Name : FCKURLParams[ 'InstanceName' ], Status : FCK_STATUS_NOTLOADED, EditMode : FCK_EDITMODE_WYSIWYG, Toolbar : null, HasFocus : false, DataProcessor : new FCKDataProcessor(), GetInstanceObject : (function() { var w = window ; return function( name ) { return w[name] ; } })(), AttachToOnSelectionChange : function( functionPointer ) { this.Events.AttachEvent( 'OnSelectionChange', functionPointer ) ; }, GetLinkedFieldValue : function() { return this.LinkedField.value ; }, GetParentForm : function() { return this.LinkedField.form ; } , // # START : IsDirty implementation StartupValue : '', IsDirty : function() { if ( this.EditMode == FCK_EDITMODE_SOURCE ) return ( this.StartupValue != this.EditingArea.Textarea.value ) ; else { // It can happen switching between design and source mode in Gecko if ( ! this.EditorDocument ) return false ; return ( this.StartupValue != this.EditorDocument.body.innerHTML ) ; } }, ResetIsDirty : function() { if ( this.EditMode == FCK_EDITMODE_SOURCE ) this.StartupValue = this.EditingArea.Textarea.value ; else if ( this.EditorDocument.body ) this.StartupValue = this.EditorDocument.body.innerHTML ; }, // # END : IsDirty implementation StartEditor : function() { this.TempBaseTag = FCKConfig.BaseHref.length > 0 ? '<base href="' + FCKConfig.BaseHref + '" _fcktemp="true"></base>' : '' ; // Setup the keystroke handler. var oKeystrokeHandler = FCK.KeystrokeHandler = new FCKKeystrokeHandler() ; oKeystrokeHandler.OnKeystroke = _FCK_KeystrokeHandler_OnKeystroke ; // Set the config keystrokes. oKeystrokeHandler.SetKeystrokes( FCKConfig.Keystrokes ) ; // In IE7, if the editor tries to access the clipboard by code, a dialog is // shown to the user asking if the application is allowed to access or not. // Due to the IE implementation of it, the KeystrokeHandler will not work //well in this case, so we must leave the pasting keys to have their default behavior. if ( FCKBrowserInfo.IsIE7 ) { if ( ( CTRL + 86 /*V*/ ) in oKeystrokeHandler.Keystrokes ) oKeystrokeHandler.SetKeystrokes( [ CTRL + 86, true ] ) ; if ( ( SHIFT + 45 /*INS*/ ) in oKeystrokeHandler.Keystrokes ) oKeystrokeHandler.SetKeystrokes( [ SHIFT + 45, true ] ) ; } // Retain default behavior for Ctrl-Backspace. (Bug #362) oKeystrokeHandler.SetKeystrokes( [ CTRL + 8, true ] ) ; this.EditingArea = new FCKEditingArea( document.getElementById( 'xEditingArea' ) ) ; this.EditingArea.FFSpellChecker = FCKConfig.FirefoxSpellChecker ; // Set the editor's startup contents. this.SetData( this.GetLinkedFieldValue(), true ) ; // Tab key handling for source mode. FCKTools.AddEventListener( document, "keydown", this._TabKeyHandler ) ; // Add selection change listeners. They must be attached only once. this.AttachToOnSelectionChange( _FCK_PaddingNodeListener ) ; if ( FCKBrowserInfo.IsGecko ) this.AttachToOnSelectionChange( this._ExecCheckEmptyBlock ) ; }, Focus : function() { FCK.EditingArea.Focus() ; }, SetStatus : function( newStatus ) { this.Status = newStatus ; if ( newStatus == FCK_STATUS_ACTIVE ) { FCKFocusManager.AddWindow( window, true ) ; if ( FCKBrowserInfo.IsIE ) FCKFocusManager.AddWindow( window.frameElement, true ) ; // Force the focus in the editor. if ( FCKConfig.StartupFocus ) FCK.Focus() ; } this.Events.FireEvent( 'OnStatusChange', newStatus ) ; }, // Fixes the body by moving all inline and text nodes to appropriate block // elements. FixBody : function() { var sBlockTag = FCKConfig.EnterMode ; // In 'br' mode, no fix must be done. if ( sBlockTag != 'p' && sBlockTag != 'div' ) return ; var oDocument = this.EditorDocument ; if ( !oDocument ) return ; var oBody = oDocument.body ; if ( !oBody ) return ; FCKDomTools.TrimNode( oBody ) ; var oNode = oBody.firstChild ; var oNewBlock ; while ( oNode ) { var bMoveNode = false ; switch ( oNode.nodeType ) { // Element Node. case 1 : var nodeName = oNode.nodeName.toLowerCase() ; if ( !FCKListsLib.BlockElements[ nodeName ] && nodeName != 'li' && !oNode.getAttribute('_fckfakelement') && oNode.getAttribute('_moz_dirty') == null ) bMoveNode = true ; break ; // Text Node. case 3 : // Ignore space only or empty text. if ( oNewBlock || oNode.nodeValue.Trim().length > 0 ) bMoveNode = true ; break; // Comment Node case 8 : if ( oNewBlock ) bMoveNode = true ; break; } if ( bMoveNode ) { var oParent = oNode.parentNode ; if ( !oNewBlock ) oNewBlock = oParent.insertBefore( oDocument.createElement( sBlockTag ), oNode ) ; oNewBlock.appendChild( oParent.removeChild( oNode ) ) ; oNode = oNewBlock.nextSibling ; } else { if ( oNewBlock ) { FCKDomTools.TrimNode( oNewBlock ) ; oNewBlock = null ; } oNode = oNode.nextSibling ; } } if ( oNewBlock ) FCKDomTools.TrimNode( oNewBlock ) ; }, GetData : function( format ) { FCK.Events.FireEvent("OnBeforeGetData") ; // We assume that if the user is in source editing, the editor value must // represent the exact contents of the source, as the user wanted it to be. if ( FCK.EditMode == FCK_EDITMODE_SOURCE ) return FCK.EditingArea.Textarea.value ; this.FixBody() ; var oDoc = FCK.EditorDocument ; if ( !oDoc ) return null ; var isFullPage = FCKConfig.FullPage ; // Call the Data Processor to generate the output data. var data = FCK.DataProcessor.ConvertToDataFormat( isFullPage ? oDoc.documentElement : oDoc.body, !isFullPage, FCKConfig.IgnoreEmptyParagraphValue, format ) ; // Restore protected attributes. data = FCK.ProtectEventsRestore( data ) ; if ( FCKBrowserInfo.IsIE ) data = data.replace( FCKRegexLib.ToReplace, '$1' ) ; if ( isFullPage ) { if ( FCK.DocTypeDeclaration && FCK.DocTypeDeclaration.length > 0 ) data = FCK.DocTypeDeclaration + '\n' + data ; if ( FCK.XmlDeclaration && FCK.XmlDeclaration.length > 0 ) data = FCK.XmlDeclaration + '\n' + data ; } data = FCKConfig.ProtectedSource.Revert( data ) ; setTimeout( function() { FCK.Events.FireEvent("OnAfterGetData") ; }, 0 ) ; return data ; }, UpdateLinkedField : function() { var value = FCK.GetXHTML( FCKConfig.FormatOutput ) ; if ( FCKConfig.HtmlEncodeOutput ) value = FCKTools.HTMLEncode( value ) ; FCK.LinkedField.value = value ; FCK.Events.FireEvent( 'OnAfterLinkedFieldUpdate' ) ; }, RegisteredDoubleClickHandlers : new Object(), OnDoubleClick : function( element ) { var oCalls = FCK.RegisteredDoubleClickHandlers[ element.tagName.toUpperCase() ] ; if ( oCalls ) { for ( var i = 0 ; i < oCalls.length ; i++ ) oCalls[ i ]( element ) ; } // Generic handler for any element oCalls = FCK.RegisteredDoubleClickHandlers[ '*' ] ; if ( oCalls ) { for ( var i = 0 ; i < oCalls.length ; i++ ) oCalls[ i ]( element ) ; } }, // Register objects that can handle double click operations. RegisterDoubleClickHandler : function( handlerFunction, tag ) { var nodeName = tag || '*' ; nodeName = nodeName.toUpperCase() ; var aTargets ; if ( !( aTargets = FCK.RegisteredDoubleClickHandlers[ nodeName ] ) ) FCK.RegisteredDoubleClickHandlers[ nodeName ] = [ handlerFunction ] ; else { // Check that the event handler isn't already registered with the same listener // It doesn't detect function pointers belonging to an object (at least in Gecko) if ( aTargets.IndexOf( handlerFunction ) == -1 ) aTargets.push( handlerFunction ) ; } }, OnAfterSetHTML : function() { FCKDocumentProcessor.Process( FCK.EditorDocument ) ; FCKUndo.SaveUndoStep() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; FCK.Events.FireEvent( 'OnAfterSetHTML' ) ; }, // Saves URLs on links and images on special attributes, so they don't change when // moving around. ProtectUrls : function( html ) { // <A> href html = html.replace( FCKRegexLib.ProtectUrlsA , '$& _fcksavedurl=$1' ) ; // <IMG> src html = html.replace( FCKRegexLib.ProtectUrlsImg , '$& _fcksavedurl=$1' ) ; // <AREA> href html = html.replace( FCKRegexLib.ProtectUrlsArea , '$& _fcksavedurl=$1' ) ; return html ; }, // Saves event attributes (like onclick) so they don't get executed while // editing. ProtectEvents : function( html ) { return html.replace( FCKRegexLib.TagsWithEvent, _FCK_ProtectEvents_ReplaceTags ) ; }, ProtectEventsRestore : function( html ) { return html.replace( FCKRegexLib.ProtectedEvents, _FCK_ProtectEvents_RestoreEvents ) ; }, ProtectTags : function( html ) { var sTags = FCKConfig.ProtectedTags ; // IE doesn't support <abbr> and it breaks it. Let's protect it. if ( FCKBrowserInfo.IsIE ) sTags += sTags.length > 0 ? '|ABBR|XML|EMBED|OBJECT' : 'ABBR|XML|EMBED|OBJECT' ; var oRegex ; if ( sTags.length > 0 ) { oRegex = new RegExp( '<(' + sTags + ')(?!\w|:)', 'gi' ) ; html = html.replace( oRegex, '<FCK:$1' ) ; oRegex = new RegExp( '<\/(' + sTags + ')>', 'gi' ) ; html = html.replace( oRegex, '<\/FCK:$1>' ) ; } // Protect some empty elements. We must do it separately because the // original tag may not contain the closing slash, like <hr>: // - <meta> tags get executed, so if you have a redirect meta, the // content will move to the target page. // - <hr> may destroy the document structure if not well // positioned. The trick is protect it here and restore them in // the FCKDocumentProcessor. sTags = 'META' ; if ( FCKBrowserInfo.IsIE ) sTags += '|HR' ; oRegex = new RegExp( '<((' + sTags + ')(?=\\s|>|/)[\\s\\S]*?)/?>', 'gi' ) ; html = html.replace( oRegex, '<FCK:$1 />' ) ; return html ; }, SetData : function( data, resetIsDirty ) { this.EditingArea.Mode = FCK.EditMode ; // If there was an onSelectionChange listener in IE we must remove it to avoid crashes #1498 if ( FCKBrowserInfo.IsIE && FCK.EditorDocument ) { FCK.EditorDocument.detachEvent("onselectionchange", Doc_OnSelectionChange ) ; } FCKTempBin.Reset() ; // Bug #2469: SelectionData.createRange becomes undefined after the editor // iframe is changed by FCK.SetData(). FCK.Selection.Release() ; if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) { // Save the resetIsDirty for later use (async) this._ForceResetIsDirty = ( resetIsDirty === true ) ; // Protect parts of the code that must remain untouched (and invisible) // during editing. data = FCKConfig.ProtectedSource.Protect( data ) ; // Call the Data Processor to transform the data. data = FCK.DataProcessor.ConvertToHtml( data ) ; // Fix for invalid self-closing tags (see #152). data = data.replace( FCKRegexLib.InvalidSelfCloseTags, '$1></$2>' ) ; // Protect event attributes (they could get fired in the editing area). data = FCK.ProtectEvents( data ) ; // Protect some things from the browser itself. data = FCK.ProtectUrls( data ) ; data = FCK.ProtectTags( data ) ; // Insert the base tag (FCKConfig.BaseHref), if not exists in the source. // The base must be the first tag in the HEAD, to get relative // links on styles, for example. if ( FCK.TempBaseTag.length > 0 && !FCKRegexLib.HasBaseTag.test( data ) ) data = data.replace( FCKRegexLib.HeadOpener, '$&' + FCK.TempBaseTag ) ; // Build the HTML for the additional things we need on <head>. var sHeadExtra = '' ; if ( !FCKConfig.FullPage ) sHeadExtra += _FCK_GetEditorAreaStyleTags() ; if ( FCKBrowserInfo.IsIE ) sHeadExtra += FCK._GetBehaviorsStyle() ; else if ( FCKConfig.ShowBorders ) sHeadExtra += FCKTools.GetStyleHtml( FCK_ShowTableBordersCSS, true ) ; sHeadExtra += FCKTools.GetStyleHtml( FCK_InternalCSS, true ) ; // Attention: do not change it before testing it well (sample07)! // This is tricky... if the head ends with <meta ... content type>, // Firefox will break. But, it works if we place our extra stuff as // the last elements in the HEAD. data = data.replace( FCKRegexLib.HeadCloser, sHeadExtra + '$&' ) ; // Load the HTML in the editing area. this.EditingArea.OnLoad = _FCK_EditingArea_OnLoad ; this.EditingArea.Start( data ) ; } else { // Remove the references to the following elements, as the editing area // IFRAME will be removed. FCK.EditorWindow = null ; FCK.EditorDocument = null ; FCKDomTools.PaddingNode = null ; this.EditingArea.OnLoad = null ; this.EditingArea.Start( data ) ; // Enables the context menu in the textarea. this.EditingArea.Textarea._FCKShowContextMenu = true ; // Removes the enter key handler. FCK.EnterKeyHandler = null ; if ( resetIsDirty ) this.ResetIsDirty() ; // Listen for keystroke events. FCK.KeystrokeHandler.AttachToElement( this.EditingArea.Textarea ) ; this.EditingArea.Textarea.focus() ; FCK.Events.FireEvent( 'OnAfterSetHTML' ) ; } if ( window.onresize ) window.onresize() ; }, // This collection is used by the browser specific implementations to tell // which named commands must be handled separately. RedirectNamedCommands : new Object(), ExecuteNamedCommand : function( commandName, commandParameter, noRedirect, noSaveUndo ) { if ( !noSaveUndo ) FCKUndo.SaveUndoStep() ; if ( !noRedirect && FCK.RedirectNamedCommands[ commandName ] != null ) FCK.ExecuteRedirectedNamedCommand( commandName, commandParameter ) ; else { FCK.Focus() ; FCK.EditorDocument.execCommand( commandName, false, commandParameter ) ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; } if ( !noSaveUndo ) FCKUndo.SaveUndoStep() ; }, GetNamedCommandState : function( commandName ) { try { // Bug #50 : Safari never returns positive state for the Paste command, override that. if ( FCKBrowserInfo.IsSafari && FCK.EditorWindow && commandName.IEquals( 'Paste' ) ) return FCK_TRISTATE_OFF ; if ( !FCK.EditorDocument.queryCommandEnabled( commandName ) ) return FCK_TRISTATE_DISABLED ; else { return FCK.EditorDocument.queryCommandState( commandName ) ? FCK_TRISTATE_ON : FCK_TRISTATE_OFF ; } } catch ( e ) { return FCK_TRISTATE_OFF ; } }, GetNamedCommandValue : function( commandName ) { var sValue = '' ; var eState = FCK.GetNamedCommandState( commandName ) ; if ( eState == FCK_TRISTATE_DISABLED ) return null ; try { sValue = this.EditorDocument.queryCommandValue( commandName ) ; } catch(e) {} return sValue ? sValue : '' ; }, Paste : function( _callListenersOnly ) { // First call 'OnPaste' listeners. if ( FCK.Status != FCK_STATUS_COMPLETE || !FCK.Events.FireEvent( 'OnPaste' ) ) return false ; // Then call the default implementation. return _callListenersOnly || FCK._ExecPaste() ; }, PasteFromWord : function() { FCKDialog.OpenDialog( 'FCKDialog_Paste', FCKLang.PasteFromWord, 'dialog/fck_paste.html', 400, 330, 'Word' ) ; }, Preview : function() { var sHTML ; if ( FCKConfig.FullPage ) { if ( FCK.TempBaseTag.length > 0 ) sHTML = FCK.TempBaseTag + FCK.GetXHTML() ; else sHTML = FCK.GetXHTML() ; } else { sHTML = FCKConfig.DocType + '<html dir="' + FCKConfig.ContentLangDirection + '">' + '<head>' + FCK.TempBaseTag + '<title>' + FCKLang.Preview + '</title>' + _FCK_GetEditorAreaStyleTags() + '</head><body' + FCKConfig.GetBodyAttributes() + '>' + FCK.GetXHTML() + '</body></html>' ; } var iWidth = FCKConfig.ScreenWidth * 0.8 ; var iHeight = FCKConfig.ScreenHeight * 0.7 ; var iLeft = ( FCKConfig.ScreenWidth - iWidth ) / 2 ; var sOpenUrl = '' ; if ( FCK_IS_CUSTOM_DOMAIN && FCKBrowserInfo.IsIE) { window._FCKHtmlToLoad = sHTML ; sOpenUrl = 'javascript:void( (function(){' + 'document.open() ;' + 'document.domain="' + document.domain + '" ;' + 'document.write( window.opener._FCKHtmlToLoad );' + 'document.close() ;' + 'window.opener._FCKHtmlToLoad = null ;' + '})() )' ; } var oWindow = window.open( sOpenUrl, null, 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' + iWidth + ',height=' + iHeight + ',left=' + iLeft ) ; if ( !FCK_IS_CUSTOM_DOMAIN || !FCKBrowserInfo.IsIE) { oWindow.document.write( sHTML ); oWindow.document.close(); } }, SwitchEditMode : function( noUndo ) { var bIsWysiwyg = ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) ; // Save the current IsDirty state, so we may restore it after the switch. var bIsDirty = FCK.IsDirty() ; var sHtml ; // Update the HTML in the view output to show, also update // FCKTempBin for IE to avoid #2263. if ( bIsWysiwyg ) { FCKCommands.GetCommand( 'ShowBlocks' ).SaveState() ; if ( !noUndo && FCKBrowserInfo.IsIE ) FCKUndo.SaveUndoStep() ; sHtml = FCK.GetXHTML( FCKConfig.FormatSource ) ; if ( FCKBrowserInfo.IsIE ) FCKTempBin.ToHtml() ; if ( sHtml == null ) return false ; } else sHtml = this.EditingArea.Textarea.value ; FCK.EditMode = bIsWysiwyg ? FCK_EDITMODE_SOURCE : FCK_EDITMODE_WYSIWYG ; FCK.SetData( sHtml, !bIsDirty ) ; // Set the Focus. FCK.Focus() ; // Update the toolbar (Running it directly causes IE to fail). FCKTools.RunFunction( FCK.ToolbarSet.RefreshModeState, FCK.ToolbarSet ) ; return true ; }, InsertElement : function( element ) { // The parameter may be a string (element name), so transform it in an element. if ( typeof element == 'string' ) element = this.EditorDocument.createElement( element ) ; var elementName = element.nodeName.toLowerCase() ; FCKSelection.Restore() ; // Create a range for the selection. V3 will have a new selection // object that may internally supply this feature. var range = new FCKDomRange( this.EditorWindow ) ; // Move to the selection and delete it. range.MoveToSelection() ; range.DeleteContents() ; if ( FCKListsLib.BlockElements[ elementName ] != null ) { if ( range.StartBlock ) { if ( range.CheckStartOfBlock() ) range.MoveToPosition( range.StartBlock, 3 ) ; else if ( range.CheckEndOfBlock() ) range.MoveToPosition( range.StartBlock, 4 ) ; else range.SplitBlock() ; } range.InsertNode( element ) ; var next = FCKDomTools.GetNextSourceElement( element, false, null, [ 'hr','br','param','img','area','input' ], true ) ; // Be sure that we have something after the new element, so we can move the cursor there. if ( !next && FCKConfig.EnterMode != 'br') { next = this.EditorDocument.body.appendChild( this.EditorDocument.createElement( FCKConfig.EnterMode ) ) ; if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( next ) ; } if ( FCKListsLib.EmptyElements[ elementName ] == null ) range.MoveToElementEditStart( element ) ; else if ( next ) range.MoveToElementEditStart( next ) ; else range.MoveToPosition( element, 4 ) ; if ( FCKBrowserInfo.IsGeckoLike ) { if ( next ) FCKDomTools.ScrollIntoView( next, false ); FCKDomTools.ScrollIntoView( element, false ); } } else { // Insert the node. range.InsertNode( element ) ; // Move the selection right after the new element. // DISCUSSION: Should we select the element instead? range.SetStart( element, 4 ) ; range.SetEnd( element, 4 ) ; } range.Select() ; range.Release() ; // REMOVE IT: The focus should not really be set here. It is up to the // calling code to reset the focus if needed. this.Focus() ; return element ; }, _InsertBlockElement : function( blockElement ) { }, _IsFunctionKey : function( keyCode ) { // keys that are captured but do not change editor contents if ( keyCode >= 16 && keyCode <= 20 ) // shift, ctrl, alt, pause, capslock return true ; if ( keyCode == 27 || ( keyCode >= 33 && keyCode <= 40 ) ) // esc, page up, page down, end, home, left, up, right, down return true ; if ( keyCode == 45 ) // insert, no effect on FCKeditor, yet return true ; return false ; }, _KeyDownListener : function( evt ) { if (! evt) evt = FCK.EditorWindow.event ; if ( FCK.EditorWindow ) { if ( !FCK._IsFunctionKey(evt.keyCode) // do not capture function key presses, like arrow keys or shift/alt/ctrl && !(evt.ctrlKey || evt.metaKey) // do not capture Ctrl hotkeys, as they have their snapshot capture logic && !(evt.keyCode == 46) ) // do not capture Del, it has its own capture logic in fckenterkey.js FCK._KeyDownUndo() ; } return true ; }, _KeyDownUndo : function() { if ( !FCKUndo.Typing ) { FCKUndo.SaveUndoStep() ; FCKUndo.Typing = true ; FCK.Events.FireEvent( "OnSelectionChange" ) ; } FCKUndo.TypesCount++ ; FCKUndo.Changed = 1 ; if ( FCKUndo.TypesCount > FCKUndo.MaxTypes ) { FCKUndo.TypesCount = 0 ; FCKUndo.SaveUndoStep() ; } }, _TabKeyHandler : function( evt ) { if ( ! evt ) evt = window.event ; var keystrokeValue = evt.keyCode ; // Pressing <Tab> in source mode should produce a tab space in the text area, not // changing the focus to something else. if ( keystrokeValue == 9 && FCK.EditMode != FCK_EDITMODE_WYSIWYG ) { if ( FCKBrowserInfo.IsIE ) { var range = document.selection.createRange() ; if ( range.parentElement() != FCK.EditingArea.Textarea ) return true ; range.text = '\t' ; range.select() ; } else { var a = [] ; var el = FCK.EditingArea.Textarea ; var selStart = el.selectionStart ; var selEnd = el.selectionEnd ; a.push( el.value.substr(0, selStart ) ) ; a.push( '\t' ) ; a.push( el.value.substr( selEnd ) ) ; el.value = a.join( '' ) ; el.setSelectionRange( selStart + 1, selStart + 1 ) ; } if ( evt.preventDefault ) return evt.preventDefault() ; return evt.returnValue = false ; } return true ; } } ; FCK.Events = new FCKEvents( FCK ) ; // DEPRECATED in favor or "GetData". FCK.GetHTML = FCK.GetXHTML = FCK.GetData ; // DEPRECATED in favor of "SetData". FCK.SetHTML = FCK.SetData ; // InsertElementAndGetIt and CreateElement are Deprecated : returns the same value as InsertElement. FCK.InsertElementAndGetIt = FCK.CreateElement = FCK.InsertElement ; // Replace all events attributes (like onclick). function _FCK_ProtectEvents_ReplaceTags( tagMatch ) { return tagMatch.replace( FCKRegexLib.EventAttributes, _FCK_ProtectEvents_ReplaceEvents ) ; } // Replace an event attribute with its respective __fckprotectedatt attribute. // The original event markup will be encoded and saved as the value of the new // attribute. function _FCK_ProtectEvents_ReplaceEvents( eventMatch, attName ) { return ' ' + attName + '_fckprotectedatt="' + encodeURIComponent( eventMatch ) + '"' ; } function _FCK_ProtectEvents_RestoreEvents( match, encodedOriginal ) { return decodeURIComponent( encodedOriginal ) ; } function _FCK_MouseEventsListener( evt ) { if ( ! evt ) evt = window.event ; if ( evt.type == 'mousedown' ) FCK.MouseDownFlag = true ; else if ( evt.type == 'mouseup' ) FCK.MouseDownFlag = false ; else if ( evt.type == 'mousemove' ) FCK.Events.FireEvent( 'OnMouseMove', evt ) ; } function _FCK_PaddingNodeListener() { if ( FCKConfig.EnterMode.IEquals( 'br' ) ) return ; FCKDomTools.EnforcePaddingNode( FCK.EditorDocument, FCKConfig.EnterMode ) ; if ( ! FCKBrowserInfo.IsIE && FCKDomTools.PaddingNode ) { // Prevent the caret from going between the body and the padding node in Firefox. // i.e. <body>|<p></p></body> var sel = FCKSelection.GetSelection() ; if ( sel && sel.rangeCount == 1 ) { var range = sel.getRangeAt( 0 ) ; if ( range.collapsed && range.startContainer == FCK.EditorDocument.body && range.startOffset == 0 ) { range.selectNodeContents( FCKDomTools.PaddingNode ) ; range.collapse( true ) ; sel.removeAllRanges() ; sel.addRange( range ) ; } } } else if ( FCKDomTools.PaddingNode ) { // Prevent the caret from going into an empty body but not into the padding node in IE. // i.e. <body><p></p>|</body> var parentElement = FCKSelection.GetParentElement() ; var paddingNode = FCKDomTools.PaddingNode ; if ( parentElement && parentElement.nodeName.IEquals( 'body' ) ) { if ( FCK.EditorDocument.body.childNodes.length == 1 && FCK.EditorDocument.body.firstChild == paddingNode ) { /* * Bug #1764: Don't move the selection if the * current selection isn't in the editor * document. */ if ( FCKSelection._GetSelectionDocument( FCK.EditorDocument.selection ) != FCK.EditorDocument ) return ; var range = FCK.EditorDocument.body.createTextRange() ; var clearContents = false ; if ( !paddingNode.childNodes.firstChild ) { paddingNode.appendChild( FCKTools.GetElementDocument( paddingNode ).createTextNode( '\ufeff' ) ) ; clearContents = true ; } range.moveToElementText( paddingNode ) ; range.select() ; if ( clearContents ) range.pasteHTML( '' ) ; } } } } function _FCK_EditingArea_OnLoad() { // Get the editor's window and document (DOM) FCK.EditorWindow = FCK.EditingArea.Window ; FCK.EditorDocument = FCK.EditingArea.Document ; if ( FCKBrowserInfo.IsIE ) FCKTempBin.ToElements() ; FCK.InitializeBehaviors() ; // Listen for mousedown and mouseup events for tracking drag and drops. FCK.MouseDownFlag = false ; FCKTools.AddEventListener( FCK.EditorDocument, 'mousemove', _FCK_MouseEventsListener ) ; FCKTools.AddEventListener( FCK.EditorDocument, 'mousedown', _FCK_MouseEventsListener ) ; FCKTools.AddEventListener( FCK.EditorDocument, 'mouseup', _FCK_MouseEventsListener ) ; if ( FCKBrowserInfo.IsSafari ) { // #3481: WebKit has a bug with paste where the paste contents may leak // outside table cells. So add padding nodes before and after the paste. FCKTools.AddEventListener( FCK.EditorDocument, 'paste', function( evt ) { var range = new FCKDomRange( FCK.EditorWindow ); var nodeBefore = FCK.EditorDocument.createTextNode( '\ufeff' ); var nodeAfter = FCK.EditorDocument.createElement( 'a' ); nodeAfter.id = 'fck_paste_padding'; nodeAfter.innerHTML = '&#65279;'; range.MoveToSelection(); range.DeleteContents(); // Insert padding nodes. range.InsertNode( nodeBefore ); range.Collapse(); range.InsertNode( nodeAfter ); // Move the selection to between the padding nodes. range.MoveToPosition( nodeAfter, 3 ); range.Select(); // Remove the padding nodes after the paste is done. setTimeout( function() { nodeBefore.parentNode.removeChild( nodeBefore ); nodeAfter = FCK.EditorDocument.getElementById( 'fck_paste_padding' ); nodeAfter.parentNode.removeChild( nodeAfter ); }, 0 ); } ); } // Most of the CTRL key combos do not work under Safari for onkeydown and onkeypress (See #1119) // But we can use the keyup event to override some of these... if ( FCKBrowserInfo.IsSafari ) { var undoFunc = function( evt ) { if ( ! ( evt.ctrlKey || evt.metaKey ) ) return ; if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; switch ( evt.keyCode ) { case 89: FCKUndo.Redo() ; break ; case 90: FCKUndo.Undo() ; break ; } } FCKTools.AddEventListener( FCK.EditorDocument, 'keyup', undoFunc ) ; } // Create the enter key handler FCK.EnterKeyHandler = new FCKEnterKey( FCK.EditorWindow, FCKConfig.EnterMode, FCKConfig.ShiftEnterMode, FCKConfig.TabSpaces ) ; // Listen for keystroke events. FCK.KeystrokeHandler.AttachToElement( FCK.EditorDocument ) ; if ( FCK._ForceResetIsDirty ) FCK.ResetIsDirty() ; // This is a tricky thing for IE. In some cases, even if the cursor is // blinking in the editing, the keystroke handler doesn't catch keyboard // events. We must activate the editing area to make it work. (#142). if ( FCKBrowserInfo.IsIE && FCK.HasFocus ) FCK.EditorDocument.body.setActive() ; FCK.OnAfterSetHTML() ; // Restore show blocks status. FCKCommands.GetCommand( 'ShowBlocks' ).RestoreState() ; // Check if it is not a startup call, otherwise complete the startup. if ( FCK.Status != FCK_STATUS_NOTLOADED ) return ; FCK.SetStatus( FCK_STATUS_ACTIVE ) ; } function _FCK_GetEditorAreaStyleTags() { return FCKTools.GetStyleHtml( FCKConfig.EditorAreaCSS ) + FCKTools.GetStyleHtml( FCKConfig.EditorAreaStyles ) ; } function _FCK_KeystrokeHandler_OnKeystroke( keystroke, keystrokeValue ) { if ( FCK.Status != FCK_STATUS_COMPLETE ) return false ; if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) { switch ( keystrokeValue ) { case 'Paste' : return !FCK.Paste() ; case 'Cut' : FCKUndo.SaveUndoStep() ; return false ; } } else { // In source mode, some actions must have their default behavior. if ( keystrokeValue.Equals( 'Paste', 'Undo', 'Redo', 'SelectAll', 'Cut' ) ) return false ; } // The return value indicates if the default behavior of the keystroke must // be cancelled. Let's do that only if the Execute() call explicitly returns "false". var oCommand = FCK.Commands.GetCommand( keystrokeValue ) ; // If the command is disabled then ignore the keystroke if ( oCommand.GetState() == FCK_TRISTATE_DISABLED ) return false ; return ( oCommand.Execute.apply( oCommand, FCKTools.ArgumentsToArray( arguments, 2 ) ) !== false ) ; } // Set the FCK.LinkedField reference to the field that will be used to post the // editor data. (function() { // There is a bug on IE... getElementById returns any META tag that has the // name set to the ID you are looking for. So the best way in to get the array // by names and look for the correct one. // As ASP.Net generates a ID that is different from the Name, we must also // look for the field based on the ID (the first one is the ID). var oDocument = window.parent.document ; // Try to get the field using the ID. var eLinkedField = oDocument.getElementById( FCK.Name ) ; var i = 0; while ( eLinkedField || i == 0 ) { if ( eLinkedField && eLinkedField.tagName.toLowerCase().Equals( 'input', 'textarea' ) ) { FCK.LinkedField = eLinkedField ; break ; } eLinkedField = oDocument.getElementsByName( FCK.Name )[i++] ; } })() ; var FCKTempBin = { Elements : new Array(), AddElement : function( element ) { var iIndex = this.Elements.length ; this.Elements[ iIndex ] = element ; return iIndex ; }, RemoveElement : function( index ) { var e = this.Elements[ index ] ; this.Elements[ index ] = null ; return e ; }, Reset : function() { var i = 0 ; while ( i < this.Elements.length ) this.Elements[ i++ ] = null ; this.Elements.length = 0 ; }, ToHtml : function() { for ( var i = 0 ; i < this.Elements.length ; i++ ) { this.Elements[i] = '<div>&nbsp;' + this.Elements[i].outerHTML + '</div>' ; this.Elements[i].isHtml = true ; } }, ToElements : function() { var node = FCK.EditorDocument.createElement( 'div' ) ; for ( var i = 0 ; i < this.Elements.length ; i++ ) { if ( this.Elements[i].isHtml ) { node.innerHTML = this.Elements[i] ; this.Elements[i] = node.firstChild.removeChild( node.firstChild.lastChild ) ; } } } } ; // # Focus Manager: Manages the focus in the editor. var FCKFocusManager = FCK.FocusManager = { IsLocked : false, AddWindow : function( win, sendToEditingArea ) { var oTarget ; if ( FCKBrowserInfo.IsIE ) oTarget = win.nodeType == 1 ? win : win.frameElement ? win.frameElement : win.document ; else if ( FCKBrowserInfo.IsSafari ) oTarget = win ; else oTarget = win.document ; FCKTools.AddEventListener( oTarget, 'blur', FCKFocusManager_Win_OnBlur ) ; FCKTools.AddEventListener( oTarget, 'focus', sendToEditingArea ? FCKFocusManager_Win_OnFocus_Area : FCKFocusManager_Win_OnFocus ) ; }, RemoveWindow : function( win ) { if ( FCKBrowserInfo.IsIE ) oTarget = win.nodeType == 1 ? win : win.frameElement ? win.frameElement : win.document ; else oTarget = win.document ; FCKTools.RemoveEventListener( oTarget, 'blur', FCKFocusManager_Win_OnBlur ) ; FCKTools.RemoveEventListener( oTarget, 'focus', FCKFocusManager_Win_OnFocus_Area ) ; FCKTools.RemoveEventListener( oTarget, 'focus', FCKFocusManager_Win_OnFocus ) ; }, Lock : function() { this.IsLocked = true ; }, Unlock : function() { if ( this._HasPendingBlur ) FCKFocusManager._Timer = window.setTimeout( FCKFocusManager_FireOnBlur, 100 ) ; this.IsLocked = false ; }, _ResetTimer : function() { this._HasPendingBlur = false ; if ( this._Timer ) { window.clearTimeout( this._Timer ) ; delete this._Timer ; } } } ; function FCKFocusManager_Win_OnBlur() { if ( typeof(FCK) != 'undefined' && FCK.HasFocus ) { FCKFocusManager._ResetTimer() ; FCKFocusManager._Timer = window.setTimeout( FCKFocusManager_FireOnBlur, 100 ) ; } } function FCKFocusManager_FireOnBlur() { if ( FCKFocusManager.IsLocked ) FCKFocusManager._HasPendingBlur = true ; else { FCK.HasFocus = false ; FCK.Events.FireEvent( "OnBlur" ) ; } } function FCKFocusManager_Win_OnFocus_Area() { // Check if we are already focusing the editor (to avoid loops). if ( FCKFocusManager._IsFocusing ) return ; FCKFocusManager._IsFocusing = true ; FCK.Focus() ; FCKFocusManager_Win_OnFocus() ; // The above FCK.Focus() call may trigger other focus related functions. // So, to avoid a loop, we delay the focusing mark removal, so it get // executed after all othre functions have been run. FCKTools.RunFunction( function() { delete FCKFocusManager._IsFocusing ; } ) ; } function FCKFocusManager_Win_OnFocus() { FCKFocusManager._ResetTimer() ; if ( !FCK.HasFocus && !FCKFocusManager.IsLocked ) { FCK.HasFocus = true ; FCK.Events.FireEvent( "OnFocus" ) ; } } /* * #1633 : Protect the editor iframe from external styles. * Notice that we can't use FCKTools.ResetStyles here since FCKTools isn't * loaded yet. */ (function() { var el = window.frameElement ; var width = el.width ; var height = el.height ; if ( /^\d+$/.test( width ) ) width += 'px' ; if ( /^\d+$/.test( height ) ) height += 'px' ; var style = el.style ; style.border = style.padding = style.margin = 0 ; style.backgroundColor = 'transparent'; style.backgroundImage = 'none'; style.width = width ; style.height = height ; })() ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Manage table operations (IE specific). */ FCKTableHandler.GetSelectedCells = function() { if ( FCKSelection.GetType() == 'Control' ) { var td = FCKSelection.MoveToAncestorNode( ['TD', 'TH'] ) ; return td ? [ td ] : [] ; } var aCells = new Array() ; var oRange = FCKSelection.GetSelection().createRange() ; // var oParent = oRange.parentElement() ; var oParent = FCKSelection.GetParentElement() ; if ( oParent && oParent.tagName.Equals( 'TD', 'TH' ) ) aCells[0] = oParent ; else { oParent = FCKSelection.MoveToAncestorNode( 'TABLE' ) ; if ( oParent ) { // Loops throw all cells checking if the cell is, or part of it, is inside the selection // and then add it to the selected cells collection. for ( var i = 0 ; i < oParent.cells.length ; i++ ) { var oCellRange = FCK.EditorDocument.body.createTextRange() ; oCellRange.moveToElementText( oParent.cells[i] ) ; if ( oRange.inRange( oCellRange ) || ( oRange.compareEndPoints('StartToStart',oCellRange) >= 0 && oRange.compareEndPoints('StartToEnd',oCellRange) <= 0 ) || ( oRange.compareEndPoints('EndToStart',oCellRange) >= 0 && oRange.compareEndPoints('EndToEnd',oCellRange) <= 0 ) ) { aCells[aCells.length] = oParent.cells[i] ; } } } } return aCells ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Manage table operations (non-IE). */ FCKTableHandler.GetSelectedCells = function() { var aCells = new Array() ; var oSelection = FCKSelection.GetSelection() ; // If the selection is a text. if ( oSelection.rangeCount == 1 && oSelection.anchorNode.nodeType == 3 ) { var oParent = FCKTools.GetElementAscensor( oSelection.anchorNode, 'TD,TH' ) ; if ( oParent ) aCells[0] = oParent ; return aCells ; } for ( var i = 0 ; i < oSelection.rangeCount ; i++ ) { var oRange = oSelection.getRangeAt(i) ; var oCell ; if ( oRange.startContainer.tagName.Equals( 'TD', 'TH' ) ) oCell = oRange.startContainer ; else oCell = oRange.startContainer.childNodes[ oRange.startOffset ] ; if ( oCell.nodeName.Equals( 'TD', 'TH' ) ) aCells[aCells.length] = oCell ; } return aCells ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Handles styles in a give document. */ var FCKStyles = FCK.Styles = { _Callbacks : {}, _ObjectStyles : {}, ApplyStyle : function( style ) { if ( typeof style == 'string' ) style = this.GetStyles()[ style ] ; if ( style ) { if ( style.GetType() == FCK_STYLE_OBJECT ) style.ApplyToObject( FCKSelection.GetSelectedElement() ) ; else style.ApplyToSelection( FCK.EditorWindow ) ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; } }, RemoveStyle : function( style ) { if ( typeof style == 'string' ) style = this.GetStyles()[ style ] ; if ( style ) { style.RemoveFromSelection( FCK.EditorWindow ) ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; } }, /** * Defines a callback function to be called when the current state of a * specific style changes. */ AttachStyleStateChange : function( styleName, callback, callbackOwner ) { var callbacks = this._Callbacks[ styleName ] ; if ( !callbacks ) callbacks = this._Callbacks[ styleName ] = [] ; callbacks.push( [ callback, callbackOwner ] ) ; }, CheckSelectionChanges : function() { var startElement = FCKSelection.GetBoundaryParentElement( true ) ; if ( !startElement ) return ; // Walks the start node parents path, checking all styles that are being listened. var path = new FCKElementPath( startElement ) ; var styles = this.GetStyles() ; for ( var styleName in styles ) { var callbacks = this._Callbacks[ styleName ] ; if ( callbacks ) { var style = styles[ styleName ] ; var state = style.CheckActive( path ) ; if ( state != ( style._LastState || null ) ) { style._LastState = state ; for ( var i = 0 ; i < callbacks.length ; i++ ) { var callback = callbacks[i][0] ; var callbackOwner = callbacks[i][1] ; callback.call( callbackOwner || window, styleName, state ) ; } } } } }, CheckStyleInSelection : function( styleName ) { return false ; }, _GetRemoveFormatTagsRegex : function () { var regex = new RegExp( '^(?:' + FCKConfig.RemoveFormatTags.replace( /,/g,'|' ) + ')$', 'i' ) ; return (this._GetRemoveFormatTagsRegex = function() { return regex ; }) && regex ; }, /** * Remove all styles from the current selection. * TODO: * - This is almost a duplication of FCKStyle.RemoveFromRange. We should * try to merge things. */ RemoveAll : function() { var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; if ( range.CheckIsCollapsed() ) return ; // Expand the range, if inside inline element boundaries. range.Expand( 'inline_elements' ) ; // Get the bookmark nodes. // Bookmark the range so we can re-select it after processing. var bookmark = range.CreateBookmark( true ) ; // The style will be applied within the bookmark boundaries. var startNode = range.GetBookmarkNode( bookmark, true ) ; var endNode = range.GetBookmarkNode( bookmark, false ) ; range.Release( true ) ; var tagsRegex = this._GetRemoveFormatTagsRegex() ; // We need to check the selection boundaries (bookmark spans) to break // the code in a way that we can properly remove partially selected nodes. // For example, removing a <b> style from // <b>This is [some text</b> to show <b>the] problem</b> // ... where [ and ] represent the selection, must result: // <b>This is </b>[some text to show the]<b> problem</b> // The strategy is simple, we just break the partial nodes before the // removal logic, having something that could be represented this way: // <b>This is </b>[<b>some text</b> to show <b>the</b>]<b> problem</b> // Let's start checking the start boundary. var path = new FCKElementPath( startNode ) ; var pathElements = path.Elements ; var pathElement ; for ( var i = 1 ; i < pathElements.length ; i++ ) { pathElement = pathElements[i] ; if ( pathElement == path.Block || pathElement == path.BlockLimit ) break ; // If this element can be removed (even partially). if ( tagsRegex.test( pathElement.nodeName ) ) FCKDomTools.BreakParent( startNode, pathElement, range ) ; } // Now the end boundary. path = new FCKElementPath( endNode ) ; pathElements = path.Elements ; for ( var i = 1 ; i < pathElements.length ; i++ ) { pathElement = pathElements[i] ; if ( pathElement == path.Block || pathElement == path.BlockLimit ) break ; elementName = pathElement.nodeName.toLowerCase() ; // If this element can be removed (even partially). if ( tagsRegex.test( pathElement.nodeName ) ) FCKDomTools.BreakParent( endNode, pathElement, range ) ; } // Navigate through all nodes between the bookmarks. var currentNode = FCKDomTools.GetNextSourceNode( startNode, true, 1 ) ; while ( currentNode ) { // If we have reached the end of the selection, stop looping. if ( currentNode == endNode ) break ; // Cache the next node to be processed. Do it now, because // currentNode may be removed. var nextNode = FCKDomTools.GetNextSourceNode( currentNode, false, 1 ) ; // Remove elements nodes that match with this style rules. if ( tagsRegex.test( currentNode.nodeName ) ) FCKDomTools.RemoveNode( currentNode, true ) ; else FCKDomTools.RemoveAttributes( currentNode, FCKConfig.RemoveAttributesArray ); currentNode = nextNode ; } range.SelectBookmark( bookmark ) ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetStyle : function( styleName ) { return this.GetStyles()[ styleName ] ; }, GetStyles : function() { var styles = this._GetStyles ; if ( !styles ) { styles = this._GetStyles = FCKTools.Merge( this._LoadStylesCore(), this._LoadStylesCustom(), this._LoadStylesXml() ) ; } return styles ; }, CheckHasObjectStyle : function( elementName ) { return !!this._ObjectStyles[ elementName ] ; }, _LoadStylesCore : function() { var styles = {}; var styleDefs = FCKConfig.CoreStyles ; for ( var styleName in styleDefs ) { // Core styles are prefixed with _FCK_. var style = styles[ '_FCK_' + styleName ] = new FCKStyle( styleDefs[ styleName ] ) ; style.IsCore = true ; } return styles ; }, _LoadStylesCustom : function() { var styles = {}; var styleDefs = FCKConfig.CustomStyles ; if ( styleDefs ) { for ( var styleName in styleDefs ) { var style = styles[ styleName ] = new FCKStyle( styleDefs[ styleName ] ) ; style.Name = styleName ; } } return styles ; }, _LoadStylesXml : function() { var styles = {}; var stylesXmlPath = FCKConfig.StylesXmlPath ; if ( !stylesXmlPath || stylesXmlPath.length == 0 ) return styles ; // Load the XML file into a FCKXml object. var xml = new FCKXml() ; xml.LoadUrl( stylesXmlPath ) ; var stylesXmlObj = FCKXml.TransformToObject( xml.SelectSingleNode( 'Styles' ) ) ; // Get the "Style" nodes defined in the XML file. var styleNodes = stylesXmlObj.$Style ; // Check that it did contain some valid nodes if ( !styleNodes ) return styles ; // Add each style to our "Styles" collection. for ( var i = 0 ; i < styleNodes.length ; i++ ) { var styleNode = styleNodes[i] ; var element = ( styleNode.element || '' ).toLowerCase() ; if ( element.length == 0 ) throw( 'The element name is required. Error loading "' + stylesXmlPath + '"' ) ; var styleDef = { Element : element, Attributes : {}, Styles : {}, Overrides : [] } ; // Get the attributes defined for the style (if any). var attNodes = styleNode.$Attribute || [] ; // Add the attributes to the style definition object. for ( var j = 0 ; j < attNodes.length ; j++ ) { styleDef.Attributes[ attNodes[j].name ] = attNodes[j].value ; } // Get the styles defined for the style (if any). var cssStyleNodes = styleNode.$Style || [] ; // Add the attributes to the style definition object. for ( j = 0 ; j < cssStyleNodes.length ; j++ ) { styleDef.Styles[ cssStyleNodes[j].name ] = cssStyleNodes[j].value ; } // Load override definitions. var cssStyleOverrideNodes = styleNode.$Override ; if ( cssStyleOverrideNodes ) { for ( j = 0 ; j < cssStyleOverrideNodes.length ; j++ ) { var overrideNode = cssStyleOverrideNodes[j] ; var overrideDef = { Element : overrideNode.element } ; var overrideAttNode = overrideNode.$Attribute ; if ( overrideAttNode ) { overrideDef.Attributes = {} ; for ( var k = 0 ; k < overrideAttNode.length ; k++ ) { var overrideAttValue = overrideAttNode[k].value || null ; if ( overrideAttValue ) { // Check if the override attribute value is a regular expression. var regexMatch = overrideAttValue && FCKRegexLib.RegExp.exec( overrideAttValue ) ; if ( regexMatch ) overrideAttValue = new RegExp( regexMatch[1], regexMatch[2] || '' ) ; } overrideDef.Attributes[ overrideAttNode[k].name ] = overrideAttValue ; } } styleDef.Overrides.push( overrideDef ) ; } } var style = new FCKStyle( styleDef ) ; style.Name = styleNode.name || element ; if ( style.GetType() == FCK_STYLE_OBJECT ) this._ObjectStyles[ element ] = true ; // Add the style to the "Styles" collection using it's name as the key. styles[ style.Name ] = style ; } return styles ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 FCKXHtml object, responsible for the XHTML operations. * IE specific. */ FCKXHtml._GetMainXmlString = function() { return this.MainNode.xml ; } FCKXHtml._AppendAttributes = function( xmlNode, htmlNode, node, nodeName ) { var aAttributes = htmlNode.attributes, bHasStyle ; for ( var n = 0 ; n < aAttributes.length ; n++ ) { var oAttribute = aAttributes[n] ; if ( oAttribute.specified ) { var sAttName = oAttribute.nodeName.toLowerCase() ; var sAttValue ; // Ignore any attribute starting with "_fck". if ( sAttName.StartsWith( '_fck' ) ) continue ; // The following must be done because of a bug on IE regarding the style // attribute. It returns "null" for the nodeValue. else if ( sAttName == 'style' ) { // Just mark it to do it later in this function. bHasStyle = true ; continue ; } // There are two cases when the oAttribute.nodeValue must be used: // - for the "class" attribute // - for events attributes (on IE only). else if ( sAttName == 'class' ) { sAttValue = oAttribute.nodeValue.replace( FCKRegexLib.FCK_Class, '' ) ; if ( sAttValue.length == 0 ) continue ; } else if ( sAttName.indexOf('on') == 0 ) sAttValue = oAttribute.nodeValue ; else if ( nodeName == 'body' && sAttName == 'contenteditable' ) continue ; // XHTML doens't support attribute minimization like "CHECKED". It must be transformed to checked="checked". else if ( oAttribute.nodeValue === true ) sAttValue = sAttName ; else { // We must use getAttribute to get it exactly as it is defined. // There are some rare cases that IE throws an error here, so we must try/catch. try { sAttValue = htmlNode.getAttribute( sAttName, 2 ) ; } catch (e) {} } this._AppendAttribute( node, sAttName, sAttValue || oAttribute.nodeValue ) ; } } // IE loses the style attribute in JavaScript-created elements tags. (#2390) if ( bHasStyle || htmlNode.style.cssText.length > 0 ) { var data = FCKTools.ProtectFormStyles( htmlNode ) ; var sStyleValue = htmlNode.style.cssText.replace( FCKRegexLib.StyleProperties, FCKTools.ToLowerCase ) ; FCKTools.RestoreFormStyles( htmlNode, data ) ; this._AppendAttribute( node, 'style', sStyleValue ) ; } } /** * Used to clean up HTML that has been processed FCKXHtml._AppendNode(). * * For objects corresponding to HTML elements, Internet Explorer will * treat a property as if it were an attribute set on that element. * * http://msdn.microsoft.com/en-us/library/ms533026(VS.85).aspx#Accessing_Element_Pr * * FCKXHtml._AppendNode() sets the property _fckxhtmljob on node objects * corresponding HTML elements to mark them as having been processed. * Counting these properties as attributes will cripple style removal * because FCK.Styles.RemoveFromSelection() will not remove an element * as long as it still has attributes. * * refs #2156 and #2834 */ FCKXHtml._RemoveXHtmlJobProperties = function ( node ) { // Select only nodes of type ELEMENT_NODE if (!node || !node.nodeType || node.nodeType != 1) return ; // Clear the _fckhtmljob attribute. if ( typeof node._fckxhtmljob == 'undefined' && node.tagName !== 'BODY') return; node.removeAttribute('_fckxhtmljob') ; // Recurse upon child nodes. if ( node.hasChildNodes() ) { var childNodes = node.childNodes ; for ( var i = childNodes.length - 1 ; i >= 0 ; i-- ) { var child = childNodes[i]; // Funny IE. #4642. It say that it has child nodes but their parent is not this node. Skip them if (child.parentNode == node) FCKXHtml._RemoveXHtmlJobProperties( child ) ; } } } // On very rare cases, IE is loosing the "align" attribute for DIV. (right align and apply bulleted list) FCKXHtml.TagProcessors['div'] = function( node, htmlNode ) { if ( htmlNode.align.length > 0 ) FCKXHtml._AppendAttribute( node, 'align', htmlNode.align ) ; node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ; return node ; } // IE automatically changes <FONT> tags to <FONT size=+0>. FCKXHtml.TagProcessors['font'] = function( node, htmlNode ) { if ( node.attributes.length == 0 ) node = FCKXHtml.XML.createDocumentFragment() ; node = FCKXHtml._AppendChildNodes( node, htmlNode ) ; return node ; } FCKXHtml.TagProcessors['form'] = function( node, htmlNode ) { if ( htmlNode.acceptCharset && htmlNode.acceptCharset.length > 0 && htmlNode.acceptCharset != 'UNKNOWN' ) FCKXHtml._AppendAttribute( node, 'accept-charset', htmlNode.acceptCharset ) ; // IE has a bug and htmlNode.attributes['name'].specified=false if there is // no element with id="name" inside the form (#360 and SF-BUG-1155726). var nameAtt = htmlNode.attributes['name'] ; if ( nameAtt && nameAtt.value.length > 0 ) FCKXHtml._AppendAttribute( node, 'name', nameAtt.value ) ; node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ; return node ; } // IE doens't see the value attribute as an attribute for the <INPUT> tag. FCKXHtml.TagProcessors['input'] = function( node, htmlNode ) { if ( htmlNode.name ) FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ; if ( htmlNode.value && !node.attributes.getNamedItem( 'value' ) ) FCKXHtml._AppendAttribute( node, 'value', htmlNode.value ) ; if ( !node.attributes.getNamedItem( 'type' ) ) FCKXHtml._AppendAttribute( node, 'type', 'text' ) ; return node ; } FCKXHtml.TagProcessors['label'] = function( node, htmlNode ) { if ( htmlNode.htmlFor.length > 0 ) FCKXHtml._AppendAttribute( node, 'for', htmlNode.htmlFor ) ; node = FCKXHtml._AppendChildNodes( node, htmlNode ) ; return node ; } // Fix behavior for IE, it doesn't read back the .name on newly created maps FCKXHtml.TagProcessors['map'] = function( node, htmlNode ) { if ( ! node.attributes.getNamedItem( 'name' ) ) { var name = htmlNode.name ; if ( name ) FCKXHtml._AppendAttribute( node, 'name', name ) ; } node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ; return node ; } FCKXHtml.TagProcessors['meta'] = function( node, htmlNode ) { var oHttpEquiv = node.attributes.getNamedItem( 'http-equiv' ) ; if ( oHttpEquiv == null || oHttpEquiv.value.length == 0 ) { // Get the http-equiv value from the outerHTML. var sHttpEquiv = htmlNode.outerHTML.match( FCKRegexLib.MetaHttpEquiv ) ; if ( sHttpEquiv ) { sHttpEquiv = sHttpEquiv[1] ; FCKXHtml._AppendAttribute( node, 'http-equiv', sHttpEquiv ) ; } } return node ; } // IE ignores the "SELECTED" attribute so we must add it manually. FCKXHtml.TagProcessors['option'] = function( node, htmlNode ) { if ( htmlNode.selected && !node.attributes.getNamedItem( 'selected' ) ) FCKXHtml._AppendAttribute( node, 'selected', 'selected' ) ; node = FCKXHtml._AppendChildNodes( node, htmlNode ) ; return node ; } // IE doens't hold the name attribute as an attribute for the <TEXTAREA> and <SELECT> tags. FCKXHtml.TagProcessors['textarea'] = FCKXHtml.TagProcessors['select'] = function( node, htmlNode ) { if ( htmlNode.name ) FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ; node = FCKXHtml._AppendChildNodes( node, htmlNode ) ; return node ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Utility functions. (IE version). */ FCKTools.CancelEvent = function( e ) { return false ; } // Appends one or more CSS files to a document. FCKTools._AppendStyleSheet = function( documentElement, cssFileUrl ) { return documentElement.createStyleSheet( cssFileUrl ).owningElement ; } // Appends a CSS style string to a document. FCKTools.AppendStyleString = function( documentElement, cssStyles ) { if ( !cssStyles ) return null ; var s = documentElement.createStyleSheet( "" ) ; s.cssText = cssStyles ; return s ; } // Removes all attributes and values from the element. FCKTools.ClearElementAttributes = function( element ) { element.clearAttributes() ; } FCKTools.GetAllChildrenIds = function( parentElement ) { var aIds = new Array() ; for ( var i = 0 ; i < parentElement.all.length ; i++ ) { var sId = parentElement.all[i].id ; if ( sId && sId.length > 0 ) aIds[ aIds.length ] = sId ; } return aIds ; } FCKTools.RemoveOuterTags = function( e ) { e.insertAdjacentHTML( 'beforeBegin', e.innerHTML ) ; e.parentNode.removeChild( e ) ; } FCKTools.CreateXmlObject = function( object ) { var aObjs ; switch ( object ) { case 'XmlHttp' : // Try the native XMLHttpRequest introduced with IE7. if ( document.location.protocol != 'file:' ) try { return new XMLHttpRequest() ; } catch (e) {} aObjs = [ 'MSXML2.XmlHttp', 'Microsoft.XmlHttp' ] ; break ; case 'DOMDocument' : aObjs = [ 'MSXML2.DOMDocument', 'Microsoft.XmlDom' ] ; break ; } for ( var i = 0 ; i < 2 ; i++ ) { try { return new ActiveXObject( aObjs[i] ) ; } catch (e) {} } if ( FCKLang.NoActiveX ) { alert( FCKLang.NoActiveX ) ; FCKLang.NoActiveX = null ; } return null ; } FCKTools.DisableSelection = function( element ) { element.unselectable = 'on' ; var e, i = 0 ; // The extra () is to avoid a warning with strict error checking. This is ok. while ( (e = element.all[ i++ ]) ) { switch ( e.tagName ) { case 'IFRAME' : case 'TEXTAREA' : case 'INPUT' : case 'SELECT' : /* Ignore the above tags */ break ; default : e.unselectable = 'on' ; } } } FCKTools.GetScrollPosition = function( relativeWindow ) { var oDoc = relativeWindow.document ; // Try with the doc element. var oPos = { X : oDoc.documentElement.scrollLeft, Y : oDoc.documentElement.scrollTop } ; if ( oPos.X > 0 || oPos.Y > 0 ) return oPos ; // If no scroll, try with the body. return { X : oDoc.body.scrollLeft, Y : oDoc.body.scrollTop } ; } FCKTools.AddEventListener = function( sourceObject, eventName, listener ) { sourceObject.attachEvent( 'on' + eventName, listener ) ; } FCKTools.RemoveEventListener = function( sourceObject, eventName, listener ) { sourceObject.detachEvent( 'on' + eventName, listener ) ; } // Listeners attached with this function cannot be detached. FCKTools.AddEventListenerEx = function( sourceObject, eventName, listener, paramsArray ) { // Ok... this is a closures party, but is the only way to make it clean of memory leaks. var o = new Object() ; o.Source = sourceObject ; o.Params = paramsArray || [] ; // Memory leak if we have DOM objects here. o.Listener = function( ev ) { return listener.apply( o.Source, [ ev ].concat( o.Params ) ) ; } if ( FCK.IECleanup ) FCK.IECleanup.AddItem( null, function() { o.Source = null ; o.Params = null ; } ) ; sourceObject.attachEvent( 'on' + eventName, o.Listener ) ; sourceObject = null ; // Memory leak cleaner (because of the above closure). paramsArray = null ; // Memory leak cleaner (because of the above closure). } // Returns and object with the "Width" and "Height" properties. FCKTools.GetViewPaneSize = function( win ) { var oSizeSource ; var oDoc = win.document.documentElement ; if ( oDoc && oDoc.clientWidth ) // IE6 Strict Mode oSizeSource = oDoc ; else oSizeSource = win.document.body ; // Other IEs if ( oSizeSource ) return { Width : oSizeSource.clientWidth, Height : oSizeSource.clientHeight } ; else return { Width : 0, Height : 0 } ; } FCKTools.SaveStyles = function( element ) { var data = FCKTools.ProtectFormStyles( element ) ; var oSavedStyles = new Object() ; if ( element.className.length > 0 ) { oSavedStyles.Class = element.className ; element.className = '' ; } var sInlineStyle = element.style.cssText ; if ( sInlineStyle.length > 0 ) { oSavedStyles.Inline = sInlineStyle ; element.style.cssText = '' ; } FCKTools.RestoreFormStyles( element, data ) ; return oSavedStyles ; } FCKTools.RestoreStyles = function( element, savedStyles ) { var data = FCKTools.ProtectFormStyles( element ) ; element.className = savedStyles.Class || '' ; element.style.cssText = savedStyles.Inline || '' ; FCKTools.RestoreFormStyles( element, data ) ; } FCKTools.RegisterDollarFunction = function( targetWindow ) { targetWindow.$ = targetWindow.document.getElementById ; } FCKTools.AppendElement = function( target, elementName ) { return target.appendChild( this.GetElementDocument( target ).createElement( elementName ) ) ; } // This function may be used by Regex replacements. FCKTools.ToLowerCase = function( strValue ) { return strValue.toLowerCase() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 FCK.ContextMenu object that is responsible for all * Context Menu operations in the editing area. */ FCK.ContextMenu = new Object() ; FCK.ContextMenu.Listeners = new Array() ; FCK.ContextMenu.RegisterListener = function( listener ) { if ( listener ) this.Listeners.push( listener ) ; } function FCK_ContextMenu_Init() { var oInnerContextMenu = FCK.ContextMenu._InnerContextMenu = new FCKContextMenu( FCKBrowserInfo.IsIE ? window : window.parent, FCKLang.Dir ) ; oInnerContextMenu.CtrlDisable = FCKConfig.BrowserContextMenuOnCtrl ; oInnerContextMenu.OnBeforeOpen = FCK_ContextMenu_OnBeforeOpen ; oInnerContextMenu.OnItemClick = FCK_ContextMenu_OnItemClick ; // Get the registering function. var oMenu = FCK.ContextMenu ; // Register all configured context menu listeners. for ( var i = 0 ; i < FCKConfig.ContextMenu.length ; i++ ) oMenu.RegisterListener( FCK_ContextMenu_GetListener( FCKConfig.ContextMenu[i] ) ) ; } function FCK_ContextMenu_GetListener( listenerName ) { switch ( listenerName ) { case 'Generic' : return { AddItems : function( menu, tag, tagName ) { menu.AddItem( 'Cut' , FCKLang.Cut , 7, FCKCommands.GetCommand( 'Cut' ).GetState() == FCK_TRISTATE_DISABLED ) ; menu.AddItem( 'Copy' , FCKLang.Copy , 8, FCKCommands.GetCommand( 'Copy' ).GetState() == FCK_TRISTATE_DISABLED ) ; menu.AddItem( 'Paste' , FCKLang.Paste , 9, FCKCommands.GetCommand( 'Paste' ).GetState() == FCK_TRISTATE_DISABLED ) ; }} ; case 'Table' : return { AddItems : function( menu, tag, tagName ) { var bIsTable = ( tagName == 'TABLE' ) ; var bIsCell = ( !bIsTable && FCKSelection.HasAncestorNode( 'TABLE' ) ) ; if ( bIsCell ) { menu.AddSeparator() ; var oItem = menu.AddItem( 'Cell' , FCKLang.CellCM ) ; oItem.AddItem( 'TableInsertCellBefore' , FCKLang.InsertCellBefore, 69 ) ; oItem.AddItem( 'TableInsertCellAfter' , FCKLang.InsertCellAfter, 58 ) ; oItem.AddItem( 'TableDeleteCells' , FCKLang.DeleteCells, 59 ) ; if ( FCKBrowserInfo.IsGecko ) oItem.AddItem( 'TableMergeCells' , FCKLang.MergeCells, 60, FCKCommands.GetCommand( 'TableMergeCells' ).GetState() == FCK_TRISTATE_DISABLED ) ; else { oItem.AddItem( 'TableMergeRight' , FCKLang.MergeRight, 60, FCKCommands.GetCommand( 'TableMergeRight' ).GetState() == FCK_TRISTATE_DISABLED ) ; oItem.AddItem( 'TableMergeDown' , FCKLang.MergeDown, 60, FCKCommands.GetCommand( 'TableMergeDown' ).GetState() == FCK_TRISTATE_DISABLED ) ; } oItem.AddItem( 'TableHorizontalSplitCell' , FCKLang.HorizontalSplitCell, 61, FCKCommands.GetCommand( 'TableHorizontalSplitCell' ).GetState() == FCK_TRISTATE_DISABLED ) ; oItem.AddItem( 'TableVerticalSplitCell' , FCKLang.VerticalSplitCell, 61, FCKCommands.GetCommand( 'TableVerticalSplitCell' ).GetState() == FCK_TRISTATE_DISABLED ) ; oItem.AddSeparator() ; oItem.AddItem( 'TableCellProp' , FCKLang.CellProperties, 57, FCKCommands.GetCommand( 'TableCellProp' ).GetState() == FCK_TRISTATE_DISABLED ) ; menu.AddSeparator() ; oItem = menu.AddItem( 'Row' , FCKLang.RowCM ) ; oItem.AddItem( 'TableInsertRowBefore' , FCKLang.InsertRowBefore, 70 ) ; oItem.AddItem( 'TableInsertRowAfter' , FCKLang.InsertRowAfter, 62 ) ; oItem.AddItem( 'TableDeleteRows' , FCKLang.DeleteRows, 63 ) ; menu.AddSeparator() ; oItem = menu.AddItem( 'Column' , FCKLang.ColumnCM ) ; oItem.AddItem( 'TableInsertColumnBefore', FCKLang.InsertColumnBefore, 71 ) ; oItem.AddItem( 'TableInsertColumnAfter' , FCKLang.InsertColumnAfter, 64 ) ; oItem.AddItem( 'TableDeleteColumns' , FCKLang.DeleteColumns, 65 ) ; } if ( bIsTable || bIsCell ) { menu.AddSeparator() ; menu.AddItem( 'TableDelete' , FCKLang.TableDelete ) ; menu.AddItem( 'TableProp' , FCKLang.TableProperties, 39 ) ; } }} ; case 'Link' : return { AddItems : function( menu, tag, tagName ) { var bInsideLink = ( tagName == 'A' || FCKSelection.HasAncestorNode( 'A' ) ) ; if ( bInsideLink || FCK.GetNamedCommandState( 'Unlink' ) != FCK_TRISTATE_DISABLED ) { // Go up to the anchor to test its properties var oLink = FCKSelection.MoveToAncestorNode( 'A' ) ; var bIsAnchor = ( oLink && oLink.name.length > 0 && oLink.href.length == 0 ) ; // If it isn't a link then don't add the Link context menu if ( bIsAnchor ) return ; menu.AddSeparator() ; menu.AddItem( 'VisitLink', FCKLang.VisitLink ) ; menu.AddSeparator() ; if ( bInsideLink ) menu.AddItem( 'Link', FCKLang.EditLink , 34 ) ; menu.AddItem( 'Unlink' , FCKLang.RemoveLink , 35 ) ; } }} ; case 'Image' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'IMG' && !tag.getAttribute( '_fckfakelement' ) ) { menu.AddSeparator() ; menu.AddItem( 'Image', FCKLang.ImageProperties, 37 ) ; } }} ; case 'Anchor' : return { AddItems : function( menu, tag, tagName ) { // Go up to the anchor to test its properties var oLink = FCKSelection.MoveToAncestorNode( 'A' ) ; var bIsAnchor = ( oLink && oLink.name.length > 0 ) ; if ( bIsAnchor || ( tagName == 'IMG' && tag.getAttribute( '_fckanchor' ) ) ) { menu.AddSeparator() ; menu.AddItem( 'Anchor', FCKLang.AnchorProp, 36 ) ; menu.AddItem( 'AnchorDelete', FCKLang.AnchorDelete ) ; } }} ; case 'Flash' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'IMG' && tag.getAttribute( '_fckflash' ) ) { menu.AddSeparator() ; menu.AddItem( 'Flash', FCKLang.FlashProperties, 38 ) ; } }} ; case 'Form' : return { AddItems : function( menu, tag, tagName ) { if ( FCKSelection.HasAncestorNode('FORM') ) { menu.AddSeparator() ; menu.AddItem( 'Form', FCKLang.FormProp, 48 ) ; } }} ; case 'Checkbox' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'INPUT' && tag.type == 'checkbox' ) { menu.AddSeparator() ; menu.AddItem( 'Checkbox', FCKLang.CheckboxProp, 49 ) ; } }} ; case 'Radio' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'INPUT' && tag.type == 'radio' ) { menu.AddSeparator() ; menu.AddItem( 'Radio', FCKLang.RadioButtonProp, 50 ) ; } }} ; case 'TextField' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'INPUT' && ( tag.type == 'text' || tag.type == 'password' ) ) { menu.AddSeparator() ; menu.AddItem( 'TextField', FCKLang.TextFieldProp, 51 ) ; } }} ; case 'HiddenField' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'IMG' && tag.getAttribute( '_fckinputhidden' ) ) { menu.AddSeparator() ; menu.AddItem( 'HiddenField', FCKLang.HiddenFieldProp, 56 ) ; } }} ; case 'ImageButton' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'INPUT' && tag.type == 'image' ) { menu.AddSeparator() ; menu.AddItem( 'ImageButton', FCKLang.ImageButtonProp, 55 ) ; } }} ; case 'Button' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'INPUT' && ( tag.type == 'button' || tag.type == 'submit' || tag.type == 'reset' ) ) { menu.AddSeparator() ; menu.AddItem( 'Button', FCKLang.ButtonProp, 54 ) ; } }} ; case 'Select' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'SELECT' ) { menu.AddSeparator() ; menu.AddItem( 'Select', FCKLang.SelectionFieldProp, 53 ) ; } }} ; case 'Textarea' : return { AddItems : function( menu, tag, tagName ) { if ( tagName == 'TEXTAREA' ) { menu.AddSeparator() ; menu.AddItem( 'Textarea', FCKLang.TextareaProp, 52 ) ; } }} ; case 'BulletedList' : return { AddItems : function( menu, tag, tagName ) { if ( FCKSelection.HasAncestorNode('UL') ) { menu.AddSeparator() ; menu.AddItem( 'BulletedList', FCKLang.BulletedListProp, 27 ) ; } }} ; case 'NumberedList' : return { AddItems : function( menu, tag, tagName ) { if ( FCKSelection.HasAncestorNode('OL') ) { menu.AddSeparator() ; menu.AddItem( 'NumberedList', FCKLang.NumberedListProp, 26 ) ; } }} ; case 'DivContainer': return { AddItems : function( menu, tag, tagName ) { var currentBlocks = FCKDomTools.GetSelectedDivContainers() ; if ( currentBlocks.length > 0 ) { menu.AddSeparator() ; menu.AddItem( 'EditDiv', FCKLang.EditDiv, 75 ) ; menu.AddItem( 'DeleteDiv', FCKLang.DeleteDiv, 76 ) ; } }} ; } return null ; } function FCK_ContextMenu_OnBeforeOpen() { // Update the UI. FCK.Events.FireEvent( 'OnSelectionChange' ) ; // Get the actual selected tag (if any). var oTag, sTagName ; // The extra () is to avoid a warning with strict error checking. This is ok. if ( (oTag = FCKSelection.GetSelectedElement()) ) sTagName = oTag.tagName ; // Cleanup the current menu items. var oMenu = FCK.ContextMenu._InnerContextMenu ; oMenu.RemoveAllItems() ; // Loop through the listeners. var aListeners = FCK.ContextMenu.Listeners ; for ( var i = 0 ; i < aListeners.length ; i++ ) aListeners[i].AddItems( oMenu, oTag, sTagName ) ; } function FCK_ContextMenu_OnItemClick( item ) { // IE might work incorrectly if we refocus the editor #798 if ( !FCKBrowserInfo.IsIE ) FCK.Focus() ; FCKCommands.GetCommand( item.Name ).Execute( item.CustomData ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == */ var FCKScayt; (function() { var scaytOnLoad = [] ; var isEngineLoaded = ( FCK && FCK.EditorWindow && FCK.EditorWindow.parent.parent.scayt) ? true : false ; var scaytEnable = false; var scaytReady = false; function ScaytEngineLoad( callback ) { if ( isEngineLoaded ) return ; isEngineLoaded = true ; var top = FCK.EditorWindow.parent.parent; var init = function () { window.scayt = top.scayt ; InitScayt() ; var ScaytCombobox = FCKToolbarItems.LoadedItems[ 'ScaytCombobox' ] ; ScaytCombobox && ScaytCombobox.SetEnabled( scyt_control && scyt_control.disabled ) ; InitSetup() ; }; if ( top.scayt ) { init() ; return ; } // Compose the scayt url. if (FCK.Config.ScaytCustomUrl) FCK.Config.ScaytCustomUrl = new String(FCK.Config.ScaytCustomUrl).replace( new RegExp( "^http[s]*:\/\/"),"") ; var protocol = document.location.protocol ; var baseUrl = FCK.Config.ScaytCustomUrl ||'svc.spellchecker.net/spellcheck3/lf/scayt/scayt4.js' ; var scaytUrl = protocol + '//' + baseUrl ; var scaytConfigBaseUrl = ParseUrl( scaytUrl ).path + '/' ; // SCAYT is targetted to CKEditor, so we need this trick to make it work here. var CKEDITOR = top.window.CKEDITOR || ( top.window.CKEDITOR = {} ) ; CKEDITOR._djScaytConfig = { baseUrl : scaytConfigBaseUrl, addOnLoad : function() { init(); }, isDebug : false }; if ( callback ) scaytOnLoad.push( callback ) ; DoLoadScript( scaytUrl ) ; } /** * DoLoadScript - load scripts with dinamic tag script creating * @param string url */ function DoLoadScript( url ) { if (!url) return false ; var top = FCK.EditorWindow.parent.parent; var s = top.document.createElement('script') ; s.type = 'text/javascript' ; s.src = url ; top.document.getElementsByTagName('head')[0].appendChild(s) ; return true ; } function ParseUrl( data ) { var m = data.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/) ; return m ? { path: m[1], file: m[2] } : data ; } function createScaytControl () { // Get public scayt params. var oParams = {} ; var top = FCK.EditorWindow.parent.parent; oParams.srcNodeRef = FCK.EditingArea.IFrame; // Get the iframe. // syntax : AppName.AppVersion@AppRevision //oParams.assocApp = "FCKEDITOR." + FCKeditorAPI.Varsion + "@" + FCKeditorAPI.VersionBuild; oParams.customerid = FCK.Config.ScaytCustomerid ; oParams.customDictionaryName = FCK.Config.ScaytCustomDictionaryName ; oParams.userDictionaryName = FCK.Config.ScaytUserDictionaryName ; oParams.defLang = FCK.Config.ScaytDefLang ; var scayt = top.scayt; var scayt_control = window.scayt_control = new scayt( oParams ) ; } function InitScayt() { createScaytControl(); var scayt_control = window.scayt_control ; if ( scayt_control ) { scayt_control.setDisabled( false ) ; scaytReady = true; scaytEnable = !scayt_control.disabled ; // set default scayt status var ScaytCombobox = FCKToolbarItems.LoadedItems[ 'ScaytCombobox' ] ; ScaytCombobox && ScaytCombobox.Enable() ; ShowScaytState() ; } for ( var i = 0 ; i < scaytOnLoad.length ; i++ ) { try { scaytOnLoad[i].call( this ) ; } catch(err) {} } } // ### // SCAYT command class. var ScaytCommand = function() { name = 'Scayt' ; } ScaytCommand.prototype.Execute = function( action ) { switch ( action ) { case 'Options' : case 'Langs' : case 'About' : if ( isEngineLoaded && scaytReady && !scaytEnable ) { ScaytMessage( 'SCAYT is not enabled' ); break; } if ( isEngineLoaded && scaytReady ) FCKDialog.OpenDialog( 'Scayt', 'SCAYT Settings', 'dialog/fck_scayt.html?' + action.toLowerCase(), 343, 343 ); break; default : if ( !isEngineLoaded ) { var me = this; ScaytEngineLoad( function () { me.SetEnabled( !window.scayt_control.disabled ) ; }) ; return true; } else if ( scaytReady ) { // Switch the current scayt state. if ( scaytEnable ) this.Disable() ; else this.Enable() ; ShowScaytState() ; } } if ( !isEngineLoaded ) return ScaytMessage( 'SCAYT is not loaded' ) || false; if ( !scaytReady ) return ScaytMessage( 'SCAYT is not ready' ) || false; return true; } ScaytCommand.prototype.Enable = function() { window.scayt_control.setDisabled( false ) ; scaytEnable = true; } ScaytCommand.prototype.Disable = function() { window.scayt_control.setDisabled( true ) ; scaytEnable = false; } ScaytCommand.prototype.SetEnabled = function( state ) { if ( state ) this.Enable() ; else this.Disable() ; ShowScaytState() ; return true; } ScaytCommand.prototype.GetState = function() { return FCK_TRISTATE_OFF; } function ShowScaytState() { var combo = FCKToolbarItems.GetItem( 'SpellCheck' ) ; if ( !combo || !combo._Combo || !combo._Combo._OuterTable ) return; var bItem = combo._Combo._OuterTable.getElementsByTagName( 'img' )[1] ; var dNode = combo._Combo.Items['trigger'] ; if ( scaytEnable ) { bItem.style.opacity = '1' ; dNode.innerHTML = GetStatusLabel() ; } else { bItem.style.opacity = '0.5' ; dNode.innerHTML = GetStatusLabel() ; } } function GetStatusLabel() { if ( !scaytReady ) return '<b>Enable SCAYT</b>' ; return scaytEnable ? '<b>Disable SCAYT</b>' : '<b>Enable SCAYT</b>' ; } // ### // Class for the toolbar item. var ToolbarScaytComboBox = function( tooltip, style ) { this.Command = FCKCommands.GetCommand( 'Scayt' ) ; this.CommandName = 'Scayt' ; this.Label = this.GetLabel() ; this.Tooltip = FCKLang.ScaytTitle ; this.Style = FCK_TOOLBARITEM_ONLYTEXT ; //FCK_TOOLBARITEM_ICONTEXT OR FCK_TOOLBARITEM_ONLYTEXT } ToolbarScaytComboBox.prototype = new FCKToolbarSpecialCombo ; //Add the items to the combo list ToolbarScaytComboBox.prototype.CreateItems = function() { this._Combo.AddItem( 'Trigger', '<b>Enable SCAYT</b>' ); this._Combo.AddItem( 'Options', FCKLang.ScaytTitleOptions || "Options" ); this._Combo.AddItem( 'Langs', FCKLang.ScaytTitleLangs || "Languages"); this._Combo.AddItem( 'About', FCKLang.ScaytTitleAbout || "About"); } // Label shown in the toolbar. ToolbarScaytComboBox.prototype.GetLabel = function() { var strip = FCKConfig.SkinPath + 'fck_strip.gif'; return FCKBrowserInfo.IsIE ? '<div class="TB_Button_Image"><img src="' + strip + '" style="top:-192px"></div>' : '<img class="TB_Button_Image" src="' + FCK_SPACER_PATH + '" style="background-position: 0px -192px;background-image: url(' + strip + ');">'; } function ScaytMessage( m ) { m && alert( m ) ; } var ScaytContextCommand = function() { name = 'ScaytContext' ; } ScaytContextCommand.prototype.Execute = function( contextInfo ) { var action = contextInfo && contextInfo.action, node = action && contextInfo.node, scayt_control = window.scayt_control; if ( node ) { switch ( action ) { case 'Suggestion' : scayt_control.replace( node, contextInfo.suggestion ) ; break ; case 'Ignore' : scayt_control.ignore( node ) ; break ; case 'Ignore All' : scayt_control.ignoreAll( node ) ; break ; case 'Add Word' : var top = FCK.EditorWindow.parent.parent ; top.scayt.addWordToUserDictionary( node ) ; break ; } } } // Register context menu listeners. function InitSetup() { FCK.ContextMenu.RegisterListener( { AddItems : function( menu ) { var top = FCK.EditorWindow.parent.parent; var scayt_control = window.scayt_control, scayt = top.scayt; if ( !scayt_control ) return; var node = scayt_control.getScaytNode() ; if ( !node ) return; var suggestions = scayt.getSuggestion( scayt_control.getWord( node ), scayt_control.getLang() ) ; if ( !suggestions || !suggestions.length ) return; menu.AddSeparator() ; var maxSuggestions = FCK.Config.ScaytMaxSuggestions || 5 ; var suggAveCount = ( maxSuggestions == -1 ) ? suggestions.length : maxSuggestions ; for ( var i = 0 ; i < suggAveCount ; i += 1 ) { if ( suggestions[i] ) { menu.AddItem( 'ScaytContext', suggestions[i], null, false, { 'action' : 'Suggestion', 'node' : node, 'suggestion' : suggestions[i] } ) ; } } menu.AddSeparator() ; menu.AddItem( 'ScaytContext', 'Ignore', null, false, { 'action' : 'Ignore', 'node' : node } ); menu.AddItem( 'ScaytContext', 'Ignore All', null, false, { 'action' : 'Ignore All', 'node' : node } ); menu.AddItem( 'ScaytContext', 'Add Word', null, false, { 'action' : 'Add Word', 'node' : node } ); try { if (scaytReady && scaytEnable) scayt_control.fireOnContextMenu( null, FCK.ContextMenu._InnerContextMenu); } catch( err ) {} } }) ; FCK.Events.AttachEvent( 'OnPaste', function() { window.scayt_control.refresh() ; return true; } ) ; } // ## // Register event listeners. FCK.Events.AttachEvent( 'OnAfterSetHTML', function() { if ( FCKConfig.SpellChecker == 'SCAYT' ) { if ( !isEngineLoaded && FCK.Config.ScaytAutoStartup ) ScaytEngineLoad() ; if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG && isEngineLoaded && scaytReady ) createScaytControl(); ShowScaytState() ; } } ) ; FCK.Events.AttachEvent( 'OnBeforeGetData', function() { scaytReady && window.scayt_control.reset(); } ) ; FCK.Events.AttachEvent( 'OnAfterGetData', function() { scaytReady && window.scayt_control.refresh(); } ) ; // ### // The main object that holds the SCAYT interaction in the code. FCKScayt = { CreateCommand : function() { return new ScaytCommand(); }, CreateContextCommand : function() { return new ScaytContextCommand(); }, CreateToolbarItem : function() { return new ToolbarScaytComboBox() ; } } ; })() ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Active selection functions. */ var FCKSelection = FCK.Selection = { GetParentBlock : function() { var retval = this.GetParentElement() ; while ( retval ) { if ( FCKListsLib.BlockBoundaries[retval.nodeName.toLowerCase()] ) break ; retval = retval.parentNode ; } return retval ; }, ApplyStyle : function( styleDefinition ) { FCKStyles.ApplyStyle( new FCKStyle( styleDefinition ) ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 some constants used by the editor. These constants are also * globally available in the page where the editor is placed. */ // Editor Instance Status. var FCK_STATUS_NOTLOADED = window.parent.FCK_STATUS_NOTLOADED = 0 ; var FCK_STATUS_ACTIVE = window.parent.FCK_STATUS_ACTIVE = 1 ; var FCK_STATUS_COMPLETE = window.parent.FCK_STATUS_COMPLETE = 2 ; // Tristate Operations. var FCK_TRISTATE_OFF = window.parent.FCK_TRISTATE_OFF = 0 ; var FCK_TRISTATE_ON = window.parent.FCK_TRISTATE_ON = 1 ; var FCK_TRISTATE_DISABLED = window.parent.FCK_TRISTATE_DISABLED = -1 ; // For unknown values. var FCK_UNKNOWN = window.parent.FCK_UNKNOWN = -9 ; // Toolbar Items Style. var FCK_TOOLBARITEM_ONLYICON = window.parent.FCK_TOOLBARITEM_ONLYICON = 0 ; var FCK_TOOLBARITEM_ONLYTEXT = window.parent.FCK_TOOLBARITEM_ONLYTEXT = 1 ; var FCK_TOOLBARITEM_ICONTEXT = window.parent.FCK_TOOLBARITEM_ICONTEXT = 2 ; // Edit Mode var FCK_EDITMODE_WYSIWYG = window.parent.FCK_EDITMODE_WYSIWYG = 0 ; var FCK_EDITMODE_SOURCE = window.parent.FCK_EDITMODE_SOURCE = 1 ; var FCK_IMAGES_PATH = 'images/' ; // Check usage. var FCK_SPACER_PATH = 'images/spacer.gif' ; var CTRL = 1000 ; var SHIFT = 2000 ; var ALT = 4000 ; var FCK_STYLE_BLOCK = 0 ; var FCK_STYLE_INLINE = 1 ; var FCK_STYLE_OBJECT = 2 ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKStyleCommand Class: represents the "Spell Check" command. * (Gecko specific implementation) */ var FCKSpellCheckCommand = function() { this.Name = 'SpellCheck' ; this.IsEnabled = ( FCKConfig.SpellChecker != 'ieSpell' ) ; } FCKSpellCheckCommand.prototype.Execute = function() { switch ( FCKConfig.SpellChecker ) { case 'SpellerPages' : FCKDialog.OpenDialog( 'FCKDialog_SpellCheck', 'Spell Check', 'dialog/fck_spellerpages.html', 440, 480 ) ; break; case 'WSC' : FCKDialog.OpenDialog( 'FCKDialog_SpellCheck', 'Spell Check', 'wsc/w.html', 530, 480 ) ; } } FCKSpellCheckCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return this.IsEnabled ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKPasteWordCommand Class: represents the "Paste from Word" command. */ var FCKPasteWordCommand = function() { this.Name = 'PasteWord' ; } FCKPasteWordCommand.prototype.Execute = function() { FCK.PasteFromWord() ; } FCKPasteWordCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || FCKConfig.ForcePasteAsPlainText ) return FCK_TRISTATE_DISABLED ; else return FCK.GetNamedCommandState( 'Paste' ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKJustifyCommand Class: controls block justification. */ var FCKJustifyCommand = function( alignValue ) { this.AlignValue = alignValue ; // Detect whether this is the instance for the default alignment. var contentDir = FCKConfig.ContentLangDirection.toLowerCase() ; this.IsDefaultAlign = ( alignValue == 'left' && contentDir == 'ltr' ) || ( alignValue == 'right' && contentDir == 'rtl' ) ; // Get the class name to be used by this instance. var cssClassName = this._CssClassName = ( function() { var classes = FCKConfig.JustifyClasses ; if ( classes ) { switch ( alignValue ) { case 'left' : return classes[0] || null ; case 'center' : return classes[1] || null ; case 'right' : return classes[2] || null ; case 'justify' : return classes[3] || null ; } } return null ; } )() ; if ( cssClassName && cssClassName.length > 0 ) this._CssClassRegex = new RegExp( '(?:^|\\s+)' + cssClassName + '(?=$|\\s)' ) ; } FCKJustifyCommand._GetClassNameRegex = function() { var regex = FCKJustifyCommand._ClassRegex ; if ( regex != undefined ) return regex ; var names = [] ; var classes = FCKConfig.JustifyClasses ; if ( classes ) { for ( var i = 0 ; i < 4 ; i++ ) { var className = classes[i] ; if ( className && className.length > 0 ) names.push( className ) ; } } if ( names.length > 0 ) regex = new RegExp( '(?:^|\\s+)(?:' + names.join( '|' ) + ')(?=$|\\s)' ) ; else regex = null ; return FCKJustifyCommand._ClassRegex = regex ; } FCKJustifyCommand.prototype = { Execute : function() { // Save an undo snapshot before doing anything. FCKUndo.SaveUndoStep() ; var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; var currentState = this.GetState() ; if ( currentState == FCK_TRISTATE_DISABLED ) return ; // Store a bookmark of the selection since the paragraph iterator might // change the DOM tree and break selections. var bookmark = range.CreateBookmark() ; var cssClassName = this._CssClassName ; // Apply alignment setting for each paragraph. var iterator = new FCKDomRangeIterator( range ) ; var block ; while ( ( block = iterator.GetNextParagraph() ) ) { block.removeAttribute( 'align' ) ; if ( cssClassName ) { // Remove the any of the alignment classes from the className. var className = block.className.replace( FCKJustifyCommand._GetClassNameRegex(), '' ) ; // Append the desired class name. if ( currentState == FCK_TRISTATE_OFF ) { if ( className.length > 0 ) className += ' ' ; block.className = className + cssClassName ; } else if ( className.length == 0 ) FCKDomTools.RemoveAttribute( block, 'class' ) ; } else { var style = block.style ; if ( currentState == FCK_TRISTATE_OFF ) style.textAlign = this.AlignValue ; else { style.textAlign = '' ; if ( style.cssText.length == 0 ) block.removeAttribute( 'style' ) ; } } } // Restore previous selection. range.MoveToBookmark( bookmark ) ; range.Select() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { // Disabled if not WYSIWYG. if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow ) return FCK_TRISTATE_DISABLED ; // Retrieve the first selected block. var path = new FCKElementPath( FCKSelection.GetBoundaryParentElement( true ) ) ; var firstBlock = path.Block || path.BlockLimit ; if ( !firstBlock || firstBlock.nodeName.toLowerCase() == 'body' ) return FCK_TRISTATE_OFF ; // Check if the desired style is already applied to the block. var currentAlign ; if ( FCKBrowserInfo.IsIE ) currentAlign = firstBlock.currentStyle.textAlign ; else currentAlign = FCK.EditorWindow.getComputedStyle( firstBlock, '' ).getPropertyValue( 'text-align' ); currentAlign = currentAlign.replace( /(-moz-|-webkit-|start|auto)/i, '' ); if ( ( !currentAlign && this.IsDefaultAlign ) || currentAlign == this.AlignValue ) return FCK_TRISTATE_ON ; return FCK_TRISTATE_OFF ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKIndentCommand Class: controls block indentation. */ var FCKIndentCommand = function( name, offset ) { this.Name = name ; this.Offset = offset ; this.IndentCSSProperty = FCKConfig.ContentLangDirection.IEquals( 'ltr' ) ? 'marginLeft' : 'marginRight' ; } FCKIndentCommand._InitIndentModeParameters = function() { if ( FCKConfig.IndentClasses && FCKConfig.IndentClasses.length > 0 ) { this._UseIndentClasses = true ; this._IndentClassMap = {} ; for ( var i = 0 ; i < FCKConfig.IndentClasses.length ;i++ ) this._IndentClassMap[FCKConfig.IndentClasses[i]] = i + 1 ; this._ClassNameRegex = new RegExp( '(?:^|\\s+)(' + FCKConfig.IndentClasses.join( '|' ) + ')(?=$|\\s)' ) ; } else this._UseIndentClasses = false ; } FCKIndentCommand.prototype = { Execute : function() { // Save an undo snapshot before doing anything. FCKUndo.SaveUndoStep() ; var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; var bookmark = range.CreateBookmark() ; // Two cases to handle here: either we're in a list, or not. // If we're in a list, then the indent/outdent operations would be done on the list nodes. // Otherwise, apply the operation on the nearest block nodes. var nearestListBlock = FCKDomTools.GetCommonParentNode( range.StartNode || range.StartContainer , range.EndNode || range.EndContainer, ['ul', 'ol'] ) ; if ( nearestListBlock ) this._IndentList( range, nearestListBlock ) ; else this._IndentBlock( range ) ; range.MoveToBookmark( bookmark ) ; range.Select() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { // Disabled if not WYSIWYG. if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow ) return FCK_TRISTATE_DISABLED ; // Initialize parameters if not already initialzed. if ( FCKIndentCommand._UseIndentClasses == undefined ) FCKIndentCommand._InitIndentModeParameters() ; // If we're not in a list, and the starting block's indentation is zero, and the current // command is the outdent command, then we should return FCK_TRISTATE_DISABLED. var startContainer = FCKSelection.GetBoundaryParentElement( true ) ; var endContainer = FCKSelection.GetBoundaryParentElement( false ) ; var listNode = FCKDomTools.GetCommonParentNode( startContainer, endContainer, ['ul','ol'] ) ; if ( listNode ) { if ( this.Name.IEquals( 'outdent' ) ) return FCK_TRISTATE_OFF ; var firstItem = FCKTools.GetElementAscensor( startContainer, 'li' ) ; if ( !firstItem || !firstItem.previousSibling ) return FCK_TRISTATE_DISABLED ; return FCK_TRISTATE_OFF ; } if ( ! FCKIndentCommand._UseIndentClasses && this.Name.IEquals( 'indent' ) ) return FCK_TRISTATE_OFF; var path = new FCKElementPath( startContainer ) ; var firstBlock = path.Block || path.BlockLimit ; if ( !firstBlock ) return FCK_TRISTATE_DISABLED ; if ( FCKIndentCommand._UseIndentClasses ) { var indentClass = firstBlock.className.match( FCKIndentCommand._ClassNameRegex ) ; var indentStep = 0 ; if ( indentClass != null ) { indentClass = indentClass[1] ; indentStep = FCKIndentCommand._IndentClassMap[indentClass] ; } if ( ( this.Name == 'outdent' && indentStep == 0 ) || ( this.Name == 'indent' && indentStep == FCKConfig.IndentClasses.length ) ) return FCK_TRISTATE_DISABLED ; return FCK_TRISTATE_OFF ; } else { var indent = parseInt( firstBlock.style[this.IndentCSSProperty], 10 ) ; if ( isNaN( indent ) ) indent = 0 ; if ( indent <= 0 ) return FCK_TRISTATE_DISABLED ; return FCK_TRISTATE_OFF ; } }, _IndentBlock : function( range ) { var iterator = new FCKDomRangeIterator( range ) ; iterator.EnforceRealBlocks = true ; range.Expand( 'block_contents' ) ; var commonParents = FCKDomTools.GetCommonParents( range.StartContainer, range.EndContainer ) ; var nearestParent = commonParents[commonParents.length - 1] ; var block ; while ( ( block = iterator.GetNextParagraph() ) ) { // We don't want to indent subtrees recursively, so only perform the indent operation // if the block itself is the nearestParent, or the block's parent is the nearestParent. if ( ! ( block == nearestParent || block.parentNode == nearestParent ) ) continue ; if ( FCKIndentCommand._UseIndentClasses ) { // Transform current class name to indent step index. var indentClass = block.className.match( FCKIndentCommand._ClassNameRegex ) ; var indentStep = 0 ; if ( indentClass != null ) { indentClass = indentClass[1] ; indentStep = FCKIndentCommand._IndentClassMap[indentClass] ; } // Operate on indent step index, transform indent step index back to class name. if ( this.Name.IEquals( 'outdent' ) ) indentStep-- ; else if ( this.Name.IEquals( 'indent' ) ) indentStep++ ; indentStep = Math.min( indentStep, FCKConfig.IndentClasses.length ) ; indentStep = Math.max( indentStep, 0 ) ; var className = block.className.replace( FCKIndentCommand._ClassNameRegex, '' ) ; if ( indentStep < 1 ) block.className = className ; else block.className = ( className.length > 0 ? className + ' ' : '' ) + FCKConfig.IndentClasses[indentStep - 1] ; } else { // Offset distance is assumed to be in pixels for now. var currentOffset = parseInt( block.style[this.IndentCSSProperty], 10 ) ; if ( isNaN( currentOffset ) ) currentOffset = 0 ; currentOffset += this.Offset ; currentOffset = Math.max( currentOffset, 0 ) ; currentOffset = Math.ceil( currentOffset / this.Offset ) * this.Offset ; block.style[this.IndentCSSProperty] = currentOffset ? currentOffset + FCKConfig.IndentUnit : '' ; if ( block.getAttribute( 'style' ) == '' ) block.removeAttribute( 'style' ) ; } } }, _IndentList : function( range, listNode ) { // Our starting and ending points of the range might be inside some blocks under a list item... // So before playing with the iterator, we need to expand the block to include the list items. var startContainer = range.StartContainer ; var endContainer = range.EndContainer ; while ( startContainer && startContainer.parentNode != listNode ) startContainer = startContainer.parentNode ; while ( endContainer && endContainer.parentNode != listNode ) endContainer = endContainer.parentNode ; if ( ! startContainer || ! endContainer ) return ; // Now we can iterate over the individual items on the same tree depth. var block = startContainer ; var itemsToMove = [] ; var stopFlag = false ; while ( stopFlag == false ) { if ( block == endContainer ) stopFlag = true ; itemsToMove.push( block ) ; block = block.nextSibling ; } if ( itemsToMove.length < 1 ) return ; // Do indent or outdent operations on the array model of the list, not the list's DOM tree itself. // The array model demands that it knows as much as possible about the surrounding lists, we need // to feed it the further ancestor node that is still a list. var listParents = FCKDomTools.GetParents( listNode ) ; for ( var i = 0 ; i < listParents.length ; i++ ) { if ( listParents[i].nodeName.IEquals( ['ul', 'ol'] ) ) { listNode = listParents[i] ; break ; } } var indentOffset = this.Name.IEquals( 'indent' ) ? 1 : -1 ; var startItem = itemsToMove[0] ; var lastItem = itemsToMove[ itemsToMove.length - 1 ] ; var markerObj = {} ; // Convert the list DOM tree into a one dimensional array. var listArray = FCKDomTools.ListToArray( listNode, markerObj ) ; // Apply indenting or outdenting on the array. var baseIndent = listArray[lastItem._FCK_ListArray_Index].indent ; for ( var i = startItem._FCK_ListArray_Index ; i <= lastItem._FCK_ListArray_Index ; i++ ) listArray[i].indent += indentOffset ; for ( var i = lastItem._FCK_ListArray_Index + 1 ; i < listArray.length && listArray[i].indent > baseIndent ; i++ ) listArray[i].indent += indentOffset ; /* For debug use only var PrintArray = function( listArray, doc ) { var s = [] ; for ( var i = 0 ; i < listArray.length ; i++ ) { for ( var j in listArray[i] ) { if ( j != 'contents' ) s.push( j + ":" + listArray[i][j] + "; " ) ; else { var docFrag = doc.createDocumentFragment() ; var tmpNode = doc.createElement( 'span' ) ; for ( var k = 0 ; k < listArray[i][j].length ; k++ ) docFrag.appendChild( listArray[i][j][k].cloneNode( true ) ) ; tmpNode.appendChild( docFrag ) ; s.push( j + ":" + tmpNode.innerHTML + "; ") ; } } s.push( '\n' ) ; } alert( s.join('') ) ; } PrintArray( listArray, FCK.EditorDocument ) ; */ // Convert the array back to a DOM forest (yes we might have a few subtrees now). // And replace the old list with the new forest. var newList = FCKDomTools.ArrayToList( listArray ) ; if ( newList ) listNode.parentNode.replaceChild( newList.listNode, listNode ) ; // Clean up the markers. FCKDomTools.ClearAllMarkers( markerObj ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKStyleCommand Class: represents the "Spell Check" command. * (IE specific implementation) */ var FCKSpellCheckCommand = function() { this.Name = 'SpellCheck' ; this.IsEnabled = true ; } FCKSpellCheckCommand.prototype.Execute = function() { switch ( FCKConfig.SpellChecker ) { case 'ieSpell' : this._RunIeSpell() ; break ; case 'SpellerPages' : FCKDialog.OpenDialog( 'FCKDialog_SpellCheck', 'Spell Check', 'dialog/fck_spellerpages.html', 440, 480 ) ; break ; case 'WSC' : FCKDialog.OpenDialog( 'FCKDialog_SpellCheck', 'Spell Check', 'wsc/w.html', 530, 480 ) ; } } FCKSpellCheckCommand.prototype._RunIeSpell = function() { try { var oIeSpell = new ActiveXObject( "ieSpell.ieSpellExtension" ) ; oIeSpell.CheckAllLinkedDocuments( FCK.EditorDocument ) ; } catch( e ) { if( e.number == -2146827859 ) { if ( confirm( FCKLang.IeSpellDownload ) ) window.open( FCKConfig.IeSpellDownloadUrl , 'IeSpellDownload' ) ; } else alert( 'Error Loading ieSpell: ' + e.message + ' (' + e.number + ')' ) ; } } FCKSpellCheckCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return this.IsEnabled ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Implementation for the "Insert/Remove Ordered/Unordered List" commands. */ var FCKListCommand = function( name, tagName ) { this.Name = name ; this.TagName = tagName ; } FCKListCommand.prototype = { GetState : function() { // Disabled if not WYSIWYG. if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow ) return FCK_TRISTATE_DISABLED ; // We'll use the style system's convention to determine list state here... // If the starting block is a descendant of an <ol> or <ul> node, then we're in a list. var startContainer = FCKSelection.GetBoundaryParentElement( true ) ; var listNode = startContainer ; while ( listNode ) { if ( listNode.nodeName.IEquals( [ 'ul', 'ol' ] ) ) break ; listNode = listNode.parentNode ; } if ( listNode && listNode.nodeName.IEquals( this.TagName ) ) return FCK_TRISTATE_ON ; else return FCK_TRISTATE_OFF ; }, Execute : function() { FCKUndo.SaveUndoStep() ; var doc = FCK.EditorDocument ; var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; var state = this.GetState() ; // Midas lists rule #1 says we can create a list even in an empty document. // But FCKDomRangeIterator wouldn't run if the document is really empty. // So create a paragraph if the document is empty and we're going to create a list. if ( state == FCK_TRISTATE_OFF ) { FCKDomTools.TrimNode( doc.body ) ; if ( ! doc.body.firstChild ) { var paragraph = doc.createElement( 'p' ) ; doc.body.appendChild( paragraph ) ; range.MoveToNodeContents( paragraph ) ; } } var bookmark = range.CreateBookmark() ; // Group the blocks up because there are many cases where multiple lists have to be created, // or multiple lists have to be cancelled. var listGroups = [] ; var markerObj = {} ; var iterator = new FCKDomRangeIterator( range ) ; var block ; iterator.ForceBrBreak = ( state == FCK_TRISTATE_OFF ) ; var nextRangeExists = true ; var rangeQueue = null ; while ( nextRangeExists ) { while ( ( block = iterator.GetNextParagraph() ) ) { var path = new FCKElementPath( block ) ; var listNode = null ; var processedFlag = false ; var blockLimit = path.BlockLimit ; // First, try to group by a list ancestor. for ( var i = path.Elements.length - 1 ; i >= 0 ; i-- ) { var el = path.Elements[i] ; if ( el.nodeName.IEquals( ['ol', 'ul'] ) ) { // If we've encountered a list inside a block limit // The last group object of the block limit element should // no longer be valid. Since paragraphs after the list // should belong to a different group of paragraphs before // the list. (Bug #1309) if ( blockLimit._FCK_ListGroupObject ) blockLimit._FCK_ListGroupObject = null ; var groupObj = el._FCK_ListGroupObject ; if ( groupObj ) groupObj.contents.push( block ) ; else { groupObj = { 'root' : el, 'contents' : [ block ] } ; listGroups.push( groupObj ) ; FCKDomTools.SetElementMarker( markerObj, el, '_FCK_ListGroupObject', groupObj ) ; } processedFlag = true ; break ; } } if ( processedFlag ) continue ; // No list ancestor? Group by block limit. var root = blockLimit ; if ( root._FCK_ListGroupObject ) root._FCK_ListGroupObject.contents.push( block ) ; else { var groupObj = { 'root' : root, 'contents' : [ block ] } ; FCKDomTools.SetElementMarker( markerObj, root, '_FCK_ListGroupObject', groupObj ) ; listGroups.push( groupObj ) ; } } if ( FCKBrowserInfo.IsIE ) nextRangeExists = false ; else { if ( rangeQueue == null ) { rangeQueue = [] ; var selectionObject = FCKSelection.GetSelection() ; if ( selectionObject && listGroups.length == 0 ) rangeQueue.push( selectionObject.getRangeAt( 0 ) ) ; for ( var i = 1 ; selectionObject && i < selectionObject.rangeCount ; i++ ) rangeQueue.push( selectionObject.getRangeAt( i ) ) ; } if ( rangeQueue.length < 1 ) nextRangeExists = false ; else { var internalRange = FCKW3CRange.CreateFromRange( doc, rangeQueue.shift() ) ; range._Range = internalRange ; range._UpdateElementInfo() ; if ( range.StartNode.nodeName.IEquals( 'td' ) ) range.SetStart( range.StartNode, 1 ) ; if ( range.EndNode.nodeName.IEquals( 'td' ) ) range.SetEnd( range.EndNode, 2 ) ; iterator = new FCKDomRangeIterator( range ) ; iterator.ForceBrBreak = ( state == FCK_TRISTATE_OFF ) ; } } } // Now we have two kinds of list groups, groups rooted at a list, and groups rooted at a block limit element. // We either have to build lists or remove lists, for removing a list does not makes sense when we are looking // at the group that's not rooted at lists. So we have three cases to handle. var listsCreated = [] ; while ( listGroups.length > 0 ) { var groupObj = listGroups.shift() ; if ( state == FCK_TRISTATE_OFF ) { if ( groupObj.root.nodeName.IEquals( ['ul', 'ol'] ) ) this._ChangeListType( groupObj, markerObj, listsCreated ) ; else this._CreateList( groupObj, listsCreated ) ; } else if ( state == FCK_TRISTATE_ON && groupObj.root.nodeName.IEquals( ['ul', 'ol'] ) ) this._RemoveList( groupObj, markerObj ) ; } // For all new lists created, merge adjacent, same type lists. for ( var i = 0 ; i < listsCreated.length ; i++ ) { var listNode = listsCreated[i] ; var stopFlag = false ; var currentNode = listNode ; while ( ! stopFlag ) { currentNode = currentNode.nextSibling ; if ( currentNode && currentNode.nodeType == 3 && currentNode.nodeValue.search( /^[\n\r\t ]*$/ ) == 0 ) continue ; stopFlag = true ; } if ( currentNode && currentNode.nodeName.IEquals( this.TagName ) ) { currentNode.parentNode.removeChild( currentNode ) ; while ( currentNode.firstChild ) listNode.appendChild( currentNode.removeChild( currentNode.firstChild ) ) ; } stopFlag = false ; currentNode = listNode ; while ( ! stopFlag ) { currentNode = currentNode.previousSibling ; if ( currentNode && currentNode.nodeType == 3 && currentNode.nodeValue.search( /^[\n\r\t ]*$/ ) == 0 ) continue ; stopFlag = true ; } if ( currentNode && currentNode.nodeName.IEquals( this.TagName ) ) { currentNode.parentNode.removeChild( currentNode ) ; while ( currentNode.lastChild ) listNode.insertBefore( currentNode.removeChild( currentNode.lastChild ), listNode.firstChild ) ; } } // Clean up, restore selection and update toolbar button states. FCKDomTools.ClearAllMarkers( markerObj ) ; range.MoveToBookmark( bookmark ) ; range.Select() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, _ChangeListType : function( groupObj, markerObj, listsCreated ) { // This case is easy... // 1. Convert the whole list into a one-dimensional array. // 2. Change the list type by modifying the array. // 3. Recreate the whole list by converting the array to a list. // 4. Replace the original list with the recreated list. var listArray = FCKDomTools.ListToArray( groupObj.root, markerObj ) ; var selectedListItems = [] ; for ( var i = 0 ; i < groupObj.contents.length ; i++ ) { var itemNode = groupObj.contents[i] ; itemNode = FCKTools.GetElementAscensor( itemNode, 'li' ) ; if ( ! itemNode || itemNode._FCK_ListItem_Processed ) continue ; selectedListItems.push( itemNode ) ; FCKDomTools.SetElementMarker( markerObj, itemNode, '_FCK_ListItem_Processed', true ) ; } var fakeParent = FCKTools.GetElementDocument( groupObj.root ).createElement( this.TagName ) ; for ( var i = 0 ; i < selectedListItems.length ; i++ ) { var listIndex = selectedListItems[i]._FCK_ListArray_Index ; listArray[listIndex].parent = fakeParent ; } var newList = FCKDomTools.ArrayToList( listArray, markerObj ) ; for ( var i = 0 ; i < newList.listNode.childNodes.length ; i++ ) { if ( newList.listNode.childNodes[i].nodeName.IEquals( this.TagName ) ) listsCreated.push( newList.listNode.childNodes[i] ) ; } groupObj.root.parentNode.replaceChild( newList.listNode, groupObj.root ) ; }, _CreateList : function( groupObj, listsCreated ) { var contents = groupObj.contents ; var doc = FCKTools.GetElementDocument( groupObj.root ) ; var listContents = [] ; // It is possible to have the contents returned by DomRangeIterator to be the same as the root. // e.g. when we're running into table cells. // In such a case, enclose the childNodes of contents[0] into a <div>. if ( contents.length == 1 && contents[0] == groupObj.root ) { var divBlock = doc.createElement( 'div' ); while ( contents[0].firstChild ) divBlock.appendChild( contents[0].removeChild( contents[0].firstChild ) ) ; contents[0].appendChild( divBlock ) ; contents[0] = divBlock ; } // Calculate the common parent node of all content blocks. var commonParent = groupObj.contents[0].parentNode ; for ( var i = 0 ; i < contents.length ; i++ ) commonParent = FCKDomTools.GetCommonParents( commonParent, contents[i].parentNode ).pop() ; // We want to insert things that are in the same tree level only, so calculate the contents again // by expanding the selected blocks to the same tree level. for ( var i = 0 ; i < contents.length ; i++ ) { var contentNode = contents[i] ; while ( contentNode.parentNode ) { if ( contentNode.parentNode == commonParent ) { listContents.push( contentNode ) ; break ; } contentNode = contentNode.parentNode ; } } if ( listContents.length < 1 ) return ; // Insert the list to the DOM tree. var insertAnchor = listContents[listContents.length - 1].nextSibling ; var listNode = doc.createElement( this.TagName ) ; listsCreated.push( listNode ) ; while ( listContents.length ) { var contentBlock = listContents.shift() ; var docFrag = doc.createDocumentFragment() ; while ( contentBlock.firstChild ) docFrag.appendChild( contentBlock.removeChild( contentBlock.firstChild ) ) ; contentBlock.parentNode.removeChild( contentBlock ) ; var listItem = doc.createElement( 'li' ) ; listItem.appendChild( docFrag ) ; listNode.appendChild( listItem ) ; } commonParent.insertBefore( listNode, insertAnchor ) ; }, _RemoveList : function( groupObj, markerObj ) { // This is very much like the change list type operation. // Except that we're changing the selected items' indent to -1 in the list array. var listArray = FCKDomTools.ListToArray( groupObj.root, markerObj ) ; var selectedListItems = [] ; for ( var i = 0 ; i < groupObj.contents.length ; i++ ) { var itemNode = groupObj.contents[i] ; itemNode = FCKTools.GetElementAscensor( itemNode, 'li' ) ; if ( ! itemNode || itemNode._FCK_ListItem_Processed ) continue ; selectedListItems.push( itemNode ) ; FCKDomTools.SetElementMarker( markerObj, itemNode, '_FCK_ListItem_Processed', true ) ; } var lastListIndex = null ; for ( var i = 0 ; i < selectedListItems.length ; i++ ) { var listIndex = selectedListItems[i]._FCK_ListArray_Index ; listArray[listIndex].indent = -1 ; lastListIndex = listIndex ; } // After cutting parts of the list out with indent=-1, we still have to maintain the array list // model's nextItem.indent <= currentItem.indent + 1 invariant. Otherwise the array model of the // list cannot be converted back to a real DOM list. for ( var i = lastListIndex + 1; i < listArray.length ; i++ ) { if ( listArray[i].indent > listArray[i-1].indent + 1 ) { var indentOffset = listArray[i-1].indent + 1 - listArray[i].indent ; var oldIndent = listArray[i].indent ; while ( listArray[i] && listArray[i].indent >= oldIndent) { listArray[i].indent += indentOffset ; i++ ; } i-- ; } } var newList = FCKDomTools.ArrayToList( listArray, markerObj ) ; // If groupObj.root is the last element in its parent, or its nextSibling is a <br>, then we should // not add a <br> after the final item. So, check for the cases and trim the <br>. if ( groupObj.root.nextSibling == null || groupObj.root.nextSibling.nodeName.IEquals( 'br' ) ) { if ( newList.listNode.lastChild.nodeName.IEquals( 'br' ) ) newList.listNode.removeChild( newList.listNode.lastChild ) ; } groupObj.root.parentNode.replaceChild( newList.listNode, groupObj.root ) ; } };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKBlockQuoteCommand Class: adds or removes blockquote tags. */ var FCKBlockQuoteCommand = function() { } FCKBlockQuoteCommand.prototype = { Execute : function() { FCKUndo.SaveUndoStep() ; var state = this.GetState() ; var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; var bookmark = range.CreateBookmark() ; // Kludge for #1592: if the bookmark nodes are in the beginning of // blockquote, then move them to the nearest block element in the // blockquote. if ( FCKBrowserInfo.IsIE ) { var bStart = range.GetBookmarkNode( bookmark, true ) ; var bEnd = range.GetBookmarkNode( bookmark, false ) ; var cursor ; if ( bStart && bStart.parentNode.nodeName.IEquals( 'blockquote' ) && !bStart.previousSibling ) { cursor = bStart ; while ( ( cursor = cursor.nextSibling ) ) { if ( FCKListsLib.BlockElements[ cursor.nodeName.toLowerCase() ] ) FCKDomTools.MoveNode( bStart, cursor, true ) ; } } if ( bEnd && bEnd.parentNode.nodeName.IEquals( 'blockquote' ) && !bEnd.previousSibling ) { cursor = bEnd ; while ( ( cursor = cursor.nextSibling ) ) { if ( FCKListsLib.BlockElements[ cursor.nodeName.toLowerCase() ] ) { if ( cursor.firstChild == bStart ) FCKDomTools.InsertAfterNode( bStart, bEnd ) ; else FCKDomTools.MoveNode( bEnd, cursor, true ) ; } } } } var iterator = new FCKDomRangeIterator( range ) ; var block ; if ( state == FCK_TRISTATE_OFF ) { var paragraphs = [] ; while ( ( block = iterator.GetNextParagraph() ) ) paragraphs.push( block ) ; // If no paragraphs, create one from the current selection position. if ( paragraphs.length < 1 ) { para = range.Window.document.createElement( FCKConfig.EnterMode.IEquals( 'p' ) ? 'p' : 'div' ) ; range.InsertNode( para ) ; para.appendChild( range.Window.document.createTextNode( '\ufeff' ) ) ; range.MoveToBookmark( bookmark ) ; range.MoveToNodeContents( para ) ; range.Collapse( true ) ; bookmark = range.CreateBookmark() ; paragraphs.push( para ) ; } // Make sure all paragraphs have the same parent. var commonParent = paragraphs[0].parentNode ; var tmp = [] ; for ( var i = 0 ; i < paragraphs.length ; i++ ) { block = paragraphs[i] ; commonParent = FCKDomTools.GetCommonParents( block.parentNode, commonParent ).pop() ; } // The common parent must not be the following tags: table, tbody, tr, ol, ul. while ( commonParent.nodeName.IEquals( 'table', 'tbody', 'tr', 'ol', 'ul' ) ) commonParent = commonParent.parentNode ; // Reconstruct the block list to be processed such that all resulting blocks // satisfy parentNode == commonParent. var lastBlock = null ; while ( paragraphs.length > 0 ) { block = paragraphs.shift() ; while ( block.parentNode != commonParent ) block = block.parentNode ; if ( block != lastBlock ) tmp.push( block ) ; lastBlock = block ; } // If any of the selected blocks is a blockquote, remove it to prevent nested blockquotes. while ( tmp.length > 0 ) { block = tmp.shift() ; if ( block.nodeName.IEquals( 'blockquote' ) ) { var docFrag = FCKTools.GetElementDocument( block ).createDocumentFragment() ; while ( block.firstChild ) { docFrag.appendChild( block.removeChild( block.firstChild ) ) ; paragraphs.push( docFrag.lastChild ) ; } block.parentNode.replaceChild( docFrag, block ) ; } else paragraphs.push( block ) ; } // Now we have all the blocks to be included in a new blockquote node. var bqBlock = range.Window.document.createElement( 'blockquote' ) ; commonParent.insertBefore( bqBlock, paragraphs[0] ) ; while ( paragraphs.length > 0 ) { block = paragraphs.shift() ; bqBlock.appendChild( block ) ; } } else if ( state == FCK_TRISTATE_ON ) { var moveOutNodes = [] ; var elementMarkers = {} ; while ( ( block = iterator.GetNextParagraph() ) ) { var bqParent = null ; var bqChild = null ; while ( block.parentNode ) { if ( block.parentNode.nodeName.IEquals( 'blockquote' ) ) { bqParent = block.parentNode ; bqChild = block ; break ; } block = block.parentNode ; } // Remember the blocks that were recorded down in the moveOutNodes array // to prevent duplicates. if ( bqParent && bqChild && !bqChild._fckblockquotemoveout ) { moveOutNodes.push( bqChild ) ; FCKDomTools.SetElementMarker( elementMarkers, bqChild, '_fckblockquotemoveout', true ) ; } } FCKDomTools.ClearAllMarkers( elementMarkers ) ; var movedNodes = [] ; var processedBlockquoteBlocks = [], elementMarkers = {} ; var noBlockLeft = function( bqBlock ) { for ( var i = 0 ; i < bqBlock.childNodes.length ; i++ ) { if ( FCKListsLib.BlockElements[ bqBlock.childNodes[i].nodeName.toLowerCase() ] ) return false ; } return true ; } ; while ( moveOutNodes.length > 0 ) { var node = moveOutNodes.shift() ; var bqBlock = node.parentNode ; // If the node is located at the beginning or the end, just take it out without splitting. // Otherwise, split the blockquote node and move the paragraph in between the two blockquote nodes. if ( node == node.parentNode.firstChild ) bqBlock.parentNode.insertBefore( bqBlock.removeChild( node ), bqBlock ) ; else if ( node == node.parentNode.lastChild ) bqBlock.parentNode.insertBefore( bqBlock.removeChild( node ), bqBlock.nextSibling ) ; else FCKDomTools.BreakParent( node, node.parentNode, range ) ; // Remember the blockquote node so we can clear it later (if it becomes empty). if ( !bqBlock._fckbqprocessed ) { processedBlockquoteBlocks.push( bqBlock ) ; FCKDomTools.SetElementMarker( elementMarkers, bqBlock, '_fckbqprocessed', true ); } movedNodes.push( node ) ; } // Clear blockquote nodes that have become empty. for ( var i = processedBlockquoteBlocks.length - 1 ; i >= 0 ; i-- ) { var bqBlock = processedBlockquoteBlocks[i] ; if ( noBlockLeft( bqBlock ) ) FCKDomTools.RemoveNode( bqBlock ) ; } FCKDomTools.ClearAllMarkers( elementMarkers ) ; if ( FCKConfig.EnterMode.IEquals( 'br' ) ) { while ( movedNodes.length ) { var node = movedNodes.shift() ; var firstTime = true ; if ( node.nodeName.IEquals( 'div' ) ) { var docFrag = FCKTools.GetElementDocument( node ).createDocumentFragment() ; var needBeginBr = firstTime && node.previousSibling && !FCKListsLib.BlockBoundaries[node.previousSibling.nodeName.toLowerCase()] ; if ( firstTime && needBeginBr ) docFrag.appendChild( FCKTools.GetElementDocument( node ).createElement( 'br' ) ) ; var needEndBr = node.nextSibling && !FCKListsLib.BlockBoundaries[node.nextSibling.nodeName.toLowerCase()] ; while ( node.firstChild ) docFrag.appendChild( node.removeChild( node.firstChild ) ) ; if ( needEndBr ) docFrag.appendChild( FCKTools.GetElementDocument( node ).createElement( 'br' ) ) ; node.parentNode.replaceChild( docFrag, node ) ; firstTime = false ; } } } } range.MoveToBookmark( bookmark ) ; range.Select() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { // Disabled if not WYSIWYG. if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow ) return FCK_TRISTATE_DISABLED ; var path = new FCKElementPath( FCKSelection.GetBoundaryParentElement( true ) ) ; var firstBlock = path.Block || path.BlockLimit ; if ( !firstBlock || firstBlock.nodeName.toLowerCase() == 'body' ) return FCK_TRISTATE_OFF ; // See if the first block has a blockquote parent. for ( var i = 0 ; i < path.Elements.length ; i++ ) { if ( path.Elements[i].nodeName.IEquals( 'blockquote' ) ) return FCK_TRISTATE_ON ; } return FCK_TRISTATE_OFF ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKNamedCommand Class: represents an internal browser command. */ var FCKNamedCommand = function( commandName ) { this.Name = commandName ; } FCKNamedCommand.prototype.Execute = function() { FCK.ExecuteNamedCommand( this.Name ) ; } FCKNamedCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK.GetNamedCommandState( this.Name ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKRemoveFormatCommand Class: controls the execution of a core style. Core * styles are usually represented as buttons in the toolbar., like Bold and * Italic. */ var FCKRemoveFormatCommand = function() { this.Name = 'RemoveFormat' ; } FCKRemoveFormatCommand.prototype = { Execute : function() { FCKStyles.RemoveAll() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { return FCK.EditorWindow ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; } };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Definition of other commands that are not available internaly in the * browser (see FCKNamedCommand). */ // ### General Dialog Box Commands. var FCKDialogCommand = function( name, title, url, width, height, getStateFunction, getStateParam, customValue ) { this.Name = name ; this.Title = title ; this.Url = url ; this.Width = width ; this.Height = height ; this.CustomValue = customValue ; this.GetStateFunction = getStateFunction ; this.GetStateParam = getStateParam ; this.Resizable = false ; } FCKDialogCommand.prototype.Execute = function() { FCKDialog.OpenDialog( 'FCKDialog_' + this.Name , this.Title, this.Url, this.Width, this.Height, this.CustomValue, this.Resizable ) ; } FCKDialogCommand.prototype.GetState = function() { if ( this.GetStateFunction ) return this.GetStateFunction( this.GetStateParam ) ; else return FCK.EditMode == FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; } // Generic Undefined command (usually used when a command is under development). var FCKUndefinedCommand = function() { this.Name = 'Undefined' ; } FCKUndefinedCommand.prototype.Execute = function() { alert( FCKLang.NotImplemented ) ; } FCKUndefinedCommand.prototype.GetState = function() { return FCK_TRISTATE_OFF ; } // ### FormatBlock var FCKFormatBlockCommand = function() {} FCKFormatBlockCommand.prototype = { Name : 'FormatBlock', Execute : FCKStyleCommand.prototype.Execute, GetState : function() { return FCK.EditorDocument ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; } }; // ### FontName var FCKFontNameCommand = function() {} FCKFontNameCommand.prototype = { Name : 'FontName', Execute : FCKStyleCommand.prototype.Execute, GetState : FCKFormatBlockCommand.prototype.GetState }; // ### FontSize var FCKFontSizeCommand = function() {} FCKFontSizeCommand.prototype = { Name : 'FontSize', Execute : FCKStyleCommand.prototype.Execute, GetState : FCKFormatBlockCommand.prototype.GetState }; // ### Preview var FCKPreviewCommand = function() { this.Name = 'Preview' ; } FCKPreviewCommand.prototype.Execute = function() { FCK.Preview() ; } FCKPreviewCommand.prototype.GetState = function() { return FCK_TRISTATE_OFF ; } // ### Save var FCKSaveCommand = function() { this.Name = 'Save' ; } FCKSaveCommand.prototype.Execute = function() { // Get the linked field form. var oForm = FCK.GetParentForm() ; if ( typeof( oForm.onsubmit ) == 'function' ) { var bRet = oForm.onsubmit() ; if ( bRet != null && bRet === false ) return ; } // Submit the form. // If there's a button named "submit" then the form.submit() function is masked and // can't be called in Mozilla, so we call the click() method of that button. if ( typeof( oForm.submit ) == 'function' ) oForm.submit() ; else oForm.submit.click() ; } FCKSaveCommand.prototype.GetState = function() { return FCK_TRISTATE_OFF ; } // ### NewPage var FCKNewPageCommand = function() { this.Name = 'NewPage' ; } FCKNewPageCommand.prototype.Execute = function() { FCKUndo.SaveUndoStep() ; FCK.SetData( '' ) ; FCKUndo.Typing = true ; FCK.Focus() ; } FCKNewPageCommand.prototype.GetState = function() { return FCK_TRISTATE_OFF ; } // ### Source button var FCKSourceCommand = function() { this.Name = 'Source' ; } FCKSourceCommand.prototype.Execute = function() { if ( FCKConfig.SourcePopup ) // Until v2.2, it was mandatory for FCKBrowserInfo.IsGecko. { var iWidth = FCKConfig.ScreenWidth * 0.65 ; var iHeight = FCKConfig.ScreenHeight * 0.65 ; FCKDialog.OpenDialog( 'FCKDialog_Source', FCKLang.Source, 'dialog/fck_source.html', iWidth, iHeight, null, true ) ; } else FCK.SwitchEditMode() ; } FCKSourceCommand.prototype.GetState = function() { return ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_OFF : FCK_TRISTATE_ON ) ; } // ### Undo var FCKUndoCommand = function() { this.Name = 'Undo' ; } FCKUndoCommand.prototype.Execute = function() { FCKUndo.Undo() ; } FCKUndoCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return ( FCKUndo.CheckUndoState() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ) ; } // ### Redo var FCKRedoCommand = function() { this.Name = 'Redo' ; } FCKRedoCommand.prototype.Execute = function() { FCKUndo.Redo() ; } FCKRedoCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return ( FCKUndo.CheckRedoState() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ) ; } // ### Page Break var FCKPageBreakCommand = function() { this.Name = 'PageBreak' ; } FCKPageBreakCommand.prototype.Execute = function() { // Take an undo snapshot before changing the document FCKUndo.SaveUndoStep() ; // var e = FCK.EditorDocument.createElement( 'CENTER' ) ; // e.style.pageBreakAfter = 'always' ; // Tidy was removing the empty CENTER tags, so the following solution has // been found. It also validates correctly as XHTML 1.0 Strict. var e = FCK.EditorDocument.createElement( 'DIV' ) ; e.style.pageBreakAfter = 'always' ; e.innerHTML = '<span style="DISPLAY:none">&nbsp;</span>' ; var oFakeImage = FCKDocumentProcessor_CreateFakeImage( 'FCK__PageBreak', e ) ; var oRange = new FCKDomRange( FCK.EditorWindow ) ; oRange.MoveToSelection() ; var oSplitInfo = oRange.SplitBlock() ; oRange.InsertNode( oFakeImage ) ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; } FCKPageBreakCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return 0 ; // FCK_TRISTATE_OFF } // FCKUnlinkCommand - by Johnny Egeland (johnny@coretrek.com) var FCKUnlinkCommand = function() { this.Name = 'Unlink' ; } FCKUnlinkCommand.prototype.Execute = function() { // Take an undo snapshot before changing the document FCKUndo.SaveUndoStep() ; if ( FCKBrowserInfo.IsGeckoLike ) { var oLink = FCK.Selection.MoveToAncestorNode( 'A' ) ; // The unlink command can generate a span in Firefox, so let's do it our way. See #430 if ( oLink ) FCKTools.RemoveOuterTags( oLink ) ; return ; } FCK.ExecuteNamedCommand( this.Name ) ; } FCKUnlinkCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; var state = FCK.GetNamedCommandState( this.Name ) ; // Check that it isn't an anchor if ( state == FCK_TRISTATE_OFF && FCK.EditMode == FCK_EDITMODE_WYSIWYG ) { var oLink = FCKSelection.MoveToAncestorNode( 'A' ) ; var bIsAnchor = ( oLink && oLink.name.length > 0 && oLink.href.length == 0 ) ; if ( bIsAnchor ) state = FCK_TRISTATE_DISABLED ; } return state ; } var FCKVisitLinkCommand = function() { this.Name = 'VisitLink'; } FCKVisitLinkCommand.prototype = { GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; var state = FCK.GetNamedCommandState( 'Unlink' ) ; if ( state == FCK_TRISTATE_OFF ) { var el = FCKSelection.MoveToAncestorNode( 'A' ) ; if ( !el.href ) state = FCK_TRISTATE_DISABLED ; } return state ; }, Execute : function() { var el = FCKSelection.MoveToAncestorNode( 'A' ) ; var url = el.getAttribute( '_fcksavedurl' ) || el.getAttribute( 'href', 2 ) ; // Check if it's a full URL. // If not full URL, we'll need to apply the BaseHref setting. if ( ! /:\/\//.test( url ) ) { var baseHref = FCKConfig.BaseHref ; var parentWindow = FCK.GetInstanceObject( 'parent' ) ; if ( !baseHref ) { baseHref = parentWindow.document.location.href ; baseHref = baseHref.substring( 0, baseHref.lastIndexOf( '/' ) + 1 ) ; } if ( /^\//.test( url ) ) { try { baseHref = baseHref.match( /^.*:\/\/+[^\/]+/ )[0] ; } catch ( e ) { baseHref = parentWindow.document.location.protocol + '://' + parentWindow.parent.document.location.host ; } } url = baseHref + url ; } if ( !window.open( url, '_blank' ) ) alert( FCKLang.VisitLinkBlocked ) ; } } ; // FCKSelectAllCommand var FCKSelectAllCommand = function() { this.Name = 'SelectAll' ; } FCKSelectAllCommand.prototype.Execute = function() { if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) { FCK.ExecuteNamedCommand( 'SelectAll' ) ; } else { // Select the contents of the textarea var textarea = FCK.EditingArea.Textarea ; if ( FCKBrowserInfo.IsIE ) { textarea.createTextRange().execCommand( 'SelectAll' ) ; } else { textarea.selectionStart = 0 ; textarea.selectionEnd = textarea.value.length ; } textarea.focus() ; } } FCKSelectAllCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK_TRISTATE_OFF ; } // FCKPasteCommand var FCKPasteCommand = function() { this.Name = 'Paste' ; } FCKPasteCommand.prototype = { Execute : function() { if ( FCKBrowserInfo.IsIE ) FCK.Paste() ; else FCK.ExecuteNamedCommand( 'Paste' ) ; }, GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK.GetNamedCommandState( 'Paste' ) ; } } ; // FCKRuleCommand var FCKRuleCommand = function() { this.Name = 'Rule' ; } FCKRuleCommand.prototype = { Execute : function() { FCKUndo.SaveUndoStep() ; FCK.InsertElement( 'hr' ) ; }, GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK.GetNamedCommandState( 'InsertHorizontalRule' ) ; } } ; // FCKCutCopyCommand var FCKCutCopyCommand = function( isCut ) { this.Name = isCut ? 'Cut' : 'Copy' ; } FCKCutCopyCommand.prototype = { Execute : function() { var enabled = false ; if ( FCKBrowserInfo.IsIE ) { // The following seems to be the only reliable way to detect that // cut/copy is enabled in IE. It will fire the oncut/oncopy event // only if the security settings enabled the command to execute. var onEvent = function() { enabled = true ; } ; var eventName = 'on' + this.Name.toLowerCase() ; FCK.EditorDocument.body.attachEvent( eventName, onEvent ) ; FCK.ExecuteNamedCommand( this.Name ) ; FCK.EditorDocument.body.detachEvent( eventName, onEvent ) ; } else { try { // Other browsers throw an error if the command is disabled. FCK.ExecuteNamedCommand( this.Name ) ; enabled = true ; } catch(e){} } if ( !enabled ) alert( FCKLang[ 'PasteError' + this.Name ] ) ; }, GetState : function() { // Strangely, the Cut command happens to have the correct states for // both Copy and Cut in all browsers. return FCK.EditMode != FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_DISABLED : FCK.GetNamedCommandState( 'Cut' ) ; } }; var FCKAnchorDeleteCommand = function() { this.Name = 'AnchorDelete' ; } FCKAnchorDeleteCommand.prototype = { Execute : function() { if (FCK.Selection.GetType() == 'Control') { FCK.Selection.Delete(); } else { var oFakeImage = FCK.Selection.GetSelectedElement() ; if ( oFakeImage ) { if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckanchor') ) oAnchor = FCK.GetRealElement( oFakeImage ) ; else oFakeImage = null ; } //Search for a real anchor if ( !oFakeImage ) { oAnchor = FCK.Selection.MoveToAncestorNode( 'A' ) ; if ( oAnchor ) FCK.Selection.SelectNode( oAnchor ) ; } // If it's also a link, then just remove the name and exit if ( oAnchor.href.length != 0 ) { oAnchor.removeAttribute( 'name' ) ; // Remove temporary class for IE if ( FCKBrowserInfo.IsIE ) oAnchor.className = oAnchor.className.replace( FCKRegexLib.FCK_Class, '' ) ; return ; } // We need to remove the anchor // If we got a fake image, then just remove it and we're done if ( oFakeImage ) { oFakeImage.parentNode.removeChild( oFakeImage ) ; return ; } // Empty anchor, so just remove it if ( oAnchor.innerHTML.length == 0 ) { oAnchor.parentNode.removeChild( oAnchor ) ; return ; } // Anchor with content, leave the content FCKTools.RemoveOuterTags( oAnchor ) ; } if ( FCKBrowserInfo.IsGecko ) FCK.Selection.Collapse( true ) ; }, GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK.GetNamedCommandState( 'Unlink') ; } }; var FCKDeleteDivCommand = function() { } FCKDeleteDivCommand.prototype = { GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; var node = FCKSelection.GetParentElement() ; var path = new FCKElementPath( node ) ; return path.BlockLimit && path.BlockLimit.nodeName.IEquals( 'div' ) ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; }, Execute : function() { // Create an undo snapshot before doing anything. FCKUndo.SaveUndoStep() ; // Find out the nodes to delete. var nodes = FCKDomTools.GetSelectedDivContainers() ; // Remember the current selection position. var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; var bookmark = range.CreateBookmark() ; // Delete the container DIV node. for ( var i = 0 ; i < nodes.length ; i++) FCKDomTools.RemoveNode( nodes[i], true ) ; // Restore selection. range.MoveToBookmark( bookmark ) ; range.Select() ; } } ; // FCKRuleCommand var FCKNbsp = function() { this.Name = 'Non Breaking Space' ; } FCKNbsp.prototype = { Execute : function() { FCK.InsertHtml( '&nbsp;' ) ; }, GetState : function() { return ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_DISABLED : FCK_TRISTATE_OFF ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKTextColorCommand Class: represents the text color comand. It shows the * color selection panel. */ // FCKTextColorCommand Constructor // type: can be 'ForeColor' or 'BackColor'. var FCKTextColorCommand = function( type ) { this.Name = type == 'ForeColor' ? 'TextColor' : 'BGColor' ; this.Type = type ; var oWindow ; if ( FCKBrowserInfo.IsIE ) oWindow = window ; else if ( FCK.ToolbarSet._IFrame ) oWindow = FCKTools.GetElementWindow( FCK.ToolbarSet._IFrame ) ; else oWindow = window.parent ; this._Panel = new FCKPanel( oWindow ) ; this._Panel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; this._Panel.MainNode.className = 'FCK_Panel' ; this._CreatePanelBody( this._Panel.Document, this._Panel.MainNode ) ; FCK.ToolbarSet.ToolbarItems.GetItem( this.Name ).RegisterPanel( this._Panel ) ; FCKTools.DisableSelection( this._Panel.Document.body ) ; } FCKTextColorCommand.prototype.Execute = function( panelX, panelY, relElement ) { // Show the Color Panel at the desired position. this._Panel.Show( panelX, panelY, relElement ) ; } FCKTextColorCommand.prototype.SetColor = function( color ) { FCKUndo.SaveUndoStep() ; var style = FCKStyles.GetStyle( '_FCK_' + ( this.Type == 'ForeColor' ? 'Color' : 'BackColor' ) ) ; if ( !color || color.length == 0 ) FCK.Styles.RemoveStyle( style ) ; else { style.SetVariable( 'Color', color ) ; FCKStyles.ApplyStyle( style ) ; } FCKUndo.SaveUndoStep() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; } FCKTextColorCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK_TRISTATE_OFF ; } function FCKTextColorCommand_OnMouseOver() { this.className = 'ColorSelected' ; } function FCKTextColorCommand_OnMouseOut() { this.className = 'ColorDeselected' ; } function FCKTextColorCommand_OnClick( ev, command, color ) { this.className = 'ColorDeselected' ; command.SetColor( color ) ; command._Panel.Hide() ; } function FCKTextColorCommand_AutoOnClick( ev, command ) { this.className = 'ColorDeselected' ; command.SetColor( '' ) ; command._Panel.Hide() ; } function FCKTextColorCommand_MoreOnClick( ev, command ) { this.className = 'ColorDeselected' ; command._Panel.Hide() ; FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320, FCKTools.Bind( command, command.SetColor ) ) ; } FCKTextColorCommand.prototype._CreatePanelBody = function( targetDocument, targetDiv ) { function CreateSelectionDiv() { var oDiv = targetDocument.createElement( "DIV" ) ; oDiv.className = 'ColorDeselected' ; FCKTools.AddEventListenerEx( oDiv, 'mouseover', FCKTextColorCommand_OnMouseOver ) ; FCKTools.AddEventListenerEx( oDiv, 'mouseout', FCKTextColorCommand_OnMouseOut ) ; return oDiv ; } // Create the Table that will hold all colors. var oTable = targetDiv.appendChild( targetDocument.createElement( "TABLE" ) ) ; oTable.className = 'ForceBaseFont' ; // Firefox 1.5 Bug. oTable.style.tableLayout = 'fixed' ; oTable.cellPadding = 0 ; oTable.cellSpacing = 0 ; oTable.border = 0 ; oTable.width = 150 ; var oCell = oTable.insertRow(-1).insertCell(-1) ; oCell.colSpan = 8 ; // Create the Button for the "Automatic" color selection. var oDiv = oCell.appendChild( CreateSelectionDiv() ) ; oDiv.innerHTML = '<table cellspacing="0" cellpadding="0" width="100%" border="0">\ <tr>\ <td><div class="ColorBoxBorder"><div class="ColorBox" style="background-color: #000000"></div></div></td>\ <td nowrap width="100%" align="center">' + FCKLang.ColorAutomatic + '</td>\ </tr>\ </table>' ; FCKTools.AddEventListenerEx( oDiv, 'click', FCKTextColorCommand_AutoOnClick, this ) ; // Dirty hack for Opera, Safari and Firefox 3. if ( !FCKBrowserInfo.IsIE ) oDiv.style.width = '96%' ; // Create an array of colors based on the configuration file. var aColors = FCKConfig.FontColors.toString().split(',') ; // Create the colors table based on the array. var iCounter = 0 ; while ( iCounter < aColors.length ) { var oRow = oTable.insertRow(-1) ; for ( var i = 0 ; i < 8 ; i++, iCounter++ ) { // The div will be created even if no more colors are available. // Extra divs will be hidden later in the code. (#1597) if ( iCounter < aColors.length ) { var colorParts = aColors[iCounter].split('/') ; var colorValue = '#' + colorParts[0] ; var colorName = colorParts[1] || colorValue ; } oDiv = oRow.insertCell(-1).appendChild( CreateSelectionDiv() ) ; oDiv.innerHTML = '<div class="ColorBoxBorder"><div class="ColorBox" style="background-color: ' + colorValue + '"></div></div>' ; if ( iCounter >= aColors.length ) oDiv.style.visibility = 'hidden' ; else FCKTools.AddEventListenerEx( oDiv, 'click', FCKTextColorCommand_OnClick, [ this, colorName ] ) ; } } // Create the Row and the Cell for the "More Colors..." button. if ( FCKConfig.EnableMoreFontColors ) { oCell = oTable.insertRow(-1).insertCell(-1) ; oCell.colSpan = 8 ; oDiv = oCell.appendChild( CreateSelectionDiv() ) ; oDiv.innerHTML = '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td nowrap align="center">' + FCKLang.ColorMoreColors + '</td></tr></table>' ; FCKTools.AddEventListenerEx( oDiv, 'click', FCKTextColorCommand_MoreOnClick, this ) ; // Dirty hack for Opera, Safari and Firefox 3. if ( !FCKBrowserInfo.IsIE ) oDiv.style.width = '96%' ; } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKPastePlainTextCommand Class: represents the * "Paste as Plain Text" command. */ var FCKTableCommand = function( command ) { this.Name = command ; } FCKTableCommand.prototype.Execute = function() { FCKUndo.SaveUndoStep() ; if ( ! FCKBrowserInfo.IsGecko ) { switch ( this.Name ) { case 'TableMergeRight' : return FCKTableHandler.MergeRight() ; case 'TableMergeDown' : return FCKTableHandler.MergeDown() ; } } switch ( this.Name ) { case 'TableInsertRowAfter' : return FCKTableHandler.InsertRow( false ) ; case 'TableInsertRowBefore' : return FCKTableHandler.InsertRow( true ) ; case 'TableDeleteRows' : return FCKTableHandler.DeleteRows() ; case 'TableInsertColumnAfter' : return FCKTableHandler.InsertColumn( false ) ; case 'TableInsertColumnBefore' : return FCKTableHandler.InsertColumn( true ) ; case 'TableDeleteColumns' : return FCKTableHandler.DeleteColumns() ; case 'TableInsertCellAfter' : return FCKTableHandler.InsertCell( null, false ) ; case 'TableInsertCellBefore' : return FCKTableHandler.InsertCell( null, true ) ; case 'TableDeleteCells' : return FCKTableHandler.DeleteCells() ; case 'TableMergeCells' : return FCKTableHandler.MergeCells() ; case 'TableHorizontalSplitCell' : return FCKTableHandler.HorizontalSplitCell() ; case 'TableVerticalSplitCell' : return FCKTableHandler.VerticalSplitCell() ; case 'TableDelete' : return FCKTableHandler.DeleteTable() ; default : return alert( FCKLang.UnknownCommand.replace( /%1/g, this.Name ) ) ; } } FCKTableCommand.prototype.GetState = function() { if ( FCK.EditorDocument != null && FCKSelection.HasAncestorNode( 'TABLE' ) ) { switch ( this.Name ) { case 'TableHorizontalSplitCell' : case 'TableVerticalSplitCell' : if ( FCKTableHandler.GetSelectedCells().length == 1 ) return FCK_TRISTATE_OFF ; else return FCK_TRISTATE_DISABLED ; case 'TableMergeCells' : if ( FCKTableHandler.CheckIsSelectionRectangular() && FCKTableHandler.GetSelectedCells().length > 1 ) return FCK_TRISTATE_OFF ; else return FCK_TRISTATE_DISABLED ; case 'TableMergeRight' : return FCKTableHandler.GetMergeRightTarget() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; case 'TableMergeDown' : return FCKTableHandler.GetMergeDownTarget() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; default : return FCK_TRISTATE_OFF ; } } else return FCK_TRISTATE_DISABLED; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKShowBlockCommand Class: the "Show Blocks" command. */ var FCKShowBlockCommand = function( name, defaultState ) { this.Name = name ; if ( defaultState != undefined ) this._SavedState = defaultState ; else this._SavedState = null ; } FCKShowBlockCommand.prototype.Execute = function() { var state = this.GetState() ; if ( state == FCK_TRISTATE_DISABLED ) return ; var body = FCK.EditorDocument.body ; if ( state == FCK_TRISTATE_ON ) body.className = body.className.replace( /(^| )FCK__ShowBlocks/g, '' ) ; else body.className += ' FCK__ShowBlocks' ; if ( FCKBrowserInfo.IsIE ) { try { FCK.EditorDocument.selection.createRange().select() ; } catch ( e ) {} } else { var focus = FCK.EditorWindow.getSelection().focusNode ; if ( focus ) { if ( focus.nodeType != 1 ) focus = focus.parentNode ; FCKDomTools.ScrollIntoView( focus, false ) ; } } FCK.Events.FireEvent( 'OnSelectionChange' ) ; } FCKShowBlockCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; // On some cases FCK.EditorDocument.body is not yet available if ( !FCK.EditorDocument ) return FCK_TRISTATE_OFF ; if ( /FCK__ShowBlocks(?:\s|$)/.test( FCK.EditorDocument.body.className ) ) return FCK_TRISTATE_ON ; return FCK_TRISTATE_OFF ; } FCKShowBlockCommand.prototype.SaveState = function() { this._SavedState = this.GetState() ; } FCKShowBlockCommand.prototype.RestoreState = function() { if ( this._SavedState != null && this.GetState() != this._SavedState ) this.Execute() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKCoreStyleCommand Class: controls the execution of a core style. Core * styles are usually represented as buttons in the toolbar., like Bold and * Italic. */ var FCKCoreStyleCommand = function( coreStyleName ) { this.Name = 'CoreStyle' ; this.StyleName = '_FCK_' + coreStyleName ; this.IsActive = false ; FCKStyles.AttachStyleStateChange( this.StyleName, this._OnStyleStateChange, this ) ; } FCKCoreStyleCommand.prototype = { Execute : function() { FCKUndo.SaveUndoStep() ; if ( this.IsActive ) FCKStyles.RemoveStyle( this.StyleName ) ; else FCKStyles.ApplyStyle( this.StyleName ) ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return this.IsActive ? FCK_TRISTATE_ON : FCK_TRISTATE_OFF ; }, _OnStyleStateChange : function( styleName, isActive ) { this.IsActive = isActive ; } };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Stretch the editor to full window size and back. */ var FCKFitWindow = function() { this.Name = 'FitWindow' ; } FCKFitWindow.prototype.Execute = function() { var eEditorFrame = window.frameElement ; var eEditorFrameStyle = eEditorFrame.style ; var eMainWindow = parent ; var eDocEl = eMainWindow.document.documentElement ; var eBody = eMainWindow.document.body ; var eBodyStyle = eBody.style ; var eParent ; // Save the current selection and scroll position. var oRange, oEditorScrollPos ; if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) { oRange = new FCKDomRange( FCK.EditorWindow ) ; oRange.MoveToSelection() ; oEditorScrollPos = FCKTools.GetScrollPosition( FCK.EditorWindow ) ; } else { var eTextarea = FCK.EditingArea.Textarea ; oRange = !FCKBrowserInfo.IsIE && [ eTextarea.selectionStart, eTextarea.selectionEnd ] ; oEditorScrollPos = [ eTextarea.scrollLeft, eTextarea.scrollTop ] ; } // No original style properties known? Go fullscreen. if ( !this.IsMaximized ) { // Registering an event handler when the window gets resized. if( FCKBrowserInfo.IsIE ) eMainWindow.attachEvent( 'onresize', FCKFitWindow_Resize ) ; else eMainWindow.addEventListener( 'resize', FCKFitWindow_Resize, true ) ; // Save the scrollbars position. this._ScrollPos = FCKTools.GetScrollPosition( eMainWindow ) ; // Save and reset the styles for the entire node tree. They could interfere in the result. eParent = eEditorFrame ; // The extra () is to avoid a warning with strict error checking. This is ok. while( (eParent = eParent.parentNode) ) { if ( eParent.nodeType == 1 ) { eParent._fckSavedStyles = FCKTools.SaveStyles( eParent ) ; eParent.style.zIndex = FCKConfig.FloatingPanelsZIndex - 1 ; } } // Hide IE scrollbars (in strict mode). if ( FCKBrowserInfo.IsIE ) { this.documentElementOverflow = eDocEl.style.overflow ; eDocEl.style.overflow = 'hidden' ; eBodyStyle.overflow = 'hidden' ; } else { // Hide the scroolbars in Firefox. eBodyStyle.overflow = 'hidden' ; eBodyStyle.width = '0px' ; eBodyStyle.height = '0px' ; } // Save the IFRAME styles. this._EditorFrameStyles = FCKTools.SaveStyles( eEditorFrame ) ; // Resize. var oViewPaneSize = FCKTools.GetViewPaneSize( eMainWindow ) ; eEditorFrameStyle.position = "absolute"; eEditorFrame.offsetLeft ; // Kludge for Safari 3.1 browser bug, do not remove. See #2066. eEditorFrameStyle.zIndex = FCKConfig.FloatingPanelsZIndex - 1; eEditorFrameStyle.left = "0px"; eEditorFrameStyle.top = "0px"; eEditorFrameStyle.width = oViewPaneSize.Width + "px"; eEditorFrameStyle.height = oViewPaneSize.Height + "px"; // Giving the frame some (huge) borders on his right and bottom // side to hide the background that would otherwise show when the // editor is in fullsize mode and the window is increased in size // not for IE, because IE immediately adapts the editor on resize, // without showing any of the background oddly in firefox, the // editor seems not to fill the whole frame, so just setting the // background of it to white to cover the page laying behind it anyway. if ( !FCKBrowserInfo.IsIE ) { eEditorFrameStyle.borderRight = eEditorFrameStyle.borderBottom = "9999px solid white" ; eEditorFrameStyle.backgroundColor = "white"; } // Scroll to top left. eMainWindow.scrollTo(0, 0); // Is the editor still not on the top left? Let's find out and fix that as well. (Bug #174) var editorPos = FCKTools.GetWindowPosition( eMainWindow, eEditorFrame ) ; if ( editorPos.x != 0 ) eEditorFrameStyle.left = ( -1 * editorPos.x ) + "px" ; if ( editorPos.y != 0 ) eEditorFrameStyle.top = ( -1 * editorPos.y ) + "px" ; this.IsMaximized = true ; } else // Resize to original size. { // Remove the event handler of window resizing. if( FCKBrowserInfo.IsIE ) eMainWindow.detachEvent( "onresize", FCKFitWindow_Resize ) ; else eMainWindow.removeEventListener( "resize", FCKFitWindow_Resize, true ) ; // Restore the CSS position for the entire node tree. eParent = eEditorFrame ; // The extra () is to avoid a warning with strict error checking. This is ok. while( (eParent = eParent.parentNode) ) { if ( eParent._fckSavedStyles ) { FCKTools.RestoreStyles( eParent, eParent._fckSavedStyles ) ; eParent._fckSavedStyles = null ; } } // Restore IE scrollbars if ( FCKBrowserInfo.IsIE ) eDocEl.style.overflow = this.documentElementOverflow ; // Restore original size FCKTools.RestoreStyles( eEditorFrame, this._EditorFrameStyles ) ; // Restore the window scroll position. eMainWindow.scrollTo( this._ScrollPos.X, this._ScrollPos.Y ) ; this.IsMaximized = false ; } FCKToolbarItems.GetItem('FitWindow').RefreshState() ; // It seams that Firefox restarts the editing area when making this changes. // On FF 1.0.x, the area is not anymore editable. On FF 1.5+, the special //configuration, like DisableFFTableHandles and DisableObjectResizing get //lost, so we must reset it. Also, the cursor position and selection are //also lost, even if you comment the following line (MakeEditable). // if ( FCKBrowserInfo.IsGecko10 ) // Initially I thought it was a FF 1.0 only problem. if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) FCK.EditingArea.MakeEditable() ; FCK.Focus() ; // Restore the selection and scroll position of inside the document. if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) { oRange.Select() ; FCK.EditorWindow.scrollTo( oEditorScrollPos.X, oEditorScrollPos.Y ) ; } else { if ( !FCKBrowserInfo.IsIE ) { eTextarea.selectionStart = oRange[0] ; eTextarea.selectionEnd = oRange[1] ; } eTextarea.scrollLeft = oEditorScrollPos[0] ; eTextarea.scrollTop = oEditorScrollPos[1] ; } } FCKFitWindow.prototype.GetState = function() { if ( FCKConfig.ToolbarLocation != 'In' ) return FCK_TRISTATE_DISABLED ; else return ( this.IsMaximized ? FCK_TRISTATE_ON : FCK_TRISTATE_OFF ); } function FCKFitWindow_Resize() { var oViewPaneSize = FCKTools.GetViewPaneSize( parent ) ; var eEditorFrameStyle = window.frameElement.style ; eEditorFrameStyle.width = oViewPaneSize.Width + 'px' ; eEditorFrameStyle.height = oViewPaneSize.Height + 'px' ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKPastePlainTextCommand Class: represents the * "Paste as Plain Text" command. */ var FCKPastePlainTextCommand = function() { this.Name = 'PasteText' ; } FCKPastePlainTextCommand.prototype.Execute = function() { FCK.PasteAsPlainText() ; } FCKPastePlainTextCommand.prototype.GetState = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return FCK_TRISTATE_DISABLED ; return FCK.GetNamedCommandState( 'Paste' ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKStyleCommand Class: represents the "Style" command. */ var FCKStyleCommand = function() {} FCKStyleCommand.prototype = { Name : 'Style', Execute : function( styleName, styleComboItem ) { FCKUndo.SaveUndoStep() ; if ( styleComboItem.Selected ) FCK.Styles.RemoveStyle( styleComboItem.Style ) ; else FCK.Styles.ApplyStyle( styleComboItem.Style ) ; FCKUndo.SaveUndoStep() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || !FCK.EditorDocument ) return FCK_TRISTATE_DISABLED ; if ( FCKSelection.GetType() == 'Control' ) { var el = FCKSelection.GetSelectedElement() ; if ( !el || !FCKStyles.CheckHasObjectStyle( el.nodeName.toLowerCase() ) ) return FCK_TRISTATE_DISABLED ; } return FCK_TRISTATE_OFF ; } };
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKStyle Class: contains a style definition, and all methods to work with * the style in a document. */ /** * @param {Object} styleDesc A "style descriptor" object, containing the raw * style definition in the following format: * '<style name>' : { * Element : '<element name>', * Attributes : { * '<att name>' : '<att value>', * ... * }, * Styles : { * '<style name>' : '<style value>', * ... * }, * Overrides : '<element name>'|{ * Element : '<element name>', * Attributes : { * '<att name>' : '<att value>'|/<att regex>/ * }, * Styles : { * '<style name>' : '<style value>'|/<style regex>/ * }, * } * } */ var FCKStyle = function( styleDesc ) { this.Element = ( styleDesc.Element || 'span' ).toLowerCase() ; this._StyleDesc = styleDesc ; } FCKStyle.prototype = { /** * Get the style type, based on its element name: * - FCK_STYLE_BLOCK (0): Block Style * - FCK_STYLE_INLINE (1): Inline Style * - FCK_STYLE_OBJECT (2): Object Style */ GetType : function() { var type = this.GetType_$ ; if ( type != undefined ) return type ; var elementName = this.Element ; if ( elementName == '#' || FCKListsLib.StyleBlockElements[ elementName ] ) type = FCK_STYLE_BLOCK ; else if ( FCKListsLib.StyleObjectElements[ elementName ] ) type = FCK_STYLE_OBJECT ; else type = FCK_STYLE_INLINE ; return ( this.GetType_$ = type ) ; }, /** * Apply the style to the current selection. */ ApplyToSelection : function( targetWindow ) { // Create a range for the current selection. var range = new FCKDomRange( targetWindow ) ; range.MoveToSelection() ; this.ApplyToRange( range, true ) ; }, /** * Apply the style to a FCKDomRange. */ ApplyToRange : function( range, selectIt, updateRange ) { // ApplyToRange is not valid for FCK_STYLE_OBJECT types. // Use ApplyToObject instead. switch ( this.GetType() ) { case FCK_STYLE_BLOCK : this.ApplyToRange = this._ApplyBlockStyle ; break ; case FCK_STYLE_INLINE : this.ApplyToRange = this._ApplyInlineStyle ; break ; default : return ; } this.ApplyToRange( range, selectIt, updateRange ) ; }, /** * Apply the style to an object. Valid for FCK_STYLE_BLOCK types only. */ ApplyToObject : function( objectElement ) { if ( !objectElement ) return ; this.BuildElement( null, objectElement ) ; }, /** * Remove the style from the current selection. */ RemoveFromSelection : function( targetWindow ) { // Create a range for the current selection. var range = new FCKDomRange( targetWindow ) ; range.MoveToSelection() ; this.RemoveFromRange( range, true ) ; }, /** * Remove the style from a FCKDomRange. Block type styles will have no * effect. */ RemoveFromRange : function( range, selectIt, updateRange ) { var bookmark ; // Create the attribute list to be used later for element comparisons. var styleAttribs = this._GetAttribsForComparison() ; var styleOverrides = this._GetOverridesForComparison() ; // If collapsed, we are removing all conflicting styles from the range // parent tree. if ( range.CheckIsCollapsed() ) { // Bookmark the range so we can re-select it after processing. var bookmark = range.CreateBookmark( true ) ; // Let's start from the bookmark <span> parent. var bookmarkStart = range.GetBookmarkNode( bookmark, true ) ; var path = new FCKElementPath( bookmarkStart.parentNode ) ; // While looping through the path, we'll be saving references to // parent elements if the range is in one of their boundaries. In // this way, we are able to create a copy of those elements when // removing a style if the range is in a boundary limit (see #1270). var boundaryElements = [] ; // Check if the range is in the boundary limits of an element // (related to #1270). var isBoundaryRight = !FCKDomTools.GetNextSibling( bookmarkStart ) ; var isBoundary = isBoundaryRight || !FCKDomTools.GetPreviousSibling( bookmarkStart ) ; // This is the last element to be removed in the boundary situation // described at #1270. var lastBoundaryElement ; var boundaryLimitIndex = -1 ; for ( var i = 0 ; i < path.Elements.length ; i++ ) { var pathElement = path.Elements[i] ; if ( this.CheckElementRemovable( pathElement ) ) { if ( isBoundary && !FCKDomTools.CheckIsEmptyElement( pathElement, function( el ) { return ( el != bookmarkStart ) ; } ) ) { lastBoundaryElement = pathElement ; // We'll be continuously including elements in the // boundaryElements array, but only those added before // setting lastBoundaryElement must be used later, so // let's mark the current index here. boundaryLimitIndex = boundaryElements.length - 1 ; } else { var pathElementName = pathElement.nodeName.toLowerCase() ; if ( pathElementName == this.Element ) { // Remove any attribute that conflict with this style, no // matter their values. for ( var att in styleAttribs ) { if ( FCKDomTools.HasAttribute( pathElement, att ) ) { switch ( att ) { case 'style' : this._RemoveStylesFromElement( pathElement ) ; break ; case 'class' : // The 'class' element value must match (#1318). if ( FCKDomTools.GetAttributeValue( pathElement, att ) != this.GetFinalAttributeValue( att ) ) continue ; /*jsl:fallthru*/ default : FCKDomTools.RemoveAttribute( pathElement, att ) ; } } } } // Remove overrides defined to the same element name. this._RemoveOverrides( pathElement, styleOverrides[ pathElementName ] ) ; // Remove the element if no more attributes are available and it's an inline style element if ( this.GetType() == FCK_STYLE_INLINE) this._RemoveNoAttribElement( pathElement ) ; } } else if ( isBoundary ) boundaryElements.push( pathElement ) ; // Check if we are still in a boundary (at the same side). isBoundary = isBoundary && ( ( isBoundaryRight && !FCKDomTools.GetNextSibling( pathElement ) ) || ( !isBoundaryRight && !FCKDomTools.GetPreviousSibling( pathElement ) ) ) ; // If we are in an element that is not anymore a boundary, or // we are at the last element, let's move things outside the // boundary (if available). if ( lastBoundaryElement && ( !isBoundary || ( i == path.Elements.length - 1 ) ) ) { // Remove the bookmark node from the DOM. var currentElement = FCKDomTools.RemoveNode( bookmarkStart ) ; // Build the collapsed group of elements that are not // removed by this style, but share the boundary. // (see comment 1 and 2 at #1270) for ( var j = 0 ; j <= boundaryLimitIndex ; j++ ) { var newElement = FCKDomTools.CloneElement( boundaryElements[j] ) ; newElement.appendChild( currentElement ) ; currentElement = newElement ; } // Re-insert the bookmark node (and the collapsed elements) // in the DOM, in the new position next to the styled element. if ( isBoundaryRight ) FCKDomTools.InsertAfterNode( lastBoundaryElement, currentElement ) ; else lastBoundaryElement.parentNode.insertBefore( currentElement, lastBoundaryElement ) ; isBoundary = false ; lastBoundaryElement = null ; } } // Re-select the original range. if ( selectIt ) range.SelectBookmark( bookmark ) ; if ( updateRange ) range.MoveToBookmark( bookmark ) ; return ; } // Expand the range, if inside inline element boundaries. range.Expand( 'inline_elements' ) ; // Bookmark the range so we can re-select it after processing. bookmark = range.CreateBookmark( true ) ; // The style will be applied within the bookmark boundaries. var startNode = range.GetBookmarkNode( bookmark, true ) ; var endNode = range.GetBookmarkNode( bookmark, false ) ; range.Release( true ) ; // We need to check the selection boundaries (bookmark spans) to break // the code in a way that we can properly remove partially selected nodes. // For example, removing a <b> style from // <b>This is [some text</b> to show <b>the] problem</b> // ... where [ and ] represent the selection, must result: // <b>This is </b>[some text to show the]<b> problem</b> // The strategy is simple, we just break the partial nodes before the // removal logic, having something that could be represented this way: // <b>This is </b>[<b>some text</b> to show <b>the</b>]<b> problem</b> // Let's start checking the start boundary. var path = new FCKElementPath( startNode ) ; var pathElements = path.Elements ; var pathElement ; for ( var i = 1 ; i < pathElements.length ; i++ ) { pathElement = pathElements[i] ; if ( pathElement == path.Block || pathElement == path.BlockLimit ) break ; // If this element can be removed (even partially). if ( this.CheckElementRemovable( pathElement ) ) FCKDomTools.BreakParent( startNode, pathElement, range ) ; } // Now the end boundary. path = new FCKElementPath( endNode ) ; pathElements = path.Elements ; for ( var i = 1 ; i < pathElements.length ; i++ ) { pathElement = pathElements[i] ; if ( pathElement == path.Block || pathElement == path.BlockLimit ) break ; elementName = pathElement.nodeName.toLowerCase() ; // If this element can be removed (even partially). if ( this.CheckElementRemovable( pathElement ) ) FCKDomTools.BreakParent( endNode, pathElement, range ) ; } // Navigate through all nodes between the bookmarks. var currentNode = FCKDomTools.GetNextSourceNode( startNode, true ) ; while ( currentNode ) { // Cache the next node to be processed. Do it now, because // currentNode may be removed. var nextNode = FCKDomTools.GetNextSourceNode( currentNode ) ; // Remove elements nodes that match with this style rules. if ( currentNode.nodeType == 1 ) { var elementName = currentNode.nodeName.toLowerCase() ; var mayRemove = ( elementName == this.Element ) ; if ( mayRemove ) { // Remove any attribute that conflict with this style, no matter // their values. for ( var att in styleAttribs ) { if ( FCKDomTools.HasAttribute( currentNode, att ) ) { switch ( att ) { case 'style' : this._RemoveStylesFromElement( currentNode ) ; break ; case 'class' : // The 'class' element value must match (#1318). if ( FCKDomTools.GetAttributeValue( currentNode, att ) != this.GetFinalAttributeValue( att ) ) continue ; /*jsl:fallthru*/ default : FCKDomTools.RemoveAttribute( currentNode, att ) ; } } } } else mayRemove = !!styleOverrides[ elementName ] ; if ( mayRemove ) { // Remove overrides defined to the same element name. this._RemoveOverrides( currentNode, styleOverrides[ elementName ] ) ; // Remove the element if no more attributes are available. this._RemoveNoAttribElement( currentNode ) ; } } // If we have reached the end of the selection, stop looping. if ( nextNode == endNode ) break ; currentNode = nextNode ; } this._FixBookmarkStart( startNode ) ; // Re-select the original range. if ( selectIt ) range.SelectBookmark( bookmark ) ; if ( updateRange ) range.MoveToBookmark( bookmark ) ; }, /** * Checks if an element, or any of its attributes, is removable by the * current style definition. */ CheckElementRemovable : function( element, fullMatch ) { if ( !element ) return false ; var elementName = element.nodeName.toLowerCase() ; // If the element name is the same as the style name. if ( elementName == this.Element ) { // If no attributes are defined in the element. if ( !fullMatch && !FCKDomTools.HasAttributes( element ) ) return true ; // If any attribute conflicts with the style attributes. var attribs = this._GetAttribsForComparison() ; var allMatched = ( attribs._length == 0 ) ; for ( var att in attribs ) { if ( att == '_length' ) continue ; if ( this._CompareAttributeValues( att, FCKDomTools.GetAttributeValue( element, att ), ( this.GetFinalAttributeValue( att ) || '' ) ) ) { allMatched = true ; if ( !fullMatch ) break ; } else { allMatched = false ; if ( fullMatch ) return false ; } } if ( allMatched ) return true ; } // Check if the element can be somehow overriden. var override = this._GetOverridesForComparison()[ elementName ] ; if ( override ) { // If no attributes have been defined, remove the element. if ( !( attribs = override.Attributes ) ) // Only one "=" return true ; for ( var i = 0 ; i < attribs.length ; i++ ) { var attName = attribs[i][0] ; if ( FCKDomTools.HasAttribute( element, attName ) ) { var attValue = attribs[i][1] ; // Remove the attribute if: // - The override definition value is null ; // - The override definition valie is a string that // matches the attribute value exactly. // - The override definition value is a regex that // has matches in the attribute value. if ( attValue == null || ( typeof attValue == 'string' && FCKDomTools.GetAttributeValue( element, attName ) == attValue ) || attValue.test( FCKDomTools.GetAttributeValue( element, attName ) ) ) return true ; } } } return false ; }, /** * Get the style state for an element path. Returns "true" if the element * is active in the path. */ CheckActive : function( elementPath ) { switch ( this.GetType() ) { case FCK_STYLE_BLOCK : return this.CheckElementRemovable( elementPath.Block || elementPath.BlockLimit, true ) ; case FCK_STYLE_INLINE : var elements = elementPath.Elements ; for ( var i = 0 ; i < elements.length ; i++ ) { var element = elements[i] ; if ( element == elementPath.Block || element == elementPath.BlockLimit ) continue ; if ( this.CheckElementRemovable( element, true ) ) return true ; } } return false ; }, /** * Removes an inline style from inside an element tree. The element node * itself is not checked or removed, only the child tree inside of it. */ RemoveFromElement : function( element ) { var attribs = this._GetAttribsForComparison() ; var overrides = this._GetOverridesForComparison() ; // Get all elements with the same name. var innerElements = element.getElementsByTagName( this.Element ) ; for ( var i = innerElements.length - 1 ; i >= 0 ; i-- ) { var innerElement = innerElements[i] ; // Remove any attribute that conflict with this style, no matter // their values. for ( var att in attribs ) { if ( FCKDomTools.HasAttribute( innerElement, att ) ) { switch ( att ) { case 'style' : this._RemoveStylesFromElement( innerElement ) ; break ; case 'class' : // The 'class' element value must match (#1318). if ( FCKDomTools.GetAttributeValue( innerElement, att ) != this.GetFinalAttributeValue( att ) ) continue ; /*jsl:fallthru*/ default : FCKDomTools.RemoveAttribute( innerElement, att ) ; } } } // Remove overrides defined to the same element name. this._RemoveOverrides( innerElement, overrides[ this.Element ] ) ; // Remove the element if no more attributes are available. this._RemoveNoAttribElement( innerElement ) ; } // Now remove any other element with different name that is // defined to be overriden. for ( var overrideElement in overrides ) { if ( overrideElement != this.Element ) { // Get all elements. innerElements = element.getElementsByTagName( overrideElement ) ; for ( var i = innerElements.length - 1 ; i >= 0 ; i-- ) { var innerElement = innerElements[i] ; this._RemoveOverrides( innerElement, overrides[ overrideElement ] ) ; this._RemoveNoAttribElement( innerElement ) ; } } } }, _RemoveStylesFromElement : function( element ) { var elementStyle = element.style.cssText ; var pattern = this.GetFinalStyleValue() ; if ( elementStyle.length > 0 && pattern.length == 0 ) return ; pattern = '(^|;)\\s*(' + pattern.replace( /\s*([^ ]+):.*?(;|$)/g, '$1|' ).replace( /\|$/, '' ) + '):[^;]+' ; var regex = new RegExp( pattern, 'gi' ) ; elementStyle = elementStyle.replace( regex, '' ).Trim() ; if ( elementStyle.length == 0 || elementStyle == ';' ) FCKDomTools.RemoveAttribute( element, 'style' ) ; else element.style.cssText = elementStyle.replace( regex, '' ) ; }, /** * Remove all attributes that are defined to be overriden, */ _RemoveOverrides : function( element, override ) { var attributes = override && override.Attributes ; if ( attributes ) { for ( var i = 0 ; i < attributes.length ; i++ ) { var attName = attributes[i][0] ; if ( FCKDomTools.HasAttribute( element, attName ) ) { var attValue = attributes[i][1] ; // Remove the attribute if: // - The override definition value is null ; // - The override definition valie is a string that // matches the attribute value exactly. // - The override definition value is a regex that // has matches in the attribute value. if ( attValue == null || ( attValue.test && attValue.test( FCKDomTools.GetAttributeValue( element, attName ) ) ) || ( typeof attValue == 'string' && FCKDomTools.GetAttributeValue( element, attName ) == attValue ) ) FCKDomTools.RemoveAttribute( element, attName ) ; } } } }, /** * If the element has no more attributes, remove it. */ _RemoveNoAttribElement : function( element ) { // If no more attributes remained in the element, remove it, // leaving its children. if ( !FCKDomTools.HasAttributes( element ) ) { // Removing elements may open points where merging is possible, // so let's cache the first and last nodes for later checking. var firstChild = element.firstChild ; var lastChild = element.lastChild ; FCKDomTools.RemoveNode( element, true ) ; // Check the cached nodes for merging. this._MergeSiblings( firstChild ) ; if ( firstChild != lastChild ) this._MergeSiblings( lastChild ) ; } }, /** * Creates a DOM element for this style object. */ BuildElement : function( targetDoc, element ) { // Create the element. var el = element || targetDoc.createElement( this.Element ) ; // Assign all defined attributes. var attribs = this._StyleDesc.Attributes ; var attValue ; if ( attribs ) { for ( var att in attribs ) { attValue = this.GetFinalAttributeValue( att ) ; if ( att.toLowerCase() == 'class' ) el.className = attValue ; else el.setAttribute( att, attValue ) ; } } // Assign the style attribute. if ( this._GetStyleText().length > 0 ) el.style.cssText = this.GetFinalStyleValue() ; return el ; }, _CompareAttributeValues : function( attName, valueA, valueB ) { if ( attName == 'style' && valueA && valueB ) { valueA = valueA.replace( /;$/, '' ).toLowerCase() ; valueB = valueB.replace( /;$/, '' ).toLowerCase() ; } // Return true if they match or if valueA is null and valueB is an empty string return ( valueA == valueB || ( ( valueA === null || valueA === '' ) && ( valueB === null || valueB === '' ) ) ) }, GetFinalAttributeValue : function( attName ) { var attValue = this._StyleDesc.Attributes ; var attValue = attValue ? attValue[ attName ] : null ; if ( !attValue && attName == 'style' ) return this.GetFinalStyleValue() ; if ( attValue && this._Variables ) // Using custom Replace() to guarantee the correct scope. attValue = attValue.Replace( FCKRegexLib.StyleVariableAttName, this._GetVariableReplace, this ) ; return attValue ; }, GetFinalStyleValue : function() { var attValue = this._GetStyleText() ; if ( attValue.length > 0 && this._Variables ) { // Using custom Replace() to guarantee the correct scope. attValue = attValue.Replace( FCKRegexLib.StyleVariableAttName, this._GetVariableReplace, this ) ; attValue = FCKTools.NormalizeCssText( attValue ) ; } return attValue ; }, _GetVariableReplace : function() { // The second group in the regex is the variable name. return this._Variables[ arguments[2] ] || arguments[0] ; }, /** * Set the value of a variable attribute or style, to be used when * appliying the style. */ SetVariable : function( name, value ) { var variables = this._Variables ; if ( !variables ) variables = this._Variables = {} ; this._Variables[ name ] = value ; }, /** * Converting from a PRE block to a non-PRE block in formatting operations. */ _FromPre : function( doc, block, newBlock ) { var innerHTML = block.innerHTML ; // Trim the first and last linebreaks immediately after and before <pre>, </pre>, // if they exist. // This is done because the linebreaks are not rendered. innerHTML = innerHTML.replace( /(\r\n|\r)/g, '\n' ) ; innerHTML = innerHTML.replace( /^[ \t]*\n/, '' ) ; innerHTML = innerHTML.replace( /\n$/, '' ) ; // 1. Convert spaces or tabs at the beginning or at the end to &nbsp; innerHTML = innerHTML.replace( /^[ \t]+|[ \t]+$/g, function( match, offset, s ) { if ( match.length == 1 ) // one space, preserve it return '&nbsp;' ; else if ( offset == 0 ) // beginning of block return new Array( match.length ).join( '&nbsp;' ) + ' ' ; else // end of block return ' ' + new Array( match.length ).join( '&nbsp;' ) ; } ) ; // 2. Convert \n to <BR>. // 3. Convert contiguous (i.e. non-singular) spaces or tabs to &nbsp; var htmlIterator = new FCKHtmlIterator( innerHTML ) ; var results = [] ; htmlIterator.Each( function( isTag, value ) { if ( !isTag ) { value = value.replace( /\n/g, '<br>' ) ; value = value.replace( /[ \t]{2,}/g, function ( match ) { return new Array( match.length ).join( '&nbsp;' ) + ' ' ; } ) ; } results.push( value ) ; } ) ; newBlock.innerHTML = results.join( '' ) ; return newBlock ; }, /** * Converting from a non-PRE block to a PRE block in formatting operations. */ _ToPre : function( doc, block, newBlock ) { // Handle converting from a regular block to a <pre> block. var innerHTML = block.innerHTML.Trim() ; // 1. Delete ANSI whitespaces immediately before and after <BR> because // they are not visible. // 2. Mark down any <BR /> nodes here so they can be turned into \n in // the next step and avoid being compressed. innerHTML = innerHTML.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '<br />' ) ; // 3. Compress other ANSI whitespaces since they're only visible as one // single space previously. // 4. Convert &nbsp; to spaces since &nbsp; is no longer needed in <PRE>. // 5. Convert any <BR /> to \n. This must not be done earlier because // the \n would then get compressed. var htmlIterator = new FCKHtmlIterator( innerHTML ) ; var results = [] ; htmlIterator.Each( function( isTag, value ) { if ( !isTag ) value = value.replace( /([ \t\n\r]+|&nbsp;)/g, ' ' ) ; else if ( isTag && value == '<br />' ) value = '\n' ; results.push( value ) ; } ) ; // Assigning innerHTML to <PRE> in IE causes all linebreaks to be // reduced to spaces. // Assigning outerHTML to <PRE> in IE doesn't work if the <PRE> isn't // contained in another node since the node reference is changed after // outerHTML assignment. // So, we need some hacks to workaround IE bugs here. if ( FCKBrowserInfo.IsIE ) { var temp = doc.createElement( 'div' ) ; temp.appendChild( newBlock ) ; newBlock.outerHTML = '<pre>\n' + results.join( '' ) + '</pre>' ; newBlock = temp.removeChild( temp.firstChild ) ; } else newBlock.innerHTML = results.join( '' ) ; return newBlock ; }, /** * Merge a <pre> block with a previous <pre> block, if available. */ _CheckAndMergePre : function( previousBlock, preBlock ) { // Check if the previous block and the current block are next // to each other. if ( previousBlock != FCKDomTools.GetPreviousSourceElement( preBlock, true ) ) return ; // Merge the previous <pre> block contents into the current <pre> // block. // // Another thing to be careful here is that currentBlock might contain // a '\n' at the beginning, and previousBlock might contain a '\n' // towards the end. These new lines are not normally displayed but they // become visible after merging. var innerHTML = previousBlock.innerHTML.replace( /\n$/, '' ) + '\n\n' + preBlock.innerHTML.replace( /^\n/, '' ) ; // Buggy IE normalizes innerHTML from <pre>, breaking whitespaces. if ( FCKBrowserInfo.IsIE ) preBlock.outerHTML = '<pre>' + innerHTML + '</pre>' ; else preBlock.innerHTML = innerHTML ; // Remove the previous <pre> block. // // The preBlock must not be moved or deleted from the DOM tree. This // guarantees the FCKDomRangeIterator in _ApplyBlockStyle would not // get lost at the next iteration. FCKDomTools.RemoveNode( previousBlock ) ; }, _CheckAndSplitPre : function( newBlock ) { var lastNewBlock ; var cursor = newBlock.firstChild ; // We are not splitting <br><br> at the beginning of the block, so // we'll start from the second child. cursor = cursor && cursor.nextSibling ; while ( cursor ) { var next = cursor.nextSibling ; // If we have two <BR>s, and they're not at the beginning or the end, // then we'll split up the contents following them into another block. // Stop processing if we are at the last child couple. if ( next && next.nextSibling && cursor.nodeName.IEquals( 'br' ) && next.nodeName.IEquals( 'br' ) ) { // Remove the first <br>. FCKDomTools.RemoveNode( cursor ) ; // Move to the node after the second <br>. cursor = next.nextSibling ; // Remove the second <br>. FCKDomTools.RemoveNode( next ) ; // Create the block that will hold the child nodes from now on. lastNewBlock = FCKDomTools.InsertAfterNode( lastNewBlock || newBlock, FCKDomTools.CloneElement( newBlock ) ) ; continue ; } // If we split it, then start moving the nodes to the new block. if ( lastNewBlock ) { cursor = cursor.previousSibling ; FCKDomTools.MoveNode(cursor.nextSibling, lastNewBlock ) ; } cursor = cursor.nextSibling ; } }, /** * Apply an inline style to a FCKDomRange. * * TODO * - Implement the "#" style handling. * - Properly handle block containers like <div> and <blockquote>. */ _ApplyBlockStyle : function( range, selectIt, updateRange ) { // Bookmark the range so we can re-select it after processing. var bookmark ; if ( selectIt ) bookmark = range.CreateBookmark() ; var iterator = new FCKDomRangeIterator( range ) ; iterator.EnforceRealBlocks = true ; var block ; var doc = range.Window.document ; var previousPreBlock ; while( ( block = iterator.GetNextParagraph() ) ) // Only one = { // Create the new node right before the current one. var newBlock = this.BuildElement( doc ) ; // Check if we are changing from/to <pre>. var newBlockIsPre = newBlock.nodeName.IEquals( 'pre' ) ; var blockIsPre = block.nodeName.IEquals( 'pre' ) ; var toPre = newBlockIsPre && !blockIsPre ; var fromPre = !newBlockIsPre && blockIsPre ; // Move everything from the current node to the new one. if ( toPre ) newBlock = this._ToPre( doc, block, newBlock ) ; else if ( fromPre ) newBlock = this._FromPre( doc, block, newBlock ) ; else // Convering from a regular block to another regular block. FCKDomTools.MoveChildren( block, newBlock ) ; // Replace the current block. block.parentNode.insertBefore( newBlock, block ) ; FCKDomTools.RemoveNode( block ) ; // Complete other tasks after inserting the node in the DOM. if ( newBlockIsPre ) { if ( previousPreBlock ) this._CheckAndMergePre( previousPreBlock, newBlock ) ; // Merge successive <pre> blocks. previousPreBlock = newBlock ; } else if ( fromPre ) this._CheckAndSplitPre( newBlock ) ; // Split <br><br> in successive <pre>s. } // Re-select the original range. if ( selectIt ) range.SelectBookmark( bookmark ) ; if ( updateRange ) range.MoveToBookmark( bookmark ) ; }, /** * Apply an inline style to a FCKDomRange. * * TODO * - Merge elements, when applying styles to similar elements that enclose * the entire selection, outputing: * <span style="color: #ff0000; background-color: #ffffff">XYZ</span> * instead of: * <span style="color: #ff0000;"><span style="background-color: #ffffff">XYZ</span></span> */ _ApplyInlineStyle : function( range, selectIt, updateRange ) { var doc = range.Window.document ; if ( range.CheckIsCollapsed() ) { // Create the element to be inserted in the DOM. var collapsedElement = this.BuildElement( doc ) ; range.InsertNode( collapsedElement ) ; range.MoveToPosition( collapsedElement, 2 ) ; range.Select() ; return ; } // The general idea here is navigating through all nodes inside the // current selection, working on distinct range blocks, defined by the // DTD compatibility between the style element and the nodes inside the // ranges. // // For example, suppose we have the following selection (where [ and ] // are the boundaries), and we apply a <b> style there: // // <p>Here we [have <b>some</b> text.<p> // <p>And some here] here.</p> // // Two different ranges will be detected: // // "have <b>some</b> text." // "And some here" // // Both ranges will be extracted, moved to a <b> element, and // re-inserted, resulting in the following output: // // <p>Here we [<b>have some text.</b><p> // <p><b>And some here</b>] here.</p> // // Note that the <b> element at <b>some</b> is also removed because it // is not needed anymore. var elementName = this.Element ; // Get the DTD definition for the element. Defaults to "span". var elementDTD = FCK.DTD[ elementName ] || FCK.DTD.span ; // Create the attribute list to be used later for element comparisons. var styleAttribs = this._GetAttribsForComparison() ; var styleNode ; // Expand the range, if inside inline element boundaries. range.Expand( 'inline_elements' ) ; // Bookmark the range so we can re-select it after processing. var bookmark = range.CreateBookmark( true ) ; // The style will be applied within the bookmark boundaries. var startNode = range.GetBookmarkNode( bookmark, true ) ; var endNode = range.GetBookmarkNode( bookmark, false ) ; // We'll be reusing the range to apply the styles. So, release it here // to indicate that it has not been initialized. range.Release( true ) ; // Let's start the nodes lookup from the node right after the bookmark // span. var currentNode = FCKDomTools.GetNextSourceNode( startNode, true ) ; while ( currentNode ) { var applyStyle = false ; var nodeType = currentNode.nodeType ; var nodeName = nodeType == 1 ? currentNode.nodeName.toLowerCase() : null ; // Check if the current node can be a child of the style element. if ( !nodeName || elementDTD[ nodeName ] ) { // Check if the style element can be a child of the current // node parent or if the element is not defined in the DTD. if ( ( FCK.DTD[ currentNode.parentNode.nodeName.toLowerCase() ] || FCK.DTD.span )[ elementName ] || !FCK.DTD[ elementName ] ) { // This node will be part of our range, so if it has not // been started, place its start right before the node. if ( !range.CheckHasRange() ) range.SetStart( currentNode, 3 ) ; // Non element nodes, or empty elements can be added // completely to the range. if ( nodeType != 1 || currentNode.childNodes.length == 0 ) { var includedNode = currentNode ; var parentNode = includedNode.parentNode ; // This node is about to be included completelly, but, // if this is the last node in its parent, we must also // check if the parent itself can be added completelly // to the range. while ( includedNode == parentNode.lastChild && elementDTD[ parentNode.nodeName.toLowerCase() ] ) { includedNode = parentNode ; } range.SetEnd( includedNode, 4 ) ; // If the included node is the last node in its parent // and its parent can't be inside the style node, apply // the style immediately. if ( includedNode == includedNode.parentNode.lastChild && !elementDTD[ includedNode.parentNode.nodeName.toLowerCase() ] ) applyStyle = true ; } else { // Element nodes will not be added directly. We need to // check their children because the selection could end // inside the node, so let's place the range end right // before the element. range.SetEnd( currentNode, 3 ) ; } } else applyStyle = true ; } else applyStyle = true ; // Get the next node to be processed. currentNode = FCKDomTools.GetNextSourceNode( currentNode ) ; // If we have reached the end of the selection, just apply the // style ot the range, and stop looping. if ( currentNode == endNode ) { currentNode = null ; applyStyle = true ; } // Apply the style if we have something to which apply it. if ( applyStyle && range.CheckHasRange() && !range.CheckIsCollapsed() ) { // Build the style element, based on the style object definition. styleNode = this.BuildElement( doc ) ; // Move the contents of the range to the style element. range.ExtractContents().AppendTo( styleNode ) ; // If it is not empty. if ( styleNode.innerHTML.RTrim().length > 0 ) { // Insert it in the range position (it is collapsed after // ExtractContents. range.InsertNode( styleNode ) ; // Here we do some cleanup, removing all duplicated // elements from the style element. this.RemoveFromElement( styleNode ) ; // Let's merge our new style with its neighbors, if possible. this._MergeSiblings( styleNode, this._GetAttribsForComparison() ) ; // As the style system breaks text nodes constantly, let's normalize // things for performance. // With IE, some paragraphs get broken when calling normalize() // repeatedly. Also, for IE, we must normalize body, not documentElement. // IE is also known for having a "crash effect" with normalize(). // We should try to normalize with IE too in some way, somewhere. if ( !FCKBrowserInfo.IsIE ) styleNode.normalize() ; } // Style applied, let's release the range, so it gets marked to // re-initialization in the next loop. range.Release( true ) ; } } this._FixBookmarkStart( startNode ) ; // Re-select the original range. if ( selectIt ) range.SelectBookmark( bookmark ) ; if ( updateRange ) range.MoveToBookmark( bookmark ) ; }, _FixBookmarkStart : function( startNode ) { // After appliying or removing an inline style, the start boundary of // the selection must be placed inside all inline elements it is // bordering. var startSibling ; while ( ( startSibling = startNode.nextSibling ) ) // Only one "=". { if ( startSibling.nodeType == 1 && FCKListsLib.InlineNonEmptyElements[ startSibling.nodeName.toLowerCase() ] ) { // If it is an empty inline element, we can safely remove it. if ( !startSibling.firstChild ) FCKDomTools.RemoveNode( startSibling ) ; else FCKDomTools.MoveNode( startNode, startSibling, true ) ; continue ; } // Empty text nodes can be safely removed to not disturb. if ( startSibling.nodeType == 3 && startSibling.length == 0 ) { FCKDomTools.RemoveNode( startSibling ) ; continue ; } break ; } }, /** * Merge an element with its similar siblings. * "attribs" is and object computed with _CreateAttribsForComparison. */ _MergeSiblings : function( element, attribs ) { if ( !element || element.nodeType != 1 || !FCKListsLib.InlineNonEmptyElements[ element.nodeName.toLowerCase() ] ) return ; this._MergeNextSibling( element, attribs ) ; this._MergePreviousSibling( element, attribs ) ; }, /** * Merge an element with its similar siblings after it. * "attribs" is and object computed with _CreateAttribsForComparison. */ _MergeNextSibling : function( element, attribs ) { // Check the next sibling. var sibling = element.nextSibling ; // Check if the next sibling is a bookmark element. In this case, jump it. var hasBookmark = ( sibling && sibling.nodeType == 1 && sibling.getAttribute( '_fck_bookmark' ) ) ; if ( hasBookmark ) sibling = sibling.nextSibling ; if ( sibling && sibling.nodeType == 1 && sibling.nodeName == element.nodeName ) { if ( !attribs ) attribs = this._CreateElementAttribsForComparison( element ) ; if ( this._CheckAttributesMatch( sibling, attribs ) ) { // Save the last child to be checked too (to merge things like <b><i></i></b><b><i></i></b>). var innerSibling = element.lastChild ; if ( hasBookmark ) FCKDomTools.MoveNode( element.nextSibling, element ) ; // Move contents from the sibling. FCKDomTools.MoveChildren( sibling, element ) ; FCKDomTools.RemoveNode( sibling ) ; // Now check the last inner child (see two comments above). if ( innerSibling ) this._MergeNextSibling( innerSibling ) ; } } }, /** * Merge an element with its similar siblings before it. * "attribs" is and object computed with _CreateAttribsForComparison. */ _MergePreviousSibling : function( element, attribs ) { // Check the previous sibling. var sibling = element.previousSibling ; // Check if the previous sibling is a bookmark element. In this case, jump it. var hasBookmark = ( sibling && sibling.nodeType == 1 && sibling.getAttribute( '_fck_bookmark' ) ) ; if ( hasBookmark ) sibling = sibling.previousSibling ; if ( sibling && sibling.nodeType == 1 && sibling.nodeName == element.nodeName ) { if ( !attribs ) attribs = this._CreateElementAttribsForComparison( element ) ; if ( this._CheckAttributesMatch( sibling, attribs ) ) { // Save the first child to be checked too (to merge things like <b><i></i></b><b><i></i></b>). var innerSibling = element.firstChild ; if ( hasBookmark ) FCKDomTools.MoveNode( element.previousSibling, element, true ) ; // Move contents to the sibling. FCKDomTools.MoveChildren( sibling, element, true ) ; FCKDomTools.RemoveNode( sibling ) ; // Now check the first inner child (see two comments above). if ( innerSibling ) this._MergePreviousSibling( innerSibling ) ; } } }, /** * Build the cssText based on the styles definition. */ _GetStyleText : function() { var stylesDef = this._StyleDesc.Styles ; // Builds the StyleText. var stylesText = ( this._StyleDesc.Attributes ? this._StyleDesc.Attributes['style'] || '' : '' ) ; if ( stylesText.length > 0 ) stylesText += ';' ; for ( var style in stylesDef ) stylesText += style + ':' + stylesDef[style] + ';' ; // Browsers make some changes to the style when applying them. So, here // we normalize it to the browser format. We'll not do that if there // are variables inside the style. if ( stylesText.length > 0 && !( /#\(/.test( stylesText ) ) ) { stylesText = FCKTools.NormalizeCssText( stylesText ) ; } return (this._GetStyleText = function() { return stylesText ; })() ; }, /** * Get the the collection used to compare the attributes defined in this * style with attributes in an element. All information in it is lowercased. */ _GetAttribsForComparison : function() { // If we have already computed it, just return it. var attribs = this._GetAttribsForComparison_$ ; if ( attribs ) return attribs ; attribs = new Object() ; // Loop through all defined attributes. var styleAttribs = this._StyleDesc.Attributes ; if ( styleAttribs ) { for ( var styleAtt in styleAttribs ) { attribs[ styleAtt.toLowerCase() ] = styleAttribs[ styleAtt ].toLowerCase() ; } } // Includes the style definitions. if ( this._GetStyleText().length > 0 ) { attribs['style'] = this._GetStyleText().toLowerCase() ; } // Appends the "length" information to the object. FCKTools.AppendLengthProperty( attribs, '_length' ) ; // Return it, saving it to the next request. return ( this._GetAttribsForComparison_$ = attribs ) ; }, /** * Get the the collection used to compare the elements and attributes, * defined in this style overrides, with other element. All information in * it is lowercased. */ _GetOverridesForComparison : function() { // If we have already computed it, just return it. var overrides = this._GetOverridesForComparison_$ ; if ( overrides ) return overrides ; overrides = new Object() ; var overridesDesc = this._StyleDesc.Overrides ; if ( overridesDesc ) { // The override description can be a string, object or array. // Internally, well handle arrays only, so transform it if needed. if ( !FCKTools.IsArray( overridesDesc ) ) overridesDesc = [ overridesDesc ] ; // Loop through all override definitions. for ( var i = 0 ; i < overridesDesc.length ; i++ ) { var override = overridesDesc[i] ; var elementName ; var overrideEl ; var attrs ; // If can be a string with the element name. if ( typeof override == 'string' ) elementName = override.toLowerCase() ; // Or an object. else { elementName = override.Element ? override.Element.toLowerCase() : this.Element ; attrs = override.Attributes ; } // We can have more than one override definition for the same // element name, so we attempt to simply append information to // it if it already exists. overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} ) ; if ( attrs ) { // The returning attributes list is an array, because we // could have different override definitions for the same // attribute name. var overrideAttrs = ( overrideEl.Attributes = overrideEl.Attributes || new Array() ) ; for ( var attName in attrs ) { // Each item in the attributes array is also an array, // where [0] is the attribute name and [1] is the // override value. overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] ) ; } } } } return ( this._GetOverridesForComparison_$ = overrides ) ; }, /* * Create and object containing all attributes specified in an element, * added by a "_length" property. All values are lowercased. */ _CreateElementAttribsForComparison : function( element ) { var attribs = new Object() ; var attribsCount = 0 ; for ( var i = 0 ; i < element.attributes.length ; i++ ) { var att = element.attributes[i] ; if ( att.specified ) { attribs[ att.nodeName.toLowerCase() ] = FCKDomTools.GetAttributeValue( element, att ).toLowerCase() ; attribsCount++ ; } } attribs._length = attribsCount ; return attribs ; }, /** * Checks is the element attributes have a perfect match with the style * attributes. */ _CheckAttributesMatch : function( element, styleAttribs ) { // Loop through all specified attributes. The same number of // attributes must be found and their values must match to // declare them as equal. var elementAttrbs = element.attributes ; var matchCount = 0 ; for ( var i = 0 ; i < elementAttrbs.length ; i++ ) { var att = elementAttrbs[i] ; if ( att.specified ) { var attName = att.nodeName.toLowerCase() ; var styleAtt = styleAttribs[ attName ] ; // The attribute is not defined in the style. if ( !styleAtt ) break ; // The values are different. if ( styleAtt != FCKDomTools.GetAttributeValue( element, att ).toLowerCase() ) break ; matchCount++ ; } } return ( matchCount == styleAttribs._length ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarPanelButton Class: Handles the Fonts combo selector. */ var FCKToolbarFontFormatCombo = function( tooltip, style ) { if ( tooltip === false ) return ; this.CommandName = 'FontFormat' ; this.Label = this.GetLabel() ; this.Tooltip = tooltip ? tooltip : this.Label ; this.Style = style ? style : FCK_TOOLBARITEM_ICONTEXT ; this.NormalLabel = 'Normal' ; this.PanelWidth = 190 ; this.DefaultLabel = FCKConfig.DefaultFontFormatLabel || '' ; } // Inherit from FCKToolbarSpecialCombo. FCKToolbarFontFormatCombo.prototype = new FCKToolbarStyleCombo( false ) ; FCKToolbarFontFormatCombo.prototype.GetLabel = function() { return FCKLang.FontFormat ; } FCKToolbarFontFormatCombo.prototype.GetStyles = function() { var styles = {} ; // Get the format names from the language file. var aNames = FCKLang['FontFormats'].split(';') ; var oNames = { p : aNames[0], pre : aNames[1], address : aNames[2], h1 : aNames[3], h2 : aNames[4], h3 : aNames[5], h4 : aNames[6], h5 : aNames[7], h6 : aNames[8], div : aNames[9] || ( aNames[0] + ' (DIV)') } ; // Get the available formats from the configuration file. var elements = FCKConfig.FontFormats.split(';') ; for ( var i = 0 ; i < elements.length ; i++ ) { var elementName = elements[ i ] ; var style = FCKStyles.GetStyle( '_FCK_' + elementName ) ; if ( style ) { style.Label = oNames[ elementName ] ; styles[ '_FCK_' + elementName ] = style ; } else alert( "The FCKConfig.CoreStyles['" + elementName + "'] setting was not found. Please check the fckconfig.js file" ) ; } return styles ; } FCKToolbarFontFormatCombo.prototype.RefreshActiveItems = function( targetSpecialCombo ) { var startElement = FCK.ToolbarSet.CurrentInstance.Selection.GetBoundaryParentElement( true ) ; if ( startElement ) { var path = new FCKElementPath( startElement ) ; var blockElement = path.Block ; if ( blockElement ) { for ( var i in targetSpecialCombo.Items ) { var item = targetSpecialCombo.Items[i] ; var style = item.Style ; if ( style.CheckElementRemovable( blockElement ) ) { targetSpecialCombo.SetLabel( style.Label ) ; return ; } } } } targetSpecialCombo.SetLabel( this.DefaultLabel ) ; } FCKToolbarFontFormatCombo.prototype.StyleCombo_OnBeforeClick = function( targetSpecialCombo ) { // Clear the current selection. targetSpecialCombo.DeselectAll() ; var startElement = FCK.ToolbarSet.CurrentInstance.Selection.GetBoundaryParentElement( true ) ; if ( startElement ) { var path = new FCKElementPath( startElement ) ; var blockElement = path.Block ; for ( var i in targetSpecialCombo.Items ) { var item = targetSpecialCombo.Items[i] ; var style = item.Style ; if ( style.CheckElementRemovable( blockElement ) ) { targetSpecialCombo.SelectItem( item ) ; return ; } } } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarSpecialCombo Class: This is a "abstract" base class to be used * by the special combo toolbar elements like font name, font size, paragraph format, etc... * * The following properties and methods must be implemented when inheriting from * this class: * - Property: CommandName [ The command name to be executed ] * - Method: GetLabel() [ Returns the label ] * - CreateItems( targetSpecialCombo ) [ Add all items in the special combo ] */ var FCKToolbarSpecialCombo = function() { this.SourceView = false ; this.ContextSensitive = true ; this.FieldWidth = null ; this.PanelWidth = null ; this.PanelMaxHeight = null ; //this._LastValue = null ; } FCKToolbarSpecialCombo.prototype.DefaultLabel = '' ; function FCKToolbarSpecialCombo_OnSelect( itemId, item ) { FCK.ToolbarSet.CurrentInstance.Commands.GetCommand( this.CommandName ).Execute( itemId, item ) ; } FCKToolbarSpecialCombo.prototype.Create = function( targetElement ) { this._Combo = new FCKSpecialCombo( this.GetLabel(), this.FieldWidth, this.PanelWidth, this.PanelMaxHeight, FCKBrowserInfo.IsIE ? window : FCKTools.GetElementWindow( targetElement ).parent ) ; /* this._Combo.FieldWidth = this.FieldWidth != null ? this.FieldWidth : 100 ; this._Combo.PanelWidth = this.PanelWidth != null ? this.PanelWidth : 150 ; this._Combo.PanelMaxHeight = this.PanelMaxHeight != null ? this.PanelMaxHeight : 150 ; */ //this._Combo.Command.Name = this.Command.Name; // this._Combo.Label = this.Label ; this._Combo.Tooltip = this.Tooltip ; this._Combo.Style = this.Style ; this.CreateItems( this._Combo ) ; this._Combo.Create( targetElement ) ; this._Combo.CommandName = this.CommandName ; this._Combo.OnSelect = FCKToolbarSpecialCombo_OnSelect ; } function FCKToolbarSpecialCombo_RefreshActiveItems( combo, value ) { combo.DeselectAll() ; combo.SelectItem( value ) ; combo.SetLabelById( value ) ; } FCKToolbarSpecialCombo.prototype.RefreshState = function() { // Gets the actual state. var eState ; // if ( FCK.EditMode == FCK_EDITMODE_SOURCE && ! this.SourceView ) // eState = FCK_TRISTATE_DISABLED ; // else // { var sValue = FCK.ToolbarSet.CurrentInstance.Commands.GetCommand( this.CommandName ).GetState() ; // FCKDebug.Output( 'RefreshState of Special Combo "' + this.TypeOf + '" - State: ' + sValue ) ; if ( sValue != FCK_TRISTATE_DISABLED ) { eState = FCK_TRISTATE_ON ; if ( this.RefreshActiveItems ) this.RefreshActiveItems( this._Combo, sValue ) ; else { if ( this._LastValue !== sValue) { this._LastValue = sValue ; if ( !sValue || sValue.length == 0 ) { this._Combo.DeselectAll() ; this._Combo.SetLabel( this.DefaultLabel ) ; } else FCKToolbarSpecialCombo_RefreshActiveItems( this._Combo, sValue ) ; } } } else eState = FCK_TRISTATE_DISABLED ; // } // If there are no state changes then do nothing and return. if ( eState == this.State ) return ; if ( eState == FCK_TRISTATE_DISABLED ) { this._Combo.DeselectAll() ; this._Combo.SetLabel( '' ) ; } // Sets the actual state. this.State = eState ; // Updates the graphical state. this._Combo.SetEnabled( eState != FCK_TRISTATE_DISABLED ) ; } FCKToolbarSpecialCombo.prototype.Enable = function() { this.RefreshState() ; } FCKToolbarSpecialCombo.prototype.Disable = function() { this.State = FCK_TRISTATE_DISABLED ; this._Combo.DeselectAll() ; this._Combo.SetLabel( '' ) ; this._Combo.SetEnabled( false ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Component that creates floating panels. It is used by many * other components, like the toolbar items, context menu, etc... */ var FCKPanel = function( parentWindow ) { this.IsRTL = ( FCKLang.Dir == 'rtl' ) ; this.IsContextMenu = false ; this._LockCounter = 0 ; this._Window = parentWindow || window ; var oDocument ; if ( FCKBrowserInfo.IsIE ) { // Create the Popup that will hold the panel. // The popup has to be created before playing with domain hacks, see #1666. this._Popup = this._Window.createPopup() ; // this._Window cannot be accessed while playing with domain hacks, but local variable is ok. // See #1666. var pDoc = this._Window.document ; // This is a trick to IE6 (not IE7). The original domain must be set // before creating the popup, so we are able to take a refence to the // document inside of it, and the set the proper domain for it. (#123) if ( FCK_IS_CUSTOM_DOMAIN && !FCKBrowserInfo.IsIE7 ) { pDoc.domain = FCK_ORIGINAL_DOMAIN ; document.domain = FCK_ORIGINAL_DOMAIN ; } oDocument = this.Document = this._Popup.document ; // Set the proper domain inside the popup. if ( FCK_IS_CUSTOM_DOMAIN ) { oDocument.domain = FCK_RUNTIME_DOMAIN ; pDoc.domain = FCK_RUNTIME_DOMAIN ; document.domain = FCK_RUNTIME_DOMAIN ; } FCK.IECleanup.AddItem( this, FCKPanel_Cleanup ) ; } else { var oIFrame = this._IFrame = this._Window.document.createElement('iframe') ; FCKTools.ResetStyles( oIFrame ); oIFrame.src = 'javascript:void(0)' ; oIFrame.allowTransparency = true ; oIFrame.frameBorder = '0' ; oIFrame.scrolling = 'no' ; oIFrame.style.width = oIFrame.style.height = '0px' ; FCKDomTools.SetElementStyles( oIFrame, { position : 'absolute', zIndex : FCKConfig.FloatingPanelsZIndex } ) ; this._Window.document.body.appendChild( oIFrame ) ; var oIFrameWindow = oIFrame.contentWindow ; oDocument = this.Document = oIFrameWindow.document ; // Workaround for Safari 12256. Ticket #63 var sBase = '' ; if ( FCKBrowserInfo.IsSafari ) sBase = '<base href="' + window.document.location + '">' ; // Initialize the IFRAME document body. oDocument.open() ; oDocument.write( '<html><head>' + sBase + '<\/head><body style="margin:0px;padding:0px;"><\/body><\/html>' ) ; oDocument.close() ; if( FCKBrowserInfo.IsAIR ) FCKAdobeAIR.Panel_Contructor( oDocument, window.document.location ) ; FCKTools.AddEventListenerEx( oIFrameWindow, 'focus', FCKPanel_Window_OnFocus, this ) ; FCKTools.AddEventListenerEx( oIFrameWindow, 'blur', FCKPanel_Window_OnBlur, this ) ; } oDocument.dir = FCKLang.Dir ; FCKTools.AddEventListener( oDocument, 'contextmenu', FCKTools.CancelEvent ) ; // Create the main DIV that is used as the panel base. this.MainNode = oDocument.body.appendChild( oDocument.createElement('DIV') ) ; // The "float" property must be set so Firefox calculates the size correctly. this.MainNode.style.cssFloat = this.IsRTL ? 'right' : 'left' ; } FCKPanel.prototype.AppendStyleSheet = function( styleSheet ) { FCKTools.AppendStyleSheet( this.Document, styleSheet ) ; } FCKPanel.prototype.Preload = function( x, y, relElement ) { // The offsetWidth and offsetHeight properties are not available if the // element is not visible. So we must "show" the popup with no size to // be able to use that values in the second call (IE only). if ( this._Popup ) this._Popup.show( x, y, 0, 0, relElement ) ; } // Workaround for IE7 problem. See #1982 // Submenus are restricted to the size of its parent, so we increase it as needed. // Returns true if the panel has been repositioned FCKPanel.prototype.ResizeForSubpanel = function( panel, width, height ) { if ( !FCKBrowserInfo.IsIE7 ) return false ; if ( !this._Popup.isOpen ) { this.Subpanel = null ; return false ; } // If we are resetting the extra space if ( width == 0 && height == 0 ) { // Another subpanel is being shown, so we must not shrink back if (this.Subpanel !== panel) return false ; // Reset values. // We leave the IncreasedY untouched to avoid vertical movement of the // menu if the submenu is higher than the main menu. this.Subpanel = null ; this.IncreasedX = 0 ; } else { this.Subpanel = panel ; // If the panel has already been increased enough, get out if ( ( this.IncreasedX >= width ) && ( this.IncreasedY >= height ) ) return false ; this.IncreasedX = Math.max( this.IncreasedX, width ) ; this.IncreasedY = Math.max( this.IncreasedY, height ) ; } var x = this.ShowRect.x ; var w = this.IncreasedX ; if ( this.IsRTL ) x = x - w ; // Horizontally increase as needed (sum of widths). // Vertically, use only the maximum of this menu or the submenu var finalWidth = this.ShowRect.w + w ; var finalHeight = Math.max( this.ShowRect.h, this.IncreasedY ) ; if ( this.ParentPanel ) this.ParentPanel.ResizeForSubpanel( this, finalWidth, finalHeight ) ; this._Popup.show( x, this.ShowRect.y, finalWidth, finalHeight, this.RelativeElement ) ; return this.IsRTL ; } FCKPanel.prototype.Show = function( x, y, relElement, width, height ) { var iMainWidth ; var eMainNode = this.MainNode ; if ( this._Popup ) { // The offsetWidth and offsetHeight properties are not available if the // element is not visible. So we must "show" the popup with no size to // be able to use that values in the second call. this._Popup.show( x, y, 0, 0, relElement ) ; // The following lines must be place after the above "show", otherwise it // doesn't has the desired effect. FCKDomTools.SetElementStyles( eMainNode, { width : width ? width + 'px' : '', height : height ? height + 'px' : '' } ) ; iMainWidth = eMainNode.offsetWidth ; if ( FCKBrowserInfo.IsIE7 ) { if (this.ParentPanel && this.ParentPanel.ResizeForSubpanel(this, iMainWidth, eMainNode.offsetHeight) ) { // As the parent has moved, allow the browser to update its internal data, so the new position is correct. FCKTools.RunFunction( this.Show, this, [x, y, relElement] ) ; return ; } } if ( this.IsRTL ) { if ( this.IsContextMenu ) x = x - iMainWidth + 1 ; else if ( relElement ) x = ( x * -1 ) + relElement.offsetWidth - iMainWidth ; } if ( FCKBrowserInfo.IsIE7 ) { // Store the values that will be used by the ResizeForSubpanel function this.ShowRect = {x:x, y:y, w:iMainWidth, h:eMainNode.offsetHeight} ; this.IncreasedX = 0 ; this.IncreasedY = 0 ; this.RelativeElement = relElement ; } // Save the popup related arguments so they can be used by others (e.g. SCAYT). this._PopupArgs = [x, y, iMainWidth, eMainNode.offsetHeight, relElement]; // Second call: Show the Popup at the specified location, with the correct size. this._Popup.show( x, y, iMainWidth, eMainNode.offsetHeight, relElement ) ; if ( this.OnHide ) { if ( this._Timer ) CheckPopupOnHide.call( this, true ) ; this._Timer = FCKTools.SetInterval( CheckPopupOnHide, 100, this ) ; } } else { // Do not fire OnBlur while the panel is opened. if ( typeof( FCK.ToolbarSet.CurrentInstance.FocusManager ) != 'undefined' ) FCK.ToolbarSet.CurrentInstance.FocusManager.Lock() ; if ( this.ParentPanel ) { this.ParentPanel.Lock() ; // Due to a bug on FF3, we must ensure that the parent panel will // blur (#1584). FCKPanel_Window_OnBlur( null, this.ParentPanel ) ; } // Toggle the iframe scrolling attribute to prevent the panel // scrollbars from disappearing in FF Mac. (#191) if ( FCKBrowserInfo.IsGecko && FCKBrowserInfo.IsMac ) { this._IFrame.scrolling = '' ; FCKTools.RunFunction( function(){ this._IFrame.scrolling = 'no'; }, this ) ; } // Be sure we'll not have more than one Panel opened at the same time. // Do not unlock focus manager here because we're displaying another floating panel // instead of returning the editor to a "no panel" state (Bug #1514). if ( FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel && FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel != this ) FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel.Hide( false, true ) ; FCKDomTools.SetElementStyles( eMainNode, { width : width ? width + 'px' : '', height : height ? height + 'px' : '' } ) ; iMainWidth = eMainNode.offsetWidth ; if ( !width ) this._IFrame.width = 1 ; if ( !height ) this._IFrame.height = 1 ; // This is weird... but with Firefox, we must get the offsetWidth before // setting the _IFrame size (which returns "0"), and then after that, // to return the correct width. Remove the first step and it will not // work when the editor is in RTL. // // The "|| eMainNode.firstChild.offsetWidth" part has been added // for Opera compatibility (see #570). iMainWidth = eMainNode.offsetWidth || eMainNode.firstChild.offsetWidth ; // Base the popup coordinates upon the coordinates of relElement. var oPos = FCKTools.GetDocumentPosition( this._Window, relElement.nodeType == 9 ? ( FCKTools.IsStrictMode( relElement ) ? relElement.documentElement : relElement.body ) : relElement ) ; // Minus the offsets provided by any positioned parent element of the panel iframe. var positionedAncestor = FCKDomTools.GetPositionedAncestor( this._IFrame.parentNode ) ; if ( positionedAncestor ) { var nPos = FCKTools.GetDocumentPosition( FCKTools.GetElementWindow( positionedAncestor ), positionedAncestor ) ; oPos.x -= nPos.x ; oPos.y -= nPos.y ; } if ( this.IsRTL && !this.IsContextMenu ) x = ( x * -1 ) ; x += oPos.x ; y += oPos.y ; if ( this.IsRTL ) { if ( this.IsContextMenu ) x = x - iMainWidth + 1 ; else if ( relElement ) x = x + relElement.offsetWidth - iMainWidth ; } else { var oViewPaneSize = FCKTools.GetViewPaneSize( this._Window ) ; var oScrollPosition = FCKTools.GetScrollPosition( this._Window ) ; var iViewPaneHeight = oViewPaneSize.Height + oScrollPosition.Y ; var iViewPaneWidth = oViewPaneSize.Width + oScrollPosition.X ; if ( ( x + iMainWidth ) > iViewPaneWidth ) x -= x + iMainWidth - iViewPaneWidth ; if ( ( y + eMainNode.offsetHeight ) > iViewPaneHeight ) y -= y + eMainNode.offsetHeight - iViewPaneHeight ; } // Set the context menu DIV in the specified location. FCKDomTools.SetElementStyles( this._IFrame, { left : x + 'px', top : y + 'px' } ) ; // Move the focus to the IFRAME so we catch the "onblur". this._IFrame.contentWindow.focus() ; this._IsOpened = true ; var me = this ; this._resizeTimer = setTimeout( function() { var iWidth = eMainNode.offsetWidth || eMainNode.firstChild.offsetWidth ; var iHeight = eMainNode.offsetHeight ; me._IFrame.style.width = iWidth + 'px' ; me._IFrame.style.height = iHeight + 'px' ; }, 0 ) ; FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel = this ; } FCKTools.RunFunction( this.OnShow, this ) ; } FCKPanel.prototype.Hide = function( ignoreOnHide, ignoreFocusManagerUnlock ) { if ( this._Popup ) this._Popup.hide() ; else { if ( !this._IsOpened || this._LockCounter > 0 ) return ; // Enable the editor to fire the "OnBlur". if ( typeof( FCKFocusManager ) != 'undefined' && !ignoreFocusManagerUnlock ) FCKFocusManager.Unlock() ; // It is better to set the sizes to 0, otherwise Firefox would have // rendering problems. this._IFrame.style.width = this._IFrame.style.height = '0px' ; this._IsOpened = false ; if ( this._resizeTimer ) { clearTimeout( this._resizeTimer ) ; this._resizeTimer = null ; } if ( this.ParentPanel ) this.ParentPanel.Unlock() ; if ( !ignoreOnHide ) FCKTools.RunFunction( this.OnHide, this ) ; } } FCKPanel.prototype.CheckIsOpened = function() { if ( this._Popup ) return this._Popup.isOpen ; else return this._IsOpened ; } FCKPanel.prototype.CreateChildPanel = function() { var oWindow = this._Popup ? FCKTools.GetDocumentWindow( this.Document ) : this._Window ; var oChildPanel = new FCKPanel( oWindow ) ; oChildPanel.ParentPanel = this ; return oChildPanel ; } FCKPanel.prototype.Lock = function() { this._LockCounter++ ; } FCKPanel.prototype.Unlock = function() { if ( --this._LockCounter == 0 && !this.HasFocus ) this.Hide() ; } /* Events */ function FCKPanel_Window_OnFocus( e, panel ) { panel.HasFocus = true ; } function FCKPanel_Window_OnBlur( e, panel ) { panel.HasFocus = false ; if ( panel._LockCounter == 0 ) FCKTools.RunFunction( panel.Hide, panel ) ; } function CheckPopupOnHide( forceHide ) { if ( forceHide || !this._Popup.isOpen ) { window.clearInterval( this._Timer ) ; this._Timer = null ; if (this._Popup && this.ParentPanel && !forceHide) this.ParentPanel.ResizeForSubpanel(this, 0, 0) ; FCKTools.RunFunction( this.OnHide, this ) ; } } function FCKPanel_Cleanup() { this._Popup = null ; this._Window = null ; this.Document = null ; this.MainNode = null ; this.RelativeElement = null ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKIECleanup Class: a generic class used as a tool to remove IE leaks. */ var FCKIECleanup = function( attachWindow ) { // If the attachWindow already have a cleanup object, just use that one. if ( attachWindow._FCKCleanupObj ) this.Items = attachWindow._FCKCleanupObj.Items ; else { this.Items = new Array() ; attachWindow._FCKCleanupObj = this ; FCKTools.AddEventListenerEx( attachWindow, 'unload', FCKIECleanup_Cleanup ) ; // attachWindow.attachEvent( 'onunload', FCKIECleanup_Cleanup ) ; } } FCKIECleanup.prototype.AddItem = function( dirtyItem, cleanupFunction ) { this.Items.push( [ dirtyItem, cleanupFunction ] ) ; } function FCKIECleanup_Cleanup() { if ( !this._FCKCleanupObj || ( FCKConfig.MsWebBrowserControlCompat && !window.FCKUnloadFlag ) ) return ; var aItems = this._FCKCleanupObj.Items ; while ( aItems.length > 0 ) { // It is important to remove from the end to the beginning (pop()), // because of the order things get created in the editor. In the code, // elements in deeper position in the DOM are placed at the end of the // cleanup function, so we must cleanup then first, otherwise IE could // throw some crazy memory errors (IE bug). var oItem = aItems.pop() ; if ( oItem ) oItem[1].call( oItem[0] ) ; } this._FCKCleanupObj = null ; if ( CollectGarbage ) CollectGarbage() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarButton Class: represents a button in the toolbar. */ var FCKToolbarButton = function( commandName, label, tooltip, style, sourceView, contextSensitive, icon ) { this.CommandName = commandName ; this.Label = label ; this.Tooltip = tooltip ; this.Style = style ; this.SourceView = sourceView ? true : false ; this.ContextSensitive = contextSensitive ? true : false ; if ( icon == null ) this.IconPath = FCKConfig.SkinPath + 'toolbar/' + commandName.toLowerCase() + '.gif' ; else if ( typeof( icon ) == 'number' ) this.IconPath = [ FCKConfig.SkinPath + 'fck_strip.gif', 16, icon ] ; else this.IconPath = icon ; } FCKToolbarButton.prototype.Create = function( targetElement ) { this._UIButton = new FCKToolbarButtonUI( this.CommandName, this.Label, this.Tooltip, this.IconPath, this.Style ) ; this._UIButton.OnClick = this.Click ; this._UIButton._ToolbarButton = this ; this._UIButton.Create( targetElement ) ; } FCKToolbarButton.prototype.RefreshState = function() { var uiButton = this._UIButton ; if ( !uiButton ) return ; // Gets the actual state. var eState = FCK.ToolbarSet.CurrentInstance.Commands.GetCommand( this.CommandName ).GetState() ; // If there are no state changes than do nothing and return. if ( eState == uiButton.State ) return ; // Sets the actual state. uiButton.ChangeState( eState ) ; } FCKToolbarButton.prototype.Click = function() { var oToolbarButton = this._ToolbarButton || this ; FCK.ToolbarSet.CurrentInstance.Commands.GetCommand( oToolbarButton.CommandName ).Execute() ; } FCKToolbarButton.prototype.Enable = function() { this.RefreshState() ; } FCKToolbarButton.prototype.Disable = function() { // Sets the actual state. this._UIButton.ChangeState( FCK_TRISTATE_DISABLED ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKXml Class: class to load and manipulate XML files. * (IE specific implementation) */ var FCKXml = function() { this.Error = false ; } FCKXml.GetAttribute = function( node, attName, defaultValue ) { var attNode = node.attributes.getNamedItem( attName ) ; return attNode ? attNode.value : defaultValue ; } /** * Transforms a XML element node in a JavaScript object. Attributes defined for * the element will be available as properties, as long as child element * nodes, but the later will generate arrays with property names prefixed with "$". * * For example, the following XML element: * * <SomeNode name="Test" key="2"> * <MyChild id="10"> * <OtherLevel name="Level 3" /> * </MyChild> * <MyChild id="25" /> * <AnotherChild price="499" /> * </SomeNode> * * ... results in the following object: * * { * name : "Test", * key : "2", * $MyChild : * [ * { * id : "10", * $OtherLevel : * { * name : "Level 3" * } * }, * { * id : "25" * } * ], * $AnotherChild : * [ * { * price : "499" * } * ] * } */ FCKXml.TransformToObject = function( element ) { if ( !element ) return null ; var obj = {} ; var attributes = element.attributes ; for ( var i = 0 ; i < attributes.length ; i++ ) { var att = attributes[i] ; obj[ att.name ] = att.value ; } var childNodes = element.childNodes ; for ( i = 0 ; i < childNodes.length ; i++ ) { var child = childNodes[i] ; if ( child.nodeType == 1 ) { var childName = '$' + child.nodeName ; var childList = obj[ childName ] ; if ( !childList ) childList = obj[ childName ] = [] ; childList.push( this.TransformToObject( child ) ) ; } } return obj ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarBreak Class: breaks the toolbars. * It makes it possible to force the toolbar to break to a new line. * This is the IE specific implementation. */ var FCKToolbarBreak = function() {} FCKToolbarBreak.prototype.Create = function( targetElement ) { var oBreakDiv = FCKTools.GetElementDocument( targetElement ).createElement( 'div' ) ; oBreakDiv.className = 'TB_Break' ; oBreakDiv.style.clear = FCKLang.Dir == 'rtl' ? 'left' : 'right' ; targetElement.appendChild( oBreakDiv ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKSpecialCombo Class: represents a special combo. */ var FCKSpecialCombo = function( caption, fieldWidth, panelWidth, panelMaxHeight, parentWindow ) { // Default properties values. this.FieldWidth = fieldWidth || 100 ; this.PanelWidth = panelWidth || 150 ; this.PanelMaxHeight = panelMaxHeight || 150 ; this.Label = '&nbsp;' ; this.Caption = caption ; this.Tooltip = caption ; this.Style = FCK_TOOLBARITEM_ICONTEXT ; this.Enabled = true ; this.Items = new Object() ; this._Panel = new FCKPanel( parentWindow || window ) ; this._Panel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; this._PanelBox = this._Panel.MainNode.appendChild( this._Panel.Document.createElement( 'DIV' ) ) ; this._PanelBox.className = 'SC_Panel' ; this._PanelBox.style.width = this.PanelWidth + 'px' ; this._PanelBox.innerHTML = '<table cellpadding="0" cellspacing="0" width="100%" style="TABLE-LAYOUT: fixed"><tr><td nowrap></td></tr></table>' ; this._ItemsHolderEl = this._PanelBox.getElementsByTagName('TD')[0] ; if ( FCK.IECleanup ) FCK.IECleanup.AddItem( this, FCKSpecialCombo_Cleanup ) ; // this._Panel.StyleSheet = FCKConfig.SkinPath + 'fck_contextmenu.css' ; // this._Panel.Create() ; // this._Panel.PanelDiv.className += ' SC_Panel' ; // this._Panel.PanelDiv.innerHTML = '<table cellpadding="0" cellspacing="0" width="100%" style="TABLE-LAYOUT: fixed"><tr><td nowrap></td></tr></table>' ; // this._ItemsHolderEl = this._Panel.PanelDiv.getElementsByTagName('TD')[0] ; } function FCKSpecialCombo_ItemOnMouseOver() { this.className += ' SC_ItemOver' ; } function FCKSpecialCombo_ItemOnMouseOut() { this.className = this.originalClass ; } function FCKSpecialCombo_ItemOnClick( ev, specialCombo, itemId ) { this.className = this.originalClass ; specialCombo._Panel.Hide() ; specialCombo.SetLabel( this.FCKItemLabel ) ; if ( typeof( specialCombo.OnSelect ) == 'function' ) specialCombo.OnSelect( itemId, this ) ; } FCKSpecialCombo.prototype.ClearItems = function () { if ( this.Items ) this.Items = {} ; var itemsholder = this._ItemsHolderEl ; while ( itemsholder.firstChild ) itemsholder.removeChild( itemsholder.firstChild ) ; } FCKSpecialCombo.prototype.AddItem = function( id, html, label, bgColor ) { // <div class="SC_Item" onmouseover="this.className='SC_Item SC_ItemOver';" onmouseout="this.className='SC_Item';"><b>Bold 1</b></div> var oDiv = this._ItemsHolderEl.appendChild( this._Panel.Document.createElement( 'DIV' ) ) ; oDiv.className = oDiv.originalClass = 'SC_Item' ; oDiv.innerHTML = html ; oDiv.FCKItemLabel = label || id ; oDiv.Selected = false ; // In IE, the width must be set so the borders are shown correctly when the content overflows. if ( FCKBrowserInfo.IsIE ) oDiv.style.width = '100%' ; if ( bgColor ) oDiv.style.backgroundColor = bgColor ; FCKTools.AddEventListenerEx( oDiv, 'mouseover', FCKSpecialCombo_ItemOnMouseOver ) ; FCKTools.AddEventListenerEx( oDiv, 'mouseout', FCKSpecialCombo_ItemOnMouseOut ) ; FCKTools.AddEventListenerEx( oDiv, 'click', FCKSpecialCombo_ItemOnClick, [ this, id ] ) ; this.Items[ id.toString().toLowerCase() ] = oDiv ; return oDiv ; } FCKSpecialCombo.prototype.SelectItem = function( item ) { if ( typeof item == 'string' ) item = this.Items[ item.toString().toLowerCase() ] ; if ( item ) { item.className = item.originalClass = 'SC_ItemSelected' ; item.Selected = true ; } } FCKSpecialCombo.prototype.SelectItemByLabel = function( itemLabel, setLabel ) { for ( var id in this.Items ) { var oDiv = this.Items[id] ; if ( oDiv.FCKItemLabel == itemLabel ) { oDiv.className = oDiv.originalClass = 'SC_ItemSelected' ; oDiv.Selected = true ; if ( setLabel ) this.SetLabel( itemLabel ) ; } } } FCKSpecialCombo.prototype.DeselectAll = function( clearLabel ) { for ( var i in this.Items ) { if ( !this.Items[i] ) continue; this.Items[i].className = this.Items[i].originalClass = 'SC_Item' ; this.Items[i].Selected = false ; } if ( clearLabel ) this.SetLabel( '' ) ; } FCKSpecialCombo.prototype.SetLabelById = function( id ) { id = id ? id.toString().toLowerCase() : '' ; var oDiv = this.Items[ id ] ; this.SetLabel( oDiv ? oDiv.FCKItemLabel : '' ) ; } FCKSpecialCombo.prototype.SetLabel = function( text ) { text = ( !text || text.length == 0 ) ? '&nbsp;' : text ; if ( text == this.Label ) return ; this.Label = text ; var labelEl = this._LabelEl ; if ( labelEl ) { labelEl.innerHTML = text ; // It may happen that the label is some HTML, including tags. This // would be a problem because when the user click on those tags, the // combo will get the selection from the editing area. So we must // disable any kind of selection here. FCKTools.DisableSelection( labelEl ) ; } } FCKSpecialCombo.prototype.SetEnabled = function( isEnabled ) { this.Enabled = isEnabled ; // In IE it can happen when the page is reloaded that _OuterTable is null, so check its existence if ( this._OuterTable ) this._OuterTable.className = isEnabled ? '' : 'SC_FieldDisabled' ; } FCKSpecialCombo.prototype.Create = function( targetElement ) { var oDoc = FCKTools.GetElementDocument( targetElement ) ; var eOuterTable = this._OuterTable = targetElement.appendChild( oDoc.createElement( 'TABLE' ) ) ; eOuterTable.cellPadding = 0 ; eOuterTable.cellSpacing = 0 ; eOuterTable.insertRow(-1) ; var sClass ; var bShowLabel ; switch ( this.Style ) { case FCK_TOOLBARITEM_ONLYICON : sClass = 'TB_ButtonType_Icon' ; bShowLabel = false; break ; case FCK_TOOLBARITEM_ONLYTEXT : sClass = 'TB_ButtonType_Text' ; bShowLabel = false; break ; case FCK_TOOLBARITEM_ICONTEXT : bShowLabel = true; break ; } if ( this.Caption && this.Caption.length > 0 && bShowLabel ) { var oCaptionCell = eOuterTable.rows[0].insertCell(-1) ; oCaptionCell.innerHTML = this.Caption ; oCaptionCell.className = 'SC_FieldCaption' ; } // Create the main DIV element. var oField = FCKTools.AppendElement( eOuterTable.rows[0].insertCell(-1), 'div' ) ; if ( bShowLabel ) { oField.className = 'SC_Field' ; oField.style.width = this.FieldWidth + 'px' ; oField.innerHTML = '<table width="100%" cellpadding="0" cellspacing="0" style="TABLE-LAYOUT: fixed;"><tbody><tr><td class="SC_FieldLabel"><label>&nbsp;</label></td><td class="SC_FieldButton">&nbsp;</td></tr></tbody></table>' ; this._LabelEl = oField.getElementsByTagName('label')[0] ; // Memory Leak this._LabelEl.innerHTML = this.Label ; } else { oField.className = 'TB_Button_Off' ; //oField.innerHTML = '<span className="SC_FieldCaption">' + this.Caption + '<table cellpadding="0" cellspacing="0" style="TABLE-LAYOUT: fixed;"><tbody><tr><td class="SC_FieldButton" style="border-left: none;">&nbsp;</td></tr></tbody></table>' ; //oField.innerHTML = '<table cellpadding="0" cellspacing="0" style="TABLE-LAYOUT: fixed;"><tbody><tr><td class="SC_FieldButton" style="border-left: none;">&nbsp;</td></tr></tbody></table>' ; // Gets the correct CSS class to use for the specified style (param). oField.innerHTML = '<table title="' + this.Tooltip + '" class="' + sClass + '" cellspacing="0" cellpadding="0" border="0">' + '<tr>' + //'<td class="TB_Icon"><img src="' + FCKConfig.SkinPath + 'toolbar/' + this.Command.Name.toLowerCase() + '.gif" width="21" height="21"></td>' + '<td><img class="TB_Button_Padding" src="' + FCK_SPACER_PATH + '" /></td>' + '<td class="TB_Text">' + this.Caption + '</td>' + '<td><img class="TB_Button_Padding" src="' + FCK_SPACER_PATH + '" /></td>' + '<td class="TB_ButtonArrow"><img src="' + FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif" width="5" height="3"></td>' + '<td><img class="TB_Button_Padding" src="' + FCK_SPACER_PATH + '" /></td>' + '</tr>' + '</table>' ; } // Events Handlers FCKTools.AddEventListenerEx( oField, 'mouseover', FCKSpecialCombo_OnMouseOver, this ) ; FCKTools.AddEventListenerEx( oField, 'mouseout', FCKSpecialCombo_OnMouseOut, this ) ; FCKTools.AddEventListenerEx( oField, 'click', FCKSpecialCombo_OnClick, this ) ; FCKTools.DisableSelection( this._Panel.Document.body ) ; } function FCKSpecialCombo_Cleanup() { this._LabelEl = null ; this._OuterTable = null ; this._ItemsHolderEl = null ; this._PanelBox = null ; if ( this.Items ) { for ( var key in this.Items ) this.Items[key] = null ; } } function FCKSpecialCombo_OnMouseOver( ev, specialCombo ) { if ( specialCombo.Enabled ) { switch ( specialCombo.Style ) { case FCK_TOOLBARITEM_ONLYICON : this.className = 'TB_Button_On_Over'; break ; case FCK_TOOLBARITEM_ONLYTEXT : this.className = 'TB_Button_On_Over'; break ; case FCK_TOOLBARITEM_ICONTEXT : this.className = 'SC_Field SC_FieldOver' ; break ; } } } function FCKSpecialCombo_OnMouseOut( ev, specialCombo ) { switch ( specialCombo.Style ) { case FCK_TOOLBARITEM_ONLYICON : this.className = 'TB_Button_Off'; break ; case FCK_TOOLBARITEM_ONLYTEXT : this.className = 'TB_Button_Off'; break ; case FCK_TOOLBARITEM_ICONTEXT : this.className='SC_Field' ; break ; } } function FCKSpecialCombo_OnClick( e, specialCombo ) { // For Mozilla we must stop the event propagation to avoid it hiding // the panel because of a click outside of it. // if ( e ) // { // e.stopPropagation() ; // FCKPanelEventHandlers.OnDocumentClick( e ) ; // } if ( specialCombo.Enabled ) { var oPanel = specialCombo._Panel ; var oPanelBox = specialCombo._PanelBox ; var oItemsHolder = specialCombo._ItemsHolderEl ; var iMaxHeight = specialCombo.PanelMaxHeight ; if ( specialCombo.OnBeforeClick ) specialCombo.OnBeforeClick( specialCombo ) ; // This is a tricky thing. We must call the "Load" function, otherwise // it will not be possible to retrieve "oItemsHolder.offsetHeight" (IE only). if ( FCKBrowserInfo.IsIE ) oPanel.Preload( 0, this.offsetHeight, this ) ; if ( oItemsHolder.offsetHeight > iMaxHeight ) // { oPanelBox.style.height = iMaxHeight + 'px' ; // if ( FCKBrowserInfo.IsGecko ) // oPanelBox.style.overflow = '-moz-scrollbars-vertical' ; // } else oPanelBox.style.height = '' ; // oPanel.PanelDiv.style.width = specialCombo.PanelWidth + 'px' ; oPanel.Show( 0, this.offsetHeight, this ) ; } // return false ; } /* Sample Combo Field HTML output: <div class="SC_Field" style="width: 80px;"> <table width="100%" cellpadding="0" cellspacing="0" style="table-layout: fixed;"> <tbody> <tr> <td class="SC_FieldLabel"><label>&nbsp;</label></td> <td class="SC_FieldButton">&nbsp;</td> </tr> </tbody> </table> </div> */
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 and renders a menu items in a menu block. */ var FCKMenuItem = function( parentMenuBlock, name, label, iconPathOrStripInfoArray, isDisabled, customData ) { this.Name = name ; this.Label = label || name ; this.IsDisabled = isDisabled ; this.Icon = new FCKIcon( iconPathOrStripInfoArray ) ; this.SubMenu = new FCKMenuBlockPanel() ; this.SubMenu.Parent = parentMenuBlock ; this.SubMenu.OnClick = FCKTools.CreateEventListener( FCKMenuItem_SubMenu_OnClick, this ) ; this.CustomData = customData ; if ( FCK.IECleanup ) FCK.IECleanup.AddItem( this, FCKMenuItem_Cleanup ) ; } FCKMenuItem.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) { this.HasSubMenu = true ; return this.SubMenu.AddItem( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) ; } FCKMenuItem.prototype.AddSeparator = function() { this.SubMenu.AddSeparator() ; } FCKMenuItem.prototype.Create = function( parentTable ) { var bHasSubMenu = this.HasSubMenu ; var oDoc = FCKTools.GetElementDocument( parentTable ) ; // Add a row in the table to hold the menu item. var r = this.MainElement = parentTable.insertRow(-1) ; r.className = this.IsDisabled ? 'MN_Item_Disabled' : 'MN_Item' ; // Set the row behavior. if ( !this.IsDisabled ) { FCKTools.AddEventListenerEx( r, 'mouseover', FCKMenuItem_OnMouseOver, [ this ] ) ; FCKTools.AddEventListenerEx( r, 'click', FCKMenuItem_OnClick, [ this ] ) ; if ( !bHasSubMenu ) FCKTools.AddEventListenerEx( r, 'mouseout', FCKMenuItem_OnMouseOut, [ this ] ) ; } // Create the icon cell. var eCell = r.insertCell(-1) ; eCell.className = 'MN_Icon' ; eCell.appendChild( this.Icon.CreateIconElement( oDoc ) ) ; // Create the label cell. eCell = r.insertCell(-1) ; eCell.className = 'MN_Label' ; eCell.noWrap = true ; eCell.appendChild( oDoc.createTextNode( this.Label ) ) ; // Create the arrow cell and setup the sub menu panel (if needed). eCell = r.insertCell(-1) ; if ( bHasSubMenu ) { eCell.className = 'MN_Arrow' ; // The arrow is a fixed size image. var eArrowImg = eCell.appendChild( oDoc.createElement( 'IMG' ) ) ; eArrowImg.src = FCK_IMAGES_PATH + 'arrow_' + FCKLang.Dir + '.gif' ; eArrowImg.width = 4 ; eArrowImg.height = 7 ; this.SubMenu.Create() ; this.SubMenu.Panel.OnHide = FCKTools.CreateEventListener( FCKMenuItem_SubMenu_OnHide, this ) ; } } FCKMenuItem.prototype.Activate = function() { this.MainElement.className = 'MN_Item_Over' ; if ( this.HasSubMenu ) { // Show the child menu block. The ( +2, -2 ) correction is done because // of the padding in the skin. It is not a good solution because one // could change the skin and so the final result would not be accurate. // For now it is ok because we are controlling the skin. this.SubMenu.Show( this.MainElement.offsetWidth + 2, -2, this.MainElement ) ; } FCKTools.RunFunction( this.OnActivate, this ) ; } FCKMenuItem.prototype.Deactivate = function() { this.MainElement.className = 'MN_Item' ; if ( this.HasSubMenu ) this.SubMenu.Hide() ; } /* Events */ function FCKMenuItem_SubMenu_OnClick( clickedItem, listeningItem ) { FCKTools.RunFunction( listeningItem.OnClick, listeningItem, [ clickedItem ] ) ; } function FCKMenuItem_SubMenu_OnHide( menuItem ) { menuItem.Deactivate() ; } function FCKMenuItem_OnClick( ev, menuItem ) { if ( menuItem.HasSubMenu ) menuItem.Activate() ; else { menuItem.Deactivate() ; FCKTools.RunFunction( menuItem.OnClick, menuItem, [ menuItem ] ) ; } } function FCKMenuItem_OnMouseOver( ev, menuItem ) { menuItem.Activate() ; } function FCKMenuItem_OnMouseOut( ev, menuItem ) { menuItem.Deactivate() ; } function FCKMenuItem_Cleanup() { this.MainElement = null ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKEditingArea Class: renders an editable area. */ /** * @constructor * @param {String} targetElement The element that will hold the editing area. Any child element present in the target will be deleted. */ var FCKEditingArea = function( targetElement ) { this.TargetElement = targetElement ; this.Mode = FCK_EDITMODE_WYSIWYG ; if ( FCK.IECleanup ) FCK.IECleanup.AddItem( this, FCKEditingArea_Cleanup ) ; } /** * @param {String} html The complete HTML for the page, including DOCTYPE and the <html> tag. */ FCKEditingArea.prototype.Start = function( html, secondCall ) { var eTargetElement = this.TargetElement ; var oTargetDocument = FCKTools.GetElementDocument( eTargetElement ) ; // Remove all child nodes from the target. while( eTargetElement.firstChild ) eTargetElement.removeChild( eTargetElement.firstChild ) ; if ( this.Mode == FCK_EDITMODE_WYSIWYG ) { // For FF, document.domain must be set only when different, otherwhise // we'll strangely have "Permission denied" issues. if ( FCK_IS_CUSTOM_DOMAIN ) html = '<script>document.domain="' + FCK_RUNTIME_DOMAIN + '";</script>' + html ; // IE has a bug with the <base> tag... it must have a </base> closer, // otherwise the all successive tags will be set as children nodes of the <base>. if ( FCKBrowserInfo.IsIE ) html = html.replace( /(<base[^>]*?)\s*\/?>(?!\s*<\/base>)/gi, '$1></base>' ) ; else if ( !secondCall ) { // Gecko moves some tags out of the body to the head, so we must use // innerHTML to set the body contents (SF BUG 1526154). // Extract the BODY contents from the html. var oMatchBefore = html.match( FCKRegexLib.BeforeBody ) ; var oMatchAfter = html.match( FCKRegexLib.AfterBody ) ; if ( oMatchBefore && oMatchAfter ) { var sBody = html.substr( oMatchBefore[1].length, html.length - oMatchBefore[1].length - oMatchAfter[1].length ) ; // This is the BODY tag contents. html = oMatchBefore[1] + // This is the HTML until the <body...> tag, inclusive. '&nbsp;' + oMatchAfter[1] ; // This is the HTML from the </body> tag, inclusive. // If nothing in the body, place a BOGUS tag so the cursor will appear. if ( FCKBrowserInfo.IsGecko && ( sBody.length == 0 || FCKRegexLib.EmptyParagraph.test( sBody ) ) ) sBody = '<br type="_moz">' ; this._BodyHTML = sBody ; } else this._BodyHTML = html ; // Invalid HTML input. } // Create the editing area IFRAME. var oIFrame = this.IFrame = oTargetDocument.createElement( 'iframe' ) ; // IE: Avoid JavaScript errors thrown by the editing are source (like tags events). // See #1055. var sOverrideError = '<script type="text/javascript" _fcktemp="true">window.onerror=function(){return true;};</script>' ; oIFrame.frameBorder = 0 ; oIFrame.style.width = oIFrame.style.height = '100%' ; if ( FCK_IS_CUSTOM_DOMAIN && FCKBrowserInfo.IsIE ) { window._FCKHtmlToLoad = html.replace( /<head>/i, '<head>' + sOverrideError ) ; oIFrame.src = 'javascript:void( (function(){' + 'document.open() ;' + 'document.domain="' + document.domain + '" ;' + 'document.write( window.parent._FCKHtmlToLoad );' + 'document.close() ;' + 'window.parent._FCKHtmlToLoad = null ;' + '})() )' ; } else if ( !FCKBrowserInfo.IsGecko ) { // Firefox will render the tables inside the body in Quirks mode if the // source of the iframe is set to javascript. see #515 oIFrame.src = 'javascript:void(0)' ; } // Append the new IFRAME to the target. For IE, it must be done after // setting the "src", to avoid the "secure/unsecure" message under HTTPS. eTargetElement.appendChild( oIFrame ) ; // Get the window and document objects used to interact with the newly created IFRAME. this.Window = oIFrame.contentWindow ; // IE: Avoid JavaScript errors thrown by the editing are source (like tags events). // TODO: This error handler is not being fired. // this.Window.onerror = function() { alert( 'Error!' ) ; return true ; } if ( !FCK_IS_CUSTOM_DOMAIN || !FCKBrowserInfo.IsIE ) { var oDoc = this.Window.document ; oDoc.open() ; oDoc.write( html.replace( /<head>/i, '<head>' + sOverrideError ) ) ; oDoc.close() ; } if ( FCKBrowserInfo.IsAIR ) FCKAdobeAIR.EditingArea_Start( oDoc, html ) ; // Firefox 1.0.x is buggy... ohh yes... so let's do it two times and it // will magically work. if ( FCKBrowserInfo.IsGecko10 && !secondCall ) { this.Start( html, true ) ; return ; } if ( oIFrame.readyState && oIFrame.readyState != 'completed' ) { var editArea = this ; // Using a IE alternative for DOMContentLoaded, similar to the // solution proposed at http://javascript.nwbox.com/IEContentLoaded/ setTimeout( function() { try { editArea.Window.document.documentElement.doScroll("left") ; } catch(e) { setTimeout( arguments.callee, 0 ) ; return ; } editArea.Window._FCKEditingArea = editArea ; FCKEditingArea_CompleteStart.call( editArea.Window ) ; }, 0 ) ; } else { this.Window._FCKEditingArea = this ; // FF 1.0.x is buggy... we must wait a lot to enable editing because // sometimes the content simply disappears, for example when pasting // "bla1!<img src='some_url'>!bla2" in the source and then switching // back to design. if ( FCKBrowserInfo.IsGecko10 ) this.Window.setTimeout( FCKEditingArea_CompleteStart, 500 ) ; else FCKEditingArea_CompleteStart.call( this.Window ) ; } } else { var eTextarea = this.Textarea = oTargetDocument.createElement( 'textarea' ) ; eTextarea.className = 'SourceField' ; eTextarea.dir = 'ltr' ; FCKDomTools.SetElementStyles( eTextarea, { width : '100%', height : '100%', border : 'none', resize : 'none', outline : 'none' } ) ; eTargetElement.appendChild( eTextarea ) ; eTextarea.value = html ; // Fire the "OnLoad" event. FCKTools.RunFunction( this.OnLoad ) ; } } // "this" here is FCKEditingArea.Window function FCKEditingArea_CompleteStart() { // On Firefox, the DOM takes a little to become available. So we must wait for it in a loop. if ( !this.document.body ) { this.setTimeout( FCKEditingArea_CompleteStart, 50 ) ; return ; } var oEditorArea = this._FCKEditingArea ; // Save this reference to be re-used later. oEditorArea.Document = oEditorArea.Window.document ; oEditorArea.MakeEditable() ; // Fire the "OnLoad" event. FCKTools.RunFunction( oEditorArea.OnLoad ) ; } FCKEditingArea.prototype.MakeEditable = function() { var oDoc = this.Document ; if ( FCKBrowserInfo.IsIE ) { // Kludge for #141 and #523 oDoc.body.disabled = true ; oDoc.body.contentEditable = true ; oDoc.body.removeAttribute( "disabled" ) ; /* The following commands don't throw errors, but have no effect. oDoc.execCommand( 'AutoDetect', false, false ) ; oDoc.execCommand( 'KeepSelection', false, true ) ; */ } else { try { // Disable Firefox 2 Spell Checker. oDoc.body.spellcheck = ( this.FFSpellChecker !== false ) ; if ( this._BodyHTML ) { oDoc.body.innerHTML = this._BodyHTML ; oDoc.body.offsetLeft ; // Don't remove, this is a hack to fix Opera 9.50, see #2264. this._BodyHTML = null ; } oDoc.designMode = 'on' ; // Tell Gecko (Firefox 1.5+) to enable or not live resizing of objects (by Alfonso Martinez) oDoc.execCommand( 'enableObjectResizing', false, !FCKConfig.DisableObjectResizing ) ; // Disable the standard table editing features of Firefox. oDoc.execCommand( 'enableInlineTableEditing', false, !FCKConfig.DisableFFTableHandles ) ; } catch (e) { // In Firefox if the iframe is initially hidden it can't be set to designMode and it raises an exception // So we set up a DOM Mutation event Listener on the HTML, as it will raise several events when the document is visible again FCKTools.AddEventListener( this.Window.frameElement, 'DOMAttrModified', FCKEditingArea_Document_AttributeNodeModified ) ; } } } // This function processes the notifications of the DOM Mutation event on the document // We use it to know that the document will be ready to be editable again (or we hope so) function FCKEditingArea_Document_AttributeNodeModified( evt ) { var editingArea = evt.currentTarget.contentWindow._FCKEditingArea ; // We want to run our function after the events no longer fire, so we can know that it's a stable situation if ( editingArea._timer ) window.clearTimeout( editingArea._timer ) ; editingArea._timer = FCKTools.SetTimeout( FCKEditingArea_MakeEditableByMutation, 1000, editingArea ) ; } // This function ideally should be called after the document is visible, it does clean up of the // mutation tracking and tries again to make the area editable. function FCKEditingArea_MakeEditableByMutation() { // Clean up delete this._timer ; // Now we don't want to keep on getting this event FCKTools.RemoveEventListener( this.Window.frameElement, 'DOMAttrModified', FCKEditingArea_Document_AttributeNodeModified ) ; // Let's try now to set the editing area editable // If it fails it will set up the Mutation Listener again automatically this.MakeEditable() ; } FCKEditingArea.prototype.Focus = function() { try { if ( this.Mode == FCK_EDITMODE_WYSIWYG ) { if ( FCKBrowserInfo.IsIE ) this._FocusIE() ; else this.Window.focus() ; } else { var oDoc = FCKTools.GetElementDocument( this.Textarea ) ; if ( (!oDoc.hasFocus || oDoc.hasFocus() ) && oDoc.activeElement == this.Textarea ) return ; this.Textarea.focus() ; } } catch(e) {} } FCKEditingArea.prototype._FocusIE = function() { // In IE it can happen that the document is in theory focused but the // active element is outside of it. this.Document.body.setActive() ; this.Window.focus() ; // Kludge for #141... yet more code to workaround IE bugs var range = this.Document.selection.createRange() ; var parentNode = range.parentElement() ; var parentTag = parentNode.nodeName.toLowerCase() ; // Only apply the fix when in a block, and the block is empty. if ( parentNode.childNodes.length > 0 || !( FCKListsLib.BlockElements[parentTag] || FCKListsLib.NonEmptyBlockElements[parentTag] ) ) { return ; } // Force the selection to happen, in this way we guarantee the focus will // be there. range = new FCKDomRange( this.Window ) ; range.MoveToElementEditStart( parentNode ) ; range.Select() ; } function FCKEditingArea_Cleanup() { if ( this.Document ) { // Avoid IE crash if an object is selected on unload #2201 this.Document.selection.empty() ; this.Document.body.innerHTML = "" ; } this.TargetElement = null ; this.IFrame = null ; this.Document = null ; this.Textarea = null ; if ( this.Window ) { this.Window._FCKEditingArea = null ; this.Window = null ; } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Controls the [Enter] keystroke behavior in a document. */ /* * Constructor. * @targetDocument : the target document. * @enterMode : the behavior for the <Enter> keystroke. * May be "p", "div", "br". Default is "p". * @shiftEnterMode : the behavior for the <Shift>+<Enter> keystroke. * May be "p", "div", "br". Defaults to "br". */ var FCKEnterKey = function( targetWindow, enterMode, shiftEnterMode, tabSpaces ) { this.Window = targetWindow ; this.EnterMode = enterMode || 'p' ; this.ShiftEnterMode = shiftEnterMode || 'br' ; // Setup the Keystroke Handler. var oKeystrokeHandler = new FCKKeystrokeHandler( false ) ; oKeystrokeHandler._EnterKey = this ; oKeystrokeHandler.OnKeystroke = FCKEnterKey_OnKeystroke ; oKeystrokeHandler.SetKeystrokes( [ [ 13 , 'Enter' ], [ SHIFT + 13, 'ShiftEnter' ], [ 8 , 'Backspace' ], [ CTRL + 8 , 'CtrlBackspace' ], [ 46 , 'Delete' ] ] ) ; this.TabText = '' ; // Safari by default inserts 4 spaces on TAB, while others make the editor // loose focus. So, we need to handle it here to not include those spaces. if ( tabSpaces > 0 || FCKBrowserInfo.IsSafari ) { while ( tabSpaces-- ) this.TabText += '\xa0' ; oKeystrokeHandler.SetKeystrokes( [ 9, 'Tab' ] ); } oKeystrokeHandler.AttachToElement( targetWindow.document ) ; } function FCKEnterKey_OnKeystroke( keyCombination, keystrokeValue ) { var oEnterKey = this._EnterKey ; try { switch ( keystrokeValue ) { case 'Enter' : return oEnterKey.DoEnter() ; break ; case 'ShiftEnter' : return oEnterKey.DoShiftEnter() ; break ; case 'Backspace' : return oEnterKey.DoBackspace() ; break ; case 'Delete' : return oEnterKey.DoDelete() ; break ; case 'Tab' : return oEnterKey.DoTab() ; break ; case 'CtrlBackspace' : return oEnterKey.DoCtrlBackspace() ; break ; } } catch (e) { // If for any reason we are not able to handle it, go // ahead with the browser default behavior. } return false ; } /* * Executes the <Enter> key behavior. */ FCKEnterKey.prototype.DoEnter = function( mode, hasShift ) { // Save an undo snapshot before doing anything FCKUndo.SaveUndoStep() ; this._HasShift = ( hasShift === true ) ; var parentElement = FCKSelection.GetParentElement() ; var parentPath = new FCKElementPath( parentElement ) ; var sMode = mode || this.EnterMode ; if ( sMode == 'br' || parentPath.Block && parentPath.Block.tagName.toLowerCase() == 'pre' ) return this._ExecuteEnterBr() ; else return this._ExecuteEnterBlock( sMode ) ; } /* * Executes the <Shift>+<Enter> key behavior. */ FCKEnterKey.prototype.DoShiftEnter = function() { return this.DoEnter( this.ShiftEnterMode, true ) ; } /* * Executes the <Backspace> key behavior. */ FCKEnterKey.prototype.DoBackspace = function() { var bCustom = false ; // Get the current selection. var oRange = new FCKDomRange( this.Window ) ; oRange.MoveToSelection() ; // Kludge for #247 if ( FCKBrowserInfo.IsIE && this._CheckIsAllContentsIncluded( oRange, this.Window.document.body ) ) { this._FixIESelectAllBug( oRange ) ; return true ; } var isCollapsed = oRange.CheckIsCollapsed() ; if ( !isCollapsed ) { // Bug #327, Backspace with an img selection would activate the default action in IE. // Let's override that with our logic here. if ( FCKBrowserInfo.IsIE && this.Window.document.selection.type.toLowerCase() == "control" ) { var controls = this.Window.document.selection.createRange() ; for ( var i = controls.length - 1 ; i >= 0 ; i-- ) { var el = controls.item( i ) ; el.parentNode.removeChild( el ) ; } return true ; } return false ; } // On IE, it is better for us handle the deletion if the caret is preceeded // by a <br> (#1383). if ( FCKBrowserInfo.IsIE ) { var previousElement = FCKDomTools.GetPreviousSourceElement( oRange.StartNode, true ) ; if ( previousElement && previousElement.nodeName.toLowerCase() == 'br' ) { // Create a range that starts after the <br> and ends at the // current range position. var testRange = oRange.Clone() ; testRange.SetStart( previousElement, 4 ) ; // If that range is empty, we can proceed cleaning that <br> manually. if ( testRange.CheckIsEmpty() ) { previousElement.parentNode.removeChild( previousElement ) ; return true ; } } } var oStartBlock = oRange.StartBlock ; var oEndBlock = oRange.EndBlock ; // The selection boundaries must be in the same "block limit" element if ( oRange.StartBlockLimit == oRange.EndBlockLimit && oStartBlock && oEndBlock ) { if ( !isCollapsed ) { var bEndOfBlock = oRange.CheckEndOfBlock() ; oRange.DeleteContents() ; if ( oStartBlock != oEndBlock ) { oRange.SetStart(oEndBlock,1) ; oRange.SetEnd(oEndBlock,1) ; // if ( bEndOfBlock ) // oEndBlock.parentNode.removeChild( oEndBlock ) ; } oRange.Select() ; bCustom = ( oStartBlock == oEndBlock ) ; } if ( oRange.CheckStartOfBlock() ) { var oCurrentBlock = oRange.StartBlock ; var ePrevious = FCKDomTools.GetPreviousSourceElement( oCurrentBlock, true, [ 'BODY', oRange.StartBlockLimit.nodeName ], ['UL','OL'] ) ; bCustom = this._ExecuteBackspace( oRange, ePrevious, oCurrentBlock ) ; } else if ( FCKBrowserInfo.IsGeckoLike ) { // Firefox and Opera (#1095) loose the selection when executing // CheckStartOfBlock, so we must reselect. oRange.Select() ; } } oRange.Release() ; return bCustom ; } FCKEnterKey.prototype.DoCtrlBackspace = function() { FCKUndo.SaveUndoStep() ; var oRange = new FCKDomRange( this.Window ) ; oRange.MoveToSelection() ; if ( FCKBrowserInfo.IsIE && this._CheckIsAllContentsIncluded( oRange, this.Window.document.body ) ) { this._FixIESelectAllBug( oRange ) ; return true ; } return false ; } FCKEnterKey.prototype._ExecuteBackspace = function( range, previous, currentBlock ) { var bCustom = false ; // We could be in a nested LI. if ( !previous && currentBlock && currentBlock.nodeName.IEquals( 'LI' ) && currentBlock.parentNode.parentNode.nodeName.IEquals( 'LI' ) ) { this._OutdentWithSelection( currentBlock, range ) ; return true ; } if ( previous && previous.nodeName.IEquals( 'LI' ) ) { var oNestedList = FCKDomTools.GetLastChild( previous, ['UL','OL'] ) ; while ( oNestedList ) { previous = FCKDomTools.GetLastChild( oNestedList, 'LI' ) ; oNestedList = FCKDomTools.GetLastChild( previous, ['UL','OL'] ) ; } } if ( previous && currentBlock ) { // If we are in a LI, and the previous block is not an LI, we must outdent it. if ( currentBlock.nodeName.IEquals( 'LI' ) && !previous.nodeName.IEquals( 'LI' ) ) { this._OutdentWithSelection( currentBlock, range ) ; return true ; } // Take a reference to the parent for post processing cleanup. var oCurrentParent = currentBlock.parentNode ; var sPreviousName = previous.nodeName.toLowerCase() ; if ( FCKListsLib.EmptyElements[ sPreviousName ] != null || sPreviousName == 'table' ) { FCKDomTools.RemoveNode( previous ) ; bCustom = true ; } else { // Remove the current block. FCKDomTools.RemoveNode( currentBlock ) ; // Remove any empty tag left by the block removal. while ( oCurrentParent.innerHTML.Trim().length == 0 ) { var oParent = oCurrentParent.parentNode ; oParent.removeChild( oCurrentParent ) ; oCurrentParent = oParent ; } // Cleanup the previous and the current elements. FCKDomTools.LTrimNode( currentBlock ) ; FCKDomTools.RTrimNode( previous ) ; // Append a space to the previous. // Maybe it is not always desirable... // previous.appendChild( this.Window.document.createTextNode( ' ' ) ) ; // Set the range to the end of the previous element and bookmark it. range.SetStart( previous, 2, true ) ; range.Collapse( true ) ; var oBookmark = range.CreateBookmark( true ) ; // Move the contents of the block to the previous element and delete it. // But for some block types (e.g. table), moving the children to the previous block makes no sense. // So a check is needed. (See #1081) if ( ! currentBlock.tagName.IEquals( [ 'TABLE' ] ) ) FCKDomTools.MoveChildren( currentBlock, previous ) ; // Place the selection at the bookmark. range.SelectBookmark( oBookmark ) ; bCustom = true ; } } return bCustom ; } /* * Executes the <Delete> key behavior. */ FCKEnterKey.prototype.DoDelete = function() { // Save an undo snapshot before doing anything // This is to conform with the behavior seen in MS Word FCKUndo.SaveUndoStep() ; // The <Delete> has the same effect as the <Backspace>, so we have the same // results if we just move to the next block and apply the same <Backspace> logic. var bCustom = false ; // Get the current selection. var oRange = new FCKDomRange( this.Window ) ; oRange.MoveToSelection() ; // Kludge for #247 if ( FCKBrowserInfo.IsIE && this._CheckIsAllContentsIncluded( oRange, this.Window.document.body ) ) { this._FixIESelectAllBug( oRange ) ; return true ; } // There is just one special case for collapsed selections at the end of a block. if ( oRange.CheckIsCollapsed() && oRange.CheckEndOfBlock( FCKBrowserInfo.IsGeckoLike ) ) { var oCurrentBlock = oRange.StartBlock ; var eCurrentCell = FCKTools.GetElementAscensor( oCurrentBlock, 'td' ); var eNext = FCKDomTools.GetNextSourceElement( oCurrentBlock, true, [ oRange.StartBlockLimit.nodeName ], ['UL','OL','TR'], true ) ; // Bug #1323 : if we're in a table cell, and the next node belongs to a different cell, then don't // delete anything. if ( eCurrentCell ) { var eNextCell = FCKTools.GetElementAscensor( eNext, 'td' ); if ( eNextCell != eCurrentCell ) return true ; } bCustom = this._ExecuteBackspace( oRange, oCurrentBlock, eNext ) ; } oRange.Release() ; return bCustom ; } /* * Executes the <Tab> key behavior. */ FCKEnterKey.prototype.DoTab = function() { var oRange = new FCKDomRange( this.Window ); oRange.MoveToSelection() ; // If the user pressed <tab> inside a table, we should give him the default behavior ( moving between cells ) // instead of giving him more non-breaking spaces. (Bug #973) var node = oRange._Range.startContainer ; while ( node ) { if ( node.nodeType == 1 ) { var tagName = node.tagName.toLowerCase() ; if ( tagName == "tr" || tagName == "td" || tagName == "th" || tagName == "tbody" || tagName == "table" ) return false ; else break ; } node = node.parentNode ; } if ( this.TabText ) { oRange.DeleteContents() ; oRange.InsertNode( this.Window.document.createTextNode( this.TabText ) ) ; oRange.Collapse( false ) ; oRange.Select() ; } return true ; } FCKEnterKey.prototype._ExecuteEnterBlock = function( blockTag, range ) { // Get the current selection. var oRange = range || new FCKDomRange( this.Window ) ; var oSplitInfo = oRange.SplitBlock( blockTag ) ; if ( oSplitInfo ) { // Get the current blocks. var ePreviousBlock = oSplitInfo.PreviousBlock ; var eNextBlock = oSplitInfo.NextBlock ; var bIsStartOfBlock = oSplitInfo.WasStartOfBlock ; var bIsEndOfBlock = oSplitInfo.WasEndOfBlock ; // If there is one block under a list item, modify the split so that the list item gets split as well. (Bug #1647) if ( eNextBlock ) { if ( eNextBlock.parentNode.nodeName.IEquals( 'li' ) ) { FCKDomTools.BreakParent( eNextBlock, eNextBlock.parentNode ) ; FCKDomTools.MoveNode( eNextBlock, eNextBlock.nextSibling, true ) ; } } else if ( ePreviousBlock && ePreviousBlock.parentNode.nodeName.IEquals( 'li' ) ) { FCKDomTools.BreakParent( ePreviousBlock, ePreviousBlock.parentNode ) ; oRange.MoveToElementEditStart( ePreviousBlock.nextSibling ); FCKDomTools.MoveNode( ePreviousBlock, ePreviousBlock.previousSibling ) ; } // If we have both the previous and next blocks, it means that the // boundaries were on separated blocks, or none of them where on the // block limits (start/end). if ( !bIsStartOfBlock && !bIsEndOfBlock ) { // If the next block is an <li> with another list tree as the first child // We'll need to append a placeholder or the list item wouldn't be editable. (Bug #1420) if ( eNextBlock.nodeName.IEquals( 'li' ) && eNextBlock.firstChild && eNextBlock.firstChild.nodeName.IEquals( ['ul', 'ol'] ) ) eNextBlock.insertBefore( FCKTools.GetElementDocument( eNextBlock ).createTextNode( '\xa0' ), eNextBlock.firstChild ) ; // Move the selection to the end block. if ( eNextBlock ) oRange.MoveToElementEditStart( eNextBlock ) ; } else { if ( bIsStartOfBlock && bIsEndOfBlock && ePreviousBlock.tagName.toUpperCase() == 'LI' ) { oRange.MoveToElementStart( ePreviousBlock ) ; this._OutdentWithSelection( ePreviousBlock, oRange ) ; oRange.Release() ; return true ; } var eNewBlock ; if ( ePreviousBlock ) { var sPreviousBlockTag = ePreviousBlock.tagName.toUpperCase() ; // If is a header tag, or we are in a Shift+Enter (#77), // create a new block element (later in the code). if ( !this._HasShift && !(/^H[1-6]$/).test( sPreviousBlockTag ) ) { // Otherwise, duplicate the previous block. eNewBlock = FCKDomTools.CloneElement( ePreviousBlock ) ; } } else if ( eNextBlock ) eNewBlock = FCKDomTools.CloneElement( eNextBlock ) ; if ( !eNewBlock ) eNewBlock = this.Window.document.createElement( blockTag ) ; // Recreate the inline elements tree, which was available // before the hitting enter, so the same styles will be // available in the new block. var elementPath = oSplitInfo.ElementPath ; if ( elementPath ) { for ( var i = 0, len = elementPath.Elements.length ; i < len ; i++ ) { var element = elementPath.Elements[i] ; if ( element == elementPath.Block || element == elementPath.BlockLimit ) break ; if ( FCKListsLib.InlineChildReqElements[ element.nodeName.toLowerCase() ] ) { element = FCKDomTools.CloneElement( element ) ; FCKDomTools.MoveChildren( eNewBlock, element ) ; eNewBlock.appendChild( element ) ; } } } if ( FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( eNewBlock ) ; oRange.InsertNode( eNewBlock ) ; // This is tricky, but to make the new block visible correctly // we must select it. if ( FCKBrowserInfo.IsIE ) { // Move the selection to the new block. oRange.MoveToElementEditStart( eNewBlock ) ; oRange.Select() ; } // Move the selection to the new block. oRange.MoveToElementEditStart( bIsStartOfBlock && !bIsEndOfBlock ? eNextBlock : eNewBlock ) ; } if ( FCKBrowserInfo.IsGeckoLike ) { if ( eNextBlock ) { // If we have split the block, adds a temporary span at the // range position and scroll relatively to it. var tmpNode = this.Window.document.createElement( 'span' ) ; // We need some content for Safari. tmpNode.innerHTML = '&nbsp;'; oRange.InsertNode( tmpNode ) ; FCKDomTools.ScrollIntoView( tmpNode, false ) ; oRange.DeleteContents() ; } else { // We may use the above scroll logic for the new block case // too, but it gives some weird result with Opera. FCKDomTools.ScrollIntoView( eNextBlock || eNewBlock, false ) ; } } oRange.Select() ; } // Release the resources used by the range. oRange.Release() ; return true ; } FCKEnterKey.prototype._ExecuteEnterBr = function( blockTag ) { // Get the current selection. var oRange = new FCKDomRange( this.Window ) ; oRange.MoveToSelection() ; // The selection boundaries must be in the same "block limit" element. if ( oRange.StartBlockLimit == oRange.EndBlockLimit ) { oRange.DeleteContents() ; // Get the new selection (it is collapsed at this point). oRange.MoveToSelection() ; var bIsStartOfBlock = oRange.CheckStartOfBlock() ; var bIsEndOfBlock = oRange.CheckEndOfBlock() ; var sStartBlockTag = oRange.StartBlock ? oRange.StartBlock.tagName.toUpperCase() : '' ; var bHasShift = this._HasShift ; var bIsPre = false ; if ( !bHasShift && sStartBlockTag == 'LI' ) return this._ExecuteEnterBlock( null, oRange ) ; // If we are at the end of a header block. if ( !bHasShift && bIsEndOfBlock && (/^H[1-6]$/).test( sStartBlockTag ) ) { // Insert a BR after the current paragraph. FCKDomTools.InsertAfterNode( oRange.StartBlock, this.Window.document.createElement( 'br' ) ) ; // The space is required by Gecko only to make the cursor blink. if ( FCKBrowserInfo.IsGecko ) FCKDomTools.InsertAfterNode( oRange.StartBlock, this.Window.document.createTextNode( '' ) ) ; // IE and Gecko have different behaviors regarding the position. oRange.SetStart( oRange.StartBlock.nextSibling, FCKBrowserInfo.IsIE ? 3 : 1 ) ; } else { var eLineBreak ; bIsPre = sStartBlockTag.IEquals( 'pre' ) ; if ( bIsPre ) eLineBreak = this.Window.document.createTextNode( FCKBrowserInfo.IsIE ? '\r' : '\n' ) ; else eLineBreak = this.Window.document.createElement( 'br' ) ; oRange.InsertNode( eLineBreak ) ; // The space is required by Gecko only to make the cursor blink. if ( FCKBrowserInfo.IsGecko ) FCKDomTools.InsertAfterNode( eLineBreak, this.Window.document.createTextNode( '' ) ) ; // If we are at the end of a block, we must be sure the bogus node is available in that block. if ( bIsEndOfBlock && FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( eLineBreak.parentNode ) ; if ( FCKBrowserInfo.IsIE ) oRange.SetStart( eLineBreak, 4 ) ; else oRange.SetStart( eLineBreak.nextSibling, 1 ) ; if ( ! FCKBrowserInfo.IsIE ) { var dummy = null ; if ( FCKBrowserInfo.IsOpera ) dummy = this.Window.document.createElement( 'span' ) ; else dummy = this.Window.document.createElement( 'br' ) ; eLineBreak.parentNode.insertBefore( dummy, eLineBreak.nextSibling ) ; FCKDomTools.ScrollIntoView( dummy, false ) ; dummy.parentNode.removeChild( dummy ) ; } } // This collapse guarantees the cursor will be blinking. oRange.Collapse( true ) ; oRange.Select( bIsPre ) ; } // Release the resources used by the range. oRange.Release() ; return true ; } // Outdents a LI, maintaining the selection defined on a range. FCKEnterKey.prototype._OutdentWithSelection = function( li, range ) { var oBookmark = range.CreateBookmark() ; FCKListHandler.OutdentListItem( li ) ; range.MoveToBookmark( oBookmark ) ; range.Select() ; } // Is all the contents under a node included by a range? FCKEnterKey.prototype._CheckIsAllContentsIncluded = function( range, node ) { var startOk = false ; var endOk = false ; /* FCKDebug.Output( 'sc='+range.StartContainer.nodeName+ ',so='+range._Range.startOffset+ ',ec='+range.EndContainer.nodeName+ ',eo='+range._Range.endOffset ) ; */ if ( range.StartContainer == node || range.StartContainer == node.firstChild ) startOk = ( range._Range.startOffset == 0 ) ; if ( range.EndContainer == node || range.EndContainer == node.lastChild ) { var nodeLength = range.EndContainer.nodeType == 3 ? range.EndContainer.length : range.EndContainer.childNodes.length ; endOk = ( range._Range.endOffset == nodeLength ) ; } return startOk && endOk ; } // Kludge for #247 FCKEnterKey.prototype._FixIESelectAllBug = function( range ) { var doc = this.Window.document ; doc.body.innerHTML = '' ; var editBlock ; if ( FCKConfig.EnterMode.IEquals( ['div', 'p'] ) ) { editBlock = doc.createElement( FCKConfig.EnterMode ) ; doc.body.appendChild( editBlock ) ; } else editBlock = doc.body ; range.MoveToNodeContents( editBlock ) ; range.Collapse( true ) ; range.Select() ; range.Release() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Manages the DOM ascensors element list of a specific DOM node * (limited to body, inclusive). */ var FCKElementPath = function( lastNode ) { var eBlock = null ; var eBlockLimit = null ; var aElements = new Array() ; var e = lastNode ; while ( e ) { if ( e.nodeType == 1 ) { if ( !this.LastElement ) this.LastElement = e ; var sElementName = e.nodeName.toLowerCase() ; if ( FCKBrowserInfo.IsIE && e.scopeName != 'HTML' ) sElementName = e.scopeName.toLowerCase() + ':' + sElementName ; if ( !eBlockLimit ) { if ( !eBlock && FCKListsLib.PathBlockElements[ sElementName ] != null ) eBlock = e ; if ( FCKListsLib.PathBlockLimitElements[ sElementName ] != null ) { // DIV is considered the Block, if no block is available (#525) // and if it doesn't contain other blocks. if ( !eBlock && sElementName == 'div' && !FCKElementPath._CheckHasBlock( e ) ) eBlock = e ; else eBlockLimit = e ; } } aElements.push( e ) ; if ( sElementName == 'body' ) break ; } e = e.parentNode ; } this.Block = eBlock ; this.BlockLimit = eBlockLimit ; this.Elements = aElements ; } /** * Check if an element contains any block element. */ FCKElementPath._CheckHasBlock = function( element ) { var childNodes = element.childNodes ; for ( var i = 0, count = childNodes.length ; i < count ; i++ ) { var child = childNodes[i] ; if ( child.nodeType == 1 && FCKListsLib.BlockElements[ child.nodeName.toLowerCase() ] ) return true ; } return false ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarPanelButton Class: represents a special button in the toolbar * that shows a panel when pressed. */ var FCKToolbarPanelButton = function( commandName, label, tooltip, style, icon ) { this.CommandName = commandName ; var oIcon ; if ( icon == null ) oIcon = FCKConfig.SkinPath + 'toolbar/' + commandName.toLowerCase() + '.gif' ; else if ( typeof( icon ) == 'number' ) oIcon = [ FCKConfig.SkinPath + 'fck_strip.gif', 16, icon ] ; var oUIButton = this._UIButton = new FCKToolbarButtonUI( commandName, label, tooltip, oIcon, style ) ; oUIButton._FCKToolbarPanelButton = this ; oUIButton.ShowArrow = true ; oUIButton.OnClick = FCKToolbarPanelButton_OnButtonClick ; } FCKToolbarPanelButton.prototype.TypeName = 'FCKToolbarPanelButton' ; FCKToolbarPanelButton.prototype.Create = function( parentElement ) { parentElement.className += 'Menu' ; this._UIButton.Create( parentElement ) ; var oPanel = FCK.ToolbarSet.CurrentInstance.Commands.GetCommand( this.CommandName )._Panel ; this.RegisterPanel( oPanel ) ; } FCKToolbarPanelButton.prototype.RegisterPanel = function( oPanel ) { if ( oPanel._FCKToolbarPanelButton ) return ; oPanel._FCKToolbarPanelButton = this ; var eLineDiv = oPanel.Document.body.appendChild( oPanel.Document.createElement( 'div' ) ) ; eLineDiv.style.position = 'absolute' ; eLineDiv.style.top = '0px' ; var eLine = oPanel._FCKToolbarPanelButtonLineDiv = eLineDiv.appendChild( oPanel.Document.createElement( 'IMG' ) ) ; eLine.className = 'TB_ConnectionLine' ; eLine.style.position = 'absolute' ; // eLine.style.backgroundColor = 'Red' ; eLine.src = FCK_SPACER_PATH ; oPanel.OnHide = FCKToolbarPanelButton_OnPanelHide ; } /* Events */ function FCKToolbarPanelButton_OnButtonClick( toolbarButton ) { var oButton = this._FCKToolbarPanelButton ; var e = oButton._UIButton.MainElement ; oButton._UIButton.ChangeState( FCK_TRISTATE_ON ) ; // oButton.LineImg.style.width = ( e.offsetWidth - 2 ) + 'px' ; var oCommand = FCK.ToolbarSet.CurrentInstance.Commands.GetCommand( oButton.CommandName ) ; var oPanel = oCommand._Panel ; oPanel._FCKToolbarPanelButtonLineDiv.style.width = ( e.offsetWidth - 2 ) + 'px' ; oCommand.Execute( 0, e.offsetHeight - 1, e ) ; // -1 to be over the border } function FCKToolbarPanelButton_OnPanelHide() { var oMenuButton = this._FCKToolbarPanelButton ; oMenuButton._UIButton.ChangeState( FCK_TRISTATE_OFF ) ; } // The Panel Button works like a normal button so the refresh state functions // defined for the normal button can be reused here. FCKToolbarPanelButton.prototype.RefreshState = FCKToolbarButton.prototype.RefreshState ; FCKToolbarPanelButton.prototype.Enable = FCKToolbarButton.prototype.Enable ; FCKToolbarPanelButton.prototype.Disable = FCKToolbarButton.prototype.Disable ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKXml Class: class to load and manipulate XML files. * (IE specific implementation) */ FCKXml.prototype = { LoadUrl : function( urlToCall ) { this.Error = false ; var oXmlHttp = FCKTools.CreateXmlObject( 'XmlHttp' ) ; if ( !oXmlHttp ) { this.Error = true ; return ; } oXmlHttp.open( "GET", urlToCall, false ) ; oXmlHttp.send( null ) ; if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 || ( oXmlHttp.status == 0 && oXmlHttp.readyState == 4 ) ) { this.DOMDocument = oXmlHttp.responseXML ; // #1426: Fallback if responseXML isn't set for some // reason (e.g. improperly configured web server) if ( !this.DOMDocument || this.DOMDocument.firstChild == null ) { this.DOMDocument = FCKTools.CreateXmlObject( 'DOMDocument' ) ; this.DOMDocument.async = false ; this.DOMDocument.resolveExternals = false ; this.DOMDocument.loadXML( oXmlHttp.responseText ) ; } } else { this.DOMDocument = null ; } if ( this.DOMDocument == null || this.DOMDocument.firstChild == null ) { this.Error = true ; if (window.confirm( 'Error loading "' + urlToCall + '"\r\nDo you want to see more info?' ) ) alert( 'URL requested: "' + urlToCall + '"\r\n' + 'Server response:\r\nStatus: ' + oXmlHttp.status + '\r\n' + 'Response text:\r\n' + oXmlHttp.responseText ) ; } }, SelectNodes : function( xpath, contextNode ) { if ( this.Error ) return new Array() ; if ( contextNode ) return contextNode.selectNodes( xpath ) ; else return this.DOMDocument.selectNodes( xpath ) ; }, SelectSingleNode : function( xpath, contextNode ) { if ( this.Error ) return null ; if ( contextNode ) return contextNode.selectSingleNode( xpath ) ; else return this.DOMDocument.selectSingleNode( xpath ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 generic Document Fragment object. It is not intended to provide * the W3C implementation, but is a way to fix the missing of a real Document * Fragment in IE (where document.createDocumentFragment() returns a normal * document instead), giving a standard interface for it. * (IE Implementation) */ var FCKDocumentFragment = function( parentDocument, baseDocFrag ) { this.RootNode = baseDocFrag || parentDocument.createDocumentFragment() ; } FCKDocumentFragment.prototype = { // Append the contents of this Document Fragment to another element. AppendTo : function( targetNode ) { targetNode.appendChild( this.RootNode ) ; }, AppendHtml : function( html ) { var eTmpDiv = this.RootNode.ownerDocument.createElement( 'div' ) ; eTmpDiv.innerHTML = html ; FCKDomTools.MoveChildren( eTmpDiv, this.RootNode ) ; }, InsertAfterNode : function( existingNode ) { FCKDomTools.InsertAfterNode( existingNode, this.RootNode ) ; } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Control keyboard keystroke combinations. */ var FCKKeystrokeHandler = function( cancelCtrlDefaults ) { this.Keystrokes = new Object() ; this.CancelCtrlDefaults = ( cancelCtrlDefaults !== false ) ; } /* * Listen to keystroke events in an element or DOM document object. * @target: The element or document to listen to keystroke events. */ FCKKeystrokeHandler.prototype.AttachToElement = function( target ) { // For newer browsers, it is enough to listen to the keydown event only. // Some browsers instead, don't cancel key events in the keydown, but in the // keypress. So we must do a longer trip in those cases. FCKTools.AddEventListenerEx( target, 'keydown', _FCKKeystrokeHandler_OnKeyDown, this ) ; if ( FCKBrowserInfo.IsGecko10 || FCKBrowserInfo.IsOpera || ( FCKBrowserInfo.IsGecko && FCKBrowserInfo.IsMac ) ) FCKTools.AddEventListenerEx( target, 'keypress', _FCKKeystrokeHandler_OnKeyPress, this ) ; } /* * Sets a list of keystrokes. It can receive either a single array or "n" * arguments, each one being an array of 1 or 2 elemenst. The first element * is the keystroke combination, and the second is the value to assign to it. * If the second element is missing, the keystroke definition is removed. */ FCKKeystrokeHandler.prototype.SetKeystrokes = function() { // Look through the arguments. for ( var i = 0 ; i < arguments.length ; i++ ) { var keyDef = arguments[i] ; // If the configuration for the keystrokes is missing some element or has any extra comma // this item won't be valid, so skip it and keep on processing. if ( !keyDef ) continue ; if ( typeof( keyDef[0] ) == 'object' ) // It is an array with arrays defining the keystrokes. this.SetKeystrokes.apply( this, keyDef ) ; else { if ( keyDef.length == 1 ) // If it has only one element, remove the keystroke. delete this.Keystrokes[ keyDef[0] ] ; else // Otherwise add it. this.Keystrokes[ keyDef[0] ] = keyDef[1] === true ? true : keyDef ; } } } function _FCKKeystrokeHandler_OnKeyDown( ev, keystrokeHandler ) { // Get the key code. var keystroke = ev.keyCode || ev.which ; // Combine it with the CTRL, SHIFT and ALT states. var keyModifiers = 0 ; if ( ev.ctrlKey || ev.metaKey ) keyModifiers += CTRL ; if ( ev.shiftKey ) keyModifiers += SHIFT ; if ( ev.altKey ) keyModifiers += ALT ; var keyCombination = keystroke + keyModifiers ; var cancelIt = keystrokeHandler._CancelIt = false ; // Look for its definition availability. var keystrokeValue = keystrokeHandler.Keystrokes[ keyCombination ] ; // FCKDebug.Output( 'KeyDown: ' + keyCombination + ' - Value: ' + keystrokeValue ) ; // If the keystroke is defined if ( keystrokeValue ) { // If the keystroke has been explicitly set to "true" OR calling the // "OnKeystroke" event, it doesn't return "true", the default behavior // must be preserved. if ( keystrokeValue === true || !( keystrokeHandler.OnKeystroke && keystrokeHandler.OnKeystroke.apply( keystrokeHandler, keystrokeValue ) ) ) return true ; cancelIt = true ; } // By default, it will cancel all combinations with the CTRL key only (except positioning keys). if ( cancelIt || ( keystrokeHandler.CancelCtrlDefaults && keyModifiers == CTRL && ( keystroke < 33 || keystroke > 40 ) ) ) { keystrokeHandler._CancelIt = true ; if ( ev.preventDefault ) return ev.preventDefault() ; ev.returnValue = false ; ev.cancelBubble = true ; return false ; } return true ; } function _FCKKeystrokeHandler_OnKeyPress( ev, keystrokeHandler ) { if ( keystrokeHandler._CancelIt ) { // FCKDebug.Output( 'KeyPress Cancel', 'Red') ; if ( ev.preventDefault ) return ev.preventDefault() ; return false ; } return true ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 class can be used to interate through nodes inside a range. * * During interation, the provided range can become invalid, due to document * mutations, so CreateBookmark() used to restore it after processing, if * needed. */ var FCKDomRangeIterator = function( range ) { /** * The FCKDomRange object that marks the interation boundaries. */ this.Range = range ; /** * Indicates that <br> elements must be used as paragraph boundaries. */ this.ForceBrBreak = false ; /** * Guarantees that the iterator will always return "real" block elements. * If "false", elements like <li>, <th> and <td> are returned. If "true", a * dedicated block element block element will be created inside those * elements to hold the selected content. */ this.EnforceRealBlocks = false ; } FCKDomRangeIterator.CreateFromSelection = function( targetWindow ) { var range = new FCKDomRange( targetWindow ) ; range.MoveToSelection() ; return new FCKDomRangeIterator( range ) ; } FCKDomRangeIterator.prototype = { /** * Get the next paragraph element. It automatically breaks the document * when necessary to generate block elements for the paragraphs. */ GetNextParagraph : function() { // The block element to be returned. var block ; // The range object used to identify the paragraph contents. var range ; // Indicated that the current element in the loop is the last one. var isLast ; // Instructs to cleanup remaining BRs. var removePreviousBr ; var removeLastBr ; var boundarySet = this.ForceBrBreak ? FCKListsLib.ListBoundaries : FCKListsLib.BlockBoundaries ; // This is the first iteration. Let's initialize it. if ( !this._LastNode ) { var range = this.Range.Clone() ; range.Expand( this.ForceBrBreak ? 'list_contents' : 'block_contents' ) ; this._NextNode = range.GetTouchedStartNode() ; this._LastNode = range.GetTouchedEndNode() ; // Let's reuse this variable. range = null ; } var currentNode = this._NextNode ; var lastNode = this._LastNode ; this._NextNode = null ; while ( currentNode ) { // closeRange indicates that a paragraph boundary has been found, // so the range can be closed. var closeRange = false ; // includeNode indicates that the current node is good to be part // of the range. By default, any non-element node is ok for it. var includeNode = ( currentNode.nodeType != 1 ) ; var continueFromSibling = false ; // If it is an element node, let's check if it can be part of the // range. if ( !includeNode ) { var nodeName = currentNode.nodeName.toLowerCase() ; if ( boundarySet[ nodeName ] && ( !FCKBrowserInfo.IsIE || currentNode.scopeName == 'HTML' ) ) { // <br> boundaries must be part of the range. It will // happen only if ForceBrBreak. if ( nodeName == 'br' ) includeNode = true ; else if ( !range && currentNode.childNodes.length == 0 && nodeName != 'hr' ) { // If we have found an empty block, and haven't started // the range yet, it means we must return this block. block = currentNode ; isLast = currentNode == lastNode ; break ; } // The range must finish right before the boundary, // including possibly skipped empty spaces. (#1603) if ( range ) { range.SetEnd( currentNode, 3, true ) ; // The found boundary must be set as the next one at this // point. (#1717) if ( nodeName != 'br' ) this._NextNode = FCKDomTools.GetNextSourceNode( currentNode, true, null, lastNode ) || currentNode ; } closeRange = true ; } else { // If we have child nodes, let's check them. if ( currentNode.firstChild ) { // If we don't have a range yet, let's start it. if ( !range ) { range = new FCKDomRange( this.Range.Window ) ; range.SetStart( currentNode, 3, true ) ; } currentNode = currentNode.firstChild ; continue ; } includeNode = true ; } } else if ( currentNode.nodeType == 3 ) { // Ignore normal whitespaces (i.e. not including &nbsp; or // other unicode whitespaces) before/after a block node. if ( /^[\r\n\t ]+$/.test( currentNode.nodeValue ) ) includeNode = false ; } // The current node is good to be part of the range and we are // starting a new range, initialize it first. if ( includeNode && !range ) { range = new FCKDomRange( this.Range.Window ) ; range.SetStart( currentNode, 3, true ) ; } // The last node has been found. isLast = ( ( !closeRange || includeNode ) && currentNode == lastNode ) ; // isLast = ( currentNode == lastNode && ( currentNode.nodeType != 1 || currentNode.childNodes.length == 0 ) ) ; // If we are in an element boundary, let's check if it is time // to close the range, otherwise we include the parent within it. if ( range && !closeRange ) { while ( !currentNode.nextSibling && !isLast ) { var parentNode = currentNode.parentNode ; if ( boundarySet[ parentNode.nodeName.toLowerCase() ] ) { closeRange = true ; isLast = isLast || ( parentNode == lastNode ) ; break ; } currentNode = parentNode ; includeNode = true ; isLast = ( currentNode == lastNode ) ; continueFromSibling = true ; } } // Now finally include the node. if ( includeNode ) range.SetEnd( currentNode, 4, true ) ; // We have found a block boundary. Let's close the range and move out of the // loop. if ( ( closeRange || isLast ) && range ) { range._UpdateElementInfo() ; if ( range.StartNode == range.EndNode && range.StartNode.parentNode == range.StartBlockLimit && range.StartNode.getAttribute && range.StartNode.getAttribute( '_fck_bookmark' ) ) range = null ; else break ; } if ( isLast ) break ; currentNode = FCKDomTools.GetNextSourceNode( currentNode, continueFromSibling, null, lastNode ) ; } // Now, based on the processed range, look for (or create) the block to be returned. if ( !block ) { // If no range has been found, this is the end. if ( !range ) { this._NextNode = null ; return null ; } block = range.StartBlock ; if ( !block && !this.EnforceRealBlocks && range.StartBlockLimit.nodeName.IEquals( 'DIV', 'TH', 'TD' ) && range.CheckStartOfBlock() && range.CheckEndOfBlock() ) { block = range.StartBlockLimit ; } else if ( !block || ( this.EnforceRealBlocks && block.nodeName.toLowerCase() == 'li' ) ) { // Create the fixed block. block = this.Range.Window.document.createElement( FCKConfig.EnterMode == 'p' ? 'p' : 'div' ) ; // Move the contents of the temporary range to the fixed block. range.ExtractContents().AppendTo( block ) ; FCKDomTools.TrimNode( block ) ; // Insert the fixed block into the DOM. range.InsertNode( block ) ; removePreviousBr = true ; removeLastBr = true ; } else if ( block.nodeName.toLowerCase() != 'li' ) { // If the range doesn't includes the entire contents of the // block, we must split it, isolating the range in a dedicated // block. if ( !range.CheckStartOfBlock() || !range.CheckEndOfBlock() ) { // The resulting block will be a clone of the current one. block = block.cloneNode( false ) ; // Extract the range contents, moving it to the new block. range.ExtractContents().AppendTo( block ) ; FCKDomTools.TrimNode( block ) ; // Split the block. At this point, the range will be in the // right position for our intents. var splitInfo = range.SplitBlock() ; removePreviousBr = !splitInfo.WasStartOfBlock ; removeLastBr = !splitInfo.WasEndOfBlock ; // Insert the new block into the DOM. range.InsertNode( block ) ; } } else if ( !isLast ) { // LIs are returned as is, with all their children (due to the // nested lists). But, the next node is the node right after // the current range, which could be an <li> child (nested // lists) or the next sibling <li>. this._NextNode = block == lastNode ? null : FCKDomTools.GetNextSourceNode( range.EndNode, true, null, lastNode ) ; return block ; } } if ( removePreviousBr ) { var previousSibling = block.previousSibling ; if ( previousSibling && previousSibling.nodeType == 1 ) { if ( previousSibling.nodeName.toLowerCase() == 'br' ) previousSibling.parentNode.removeChild( previousSibling ) ; else if ( previousSibling.lastChild && previousSibling.lastChild.nodeName.IEquals( 'br' ) ) previousSibling.removeChild( previousSibling.lastChild ) ; } } if ( removeLastBr ) { var lastChild = block.lastChild ; if ( lastChild && lastChild.nodeType == 1 && lastChild.nodeName.toLowerCase() == 'br' ) block.removeChild( lastChild ) ; } // Get a reference for the next element. This is important because the // above block can be removed or changed, so we can rely on it for the // next interation. if ( !this._NextNode ) this._NextNode = ( isLast || block == lastNode ) ? null : FCKDomTools.GetNextSourceNode( block, true, null, lastNode ) ; return block ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKXml Class: class to load and manipulate XML files. */ FCKXml.prototype = { LoadUrl : function( urlToCall ) { this.Error = false ; var oXml ; var oXmlHttp = FCKTools.CreateXmlObject( 'XmlHttp' ) ; oXmlHttp.open( 'GET', urlToCall, false ) ; oXmlHttp.send( null ) ; if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 || ( oXmlHttp.status == 0 && oXmlHttp.readyState == 4 ) ) { oXml = oXmlHttp.responseXML ; // #1426: Fallback if responseXML isn't set for some // reason (e.g. improperly configured web server) if ( !oXml ) oXml = (new DOMParser()).parseFromString( oXmlHttp.responseText, 'text/xml' ) ; } else oXml = null ; if ( oXml ) { // Try to access something on it. try { var test = oXml.firstChild ; } catch (e) { // If document.domain has been changed (#123), we'll have a security // error at this point. The workaround here is parsing the responseText: // http://alexander.kirk.at/2006/07/27/firefox-15-xmlhttprequest-reqresponsexml-and-documentdomain/ oXml = (new DOMParser()).parseFromString( oXmlHttp.responseText, 'text/xml' ) ; } } if ( !oXml || !oXml.firstChild ) { this.Error = true ; if ( window.confirm( 'Error loading "' + urlToCall + '" (HTTP Status: ' + oXmlHttp.status + ').\r\nDo you want to see the server response dump?' ) ) alert( oXmlHttp.responseText ) ; } this.DOMDocument = oXml ; }, SelectNodes : function( xpath, contextNode ) { if ( this.Error ) return new Array() ; var aNodeArray = new Array(); var xPathResult = this.DOMDocument.evaluate( xpath, contextNode ? contextNode : 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 ; }, SelectSingleNode : function( xpath, contextNode ) { if ( this.Error ) return null ; var xPathResult = this.DOMDocument.evaluate( xpath, contextNode ? contextNode : 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-2010 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 == * * FCKToolbarPanelButton Class: Handles the Fonts combo selector. */ var FCKToolbarStyleCombo = function( tooltip, style ) { if ( tooltip === false ) return ; this.CommandName = 'Style' ; this.Label = this.GetLabel() ; this.Tooltip = tooltip ? tooltip : this.Label ; this.Style = style ? style : FCK_TOOLBARITEM_ICONTEXT ; this.DefaultLabel = FCKConfig.DefaultStyleLabel || '' ; } // Inherit from FCKToolbarSpecialCombo. FCKToolbarStyleCombo.prototype = new FCKToolbarSpecialCombo ; FCKToolbarStyleCombo.prototype.GetLabel = function() { return FCKLang.Style ; } FCKToolbarStyleCombo.prototype.GetStyles = function() { var styles = {} ; var allStyles = FCK.ToolbarSet.CurrentInstance.Styles.GetStyles() ; for ( var styleName in allStyles ) { var style = allStyles[ styleName ] ; if ( !style.IsCore ) styles[ styleName ] = style ; } return styles ; } FCKToolbarStyleCombo.prototype.CreateItems = function( targetSpecialCombo ) { var targetDoc = targetSpecialCombo._Panel.Document ; // Add the Editor Area CSS to the panel so the style classes are previewed correctly. FCKTools.AppendStyleSheet( targetDoc, FCKConfig.ToolbarComboPreviewCSS ) ; FCKTools.AppendStyleString( targetDoc, FCKConfig.EditorAreaStyles ) ; targetDoc.body.className += ' ForceBaseFont' ; // Add ID and Class to the body. FCKConfig.ApplyBodyAttributes( targetDoc.body ) ; // Get the styles list. var styles = this.GetStyles() ; for ( var styleName in styles ) { var style = styles[ styleName ] ; // Object type styles have no preview. var caption = style.GetType() == FCK_STYLE_OBJECT ? styleName : FCKToolbarStyleCombo_BuildPreview( style, style.Label || styleName ) ; var item = targetSpecialCombo.AddItem( styleName, caption ) ; item.Style = style ; } // We must prepare the list before showing it. targetSpecialCombo.OnBeforeClick = this.StyleCombo_OnBeforeClick ; } FCKToolbarStyleCombo.prototype.RefreshActiveItems = function( targetSpecialCombo ) { var startElement = FCK.ToolbarSet.CurrentInstance.Selection.GetBoundaryParentElement( true ) ; if ( startElement ) { var path = new FCKElementPath( startElement ) ; var elements = path.Elements ; for ( var e = 0 ; e < elements.length ; e++ ) { for ( var i in targetSpecialCombo.Items ) { var item = targetSpecialCombo.Items[i] ; var style = item.Style ; if ( style.CheckElementRemovable( elements[ e ], true ) ) { targetSpecialCombo.SetLabel( style.Label || style.Name ) ; return ; } } } } targetSpecialCombo.SetLabel( this.DefaultLabel ) ; } FCKToolbarStyleCombo.prototype.StyleCombo_OnBeforeClick = function( targetSpecialCombo ) { // Two things are done here: // - In a control selection, get the element name, so we'll display styles // for that element only. // - Select the styles that are active for the current selection. // Clear the current selection. targetSpecialCombo.DeselectAll() ; var startElement ; var path ; var tagName ; var selection = FCK.ToolbarSet.CurrentInstance.Selection ; if ( selection.GetType() == 'Control' ) { startElement = selection.GetSelectedElement() ; tagName = startElement.nodeName.toLowerCase() ; } else { startElement = selection.GetBoundaryParentElement( true ) ; path = new FCKElementPath( startElement ) ; } for ( var i in targetSpecialCombo.Items ) { var item = targetSpecialCombo.Items[i] ; var style = item.Style ; if ( ( tagName && style.Element == tagName ) || ( !tagName && style.GetType() != FCK_STYLE_OBJECT ) ) { item.style.display = '' ; if ( ( path && style.CheckActive( path ) ) || ( !path && style.CheckElementRemovable( startElement, true ) ) ) targetSpecialCombo.SelectItem( style.Name ) ; } else item.style.display = 'none' ; } } function FCKToolbarStyleCombo_BuildPreview( style, caption ) { var styleType = style.GetType() ; var html = [] ; if ( styleType == FCK_STYLE_BLOCK ) html.push( '<div class="BaseFont">' ) ; var elementName = style.Element ; // Avoid <bdo> in the preview. if ( elementName == 'bdo' ) elementName = 'span' ; html = [ '<', elementName ] ; // Assign all defined attributes. var attribs = style._StyleDesc.Attributes ; if ( attribs ) { for ( var att in attribs ) { html.push( ' ', att, '="', style.GetFinalAttributeValue( att ), '"' ) ; } } // Assign the style attribute. if ( style._GetStyleText().length > 0 ) html.push( ' style="', style.GetFinalStyleValue(), '"' ) ; html.push( '>', caption, '</', elementName, '>' ) ; if ( styleType == FCK_STYLE_BLOCK ) html.push( '</div>' ) ; return html.join( '' ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarButtonUI Class: interface representation of a toolbar button. */ var FCKToolbarButtonUI = function( name, label, tooltip, iconPathOrStripInfoArray, style, state ) { this.Name = name ; this.Label = label || name ; this.Tooltip = tooltip || this.Label ; this.Style = style || FCK_TOOLBARITEM_ONLYICON ; this.State = state || FCK_TRISTATE_OFF ; this.Icon = new FCKIcon( iconPathOrStripInfoArray ) ; if ( FCK.IECleanup ) FCK.IECleanup.AddItem( this, FCKToolbarButtonUI_Cleanup ) ; } FCKToolbarButtonUI.prototype._CreatePaddingElement = function( document ) { var oImg = document.createElement( 'IMG' ) ; oImg.className = 'TB_Button_Padding' ; oImg.src = FCK_SPACER_PATH ; return oImg ; } FCKToolbarButtonUI.prototype.Create = function( parentElement ) { var oDoc = FCKTools.GetElementDocument( parentElement ) ; // Create the Main Element. var oMainElement = this.MainElement = oDoc.createElement( 'DIV' ) ; oMainElement.title = this.Tooltip ; // The following will prevent the button from catching the focus. if ( FCKBrowserInfo.IsGecko ) oMainElement.onmousedown = FCKTools.CancelEvent ; FCKTools.AddEventListenerEx( oMainElement, 'mouseover', FCKToolbarButtonUI_OnMouseOver, this ) ; FCKTools.AddEventListenerEx( oMainElement, 'mouseout', FCKToolbarButtonUI_OnMouseOut, this ) ; FCKTools.AddEventListenerEx( oMainElement, 'click', FCKToolbarButtonUI_OnClick, this ) ; this.ChangeState( this.State, true ) ; if ( this.Style == FCK_TOOLBARITEM_ONLYICON && !this.ShowArrow ) { // <td><div class="TB_Button_On" title="Smiley">{Image}</div></td> oMainElement.appendChild( this.Icon.CreateIconElement( oDoc ) ) ; } else { // <td><div class="TB_Button_On" title="Smiley"><table cellpadding="0" cellspacing="0"><tr><td>{Image}</td><td nowrap>Toolbar Button</td><td><img class="TB_Button_Padding"></td></tr></table></div></td> // <td><div class="TB_Button_On" title="Smiley"><table cellpadding="0" cellspacing="0"><tr><td><img class="TB_Button_Padding"></td><td nowrap>Toolbar Button</td><td><img class="TB_Button_Padding"></td></tr></table></div></td> var oTable = oMainElement.appendChild( oDoc.createElement( 'TABLE' ) ) ; oTable.cellPadding = 0 ; oTable.cellSpacing = 0 ; var oRow = oTable.insertRow(-1) ; // The Image cell (icon or padding). var oCell = oRow.insertCell(-1) ; if ( this.Style == FCK_TOOLBARITEM_ONLYICON || this.Style == FCK_TOOLBARITEM_ICONTEXT ) oCell.appendChild( this.Icon.CreateIconElement( oDoc ) ) ; else oCell.appendChild( this._CreatePaddingElement( oDoc ) ) ; if ( this.Style == FCK_TOOLBARITEM_ONLYTEXT || this.Style == FCK_TOOLBARITEM_ICONTEXT ) { // The Text cell. oCell = oRow.insertCell(-1) ; oCell.className = 'TB_Button_Text' ; oCell.noWrap = true ; oCell.appendChild( oDoc.createTextNode( this.Label ) ) ; } if ( this.ShowArrow ) { if ( this.Style != FCK_TOOLBARITEM_ONLYICON ) { // A padding cell. oRow.insertCell(-1).appendChild( this._CreatePaddingElement( oDoc ) ) ; } oCell = oRow.insertCell(-1) ; var eImg = oCell.appendChild( oDoc.createElement( 'IMG' ) ) ; eImg.src = FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ; eImg.width = 5 ; eImg.height = 3 ; } // The last padding cell. oCell = oRow.insertCell(-1) ; oCell.appendChild( this._CreatePaddingElement( oDoc ) ) ; } parentElement.appendChild( oMainElement ) ; } FCKToolbarButtonUI.prototype.ChangeState = function( newState, force ) { if ( !force && this.State == newState ) return ; var e = this.MainElement ; // In IE it can happen when the page is reloaded that MainElement is null, so exit here if ( !e ) return ; switch ( parseInt( newState, 10 ) ) { case FCK_TRISTATE_OFF : e.className = 'TB_Button_Off' ; break ; case FCK_TRISTATE_ON : e.className = 'TB_Button_On' ; break ; case FCK_TRISTATE_DISABLED : e.className = 'TB_Button_Disabled' ; break ; } this.State = newState ; } function FCKToolbarButtonUI_OnMouseOver( ev, button ) { if ( button.State == FCK_TRISTATE_OFF ) this.className = 'TB_Button_Off_Over' ; else if ( button.State == FCK_TRISTATE_ON ) this.className = 'TB_Button_On_Over' ; } function FCKToolbarButtonUI_OnMouseOut( ev, button ) { if ( button.State == FCK_TRISTATE_OFF ) this.className = 'TB_Button_Off' ; else if ( button.State == FCK_TRISTATE_ON ) this.className = 'TB_Button_On' ; } function FCKToolbarButtonUI_OnClick( ev, button ) { if ( button.OnClick && button.State != FCK_TRISTATE_DISABLED ) button.OnClick( button ) ; } function FCKToolbarButtonUI_Cleanup() { // This one should not cause memory leak, but just for safety, let's clean // it up. this.MainElement = null ; } /* Sample outputs: This is the base structure. The variation is the image that is marked as {Image}: <td><div class="TB_Button_On" title="Smiley">{Image}</div></td> <td><div class="TB_Button_On" title="Smiley"><table cellpadding="0" cellspacing="0"><tr><td>{Image}</td><td nowrap>Toolbar Button</td><td><img class="TB_Button_Padding"></td></tr></table></div></td> <td><div class="TB_Button_On" title="Smiley"><table cellpadding="0" cellspacing="0"><tr><td><img class="TB_Button_Padding"></td><td nowrap>Toolbar Button</td><td><img class="TB_Button_Padding"></td></tr></table></div></td> These are samples of possible {Image} values: Strip - IE version: <div class="TB_Button_Image"><img src="strip.gif" style="top:-16px"></div> Strip : Firefox, Safari and Opera version <img class="TB_Button_Image" style="background-position: 0px -16px;background-image: url(strip.gif);"> No-Strip : Browser independent: <img class="TB_Button_Image" src="smiley.gif"> */
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKContextMenu Class: renders an control a context menu. */ var FCKContextMenu = function( parentWindow, langDir ) { this.CtrlDisable = false ; var oPanel = this._Panel = new FCKPanel( parentWindow ) ; oPanel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; oPanel.IsContextMenu = true ; // The FCKTools.DisableSelection doesn't seems to work to avoid dragging of the icons in Mozilla // so we stop the start of the dragging if ( FCKBrowserInfo.IsGecko ) oPanel.Document.addEventListener( 'draggesture', function(e) {e.preventDefault(); return false;}, true ) ; var oMenuBlock = this._MenuBlock = new FCKMenuBlock() ; oMenuBlock.Panel = oPanel ; oMenuBlock.OnClick = FCKTools.CreateEventListener( FCKContextMenu_MenuBlock_OnClick, this ) ; this._Redraw = true ; } FCKContextMenu.prototype.SetMouseClickWindow = function( mouseClickWindow ) { if ( !FCKBrowserInfo.IsIE ) { this._Document = mouseClickWindow.document ; if ( FCKBrowserInfo.IsOpera && !( 'oncontextmenu' in document.createElement('foo') ) ) { this._Document.addEventListener( 'mousedown', FCKContextMenu_Document_OnMouseDown, false ) ; this._Document.addEventListener( 'mouseup', FCKContextMenu_Document_OnMouseUp, false ) ; } this._Document.addEventListener( 'contextmenu', FCKContextMenu_Document_OnContextMenu, false ) ; } } /** The customData parameter is just a value that will be send to the command that is executed, so it's possible to reuse the same command for several items just by assigning different data for each one. */ FCKContextMenu.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) { var oItem = this._MenuBlock.AddItem( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) ; this._Redraw = true ; return oItem ; } FCKContextMenu.prototype.AddSeparator = function() { this._MenuBlock.AddSeparator() ; this._Redraw = true ; } FCKContextMenu.prototype.RemoveAllItems = function() { this._MenuBlock.RemoveAllItems() ; this._Redraw = true ; } FCKContextMenu.prototype.AttachToElement = function( element ) { if ( FCKBrowserInfo.IsIE ) FCKTools.AddEventListenerEx( element, 'contextmenu', FCKContextMenu_AttachedElement_OnContextMenu, this ) ; else element._FCKContextMenu = this ; } function FCKContextMenu_Document_OnContextMenu( e ) { if ( FCKConfig.BrowserContextMenu ) return true ; var el = e.target ; while ( el ) { if ( el._FCKContextMenu ) { if ( el._FCKContextMenu.CtrlDisable && ( e.ctrlKey || e.metaKey ) ) return true ; FCKTools.CancelEvent( e ) ; FCKContextMenu_AttachedElement_OnContextMenu( e, el._FCKContextMenu, el ) ; return false ; } el = el.parentNode ; } return true ; } var FCKContextMenu_OverrideButton ; function FCKContextMenu_Document_OnMouseDown( e ) { if( !e || e.button != 2 ) return false ; if ( FCKConfig.BrowserContextMenu ) return true ; var el = e.target ; while ( el ) { if ( el._FCKContextMenu ) { if ( el._FCKContextMenu.CtrlDisable && ( e.ctrlKey || e.metaKey ) ) return true ; var overrideButton = FCKContextMenu_OverrideButton ; if( !overrideButton ) { var doc = FCKTools.GetElementDocument( e.target ) ; overrideButton = FCKContextMenu_OverrideButton = doc.createElement('input') ; overrideButton.type = 'button' ; var buttonHolder = doc.createElement('p') ; doc.body.appendChild( buttonHolder ) ; buttonHolder.appendChild( overrideButton ) ; } overrideButton.style.cssText = 'position:absolute;top:' + ( e.clientY - 2 ) + 'px;left:' + ( e.clientX - 2 ) + 'px;width:5px;height:5px;opacity:0.01' ; } el = el.parentNode ; } return false ; } function FCKContextMenu_Document_OnMouseUp( e ) { if ( FCKConfig.BrowserContextMenu ) return true ; var overrideButton = FCKContextMenu_OverrideButton ; if ( overrideButton ) { var parent = overrideButton.parentNode ; parent.parentNode.removeChild( parent ) ; FCKContextMenu_OverrideButton = undefined ; if( e && e.button == 2 ) { FCKContextMenu_Document_OnContextMenu( e ) ; return false ; } } return true ; } function FCKContextMenu_AttachedElement_OnContextMenu( ev, fckContextMenu, el ) { if ( ( fckContextMenu.CtrlDisable && ( ev.ctrlKey || ev.metaKey ) ) || FCKConfig.BrowserContextMenu ) return true ; var eTarget = el || this ; if ( fckContextMenu.OnBeforeOpen ) fckContextMenu.OnBeforeOpen.call( fckContextMenu, eTarget ) ; if ( fckContextMenu._MenuBlock.Count() == 0 ) return false ; if ( fckContextMenu._Redraw ) { fckContextMenu._MenuBlock.Create( fckContextMenu._Panel.MainNode ) ; fckContextMenu._Redraw = false ; } // This will avoid that the content of the context menu can be dragged in IE // as the content of the panel is recreated we need to do it every time FCKTools.DisableSelection( fckContextMenu._Panel.Document.body ) ; var x = 0 ; var y = 0 ; if ( FCKBrowserInfo.IsIE ) { x = ev.screenX ; y = ev.screenY ; } else if ( FCKBrowserInfo.IsSafari ) { x = ev.clientX ; y = ev.clientY ; } else { x = ev.pageX ; y = ev.pageY ; } fckContextMenu._Panel.Show( x, y, ev.currentTarget || null ) ; return false ; } function FCKContextMenu_MenuBlock_OnClick( menuItem, contextMenu ) { contextMenu._Panel.Hide() ; FCKTools.RunFunction( contextMenu.OnItemClick, contextMenu, menuItem ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 class partially implements the W3C DOM Range for browser that don't * support the standards (like IE): * http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html */ var FCKW3CRange = function( parentDocument ) { this._Document = parentDocument ; this.startContainer = null ; this.startOffset = null ; this.endContainer = null ; this.endOffset = null ; this.collapsed = true ; } FCKW3CRange.CreateRange = function( parentDocument ) { // We could opt to use the Range implementation of the browsers. The problem // is that every browser have different bugs on their implementations, // mostly related to different interpretations of the W3C specifications. // So, for now, let's use our implementation and pray for browsers fixings // soon. Otherwise will go crazy on trying to find out workarounds. /* // Get the browser implementation of the range, if available. if ( parentDocument.createRange ) { var range = parentDocument.createRange() ; if ( typeof( range.startContainer ) != 'undefined' ) return range ; } */ return new FCKW3CRange( parentDocument ) ; } FCKW3CRange.CreateFromRange = function( parentDocument, sourceRange ) { var range = FCKW3CRange.CreateRange( parentDocument ) ; range.setStart( sourceRange.startContainer, sourceRange.startOffset ) ; range.setEnd( sourceRange.endContainer, sourceRange.endOffset ) ; return range ; } FCKW3CRange.prototype = { _UpdateCollapsed : function() { this.collapsed = ( this.startContainer == this.endContainer && this.startOffset == this.endOffset ) ; }, // W3C requires a check for the new position. If it is after the end // boundary, the range should be collapsed to the new start. It seams we // will not need this check for our use of this class so we can ignore it for now. setStart : function( refNode, offset ) { this.startContainer = refNode ; this.startOffset = offset ; if ( !this.endContainer ) { this.endContainer = refNode ; this.endOffset = offset ; } this._UpdateCollapsed() ; }, // W3C requires a check for the new position. If it is before the start // boundary, the range should be collapsed to the new end. It seams we // will not need this check for our use of this class so we can ignore it for now. setEnd : function( refNode, offset ) { this.endContainer = refNode ; this.endOffset = offset ; if ( !this.startContainer ) { this.startContainer = refNode ; this.startOffset = offset ; } this._UpdateCollapsed() ; }, setStartAfter : function( refNode ) { this.setStart( refNode.parentNode, FCKDomTools.GetIndexOf( refNode ) + 1 ) ; }, setStartBefore : function( refNode ) { this.setStart( refNode.parentNode, FCKDomTools.GetIndexOf( refNode ) ) ; }, setEndAfter : function( refNode ) { this.setEnd( refNode.parentNode, FCKDomTools.GetIndexOf( refNode ) + 1 ) ; }, setEndBefore : function( refNode ) { this.setEnd( refNode.parentNode, FCKDomTools.GetIndexOf( refNode ) ) ; }, collapse : function( toStart ) { if ( toStart ) { this.endContainer = this.startContainer ; this.endOffset = this.startOffset ; } else { this.startContainer = this.endContainer ; this.startOffset = this.endOffset ; } this.collapsed = true ; }, selectNodeContents : function( refNode ) { this.setStart( refNode, 0 ) ; this.setEnd( refNode, refNode.nodeType == 3 ? refNode.data.length : refNode.childNodes.length ) ; }, insertNode : function( newNode ) { var startContainer = this.startContainer ; var startOffset = this.startOffset ; // If we are in a text node. if ( startContainer.nodeType == 3 ) { startContainer.splitText( startOffset ) ; // Check if it is necessary to update the end boundary. if ( startContainer == this.endContainer ) this.setEnd( startContainer.nextSibling, this.endOffset - this.startOffset ) ; // Insert the new node it after the text node. FCKDomTools.InsertAfterNode( startContainer, newNode ) ; return ; } else { // Simply insert the new node before the current start node. startContainer.insertBefore( newNode, startContainer.childNodes[ startOffset ] || null ) ; // Check if it is necessary to update the end boundary. if ( startContainer == this.endContainer ) { this.endOffset++ ; this.collapsed = false ; } } }, deleteContents : function() { if ( this.collapsed ) return ; this._ExecContentsAction( 0 ) ; }, extractContents : function() { var docFrag = new FCKDocumentFragment( this._Document ) ; if ( !this.collapsed ) this._ExecContentsAction( 1, docFrag ) ; return docFrag ; }, // The selection may be lost when cloning (due to the splitText() call). cloneContents : function() { var docFrag = new FCKDocumentFragment( this._Document ) ; if ( !this.collapsed ) this._ExecContentsAction( 2, docFrag ) ; return docFrag ; }, _ExecContentsAction : function( action, docFrag ) { var startNode = this.startContainer ; var endNode = this.endContainer ; var startOffset = this.startOffset ; var endOffset = this.endOffset ; var removeStartNode = false ; var removeEndNode = false ; // Check the start and end nodes and make the necessary removals or changes. // Start from the end, otherwise DOM mutations (splitText) made in the // start boundary may interfere on the results here. // For text containers, we must simply split the node and point to the // second part. The removal will be handled by the rest of the code . if ( endNode.nodeType == 3 ) endNode = endNode.splitText( endOffset ) ; else { // If the end container has children and the offset is pointing // to a child, then we should start from it. if ( endNode.childNodes.length > 0 ) { // If the offset points after the last node. if ( endOffset > endNode.childNodes.length - 1 ) { // Let's create a temporary node and mark it for removal. endNode = FCKDomTools.InsertAfterNode( endNode.lastChild, this._Document.createTextNode('') ) ; removeEndNode = true ; } else endNode = endNode.childNodes[ endOffset ] ; } } // For text containers, we must simply split the node. The removal will // be handled by the rest of the code . if ( startNode.nodeType == 3 ) { startNode.splitText( startOffset ) ; // In cases the end node is the same as the start node, the above // splitting will also split the end, so me must move the end to // the second part of the split. if ( startNode == endNode ) endNode = startNode.nextSibling ; } else { // If the start container has children and the offset is pointing // to a child, then we should start from its previous sibling. // If the offset points to the first node, we don't have a // sibling, so let's use the first one, but mark it for removal. if ( startOffset == 0 ) { // Let's create a temporary node and mark it for removal. startNode = startNode.insertBefore( this._Document.createTextNode(''), startNode.firstChild ) ; removeStartNode = true ; } else if ( startOffset > startNode.childNodes.length - 1 ) { // Let's create a temporary node and mark it for removal. startNode = startNode.appendChild( this._Document.createTextNode('') ) ; removeStartNode = true ; } else startNode = startNode.childNodes[ startOffset ].previousSibling ; } // Get the parent nodes tree for the start and end boundaries. var startParents = FCKDomTools.GetParents( startNode ) ; var endParents = FCKDomTools.GetParents( endNode ) ; // Compare them, to find the top most siblings. var i, topStart, topEnd ; for ( i = 0 ; i < startParents.length ; i++ ) { topStart = startParents[i] ; topEnd = endParents[i] ; // The compared nodes will match until we find the top most // siblings (different nodes that have the same parent). // "i" will hold the index in the parents array for the top // most element. if ( topStart != topEnd ) break ; } var clone, levelStartNode, levelClone, currentNode, currentSibling ; if ( docFrag ) clone = docFrag.RootNode ; // Remove all successive sibling nodes for every node in the // startParents tree. for ( var j = i ; j < startParents.length ; j++ ) { levelStartNode = startParents[j] ; // For Extract and Clone, we must clone this level. if ( clone && levelStartNode != startNode ) // action = 0 = Delete levelClone = clone.appendChild( levelStartNode.cloneNode( levelStartNode == startNode ) ) ; currentNode = levelStartNode.nextSibling ; while( currentNode ) { // Stop processing when the current node matches a node in the // endParents tree or if it is the endNode. if ( currentNode == endParents[j] || currentNode == endNode ) break ; // Cache the next sibling. currentSibling = currentNode.nextSibling ; // If cloning, just clone it. if ( action == 2 ) // 2 = Clone clone.appendChild( currentNode.cloneNode( true ) ) ; else { // Both Delete and Extract will remove the node. currentNode.parentNode.removeChild( currentNode ) ; // When Extracting, move the removed node to the docFrag. if ( action == 1 ) // 1 = Extract clone.appendChild( currentNode ) ; } currentNode = currentSibling ; } if ( clone ) clone = levelClone ; } if ( docFrag ) clone = docFrag.RootNode ; // Remove all previous sibling nodes for every node in the // endParents tree. for ( var k = i ; k < endParents.length ; k++ ) { levelStartNode = endParents[k] ; // For Extract and Clone, we must clone this level. if ( action > 0 && levelStartNode != endNode ) // action = 0 = Delete levelClone = clone.appendChild( levelStartNode.cloneNode( levelStartNode == endNode ) ) ; // The processing of siblings may have already been done by the parent. if ( !startParents[k] || levelStartNode.parentNode != startParents[k].parentNode ) { currentNode = levelStartNode.previousSibling ; while( currentNode ) { // Stop processing when the current node matches a node in the // startParents tree or if it is the startNode. if ( currentNode == startParents[k] || currentNode == startNode ) break ; // Cache the next sibling. currentSibling = currentNode.previousSibling ; // If cloning, just clone it. if ( action == 2 ) // 2 = Clone clone.insertBefore( currentNode.cloneNode( true ), clone.firstChild ) ; else { // Both Delete and Extract will remove the node. currentNode.parentNode.removeChild( currentNode ) ; // When Extracting, mode the removed node to the docFrag. if ( action == 1 ) // 1 = Extract clone.insertBefore( currentNode, clone.firstChild ) ; } currentNode = currentSibling ; } } if ( clone ) clone = levelClone ; } if ( action == 2 ) // 2 = Clone. { // No changes in the DOM should be done, so fix the split text (if any). var startTextNode = this.startContainer ; if ( startTextNode.nodeType == 3 ) { startTextNode.data += startTextNode.nextSibling.data ; startTextNode.parentNode.removeChild( startTextNode.nextSibling ) ; } var endTextNode = this.endContainer ; if ( endTextNode.nodeType == 3 && endTextNode.nextSibling ) { endTextNode.data += endTextNode.nextSibling.data ; endTextNode.parentNode.removeChild( endTextNode.nextSibling ) ; } } else { // Collapse the range. // If a node has been partially selected, collapse the range between // topStart and topEnd. Otherwise, simply collapse it to the start. (W3C specs). if ( topStart && topEnd && ( startNode.parentNode != topStart.parentNode || endNode.parentNode != topEnd.parentNode ) ) { var endIndex = FCKDomTools.GetIndexOf( topEnd ) ; // If the start node is to be removed, we must correct the // index to reflect the removal. if ( removeStartNode && topEnd.parentNode == startNode.parentNode ) endIndex-- ; this.setStart( topEnd.parentNode, endIndex ) ; } // Collapse it to the start. this.collapse( true ) ; } // Cleanup any marked node. if( removeStartNode ) startNode.parentNode.removeChild( startNode ) ; if( removeEndNode && endNode.parentNode ) endNode.parentNode.removeChild( endNode ) ; }, cloneRange : function() { return FCKW3CRange.CreateFromRange( this._Document, this ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 generic Document Fragment object. It is not intended to provide * the W3C implementation, but is a way to fix the missing of a real Document * Fragment in IE (where document.createDocumentFragment() returns a normal * document instead), giving a standard interface for it. * (IE Implementation) */ var FCKDocumentFragment = function( parentDocument ) { this._Document = parentDocument ; this.RootNode = parentDocument.createElement( 'div' ) ; } // Append the contents of this Document Fragment to another node. FCKDocumentFragment.prototype = { AppendTo : function( targetNode ) { FCKDomTools.MoveChildren( this.RootNode, targetNode ) ; }, AppendHtml : function( html ) { var eTmpDiv = this._Document.createElement( 'div' ) ; eTmpDiv.innerHTML = html ; FCKDomTools.MoveChildren( eTmpDiv, this.RootNode ) ; }, InsertAfterNode : function( existingNode ) { var eRoot = this.RootNode ; var eLast ; while( ( eLast = eRoot.lastChild ) ) FCKDomTools.InsertAfterNode( existingNode, eRoot.removeChild( eLast ) ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarPanelButton Class: Handles the Fonts combo selector. */ var FCKToolbarFontSizeCombo = function( tooltip, style ) { this.CommandName = 'FontSize' ; this.Label = this.GetLabel() ; this.Tooltip = tooltip ? tooltip : this.Label ; this.Style = style ? style : FCK_TOOLBARITEM_ICONTEXT ; this.DefaultLabel = FCKConfig.DefaultFontSizeLabel || '' ; this.FieldWidth = 70 ; } // Inherit from FCKToolbarSpecialCombo. FCKToolbarFontSizeCombo.prototype = new FCKToolbarFontFormatCombo( false ) ; FCKToolbarFontSizeCombo.prototype.GetLabel = function() { return FCKLang.FontSize ; } FCKToolbarFontSizeCombo.prototype.GetStyles = function() { var baseStyle = FCKStyles.GetStyle( '_FCK_Size' ) ; if ( !baseStyle ) { alert( "The FCKConfig.CoreStyles['FontFace'] setting was not found. Please check the fckconfig.js file" ) ; return {} ; } var styles = {} ; var fonts = FCKConfig.FontSizes.split(';') ; for ( var i = 0 ; i < fonts.length ; i++ ) { var fontParts = fonts[i].split('/') ; var font = fontParts[0] ; var caption = fontParts[1] || font ; var style = FCKTools.CloneObject( baseStyle ) ; style.SetVariable( 'Size', font ) ; style.Label = caption ; styles[ caption ] = style ; } return styles ; } FCKToolbarFontSizeCombo.prototype.RefreshActiveItems = FCKToolbarStyleCombo.prototype.RefreshActiveItems ; FCKToolbarFontSizeCombo.prototype.StyleCombo_OnBeforeClick = FCKToolbarFontsCombo.prototype.StyleCombo_OnBeforeClick ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarBreak Class: breaks the toolbars. * It makes it possible to force the toolbar to break to a new line. * This is the Gecko specific implementation. */ var FCKToolbarBreak = function() {} FCKToolbarBreak.prototype.Create = function( targetElement ) { var oBreakDiv = targetElement.ownerDocument.createElement( 'div' ) ; oBreakDiv.style.clear = oBreakDiv.style.cssFloat = FCKLang.Dir == 'rtl' ? 'right' : 'left' ; targetElement.appendChild( oBreakDiv ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKIcon Class: renders an icon from a single image, a strip or even a * spacer. */ var FCKIcon = function( iconPathOrStripInfoArray ) { var sTypeOf = iconPathOrStripInfoArray ? typeof( iconPathOrStripInfoArray ) : 'undefined' ; switch ( sTypeOf ) { case 'number' : this.Path = FCKConfig.SkinPath + 'fck_strip.gif' ; this.Size = 16 ; this.Position = iconPathOrStripInfoArray ; break ; case 'undefined' : this.Path = FCK_SPACER_PATH ; break ; case 'string' : this.Path = iconPathOrStripInfoArray ; break ; default : // It is an array in the format [ StripFilePath, IconSize, IconPosition ] this.Path = iconPathOrStripInfoArray[0] ; this.Size = iconPathOrStripInfoArray[1] ; this.Position = iconPathOrStripInfoArray[2] ; } } FCKIcon.prototype.CreateIconElement = function( document ) { var eIcon, eIconImage ; if ( this.Position ) // It is using an icons strip image. { var sPos = '-' + ( ( this.Position - 1 ) * this.Size ) + 'px' ; if ( FCKBrowserInfo.IsIE ) { // <div class="TB_Button_Image"><img src="strip.gif" style="top:-16px"></div> eIcon = document.createElement( 'DIV' ) ; eIconImage = eIcon.appendChild( document.createElement( 'IMG' ) ) ; eIconImage.src = this.Path ; eIconImage.style.top = sPos ; } else { // <img class="TB_Button_Image" src="spacer.gif" style="background-position: 0px -16px;background-image: url(strip.gif);"> eIcon = document.createElement( 'IMG' ) ; eIcon.src = FCK_SPACER_PATH ; eIcon.style.backgroundPosition = '0px ' + sPos ; eIcon.style.backgroundImage = 'url("' + this.Path + '")' ; } } else // It is using a single icon image. { if ( FCKBrowserInfo.IsIE ) { // IE makes the button 1px higher if using the <img> directly, so we // are changing to the <div> system to clip the image correctly. eIcon = document.createElement( 'DIV' ) ; eIconImage = eIcon.appendChild( document.createElement( 'IMG' ) ) ; eIconImage.src = this.Path ? this.Path : FCK_SPACER_PATH ; } else { // This is not working well with IE. See notes above. // <img class="TB_Button_Image" src="smiley.gif"> eIcon = document.createElement( 'IMG' ) ; eIcon.src = this.Path ? this.Path : FCK_SPACER_PATH ; } } eIcon.className = 'TB_Button_Image' ; return eIcon ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Class for working with a selection range, much like the W3C DOM Range, but * it is not intended to be an implementation of the W3C interface. */ var FCKDomRange = function( sourceWindow ) { this.Window = sourceWindow ; this._Cache = {} ; } FCKDomRange.prototype = { _UpdateElementInfo : function() { var innerRange = this._Range ; if ( !innerRange ) this.Release( true ) ; else { // For text nodes, the node itself is the StartNode. var eStart = innerRange.startContainer ; var oElementPath = new FCKElementPath( eStart ) ; this.StartNode = eStart.nodeType == 3 ? eStart : eStart.childNodes[ innerRange.startOffset ] ; this.StartContainer = eStart ; this.StartBlock = oElementPath.Block ; this.StartBlockLimit = oElementPath.BlockLimit ; if ( innerRange.collapsed ) { this.EndNode = this.StartNode ; this.EndContainer = this.StartContainer ; this.EndBlock = this.StartBlock ; this.EndBlockLimit = this.StartBlockLimit ; } else { var eEnd = innerRange.endContainer ; if ( eStart != eEnd ) oElementPath = new FCKElementPath( eEnd ) ; // The innerRange.endContainer[ innerRange.endOffset ] is not // usually part of the range, but the marker for the range end. So, // let's get the previous available node as the real end. var eEndNode = eEnd ; if ( innerRange.endOffset == 0 ) { while ( eEndNode && !eEndNode.previousSibling ) eEndNode = eEndNode.parentNode ; if ( eEndNode ) eEndNode = eEndNode.previousSibling ; } else if ( eEndNode.nodeType == 1 ) eEndNode = eEndNode.childNodes[ innerRange.endOffset - 1 ] ; this.EndNode = eEndNode ; this.EndContainer = eEnd ; this.EndBlock = oElementPath.Block ; this.EndBlockLimit = oElementPath.BlockLimit ; } } this._Cache = {} ; }, CreateRange : function() { return new FCKW3CRange( this.Window.document ) ; }, DeleteContents : function() { if ( this._Range ) { this._Range.deleteContents() ; this._UpdateElementInfo() ; } }, ExtractContents : function() { if ( this._Range ) { var docFrag = this._Range.extractContents() ; this._UpdateElementInfo() ; return docFrag ; } return null ; }, CheckIsCollapsed : function() { if ( this._Range ) return this._Range.collapsed ; return false ; }, Collapse : function( toStart ) { if ( this._Range ) this._Range.collapse( toStart ) ; this._UpdateElementInfo() ; }, Clone : function() { var oClone = FCKTools.CloneObject( this ) ; if ( this._Range ) oClone._Range = this._Range.cloneRange() ; return oClone ; }, MoveToNodeContents : function( targetNode ) { if ( !this._Range ) this._Range = this.CreateRange() ; this._Range.selectNodeContents( targetNode ) ; this._UpdateElementInfo() ; }, MoveToElementStart : function( targetElement ) { this.SetStart(targetElement,1) ; this.SetEnd(targetElement,1) ; }, // Moves to the first editing point inside a element. For example, in a // element tree like "<p><b><i></i></b> Text</p>", the start editing point // is "<p><b><i>^</i></b> Text</p>" (inside <i>). MoveToElementEditStart : function( targetElement ) { var editableElement ; while ( targetElement && targetElement.nodeType == 1 ) { if ( FCKDomTools.CheckIsEditable( targetElement ) ) editableElement = targetElement ; else if ( editableElement ) break ; // If we already found an editable element, stop the loop. targetElement = targetElement.firstChild ; } if ( editableElement ) this.MoveToElementStart( editableElement ) ; }, InsertNode : function( node ) { if ( this._Range ) this._Range.insertNode( node ) ; }, CheckIsEmpty : function() { if ( this.CheckIsCollapsed() ) return true ; // Inserts the contents of the range in a div tag. var eToolDiv = this.Window.document.createElement( 'div' ) ; this._Range.cloneContents().AppendTo( eToolDiv ) ; FCKDomTools.TrimNode( eToolDiv ) ; return ( eToolDiv.innerHTML.length == 0 ) ; }, /** * Checks if the start boundary of the current range is "visually" (like a * selection caret) at the beginning of the block. It means that some * things could be brefore the range, like spaces or empty inline elements, * but it would still be considered at the beginning of the block. */ CheckStartOfBlock : function() { var cache = this._Cache ; var bIsStartOfBlock = cache.IsStartOfBlock ; if ( bIsStartOfBlock != undefined ) return bIsStartOfBlock ; // Take the block reference. var block = this.StartBlock || this.StartBlockLimit ; var container = this._Range.startContainer ; var offset = this._Range.startOffset ; var currentNode ; if ( offset > 0 ) { // First, check the start container. If it is a text node, get the // substring of the node value before the range offset. if ( container.nodeType == 3 ) { var textValue = container.nodeValue.substr( 0, offset ).Trim() ; // If we have some text left in the container, we are not at // the end for the block. if ( textValue.length != 0 ) return cache.IsStartOfBlock = false ; } else currentNode = container.childNodes[ offset - 1 ] ; } // We'll not have a currentNode if the container was a text node, or // the offset is zero. if ( !currentNode ) currentNode = FCKDomTools.GetPreviousSourceNode( container, true, null, block ) ; while ( currentNode ) { switch ( currentNode.nodeType ) { case 1 : // It's not an inline element. if ( !FCKListsLib.InlineChildReqElements[ currentNode.nodeName.toLowerCase() ] ) return cache.IsStartOfBlock = false ; break ; case 3 : // It's a text node with real text. if ( currentNode.nodeValue.Trim().length > 0 ) return cache.IsStartOfBlock = false ; } currentNode = FCKDomTools.GetPreviousSourceNode( currentNode, false, null, block ) ; } return cache.IsStartOfBlock = true ; }, /** * Checks if the end boundary of the current range is "visually" (like a * selection caret) at the end of the block. It means that some things * could be after the range, like spaces, empty inline elements, or a * single <br>, but it would still be considered at the end of the block. */ CheckEndOfBlock : function( refreshSelection ) { var isEndOfBlock = this._Cache.IsEndOfBlock ; if ( isEndOfBlock != undefined ) return isEndOfBlock ; // Take the block reference. var block = this.EndBlock || this.EndBlockLimit ; var container = this._Range.endContainer ; var offset = this._Range.endOffset ; var currentNode ; // First, check the end container. If it is a text node, get the // substring of the node value after the range offset. if ( container.nodeType == 3 ) { var textValue = container.nodeValue ; if ( offset < textValue.length ) { textValue = textValue.substr( offset ) ; // If we have some text left in the container, we are not at // the end for the block. if ( textValue.Trim().length != 0 ) return this._Cache.IsEndOfBlock = false ; } } else currentNode = container.childNodes[ offset ] ; // We'll not have a currentNode if the container was a text node, of // the offset is out the container children limits (after it probably). if ( !currentNode ) currentNode = FCKDomTools.GetNextSourceNode( container, true, null, block ) ; var hadBr = false ; while ( currentNode ) { switch ( currentNode.nodeType ) { case 1 : var nodeName = currentNode.nodeName.toLowerCase() ; // It's an inline element. if ( FCKListsLib.InlineChildReqElements[ nodeName ] ) break ; // It is the first <br> found. if ( nodeName == 'br' && !hadBr ) { hadBr = true ; break ; } return this._Cache.IsEndOfBlock = false ; case 3 : // It's a text node with real text. if ( currentNode.nodeValue.Trim().length > 0 ) return this._Cache.IsEndOfBlock = false ; } currentNode = FCKDomTools.GetNextSourceNode( currentNode, false, null, block ) ; } if ( refreshSelection ) this.Select() ; return this._Cache.IsEndOfBlock = true ; }, // This is an "intrusive" way to create a bookmark. It includes <span> tags // in the range boundaries. The advantage of it is that it is possible to // handle DOM mutations when moving back to the bookmark. // Attention: the inclusion of nodes in the DOM is a design choice and // should not be changed as there are other points in the code that may be // using those nodes to perform operations. See GetBookmarkNode. // For performance, includeNodes=true if intended to SelectBookmark. CreateBookmark : function( includeNodes ) { // Create the bookmark info (random IDs). var oBookmark = { StartId : (new Date()).valueOf() + Math.floor(Math.random()*1000) + 'S', EndId : (new Date()).valueOf() + Math.floor(Math.random()*1000) + 'E' } ; var oDoc = this.Window.document ; var eStartSpan ; var eEndSpan ; var oClone ; // For collapsed ranges, add just the start marker. if ( !this.CheckIsCollapsed() ) { eEndSpan = oDoc.createElement( 'span' ) ; eEndSpan.style.display = 'none' ; eEndSpan.id = oBookmark.EndId ; eEndSpan.setAttribute( '_fck_bookmark', true ) ; // For IE, it must have something inside, otherwise it may be // removed during DOM operations. // if ( FCKBrowserInfo.IsIE ) eEndSpan.innerHTML = '&nbsp;' ; oClone = this.Clone() ; oClone.Collapse( false ) ; oClone.InsertNode( eEndSpan ) ; } eStartSpan = oDoc.createElement( 'span' ) ; eStartSpan.style.display = 'none' ; eStartSpan.id = oBookmark.StartId ; eStartSpan.setAttribute( '_fck_bookmark', true ) ; // For IE, it must have something inside, otherwise it may be removed // during DOM operations. // if ( FCKBrowserInfo.IsIE ) eStartSpan.innerHTML = '&nbsp;' ; oClone = this.Clone() ; oClone.Collapse( true ) ; oClone.InsertNode( eStartSpan ) ; if ( includeNodes ) { oBookmark.StartNode = eStartSpan ; oBookmark.EndNode = eEndSpan ; } // Update the range position. if ( eEndSpan ) { this.SetStart( eStartSpan, 4 ) ; this.SetEnd( eEndSpan, 3 ) ; } else this.MoveToPosition( eStartSpan, 4 ) ; return oBookmark ; }, // This one should be a part of a hypothetic "bookmark" object. GetBookmarkNode : function( bookmark, start ) { var doc = this.Window.document ; if ( start ) return bookmark.StartNode || doc.getElementById( bookmark.StartId ) ; else return bookmark.EndNode || doc.getElementById( bookmark.EndId ) ; }, MoveToBookmark : function( bookmark, preserveBookmark ) { var eStartSpan = this.GetBookmarkNode( bookmark, true ) ; var eEndSpan = this.GetBookmarkNode( bookmark, false ) ; this.SetStart( eStartSpan, 3 ) ; if ( !preserveBookmark ) FCKDomTools.RemoveNode( eStartSpan ) ; // If collapsed, the end span will not be available. if ( eEndSpan ) { this.SetEnd( eEndSpan, 3 ) ; if ( !preserveBookmark ) FCKDomTools.RemoveNode( eEndSpan ) ; } else this.Collapse( true ) ; this._UpdateElementInfo() ; }, // Non-intrusive bookmark algorithm CreateBookmark2 : function() { // If there is no range then get out of here. // It happens on initial load in Safari #962 and if the editor it's hidden also in Firefox if ( ! this._Range ) return { "Start" : 0, "End" : 0 } ; // First, we record down the offset values var bookmark = { "Start" : [ this._Range.startOffset ], "End" : [ this._Range.endOffset ] } ; // Since we're treating the document tree as normalized, we need to backtrack the text lengths // of previous text nodes into the offset value. var curStart = this._Range.startContainer.previousSibling ; var curEnd = this._Range.endContainer.previousSibling ; // Also note that the node that we use for "address base" would change during backtracking. var addrStart = this._Range.startContainer ; var addrEnd = this._Range.endContainer ; while ( curStart && curStart.nodeType == 3 && addrStart.nodeType == 3 ) { bookmark.Start[0] += curStart.length ; addrStart = curStart ; curStart = curStart.previousSibling ; } while ( curEnd && curEnd.nodeType == 3 && addrEnd.nodeType == 3 ) { bookmark.End[0] += curEnd.length ; addrEnd = curEnd ; curEnd = curEnd.previousSibling ; } // If the object pointed to by the startOffset and endOffset are text nodes, we need // to backtrack and add in the text offset to the bookmark addresses. if ( addrStart.nodeType == 1 && addrStart.childNodes[bookmark.Start[0]] && addrStart.childNodes[bookmark.Start[0]].nodeType == 3 ) { var curNode = addrStart.childNodes[bookmark.Start[0]] ; var offset = 0 ; while ( curNode.previousSibling && curNode.previousSibling.nodeType == 3 ) { curNode = curNode.previousSibling ; offset += curNode.length ; } addrStart = curNode ; bookmark.Start[0] = offset ; } if ( addrEnd.nodeType == 1 && addrEnd.childNodes[bookmark.End[0]] && addrEnd.childNodes[bookmark.End[0]].nodeType == 3 ) { var curNode = addrEnd.childNodes[bookmark.End[0]] ; var offset = 0 ; while ( curNode.previousSibling && curNode.previousSibling.nodeType == 3 ) { curNode = curNode.previousSibling ; offset += curNode.length ; } addrEnd = curNode ; bookmark.End[0] = offset ; } // Then, we record down the precise position of the container nodes // by walking up the DOM tree and counting their childNode index bookmark.Start = FCKDomTools.GetNodeAddress( addrStart, true ).concat( bookmark.Start ) ; bookmark.End = FCKDomTools.GetNodeAddress( addrEnd, true ).concat( bookmark.End ) ; return bookmark; }, MoveToBookmark2 : function( bookmark ) { // Reverse the childNode counting algorithm in CreateBookmark2() var curStart = FCKDomTools.GetNodeFromAddress( this.Window.document, bookmark.Start.slice( 0, -1 ), true ) ; var curEnd = FCKDomTools.GetNodeFromAddress( this.Window.document, bookmark.End.slice( 0, -1 ), true ) ; // Generate the W3C Range object and update relevant data this.Release( true ) ; this._Range = new FCKW3CRange( this.Window.document ) ; var startOffset = bookmark.Start[ bookmark.Start.length - 1 ] ; var endOffset = bookmark.End[ bookmark.End.length - 1 ] ; while ( curStart.nodeType == 3 && startOffset > curStart.length ) { if ( ! curStart.nextSibling || curStart.nextSibling.nodeType != 3 ) break ; startOffset -= curStart.length ; curStart = curStart.nextSibling ; } while ( curEnd.nodeType == 3 && endOffset > curEnd.length ) { if ( ! curEnd.nextSibling || curEnd.nextSibling.nodeType != 3 ) break ; endOffset -= curEnd.length ; curEnd = curEnd.nextSibling ; } this._Range.setStart( curStart, startOffset ) ; this._Range.setEnd( curEnd, endOffset ) ; this._UpdateElementInfo() ; }, MoveToPosition : function( targetElement, position ) { this.SetStart( targetElement, position ) ; this.Collapse( true ) ; }, /* * Moves the position of the start boundary of the range to a specific position * relatively to a element. * @position: * 1 = After Start <target>^contents</target> * 2 = Before End <target>contents^</target> * 3 = Before Start ^<target>contents</target> * 4 = After End <target>contents</target>^ */ SetStart : function( targetElement, position, noInfoUpdate ) { var oRange = this._Range ; if ( !oRange ) oRange = this._Range = this.CreateRange() ; switch( position ) { case 1 : // After Start <target>^contents</target> oRange.setStart( targetElement, 0 ) ; break ; case 2 : // Before End <target>contents^</target> oRange.setStart( targetElement, targetElement.childNodes.length ) ; break ; case 3 : // Before Start ^<target>contents</target> oRange.setStartBefore( targetElement ) ; break ; case 4 : // After End <target>contents</target>^ oRange.setStartAfter( targetElement ) ; } if ( !noInfoUpdate ) this._UpdateElementInfo() ; }, /* * Moves the position of the start boundary of the range to a specific position * relatively to a element. * @position: * 1 = After Start <target>^contents</target> * 2 = Before End <target>contents^</target> * 3 = Before Start ^<target>contents</target> * 4 = After End <target>contents</target>^ */ SetEnd : function( targetElement, position, noInfoUpdate ) { var oRange = this._Range ; if ( !oRange ) oRange = this._Range = this.CreateRange() ; switch( position ) { case 1 : // After Start <target>^contents</target> oRange.setEnd( targetElement, 0 ) ; break ; case 2 : // Before End <target>contents^</target> oRange.setEnd( targetElement, targetElement.childNodes.length ) ; break ; case 3 : // Before Start ^<target>contents</target> oRange.setEndBefore( targetElement ) ; break ; case 4 : // After End <target>contents</target>^ oRange.setEndAfter( targetElement ) ; } if ( !noInfoUpdate ) this._UpdateElementInfo() ; }, Expand : function( unit ) { var oNode, oSibling ; switch ( unit ) { // Expand the range to include all inline parent elements if we are // are in their boundary limits. // For example (where [ ] are the range limits): // Before => Some <b>[<i>Some sample text]</i></b>. // After => Some [<b><i>Some sample text</i></b>]. case 'inline_elements' : // Expand the start boundary. if ( this._Range.startOffset == 0 ) { oNode = this._Range.startContainer ; if ( oNode.nodeType != 1 ) oNode = oNode.previousSibling ? null : oNode.parentNode ; if ( oNode ) { while ( FCKListsLib.InlineNonEmptyElements[ oNode.nodeName.toLowerCase() ] ) { this._Range.setStartBefore( oNode ) ; if ( oNode != oNode.parentNode.firstChild ) break ; oNode = oNode.parentNode ; } } } // Expand the end boundary. oNode = this._Range.endContainer ; var offset = this._Range.endOffset ; if ( ( oNode.nodeType == 3 && offset >= oNode.nodeValue.length ) || ( oNode.nodeType == 1 && offset >= oNode.childNodes.length ) || ( oNode.nodeType != 1 && oNode.nodeType != 3 ) ) { if ( oNode.nodeType != 1 ) oNode = oNode.nextSibling ? null : oNode.parentNode ; if ( oNode ) { while ( FCKListsLib.InlineNonEmptyElements[ oNode.nodeName.toLowerCase() ] ) { this._Range.setEndAfter( oNode ) ; if ( oNode != oNode.parentNode.lastChild ) break ; oNode = oNode.parentNode ; } } } break ; case 'block_contents' : case 'list_contents' : var boundarySet = FCKListsLib.BlockBoundaries ; if ( unit == 'list_contents' || FCKConfig.EnterMode == 'br' ) boundarySet = FCKListsLib.ListBoundaries ; if ( this.StartBlock && FCKConfig.EnterMode != 'br' && unit == 'block_contents' ) this.SetStart( this.StartBlock, 1 ) ; else { // Get the start node for the current range. oNode = this._Range.startContainer ; // If it is an element, get the node right before of it (in source order). if ( oNode.nodeType == 1 ) { var lastNode = oNode.childNodes[ this._Range.startOffset ] ; if ( lastNode ) oNode = FCKDomTools.GetPreviousSourceNode( lastNode, true ) ; else oNode = oNode.lastChild || oNode ; } // We must look for the left boundary, relative to the range // start, which is limited by a block element. while ( oNode && ( oNode.nodeType != 1 || ( oNode != this.StartBlockLimit && !boundarySet[ oNode.nodeName.toLowerCase() ] ) ) ) { this._Range.setStartBefore( oNode ) ; oNode = oNode.previousSibling || oNode.parentNode ; } } if ( this.EndBlock && FCKConfig.EnterMode != 'br' && unit == 'block_contents' && this.EndBlock.nodeName.toLowerCase() != 'li' ) this.SetEnd( this.EndBlock, 2 ) ; else { oNode = this._Range.endContainer ; if ( oNode.nodeType == 1 ) oNode = oNode.childNodes[ this._Range.endOffset ] || oNode.lastChild ; // We must look for the right boundary, relative to the range // end, which is limited by a block element. while ( oNode && ( oNode.nodeType != 1 || ( oNode != this.StartBlockLimit && !boundarySet[ oNode.nodeName.toLowerCase() ] ) ) ) { this._Range.setEndAfter( oNode ) ; oNode = oNode.nextSibling || oNode.parentNode ; } // In EnterMode='br', the end <br> boundary element must // be included in the expanded range. if ( oNode && oNode.nodeName.toLowerCase() == 'br' ) this._Range.setEndAfter( oNode ) ; } this._UpdateElementInfo() ; } }, /** * Split the block element for the current range. It deletes the contents * of the range and splits the block in the collapsed position, resulting * in two sucessive blocks. The range is then positioned in the middle of * them. * * It returns and object with the following properties: * - PreviousBlock : a reference to the block element that preceeds * the range after the split. * - NextBlock : a reference to the block element that follows the * range after the split. * - WasStartOfBlock : a boolean indicating that the range was * originaly at the start of the block. * - WasEndOfBlock : a boolean indicating that the range was originaly * at the end of the block. * * If the range was originaly at the start of the block, no split will happen * and the PreviousBlock value will be null. The same is valid for the * NextBlock value if the range was at the end of the block. */ SplitBlock : function( forceBlockTag ) { var blockTag = forceBlockTag || FCKConfig.EnterMode ; if ( !this._Range ) this.MoveToSelection() ; // The range boundaries must be in the same "block limit" element. if ( this.StartBlockLimit == this.EndBlockLimit ) { // Get the current blocks. var eStartBlock = this.StartBlock ; var eEndBlock = this.EndBlock ; var oElementPath = null ; if ( blockTag != 'br' ) { if ( !eStartBlock ) { eStartBlock = this.FixBlock( true, blockTag ) ; eEndBlock = this.EndBlock ; // FixBlock may have fixed the EndBlock too. } if ( !eEndBlock ) eEndBlock = this.FixBlock( false, blockTag ) ; } // Get the range position. var bIsStartOfBlock = ( eStartBlock != null && this.CheckStartOfBlock() ) ; var bIsEndOfBlock = ( eEndBlock != null && this.CheckEndOfBlock() ) ; // Delete the current contents. if ( !this.CheckIsEmpty() ) this.DeleteContents() ; if ( eStartBlock && eEndBlock && eStartBlock == eEndBlock ) { if ( bIsEndOfBlock ) { oElementPath = new FCKElementPath( this.StartContainer ) ; this.MoveToPosition( eEndBlock, 4 ) ; eEndBlock = null ; } else if ( bIsStartOfBlock ) { oElementPath = new FCKElementPath( this.StartContainer ) ; this.MoveToPosition( eStartBlock, 3 ) ; eStartBlock = null ; } else { // Extract the contents of the block from the selection point to the end of its contents. this.SetEnd( eStartBlock, 2 ) ; var eDocFrag = this.ExtractContents() ; // Duplicate the block element after it. eEndBlock = eStartBlock.cloneNode( false ) ; eEndBlock.removeAttribute( 'id', false ) ; // Place the extracted contents in the duplicated block. eDocFrag.AppendTo( eEndBlock ) ; FCKDomTools.InsertAfterNode( eStartBlock, eEndBlock ) ; this.MoveToPosition( eStartBlock, 4 ) ; // In Gecko, the last child node must be a bogus <br>. // Note: bogus <br> added under <ul> or <ol> would cause lists to be incorrectly rendered. if ( FCKBrowserInfo.IsGecko && ! eStartBlock.nodeName.IEquals( ['ul', 'ol'] ) ) FCKTools.AppendBogusBr( eStartBlock ) ; } } return { PreviousBlock : eStartBlock, NextBlock : eEndBlock, WasStartOfBlock : bIsStartOfBlock, WasEndOfBlock : bIsEndOfBlock, ElementPath : oElementPath } ; } return null ; }, // Transform a block without a block tag in a valid block (orphan text in the body or td, usually). FixBlock : function( isStart, blockTag ) { // Bookmark the range so we can restore it later. var oBookmark = this.CreateBookmark() ; // Collapse the range to the requested ending boundary. this.Collapse( isStart ) ; // Expands it to the block contents. this.Expand( 'block_contents' ) ; // Create the fixed block. var oFixedBlock = this.Window.document.createElement( blockTag ) ; // Move the contents of the temporary range to the fixed block. this.ExtractContents().AppendTo( oFixedBlock ) ; FCKDomTools.TrimNode( oFixedBlock ) ; // If the fixed block is empty (not counting bookmark nodes) // Add a <br /> inside to expand it. if ( FCKDomTools.CheckIsEmptyElement(oFixedBlock, function( element ) { return element.getAttribute('_fck_bookmark') != 'true' ; } ) && FCKBrowserInfo.IsGeckoLike ) FCKTools.AppendBogusBr( oFixedBlock ) ; // Insert the fixed block into the DOM. this.InsertNode( oFixedBlock ) ; // Move the range back to the bookmarked place. this.MoveToBookmark( oBookmark ) ; return oFixedBlock ; }, Release : function( preserveWindow ) { if ( !preserveWindow ) this.Window = null ; this.StartNode = null ; this.StartContainer = null ; this.StartBlock = null ; this.StartBlockLimit = null ; this.EndNode = null ; this.EndContainer = null ; this.EndBlock = null ; this.EndBlockLimit = null ; this._Range = null ; this._Cache = null ; }, CheckHasRange : function() { return !!this._Range ; }, GetTouchedStartNode : function() { var range = this._Range ; var container = range.startContainer ; if ( range.collapsed || container.nodeType != 1 ) return container ; return container.childNodes[ range.startOffset ] || container ; }, GetTouchedEndNode : function() { var range = this._Range ; var container = range.endContainer ; if ( range.collapsed || container.nodeType != 1 ) return container ; return container.childNodes[ range.endOffset - 1 ] || container ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbar Class: represents a toolbar in the toolbarset. It is a group of * toolbar items. */ var FCKToolbar = function() { this.Items = new Array() ; } FCKToolbar.prototype.AddItem = function( item ) { return this.Items[ this.Items.length ] = item ; } FCKToolbar.prototype.AddButton = function( name, label, tooltip, iconPathOrStripInfoArrayOrIndex, style, state ) { if ( typeof( iconPathOrStripInfoArrayOrIndex ) == 'number' ) iconPathOrStripInfoArrayOrIndex = [ this.DefaultIconsStrip, this.DefaultIconSize, iconPathOrStripInfoArrayOrIndex ] ; var oButton = new FCKToolbarButtonUI( name, label, tooltip, iconPathOrStripInfoArrayOrIndex, style, state ) ; oButton._FCKToolbar = this ; oButton.OnClick = FCKToolbar_OnItemClick ; return this.AddItem( oButton ) ; } function FCKToolbar_OnItemClick( item ) { var oToolbar = item._FCKToolbar ; if ( oToolbar.OnItemClick ) oToolbar.OnItemClick( oToolbar, item ) ; } FCKToolbar.prototype.AddSeparator = function() { this.AddItem( new FCKToolbarSeparator() ) ; } FCKToolbar.prototype.Create = function( parentElement ) { var oDoc = FCKTools.GetElementDocument( parentElement ) ; var e = oDoc.createElement( 'table' ) ; e.className = 'TB_Toolbar' ; e.style.styleFloat = e.style.cssFloat = ( FCKLang.Dir == 'ltr' ? 'left' : 'right' ) ; e.dir = FCKLang.Dir ; e.cellPadding = 0 ; e.cellSpacing = 0 ; var targetRow = e.insertRow(-1) ; // Insert the start cell. var eCell ; if ( !this.HideStart ) { eCell = targetRow.insertCell(-1) ; eCell.appendChild( oDoc.createElement( 'div' ) ).className = 'TB_Start' ; } for ( var i = 0 ; i < this.Items.length ; i++ ) { this.Items[i].Create( targetRow.insertCell(-1) ) ; } // Insert the ending cell. if ( !this.HideEnd ) { eCell = targetRow.insertCell(-1) ; eCell.appendChild( oDoc.createElement( 'div' ) ).className = 'TB_End' ; } parentElement.appendChild( e ) ; } var FCKToolbarSeparator = function() {} FCKToolbarSeparator.prototype.Create = function( parentElement ) { FCKTools.AppendElement( parentElement, 'div' ).className = 'TB_Separator' ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKEvents Class: used to handle events is a advanced way. */ var FCKEvents = function( eventsOwner ) { this.Owner = eventsOwner ; this._RegisteredEvents = new Object() ; } FCKEvents.prototype.AttachEvent = function( eventName, functionPointer ) { var aTargets ; if ( !( aTargets = this._RegisteredEvents[ eventName ] ) ) this._RegisteredEvents[ eventName ] = [ functionPointer ] ; else { // Check that the event handler isn't already registered with the same listener // It doesn't detect function pointers belonging to an object (at least in Gecko) if ( aTargets.IndexOf( functionPointer ) == -1 ) aTargets.push( functionPointer ) ; } } FCKEvents.prototype.FireEvent = function( eventName, params ) { var bReturnValue = true ; var oCalls = this._RegisteredEvents[ eventName ] ; if ( oCalls ) { for ( var i = 0 ; i < oCalls.length ; i++ ) { try { bReturnValue = ( oCalls[ i ]( this.Owner, params ) && bReturnValue ) ; } catch(e) { // Ignore the following error. It may happen if pointing to a // script not anymore available (#934): // -2146823277 = Can't execute code from a freed script if ( e.number != -2146823277 ) throw e ; } } } return bReturnValue ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Class for working with a selection range, much like the W3C DOM Range, but * it is not intended to be an implementation of the W3C interface. * (IE Implementation) */ FCKDomRange.prototype.MoveToSelection = function() { this.Release( true ) ; this._Range = new FCKW3CRange( this.Window.document ) ; var oSel = this.Window.document.selection ; if ( oSel.type != 'Control' ) { var eMarkerStart = this._GetSelectionMarkerTag( true ) ; var eMarkerEnd = this._GetSelectionMarkerTag( false ) ; if ( !eMarkerStart && !eMarkerEnd ) { this._Range.setStart( this.Window.document.body, 0 ) ; this._UpdateElementInfo() ; return ; } // Set the start boundary. this._Range.setStart( eMarkerStart.parentNode, FCKDomTools.GetIndexOf( eMarkerStart ) ) ; eMarkerStart.parentNode.removeChild( eMarkerStart ) ; // Set the end boundary. this._Range.setEnd( eMarkerEnd.parentNode, FCKDomTools.GetIndexOf( eMarkerEnd ) ) ; eMarkerEnd.parentNode.removeChild( eMarkerEnd ) ; this._UpdateElementInfo() ; } else { var oControl = oSel.createRange().item(0) ; if ( oControl ) { this._Range.setStartBefore( oControl ) ; this._Range.setEndAfter( oControl ) ; this._UpdateElementInfo() ; } } } FCKDomRange.prototype.Select = function( forceExpand ) { if ( this._Range ) this.SelectBookmark( this.CreateBookmark( true ), forceExpand ) ; } // Not compatible with bookmark created with CreateBookmark2. // The bookmark nodes will be deleted from the document. FCKDomRange.prototype.SelectBookmark = function( bookmark, forceExpand ) { var bIsCollapsed = this.CheckIsCollapsed() ; var bIsStartMarkerAlone ; var dummySpan ; // Create marker tags for the start and end boundaries. var eStartMarker = this.GetBookmarkNode( bookmark, true ) ; if ( !eStartMarker ) return ; var eEndMarker ; if ( !bIsCollapsed ) eEndMarker = this.GetBookmarkNode( bookmark, false ) ; // Create the main range which will be used for the selection. var oIERange = this.Window.document.body.createTextRange() ; // Position the range at the start boundary. oIERange.moveToElementText( eStartMarker ) ; oIERange.moveStart( 'character', 1 ) ; if ( eEndMarker ) { // Create a tool range for the end. var oIERangeEnd = this.Window.document.body.createTextRange() ; // Position the tool range at the end. oIERangeEnd.moveToElementText( eEndMarker ) ; // Move the end boundary of the main range to match the tool range. oIERange.setEndPoint( 'EndToEnd', oIERangeEnd ) ; oIERange.moveEnd( 'character', -1 ) ; } else { bIsStartMarkerAlone = forceExpand || !eStartMarker.previousSibling || eStartMarker.previousSibling.nodeName.toLowerCase() == 'br'; // Append a temporary <span>&#65279;</span> before the selection. // This is needed to avoid IE destroying selections inside empty // inline elements, like <b></b> (#253). // It is also needed when placing the selection right after an inline // element to avoid the selection moving inside of it. dummySpan = this.Window.document.createElement( 'span' ) ; dummySpan.innerHTML = '&#65279;' ; // Zero Width No-Break Space (U+FEFF). See #1359. eStartMarker.parentNode.insertBefore( dummySpan, eStartMarker ) ; if ( bIsStartMarkerAlone ) { // To expand empty blocks or line spaces after <br>, we need // instead to have any char, which will be later deleted using the // selection. // \ufeff = Zero Width No-Break Space (U+FEFF). See #1359. eStartMarker.parentNode.insertBefore( this.Window.document.createTextNode( '\ufeff' ), eStartMarker ) ; } } if ( !this._Range ) this._Range = this.CreateRange() ; // Remove the markers (reset the position, because of the changes in the DOM tree). this._Range.setStartBefore( eStartMarker ) ; eStartMarker.parentNode.removeChild( eStartMarker ) ; if ( bIsCollapsed ) { if ( bIsStartMarkerAlone ) { // Move the selection start to include the temporary &#65279;. oIERange.moveStart( 'character', -1 ) ; oIERange.select() ; // Remove our temporary stuff. this.Window.document.selection.clear() ; } else oIERange.select() ; FCKDomTools.RemoveNode( dummySpan ) ; } else { this._Range.setEndBefore( eEndMarker ) ; eEndMarker.parentNode.removeChild( eEndMarker ) ; oIERange.select() ; } } FCKDomRange.prototype._GetSelectionMarkerTag = function( toStart ) { var doc = this.Window.document ; var selection = doc.selection ; // Get a range for the start boundary. var oRange ; // IE may throw an "unspecified error" on some cases (it happened when // loading _samples/default.html), so try/catch. try { oRange = selection.createRange() ; } catch (e) { return null ; } // IE might take the range object to the main window instead of inside the editor iframe window. // This is known to happen when the editor window has not been selected before (See #933). // We need to avoid that. if ( oRange.parentElement().document != doc ) return null ; oRange.collapse( toStart === true ) ; // Paste a marker element at the collapsed range and get it from the DOM. var sMarkerId = 'fck_dom_range_temp_' + (new Date()).valueOf() + '_' + Math.floor(Math.random()*1000) ; oRange.pasteHTML( '<span id="' + sMarkerId + '"></span>' ) ; return doc.getElementById( sMarkerId ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 class can be used to interate through nodes inside a range. * * During interation, the provided range can become invalid, due to document * mutations, so CreateBookmark() used to restore it after processing, if * needed. */ var FCKHtmlIterator = function( source ) { this._sourceHtml = source ; } FCKHtmlIterator.prototype = { Next : function() { var sourceHtml = this._sourceHtml ; if ( sourceHtml == null ) return null ; var match = FCKRegexLib.HtmlTag.exec( sourceHtml ) ; var isTag = false ; var value = "" ; if ( match ) { if ( match.index > 0 ) { value = sourceHtml.substr( 0, match.index ) ; this._sourceHtml = sourceHtml.substr( match.index ) ; } else { isTag = true ; value = match[0] ; this._sourceHtml = sourceHtml.substr( match[0].length ) ; } } else { value = sourceHtml ; this._sourceHtml = null ; } return { 'isTag' : isTag, 'value' : value } ; }, Each : function( func ) { var chunk ; while ( ( chunk = this.Next() ) ) func( chunk.isTag, chunk.value ) ; } } ; /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 class can be used to interate through nodes inside a range. * * During interation, the provided range can become invalid, due to document * mutations, so CreateBookmark() used to restore it after processing, if * needed. */ var FCKHtmlIterator = function( source ) { this._sourceHtml = source ; } FCKHtmlIterator.prototype = { Next : function() { var sourceHtml = this._sourceHtml ; if ( sourceHtml == null ) return null ; var match = FCKRegexLib.HtmlTag.exec( sourceHtml ) ; var isTag = false ; var value = "" ; if ( match ) { if ( match.index > 0 ) { value = sourceHtml.substr( 0, match.index ) ; this._sourceHtml = sourceHtml.substr( match.index ) ; } else { isTag = true ; value = match[0] ; this._sourceHtml = sourceHtml.substr( match[0].length ) ; } } else { value = sourceHtml ; this._sourceHtml = null ; } return { 'isTag' : isTag, 'value' : value } ; }, Each : function( func ) { var chunk ; while ( ( chunk = this.Next() ) ) func( chunk.isTag, chunk.value ) ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Class for working with a selection range, much like the W3C DOM Range, but * it is not intended to be an implementation of the W3C interface. * (Gecko Implementation) */ FCKDomRange.prototype.MoveToSelection = function() { this.Release( true ) ; var oSel = this.Window.getSelection() ; if ( oSel && oSel.rangeCount > 0 ) { this._Range = FCKW3CRange.CreateFromRange( this.Window.document, oSel.getRangeAt(0) ) ; this._UpdateElementInfo() ; } else if ( this.Window.document ) this.MoveToElementStart( this.Window.document.body ) ; } FCKDomRange.prototype.Select = function() { var oRange = this._Range ; if ( oRange ) { var startContainer = oRange.startContainer ; // If we have a collapsed range, inside an empty element, we must add // something to it, otherwise the caret will not be visible. if ( oRange.collapsed && startContainer.nodeType == 1 && startContainer.childNodes.length == 0 ) startContainer.appendChild( oRange._Document.createTextNode('') ) ; var oDocRange = this.Window.document.createRange() ; oDocRange.setStart( startContainer, oRange.startOffset ) ; try { oDocRange.setEnd( oRange.endContainer, oRange.endOffset ) ; } catch ( e ) { // There is a bug in Firefox implementation (it would be too easy // otherwise). The new start can't be after the end (W3C says it can). // So, let's create a new range and collapse it to the desired point. if ( e.toString().Contains( 'NS_ERROR_ILLEGAL_VALUE' ) ) { oRange.collapse( true ) ; oDocRange.setEnd( oRange.endContainer, oRange.endOffset ) ; } else throw( e ) ; } var oSel = this.Window.getSelection() ; oSel.removeAllRanges() ; // We must add a clone otherwise Firefox will have rendering issues. oSel.addRange( oDocRange ) ; } } // Not compatible with bookmark created with CreateBookmark2. // The bookmark nodes will be deleted from the document. FCKDomRange.prototype.SelectBookmark = function( bookmark ) { var domRange = this.Window.document.createRange() ; var startNode = this.GetBookmarkNode( bookmark, true ) ; var endNode = this.GetBookmarkNode( bookmark, false ) ; domRange.setStart( startNode.parentNode, FCKDomTools.GetIndexOf( startNode ) ) ; FCKDomTools.RemoveNode( startNode ) ; if ( endNode ) { domRange.setEnd( endNode.parentNode, FCKDomTools.GetIndexOf( endNode ) ) ; FCKDomTools.RemoveNode( endNode ) ; } var selection = this.Window.getSelection() ; selection.removeAllRanges() ; selection.addRange( domRange ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * The Data Processor is responsible for transforming the input and output data * in the editor. For more info: * http://dev.fckeditor.net/wiki/Components/DataProcessor * * The default implementation offers the base XHTML compatibility features of * FCKeditor. Further Data Processors may be implemented for other purposes. * */ var FCKDataProcessor = function() {} FCKDataProcessor.prototype = { /* * 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>, including <head>, <body> and * eventually the DOCTYPE. * Note: HTML comments may already be part of the data because of the * pre-processing made with ProtectedSource. * @param {String} data The data to be converted in the * DataProcessor specific format. */ ConvertToHtml : function( data ) { // The default data processor must handle two different cases depending // on the FullPage setting. Custom Data Processors will not be // compatible with FullPage, much probably. if ( FCKConfig.FullPage ) { // Save the DOCTYPE. FCK.DocTypeDeclaration = data.match( FCKRegexLib.DocTypeTag ) ; // Check if the <body> tag is available. if ( !FCKRegexLib.HasBodyTag.test( data ) ) data = '<body>' + data + '</body>' ; // Check if the <html> tag is available. if ( !FCKRegexLib.HtmlOpener.test( data ) ) data = '<html dir="' + FCKConfig.ContentLangDirection + '">' + data + '</html>' ; // Check if the <head> tag is available. if ( !FCKRegexLib.HeadOpener.test( data ) ) data = data.replace( FCKRegexLib.HtmlOpener, '$&<head><title></title></head>' ) ; return data ; } else { var html = FCKConfig.DocType + '<html dir="' + FCKConfig.ContentLangDirection + '"' ; // On IE, if you are using a DOCTYPE different of HTML 4 (like // XHTML), you must force the vertical scroll to show, otherwise // the horizontal one may appear when the page needs vertical scrolling. // TODO : Check it with IE7 and make it IE6- if it is the case. if ( FCKBrowserInfo.IsIE && FCKConfig.DocType.length > 0 && !FCKRegexLib.Html4DocType.test( FCKConfig.DocType ) ) html += ' style="overflow-y: scroll"' ; html += '><head><title></title></head>' + '<body' + FCKConfig.GetBodyAttributes() + '>' + data + '</body></html>' ; return 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 = FCKXHtml.GetXHTML( rootNode, !excludeRoot, format ) ; if ( ignoreIfEmptyParagraph && FCKRegexLib.EmptyOutParagraph.test( data ) ) return '' ; 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 ; } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Preload a list of images, firing an event when complete. */ var FCKImagePreloader = function() { this._Images = new Array() ; } FCKImagePreloader.prototype = { AddImages : function( images ) { if ( typeof( images ) == 'string' ) images = images.split( ';' ) ; this._Images = this._Images.concat( images ) ; }, Start : function() { var aImages = this._Images ; this._PreloadCount = aImages.length ; for ( var i = 0 ; i < aImages.length ; i++ ) { var eImg = document.createElement( 'img' ) ; FCKTools.AddEventListenerEx( eImg, 'load', _FCKImagePreloader_OnImage, this ) ; FCKTools.AddEventListenerEx( eImg, 'error', _FCKImagePreloader_OnImage, this ) ; eImg.src = aImages[i] ; _FCKImagePreloader_ImageCache.push( eImg ) ; } } }; // All preloaded images must be placed in a global array, otherwise the preload // magic will not happen. var _FCKImagePreloader_ImageCache = new Array() ; function _FCKImagePreloader_OnImage( ev, imagePreloader ) { if ( (--imagePreloader._PreloadCount) == 0 && imagePreloader.OnComplete ) imagePreloader.OnComplete() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKPlugin Class: Represents a single plugin. */ var FCKPlugin = function( name, availableLangs, basePath ) { this.Name = name ; this.BasePath = basePath ? basePath : FCKConfig.PluginsPath ; this.Path = this.BasePath + name + '/' ; if ( !availableLangs || availableLangs.length == 0 ) this.AvailableLangs = new Array() ; else this.AvailableLangs = availableLangs.split(',') ; } FCKPlugin.prototype.Load = function() { // Load the language file, if defined. if ( this.AvailableLangs.length > 0 ) { var sLang ; // Check if the plugin has the language file for the active language. if ( this.AvailableLangs.IndexOf( FCKLanguageManager.ActiveLanguage.Code ) >= 0 ) sLang = FCKLanguageManager.ActiveLanguage.Code ; else // Load the default language file (first one) if the current one is not available. sLang = this.AvailableLangs[0] ; // Add the main plugin script. LoadScript( this.Path + 'lang/' + sLang + '.js' ) ; } // Add the main plugin script. LoadScript( this.Path + 'fckplugin.js' ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 class is a menu block that behaves like a panel. It's a mix of the * FCKMenuBlock and FCKPanel classes. */ var FCKMenuBlockPanel = function() { // Call the "base" constructor. FCKMenuBlock.call( this ) ; } FCKMenuBlockPanel.prototype = new FCKMenuBlock() ; // Override the create method. FCKMenuBlockPanel.prototype.Create = function() { var oPanel = this.Panel = ( this.Parent && this.Parent.Panel ? this.Parent.Panel.CreateChildPanel() : new FCKPanel() ) ; oPanel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; // Call the "base" implementation. FCKMenuBlock.prototype.Create.call( this, oPanel.MainNode ) ; } FCKMenuBlockPanel.prototype.Show = function( x, y, relElement ) { if ( !this.Panel.CheckIsOpened() ) this.Panel.Show( x, y, relElement ) ; } FCKMenuBlockPanel.prototype.Hide = function() { if ( this.Panel.CheckIsOpened() ) this.Panel.Hide() ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Renders a list of menu items. */ var FCKMenuBlock = function() { this._Items = new Array() ; } FCKMenuBlock.prototype.Count = function() { return this._Items.length ; } FCKMenuBlock.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) { var oItem = new FCKMenuItem( this, name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) ; oItem.OnClick = FCKTools.CreateEventListener( FCKMenuBlock_Item_OnClick, this ) ; oItem.OnActivate = FCKTools.CreateEventListener( FCKMenuBlock_Item_OnActivate, this ) ; this._Items.push( oItem ) ; return oItem ; } FCKMenuBlock.prototype.AddSeparator = function() { this._Items.push( new FCKMenuSeparator() ) ; } FCKMenuBlock.prototype.RemoveAllItems = function() { this._Items = new Array() ; var eItemsTable = this._ItemsTable ; if ( eItemsTable ) { while ( eItemsTable.rows.length > 0 ) eItemsTable.deleteRow( 0 ) ; } } FCKMenuBlock.prototype.Create = function( parentElement ) { if ( !this._ItemsTable ) { if ( FCK.IECleanup ) FCK.IECleanup.AddItem( this, FCKMenuBlock_Cleanup ) ; this._Window = FCKTools.GetElementWindow( parentElement ) ; var oDoc = FCKTools.GetElementDocument( parentElement ) ; var eTable = parentElement.appendChild( oDoc.createElement( 'table' ) ) ; eTable.cellPadding = 0 ; eTable.cellSpacing = 0 ; FCKTools.DisableSelection( eTable ) ; var oMainElement = eTable.insertRow(-1).insertCell(-1) ; oMainElement.className = 'MN_Menu' ; var eItemsTable = this._ItemsTable = oMainElement.appendChild( oDoc.createElement( 'table' ) ) ; eItemsTable.cellPadding = 0 ; eItemsTable.cellSpacing = 0 ; } for ( var i = 0 ; i < this._Items.length ; i++ ) this._Items[i].Create( this._ItemsTable ) ; } /* Events */ function FCKMenuBlock_Item_OnClick( clickedItem, menuBlock ) { if ( menuBlock.Hide ) menuBlock.Hide() ; FCKTools.RunFunction( menuBlock.OnClick, menuBlock, [ clickedItem ] ) ; } function FCKMenuBlock_Item_OnActivate( menuBlock ) { var oActiveItem = menuBlock._ActiveItem ; if ( oActiveItem && oActiveItem != this ) { // Set the focus to this menu block window (to fire OnBlur on opened panels). if ( !FCKBrowserInfo.IsIE && oActiveItem.HasSubMenu && !this.HasSubMenu ) { menuBlock._Window.focus() ; // Due to the event model provided by Opera, we need to set // HasFocus here as the above focus() call will not fire the focus // event in the panel immediately (#1200). menuBlock.Panel.HasFocus = true ; } oActiveItem.Deactivate() ; } menuBlock._ActiveItem = this ; } function FCKMenuBlock_Cleanup() { this._Window = null ; this._ItemsTable = null ; } // ################# // var FCKMenuSeparator = function() {} FCKMenuSeparator.prototype.Create = function( parentTable ) { var oDoc = FCKTools.GetElementDocument( parentTable ) ; var r = parentTable.insertRow(-1) ; var eCell = r.insertCell(-1) ; eCell.className = 'MN_Separator MN_Icon' ; eCell = r.insertCell(-1) ; eCell.className = 'MN_Separator' ; eCell.appendChild( oDoc.createElement( 'DIV' ) ).className = 'MN_Separator_Line' ; eCell = r.insertCell(-1) ; eCell.className = 'MN_Separator' ; eCell.appendChild( oDoc.createElement( 'DIV' ) ).className = 'MN_Separator_Line' ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * FCKToolbarPanelButton Class: Handles the Fonts combo selector. */ var FCKToolbarFontsCombo = function( tooltip, style ) { this.CommandName = 'FontName' ; this.Label = this.GetLabel() ; this.Tooltip = tooltip ? tooltip : this.Label ; this.Style = style ? style : FCK_TOOLBARITEM_ICONTEXT ; this.DefaultLabel = FCKConfig.DefaultFontLabel || '' ; } // Inherit from FCKToolbarSpecialCombo. FCKToolbarFontsCombo.prototype = new FCKToolbarFontFormatCombo( false ) ; FCKToolbarFontsCombo.prototype.GetLabel = function() { return FCKLang.Font ; } FCKToolbarFontsCombo.prototype.GetStyles = function() { var baseStyle = FCKStyles.GetStyle( '_FCK_FontFace' ) ; if ( !baseStyle ) { alert( "The FCKConfig.CoreStyles['Size'] setting was not found. Please check the fckconfig.js file" ) ; return {} ; } var styles = {} ; var fonts = FCKConfig.FontNames.split(';') ; for ( var i = 0 ; i < fonts.length ; i++ ) { var fontParts = fonts[i].split('/') ; var font = fontParts[0] ; var caption = fontParts[1] || font ; var style = FCKTools.CloneObject( baseStyle ) ; style.SetVariable( 'Font', font ) ; style.Label = caption ; styles[ caption ] = style ; } return styles ; } FCKToolbarFontsCombo.prototype.RefreshActiveItems = FCKToolbarStyleCombo.prototype.RefreshActiveItems ; FCKToolbarFontsCombo.prototype.StyleCombo_OnBeforeClick = function( targetSpecialCombo ) { // Clear the current selection. targetSpecialCombo.DeselectAll() ; var startElement = FCKSelection.GetBoundaryParentElement( true ) ; if ( startElement ) { var path = new FCKElementPath( startElement ) ; for ( var i in targetSpecialCombo.Items ) { var item = targetSpecialCombo.Items[i] ; var style = item.Style ; if ( style.CheckActive( path ) ) { targetSpecialCombo.SelectItem( item ) ; return ; } } } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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/default/' ; 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 ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = true ; FCKConfig.DefaultLanguage = 'en' ; 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["Basic"] = [ ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] ] ; 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' | 'SCAYT' | '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.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.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // 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
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * French language file for the sample plugin. */ FCKLang['DlgMyReplaceTitle'] = 'Plugin - Remplacer' ; FCKLang['DlgMyReplaceFindLbl'] = 'Chercher:' ; FCKLang['DlgMyReplaceReplaceLbl'] = 'Remplacer par:' ; FCKLang['DlgMyReplaceCaseChk'] = 'Respecter la casse' ; FCKLang['DlgMyReplaceReplaceBtn'] = 'Remplacer' ; FCKLang['DlgMyReplaceReplAllBtn'] = 'Remplacer Tout' ; FCKLang['DlgMyReplaceWordChk'] = 'Mot entier' ; FCKLang['DlgMyFindTitle'] = 'Plugin - Chercher' ; FCKLang['DlgMyFindFindBtn'] = 'Chercher' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Italian language file for the sample plugin. */ FCKLang['DlgMyReplaceTitle'] = 'Plugin - Sostituisci' ; FCKLang['DlgMyReplaceFindLbl'] = 'Trova:' ; FCKLang['DlgMyReplaceReplaceLbl'] = 'Sostituisci con:' ; FCKLang['DlgMyReplaceCaseChk'] = 'Maiuscole/minuscole' ; FCKLang['DlgMyReplaceReplaceBtn'] = 'Sostituisci' ; FCKLang['DlgMyReplaceReplAllBtn'] = 'Sostituisci tutto' ; FCKLang['DlgMyReplaceWordChk'] = 'Parola intera' ; FCKLang['DlgMyFindTitle'] = 'Plugin - Cerca' ; FCKLang['DlgMyFindFindBtn'] = 'Cerca' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * English language file for the sample plugin. */ FCKLang['DlgMyReplaceTitle'] = 'Plugin - Replace' ; FCKLang['DlgMyReplaceFindLbl'] = 'Find what:' ; FCKLang['DlgMyReplaceReplaceLbl'] = 'Replace with:' ; FCKLang['DlgMyReplaceCaseChk'] = 'Match case' ; FCKLang['DlgMyReplaceReplaceBtn'] = 'Replace' ; FCKLang['DlgMyReplaceReplAllBtn'] = 'Replace All' ; FCKLang['DlgMyReplaceWordChk'] = 'Match whole word' ; FCKLang['DlgMyFindTitle'] = 'Plugin - Find' ; FCKLang['DlgMyFindFindBtn'] = 'Find' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 sample plugin definition file. */ // Register the related commands. FCKCommands.RegisterCommand( 'My_Find' , new FCKDialogCommand( FCKLang['DlgMyFindTitle'] , FCKLang['DlgMyFindTitle'] , FCKConfig.PluginsPath + 'findreplace/find.html' , 340, 170 ) ) ; FCKCommands.RegisterCommand( 'My_Replace' , new FCKDialogCommand( FCKLang['DlgMyReplaceTitle'], FCKLang['DlgMyReplaceTitle'] , FCKConfig.PluginsPath + 'findreplace/replace.html', 340, 200 ) ) ; // Create the "Find" toolbar button. var oFindItem = new FCKToolbarButton( 'My_Find', FCKLang['DlgMyFindTitle'] ) ; oFindItem.IconPath = FCKConfig.PluginsPath + 'findreplace/find.gif' ; FCKToolbarItems.RegisterItem( 'My_Find', oFindItem ) ; // 'My_Find' is the name used in the Toolbar config. // Create the "Replace" toolbar button. var oReplaceItem = new FCKToolbarButton( 'My_Replace', FCKLang['DlgMyReplaceTitle'] ) ; oReplaceItem.IconPath = FCKConfig.PluginsPath + 'findreplace/replace.gif' ; FCKToolbarItems.RegisterItem( 'My_Replace', oReplaceItem ) ; // 'My_Replace' is the name used in the Toolbar config.
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 plugin definition file. */ // Here we define our custom Style combo, with custom widths. var oMyBigStyleCombo = new FCKToolbarStyleCombo() ; oMyBigStyleCombo.FieldWidth = 250 ; oMyBigStyleCombo.PanelWidth = 300 ; FCKToolbarItems.RegisterItem( 'My_BigStyle', oMyBigStyleCombo ) ; // ##### Defining a custom context menu entry. // ## 1. Define the command to be executed when selecting the context menu item. var oMyCMCommand = new Object() ; oMyCMCommand.Name = 'OpenImage' ; // This is the standard function used to execute the command (called when clicking in the context menu item). oMyCMCommand.Execute = function() { // This command is called only when an image element is selected (IMG). // Get image URL (src). var sUrl = FCKSelection.GetSelectedElement().src ; // Open the URL in a new window. window.top.open( sUrl ) ; } // This is the standard function used to retrieve the command state (it could be disabled for some reason). oMyCMCommand.GetState = function() { // Let's make it always enabled. return FCK_TRISTATE_OFF ; } // ## 2. Register our custom command. FCKCommands.RegisterCommand( 'OpenImage', oMyCMCommand ) ; // ## 3. Define the context menu "listener". var oMyContextMenuListener = new Object() ; // This is the standard function called right before sowing the context menu. oMyContextMenuListener.AddItems = function( contextMenu, tag, tagName ) { // Let's show our custom option only for images. if ( tagName == 'IMG' ) { contextMenu.AddSeparator() ; contextMenu.AddItem( 'OpenImage', 'Open image in a new window (Custom)' ) ; } } // ## 4. Register our context menu listener. FCK.ContextMenu.RegisterListener( oMyContextMenuListener ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Configuration settings used by the XHTML 1.1 sample page (sample14.html). */ // Our intention is force all formatting features to use CSS classes or // semantic aware elements. // Load our custom CSS files for this sample. // We are using "BasePath" just for this sample convenience. In normal // situations it would be just pointed to the file directly, // like "/css/myfile.css". FCKConfig.EditorAreaCSS = FCKConfig.BasePath + '../_samples/html/assets/sample14.styles.css' ; /** * Core styles. */ FCKConfig.CoreStyles.Bold = { Element : 'span', Attributes : { 'class' : 'Bold' } } ; FCKConfig.CoreStyles.Italic = { Element : 'span', Attributes : { 'class' : 'Italic' } } ; FCKConfig.CoreStyles.Underline = { Element : 'span', Attributes : { 'class' : 'Underline' } } ; FCKConfig.CoreStyles.StrikeThrough = { Element : 'span', Attributes : { 'class' : 'StrikeThrough' } } ; /** * Font face */ // List of fonts available in the toolbar combo. Each font definition is // separated by a semi-colon (;). We are using class names here, so each font // is defined by {Class Name}/{Combo Label}. FCKConfig.FontNames = 'FontComic/Comic Sans MS;FontCourier/Courier New;FontTimes/Times New Roman' ; // Define the way font elements will be applied to the document. The "span" // element will be used. When a font is selected, the font name defined in the // above list is passed to this definition with the name "Font", being it // injected in the "class" attribute. // We must also instruct the editor to replace span elements that are used to // set the font (Overrides). FCKConfig.CoreStyles.FontFace = { Element : 'span', Attributes : { 'class' : '#("Font")' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^Font(?:Comic|Courier|Times)$/ } } ] } ; /** * Font sizes. */ FCKConfig.FontSizes = 'FontSmaller/Smaller;FontLarger/Larger;FontSmall/8pt;FontBig/14pt;FontDouble/Double Size' ; FCKConfig.CoreStyles.Size = { Element : 'span', Attributes : { 'class' : '#("Size")' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^Font(?:Smaller|Larger|Small|Big|Double)$/ } } ] } ; /** * Font colors. */ FCKConfig.EnableMoreFontColors = false ; FCKConfig.FontColors = 'ff9900/FontColor1,0066cc/FontColor2,ff0000/FontColor3' ; FCKConfig.CoreStyles.Color = { Element : 'span', Attributes : { 'class' : '#("Color")' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^FontColor(?:1|2|3)$/ } } ] } ; FCKConfig.CoreStyles.BackColor = { Element : 'span', Attributes : { 'class' : '#("Color")BG' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^FontColor(?:1|2|3)BG$/ } } ] } ; /** * Indentation. */ FCKConfig.IndentClasses = [ 'Indent1', 'Indent2', 'Indent3' ] ; /** * Paragraph justification. */ FCKConfig.JustifyClasses = [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyFull' ] ; /** * Styles combo. */ FCKConfig.StylesXmlPath = '' ; FCKConfig.CustomStyles = { 'Strong Emphasis' : { Element : 'strong' }, 'Emphasis' : { Element : 'em' }, 'Computer Code' : { Element : 'code' }, 'Keyboard Phrase' : { Element : 'kbd' }, 'Sample Text' : { Element : 'samp' }, 'Variable' : { Element : 'var' }, 'Deleted Text' : { Element : 'del' }, 'Inserted Text' : { Element : 'ins' }, 'Cited Work' : { Element : 'cite' }, 'Inline Quotation' : { Element : 'q' } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Configuration settings used by the XHTML 1.1 sample page (sample14.html). */ // Our intention is force all formatting features to use CSS classes or // semantic aware elements. /** * Core styles. */ FCKConfig.CoreStyles.Bold = { Element : 'b' } ; FCKConfig.CoreStyles.Italic = { Element : 'i' } ; FCKConfig.CoreStyles.Underline = { Element : 'u' } ; /** * Font face */ // Define the way font elements will be applied to the document. The "span" // element will be used. When a font is selected, the font name defined in the // above list is passed to this definition with the name "Font", being it // injected in the "class" attribute. // We must also instruct the editor to replace span elements that are used to // set the font (Overrides). FCKConfig.CoreStyles.FontFace = { Element : 'font', Attributes : { 'face' : '#("Font")' } } ; /** * Font sizes. * The CSS part of the font sizes isn't used by Flash, it is there to get the * font rendered correctly in FCKeditor. */ FCKConfig.FontSizes = '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px' ; FCKConfig.CoreStyles.Size = { Element : 'font', Attributes : { 'size' : '#("Size")' }, Styles : { 'font-size' : '#("Size","fontSize")' } } ; /** * Font colors. */ FCKConfig.EnableMoreFontColors = true ; FCKConfig.CoreStyles.Color = { Element : 'font', Attributes : { 'color' : '#("Color")' } } ; /** * Styles combo. */ FCKConfig.StylesXmlPath = '' ; FCKConfig.CustomStyles = { } ; /** * Toolbar set for Flash HTML editing. */ FCKConfig.ToolbarSets['Flash'] = [ ['Source','-','Bold','Italic','Underline','-','UnorderedList','-','Link','Unlink'], ['FontName','FontSize','-','About'] ] ; /** * Flash specific formatting settings. */ FCKConfig.EditorAreaStyles = 'p, ol, ul {margin-top: 0px; margin-bottom: 0px;}' ; FCKConfig.FormatSource = false ; FCKConfig.FormatOutput = false ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 == * * Configuration settings used by the XHTML 1.1 sample page (sample14.html). */ // Our intention is force all formatting features to use CSS classes or // semantic aware elements. /** * Core styles. */ FCKConfig.CoreStyles.Bold = { Element : 'b' } ; FCKConfig.CoreStyles.Italic = { Element : 'i' } ; FCKConfig.CoreStyles.Underline = { Element : 'u' } ; FCKConfig.CoreStyles.StrikeThrough = { Element : 'strike' } ; /** * Font face */ // Define the way font elements will be applied to the document. The "span" // element will be used. When a font is selected, the font name defined in the // above list is passed to this definition with the name "Font", being it // injected in the "class" attribute. // We must also instruct the editor to replace span elements that are used to // set the font (Overrides). FCKConfig.CoreStyles.FontFace = { Element : 'font', Attributes : { 'face' : '#("Font")' } } ; /** * Font sizes. */ FCKConfig.FontSizes = '1/xx-small;2/x-small;3/small;4/medium;5/large;6/x-large;7/xx-large' ; FCKConfig.CoreStyles.Size = { Element : 'font', Attributes : { 'size' : '#("Size")' } } ; /** * Font colors. */ FCKConfig.EnableMoreFontColors = true ; FCKConfig.CoreStyles.Color = { Element : 'font', Attributes : { 'color' : '#("Color")' } } ; FCKConfig.CoreStyles.BackColor = { Element : 'font', Styles : { 'background-color' : '#("Color","color")' } } ; /** * Styles combo. */ FCKConfig.StylesXmlPath = '' ; FCKConfig.CustomStyles = { 'Computer Code' : { Element : 'code' }, 'Keyboard Phrase' : { Element : 'kbd' }, 'Sample Text' : { Element : 'samp' }, 'Variable' : { Element : 'var' }, 'Deleted Text' : { Element : 'del' }, 'Inserted Text' : { Element : 'ins' }, 'Cited Work' : { Element : 'cite' }, 'Inline Quotation' : { Element : 'q' } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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 in the plugin sample page (sample06). */ // Set our sample toolbar. FCKConfig.ToolbarSets['PluginTest'] = [ ['SourceSimple'], ['My_Find','My_Replace','-','Placeholder'], ['StyleSimple','FontFormatSimple','FontNameSimple','FontSizeSimple'], ['Table','-','TableInsertRowAfter','TableDeleteRows','TableInsertColumnAfter','TableDeleteColumns','TableInsertCellAfter','TableDeleteCells','TableMergeCells','TableHorizontalSplitCell','TableCellProp'], ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink'], '/', ['My_BigStyle','-','Smiley','-','About'] ] ; // Change the default plugin path. FCKConfig.PluginsPath = FCKConfig.BasePath.substr(0, FCKConfig.BasePath.length - 7) + '_samples/_plugins/' ; // Add our plugin to the plugins list. // FCKConfig.Plugins.Add( pluginName, availableLanguages ) // pluginName: The plugin name. The plugin directory must match this name. // availableLanguages: a list of available language files for the plugin (separated by a comma). FCKConfig.Plugins.Add( 'findreplace', 'en,fr,it' ) ; FCKConfig.Plugins.Add( 'samples' ) ; // If you want to use plugins found on other directories, just use the third parameter. var sOtherPluginPath = FCKConfig.BasePath.substr(0, FCKConfig.BasePath.length - 7) + 'editor/plugins/' ; FCKConfig.Plugins.Add( 'placeholder', 'de,en,es,fr,it,pl', sOtherPluginPath ) ; FCKConfig.Plugins.Add( 'tablecommands', null, sOtherPluginPath ) ; FCKConfig.Plugins.Add( 'simplecommands', null, sOtherPluginPath ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 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.6' ; FCKeditor.prototype.VersionBuild = '25427' ; 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
var cal; var isFocus=false; //是否为焦点 function SelectDate(obj,strFormat) { var date = new Date(); var by = date.getFullYear()-50; //最小值 → 50 年前 var ey = date.getFullYear()+50; //最大值 → 50 年后 cal = (cal==null) ? new Calendar(by, ey, 1) : cal; cal.dateFormatStyle = strFormat; cal.show(obj); } String.prototype.toDate = function(style) { var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年 var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月 var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日 if(isNaN(y)) y = new Date().getFullYear(); if(isNaN(m)) m = new Date().getMonth(); if(isNaN(d)) d = new Date().getDate(); var dt ; eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')"); return dt; } /**//**//**//** * 格式化日期 * @param d the delimiter * @param p the pattern of your date * @author meizz */ Date.prototype.format = function(style) { var o = { "M+" : this.getMonth() + 1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "w+" : "天一二三四五六".charAt(this.getDay()), //week "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(style)) { style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for(var k in o){ if(new RegExp("("+ k +")").test(style)){ style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return style; }; function Calendar(beginYear, endYear, lang, dateFormatStyle) { this.beginYear = 1990; this.endYear = 2010; this.lang = 1; //0(中文) | 1(英文) this.dateFormatStyle = "yyyy-MM-dd"; if (beginYear != null && endYear != null){ this.beginYear = beginYear; this.endYear = endYear; } if (lang != null){ this.lang = lang } if (dateFormatStyle != null){ this.dateFormatStyle = dateFormatStyle } this.dateControl = null; this.panel = this.getElementById("calendarPanel"); this.container = this.getElementById("ContainerPanel"); this.form = null; this.date = new Date(); this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.colors = { "cur_word" : "#FFFFFF", //当日日期文字颜色 "cur_bg" : "#00FF00", //当日日期单元格背影色 "sel_bg" : "#FFCCCC", //已被选择的日期单元格背影色 "sun_word" : "#FF0000", //星期天文字颜色 "sat_word" : "#0000FF", //星期六文字颜色 "td_word_light" : "#333333", //单元格文字颜色 "td_word_dark" : "#CCCCCC", //单元格文字暗色 "td_bg_out" : "#EFEFEF", //单元格背影色 "td_bg_over" : "#FFCC00", //单元格背影色 "tr_word" : "#FFFFFF", //日历头文字颜色 "tr_bg" : "#666666", //日历头背影色 "input_border" : "#CCCCCC", //input控件的边框颜色 "input_bg" : "#EFEFEF" //input控件的背影色 } this.draw(); this.bindYear(); this.bindMonth(); this.changeSelect(); this.bindData(); } /**//**//**//** * 日历类属性(语言包,可自由扩展) */ Calendar.language = { "year" : [[""], [""]], "months" : [["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"], ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"] ], "weeks" : [["日","一","二","三","四","五","六"], ["SUN","MON","TUR","WED","THU","FRI","SAT"] ], "clear" : [["清空"], ["CLS"]], "today" : [["今天"], ["TODAY"]], "close" : [["关闭"], ["CLOSE"]] } Calendar.prototype.draw = function() { calendar = this; var mvAry = []; mvAry[mvAry.length] = ' <div name="calendarForm" style="margin: 0px;">'; mvAry[mvAry.length] = ' <table width="100%" border="0" cellpadding="0" cellspacing="1">'; mvAry[mvAry.length] = ' <tr>'; mvAry[mvAry.length] = ' <th align="left" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="prevMonth" type="button" id="prevMonth" value="&lt;" /></th>'; mvAry[mvAry.length] = ' <th align="center" width="98%" nowrap="nowrap"><select name="calendarYear" id="calendarYear" style="font-size:12px;"></select><select name="calendarMonth" id="calendarMonth" style="font-size:12px;"></select></th>'; mvAry[mvAry.length] = ' <th align="right" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="nextMonth" type="button" id="nextMonth" value="&gt;" /></th>'; mvAry[mvAry.length] = ' </tr>'; mvAry[mvAry.length] = ' </table>'; mvAry[mvAry.length] = ' <table id="calendarTable" width="100%" style="border:0px solid #CCCCCC;background-color:#FFFFFF" border="0" cellpadding="3" cellspacing="1">'; mvAry[mvAry.length] = ' <tr>'; for(var i = 0; i < 7; i++) { mvAry[mvAry.length] = ' <th style="font-weight:normal;background-color:' + calendar.colors["tr_bg"] + ';color:' + calendar.colors["tr_word"] + ';">' + Calendar.language["weeks"][this.lang][i] + '</th>'; } mvAry[mvAry.length] = ' </tr>'; for(var i = 0; i < 6;i++){ mvAry[mvAry.length] = ' <tr align="center">'; for(var j = 0; j < 7; j++) { if (j == 0){ mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sun_word"] + ';"></td>'; } else if(j == 6) { mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sat_word"] + ';"></td>'; } else { mvAry[mvAry.length] = ' <td style="cursor:default;"></td>'; } } mvAry[mvAry.length] = ' </tr>'; } mvAry[mvAry.length] = ' <tr style="background-color:' + calendar.colors["input_bg"] + ';">'; mvAry[mvAry.length] = ' <th colspan="2"><input name="calendarClear" type="button" id="calendarClear" value="' + Calendar.language["clear"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' <th colspan="3"><input name="calendarToday" type="button" id="calendarToday" value="' + Calendar.language["today"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' <th colspan="2"><input name="calendarClose" type="button" id="calendarClose" value="' + Calendar.language["close"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>'; mvAry[mvAry.length] = ' </tr>'; mvAry[mvAry.length] = ' </table>'; //mvAry[mvAry.length] = ' </from>'; mvAry[mvAry.length] = ' </div>'; this.panel.innerHTML = mvAry.join(""); var obj = this.getElementById("prevMonth"); obj.onclick = function () {calendar.goPrevMonth(calendar);} obj.onblur = function () {calendar.onblur();} this.prevMonth= obj; obj = this.getElementById("nextMonth"); obj.onclick = function () {calendar.goNextMonth(calendar);} obj.onblur = function () {calendar.onblur();} this.nextMonth= obj; obj = this.getElementById("calendarClear"); obj.onclick = function () {calendar.dateControl.value = "";calendar.hide();} this.calendarClear = obj; obj = this.getElementById("calendarClose"); obj.onclick = function () {calendar.hide();} this.calendarClose = obj; obj = this.getElementById("calendarYear"); obj.onchange = function () {calendar.update(calendar);} obj.onblur = function () {calendar.onblur();} this.calendarYear = obj; obj = this.getElementById("calendarMonth"); with(obj) { onchange = function () {calendar.update(calendar);} onblur = function () {calendar.onblur();} }this.calendarMonth = obj; obj = this.getElementById("calendarToday"); obj.onclick = function () { var today = new Date(); calendar.date = today; calendar.year = today.getFullYear(); calendar.month = today.getMonth(); calendar.changeSelect(); calendar.bindData(); calendar.dateControl.value = today.format(calendar.dateFormatStyle); calendar.hide(); } this.calendarToday = obj; } //年份下拉框绑定数据 Calendar.prototype.bindYear = function() { //var cy = this.form.calendarYear; var cy = this.calendarYear; cy.length = 0; for (var i = this.beginYear; i <= this.endYear; i++){ cy.options[cy.length] = new Option(i + Calendar.language["year"][this.lang], i); } } //月份下拉框绑定数据 Calendar.prototype.bindMonth = function() { //var cm = this.form.calendarMonth; var cm = this.calendarMonth; cm.length = 0; for (var i = 0; i < 12; i++){ cm.options[cm.length] = new Option(Calendar.language["months"][this.lang][i], i); } } //向前一月 Calendar.prototype.goPrevMonth = function(e){ if (this.year == this.beginYear && this.month == 0){return;} this.month--; if (this.month == -1) { this.year--; this.month = 11; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //向后一月 Calendar.prototype.goNextMonth = function(e){ if (this.year == this.endYear && this.month == 11){return;} this.month++; if (this.month == 12) { this.year++; this.month = 0; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //改变SELECT选中状态 Calendar.prototype.changeSelect = function() { //var cy = this.form.calendarYear; //var cm = this.form.calendarMonth; var cy = this.calendarYear; var cm = this.calendarMonth; for (var i= 0; i < cy.length; i++){ if (cy.options[i].value == this.date.getFullYear()){ cy[i].selected = true; break; } } for (var i= 0; i < cm.length; i++){ if (cm.options[i].value == this.date.getMonth()){ cm[i].selected = true; break; } } } //更新年、月 Calendar.prototype.update = function (e){ //this.year = e.form.calendarYear.options[e.form.calendarYear.selectedIndex].value; //this.month = e.form.calendarMonth.options[e.form.calendarMonth.selectedIndex].value; this.year = e.calendarYear.options[e.calendarYear.selectedIndex].value; this.month = e.calendarMonth.options[e.calendarMonth.selectedIndex].value; this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); } //绑定数据到月视图 Calendar.prototype.bindData = function () { var calendar = this; var dateArray = this.getMonthViewArray(this.date.getYear(), this.date.getMonth()); var tds = this.getElementById("calendarTable").getElementsByTagName("td"); for(var i = 0; i < tds.length; i++) { //tds[i].style.color = calendar.colors["td_word_light"]; tds[i].style.backgroundColor = calendar.colors["td_bg_out"]; tds[i].onclick = function () {return;} tds[i].onmouseover = function () {return;} tds[i].onmouseout = function () {return;} if (i > dateArray.length - 1) break; tds[i].innerHTML = dateArray[i]; if (dateArray[i] != "&nbsp;"){ tds[i].onclick = function () { if (calendar.dateControl != null){ calendar.dateControl.value = new Date(calendar.date.getFullYear(), calendar.date.getMonth(), this.innerHTML).format(calendar.dateFormatStyle); } calendar.hide(); } tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["td_bg_out"]; } if (new Date().format(calendar.dateFormatStyle) == new Date(calendar.date.getFullYear(), calendar.date.getMonth(), dateArray[i]).format(calendar.dateFormatStyle)) { //tds[i].style.color = calendar.colors["cur_word"]; tds[i].style.backgroundColor = calendar.colors["cur_bg"]; tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["cur_bg"]; } //continue; //若不想当天单元格的背景被下面的覆盖,请取消注释 }//end if if (calendar.dateControl != null && calendar.dateControl.value == new Date(calendar.date.getFullYear(), calendar.date.getMonth(), dateArray[i]).format(calendar.dateFormatStyle)) { tds[i].style.backgroundColor = calendar.colors["sel_bg"]; tds[i].onmouseover = function () { this.style.backgroundColor = calendar.colors["td_bg_over"]; } tds[i].onmouseout = function () { this.style.backgroundColor = calendar.colors["sel_bg"]; } } } } } //根据年、月得到月视图数据(数组形式) Calendar.prototype.getMonthViewArray = function (y, m) { var mvArray = []; var dayOfFirstDay = new Date(y, m, 1).getDay(); var daysOfMonth = new Date(y, m + 1, 0).getDate(); for (var i = 0; i < 42; i++) { mvArray[i] = "&nbsp;"; } for (var i = 0; i < daysOfMonth; i++){ mvArray[i + dayOfFirstDay] = i + 1; } return mvArray; } //扩展 document.getElementById(id) 多浏览器兼容性 from meizz tree source Calendar.prototype.getElementById = function(id){ if (typeof(id) != "string" || id == "") return null; if (document.getElementById) return document.getElementById(id); if (document.all) return document.all(id); try {return eval(id);} catch(e){ return null;} } //扩展 object.getElementsByTagName(tagName) Calendar.prototype.getElementsByTagName = function(object, tagName){ if (document.getElementsByTagName) return document.getElementsByTagName(tagName); if (document.all) return document.all.tags(tagName); } //取得HTML控件绝对位置 Calendar.prototype.getAbsPoint = function (e){ var x = e.offsetLeft; var y = e.offsetTop; while(e = e.offsetParent){ x += e.offsetLeft; y += e.offsetTop; } return {"x": x, "y": y}; } //显示日历 Calendar.prototype.show = function (dateObj, popControl) { if (dateObj == null){ throw new Error("arguments[0] is necessary") } this.dateControl = dateObj; this.date = (dateObj.value.length > 0) ? new Date(dateObj.value.toDate(this.dateFormatStyle)) : new Date() this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.changeSelect(); this.bindData(); //} if (popControl == null){ popControl = dateObj; } var xy = this.getAbsPoint(popControl); this.panel.style.left = xy.x -25 + "px"; this.panel.style.top = (xy.y + dateObj.offsetHeight) + "px"; this.panel.style.display = ""; this.container.style.display = ""; dateObj.onblur = function(){calendar.onblur();} this.container.onmouseover = function(){isFocus=true;} this.container.onmouseout = function(){isFocus=false;} } //隐藏日历 Calendar.prototype.hide = function() { //this.setDisplayStyle("select", "visible"); //this.panel.style.visibility = "hidden"; //this.container.style.visibility = "hidden"; this.panel.style.display = "none"; this.container.style.display = "none"; isFocus=false; } Calendar.prototype.onblur = function() { if(!isFocus){this.hide();} } document.write('<div id="ContainerPanel" style="display:none"><div id="calendarPanel" style="position: absolute;display: none;z-index: 9999;'); document.write('background-color: #FFFFFF;border: 1px solid #CCCCCC;width:175px;font-size:12px;"></div>'); if(document.all) { document.write('<iframe style="position:absolute;z-index:2000;width:expression(this.previousSibling.offsetWidth);'); document.write('height:expression(this.previousSibling.offsetHeight);'); document.write('left:expression(this.previousSibling.offsetLeft);top:expression(this.previousSibling.offsetTop);'); document.write('display:expression(this.previousSibling.style.display);" scrolling="no" frameborder="no"></iframe>'); } document.write('</div>'); //调用calendar.show(dateControl, popControl);
JavaScript
function Window() { this.commonPop = popWin; } function popWin(theURL,winName,theW,theH,showAsModal) { theTop = (window.screen.height-theH)/2; theLeft = (window.screen.width-theW)/2; var features = "toolbar=0,scrollbars=yes,left=" + theLeft + ",top=" + theTop + ",width=" + theW + ",height=" + theH; window.SubWin = window.open(theURL,winName,features); window.SubWin.focus(); if(showAsModal){ window.CtrlsDisabled = new Array(); DisableCtrls("INPUT;SELECT;TEXTAREA;BUTTON"); } function DisableCtrls(tagNameStr){ var arrTags = tagNameStr.split(";"); for(var i=0;i<arrTags.length;i++){ var arrEle = document.getElementsByTagName(arrTags[i]); PushToCtrlsDisabled(arrEle); } for(var i=0;i<window.CtrlsDisabled.length;i++){ window.CtrlsDisabled[i].disabled = true; window.CtrlsDisabled[i].readOnly = true; } } function PushToCtrlsDisabled(arrEle){ for(var i=0;i<arrEle.length;i++){ if(!arrEle[i].disabled){ window.CtrlsDisabled.push(arrEle[i]); } } } window.onfocus = function(){ if(window.SubWin && showAsModal){ if(window.SubWin.closed == true || typeof(window.SubWin.closed) == "undefined"){ for(var i=0;i<window.CtrlsDisabled.length;i++){ window.CtrlsDisabled[i].disabled = false; window.CtrlsDisabled[i].readOnly = false; } }else{ window.SubWin.focus(); } } } }
JavaScript
/* 文档说明-->WEB前台验证的类 * * @link http://... * @copyright 2005 Ling Deming * @author gaby <ldmmyx@hotmail.com> * @version 1.0 */ /* 验证对象的构造函数 * */ function Validation() { this.errorInfo = ''; //-- 函数返回的错误信息 this.isNumber = isNumber; //-- 判断是否是数字的方法 this.isEmail = isEmail; //-- 判断是否是Email地址的方法 this.isUrl = isUrl; //-- 判断是否是网址的方法 this.isDate = isDate; //-- 判断是否是日期 this.isChinese = isChinese; //-- 判断是否是中文 this.isEmpty = isEmpty; //-- this.isEmailEN = isEmailEN; //-- this.isCompare = isCompare; //-- 比较两个字串的长度和是否相等,一般用在密码比较 this.isMobile = isMobile; //-- 判断是否手机号码(简单的测试) this.strCheckMobile = strCheckMobile; //-- 判断是否手机号码(简单的测试) this.validFloat = validFloat; //-- 判断是否是数字和小数位数限制 this.isConfirmOperate = isConfirmOperate ; this.isCompareEN = isCompareEN; //-- 比较两个字串的长度和是否相等,一般用在密码比较 } /* 判断是否是数字 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param return boolean ← true: 是数字 false: 不是数字 */ function isNumber(objectID,labelName, allowEmpty) { if(allowEmpty != undefined){ if(document.getElementById(objectID).value == ''){ return true; } } if(labelName == undefined) labelName=''; if(document.getElementById(objectID).value == ''){ alert(labelName+" isn't number."); document.getElementById(objectID).focus(); return false; }else if(document.getElementById(objectID).value.match('^[0-9]{1,}$')) return true; else{ alert(labelName+" isn't number."); document.getElementById(objectID).focus(); return false; } } /* 判断是否是email地址 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param string allowEmpty ← 是否允许空值,不定义是不允许 * @param return boolean ← true: 是email地址 false: 不是email地址 */ function isEmail(objectID,labelName,allowEmpty) { if(allowEmpty != undefined){ if(document.getElementById(objectID).value == ''){ return true; } } if(labelName == undefined) labelName=''; if(document.getElementById(objectID).value == ''){ alert(labelName+'请输入Email地址!'); document.getElementById(objectID).focus(); return false; }else if (document.getElementById(objectID).value.match("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}$")) return true; else{ alert(labelName+'输入的不是正确的Email地址!'); document.getElementById(objectID).focus(); return false; } } /* 判断是否是email地址 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param string allowEmpty ← 是否允许空值,不定义是不允许 * @param return boolean ← true: 是email地址 false: 不是email地址 */ function isEmailEN(objectID,labelName,allowEmpty) { if(allowEmpty != undefined){ if(document.getElementById(objectID).value == ''){ return true; } } if(labelName == undefined) labelName=''; if(document.getElementById(objectID).value == ''){ alert(labelName+' is required.'); document.getElementById(objectID).focus(); return false; }else if (document.getElementById(objectID).value.match("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}$")) return true; else{ alert(labelName+' is invalid.'); document.getElementById(objectID).focus(); return false; } } /* 判断是否是网址 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param string DefaulValue ← 设默认值,有默认值时对象的值和默认值相同返回真,不定义时进行验证 * @param return boolean ← true: 是网址 false: 不是网址 */ function isUrl(objectID,labelName,DefaulValue) { if(labelName == undefined) labelName=''; if(DefaulValue != undefined){ if(document.getElementById(objectID).value == DefaulValue){ return true; } } if(document.getElementById(objectID).value == ''){ alert(labelName+'请输入网址!'); document.getElementById(objectID).focus(); return false; }else if (document.getElementById(objectID).value.match('^http:\/\/[a-z0-9@:%_.~#-\?&]+$')) return true; else{ alert(labelName+'输入的不是正确的网址!'); document.getElementById(objectID).focus(); return false; } } /* 判断是否是中文 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param string yesVSno ← 要判断的是不是中文,默认是 * @param return boolean ← true: 是中文 false: 不是中文 */ function isChinese(objectID,labelName,yesVSno) { if(labelName == undefined) labelName=''; if(yesVSno == undefined) yesVSno='yes'; if(document.getElementById(objectID).value == ''){ if(yesVSno == 'yes') alert(labelName+'请输入中文字符!'); else alert(labelName+'请输入不包含中文的字符!'); document.getElementById(objectID).focus(); return false; }else if (document.getElementById(objectID).value.replace(/[ -}]/g,'')){ if(yesVSno == 'no'){ alert(labelName+'输入的字符中有中文字符!'); document.getElementById(objectID).focus(); return false; }else return true; }else{ if(yesVSno == 'yes'){ alert(labelName+'输入的不是中文!'); document.getElementById(objectID).focus(); return false; }else return true; } } /* 判断是否是日期 格式 yyyy-mm-dd * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param return boolean ← true: 是日期 false: 不是日期 */ function isDate(objectID,labelName) { if(labelName == undefined) labelName=''; if(document.getElementById(objectID).value == ''){ alert(labelName+'请输入日期!'); document.getElementById(objectID).focus(); return false; }else if (document.getElementById(objectID).value.match("[0-2][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9]")){ if(parseInt(document.getElementById(objectID).value.substr(5,2))>12){ alert(labelName+'输入的日期月份不对!'); document.getElementById(objectID).focus(); return false; }else if(parseInt(document.getElementById(objectID).value.substr(8,2))>31){ alert(labelName+'输入的日期天数不对!'); document.getElementById(objectID).focus(); return false; }else return true; }else{ alert(labelName+'输入的不是正确的日期格式!格式:yyyy-mm-dd'); document.getElementById(objectID).focus(); return false; } } /* 判断是否为空 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param string limitLength ← 限制长度的大小 * @param return boolean ← true: 是空 false: 不为空 */ function isEmpty(objectID,labelName, limitLength) { if(labelName == undefined) labelName=''; if(document.getElementById(objectID).value == ''){ alert(labelName+" is required."); document.getElementById(objectID).focus(); return true; }else if(limitLength != undefined){ if(document.getElementById(objectID).value.length > limitLength){ alert(labelName + ' length more than' + limitLength + " char."); document.getElementById(objectID).focus(); return true; }else return false; }else return false; } /* 比较两个字串的长度和是否相等,一般用在密码比较 * * @param string inputObject1 ← 要比较的对象1 * @param string inputObject2 ← 要比较的对象2 * @param string downLength ← 限定下限长度 * @param string topLength ← 限定上限长度 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param return boolean ← true: 一致 false: 不同 */ function isCompare(objectID1,objectID2,labelName,downLength,topLength) { if(labelName == undefined) labelName=''; if(document.getElementById(objectID1).value == ''){ alert(labelName+'不能为空!'); document.getElementById(objectID1).focus(); return false; } if(downLength != undefined && downLength != 0){ if(document.getElementById(objectID1).value.length < downLength){ alert(labelName+'需要输入至少'+downLength+'个字符!'); document.getElementById(objectID1).focus(); return false; } } if(topLength != undefined && topLength != 0){ if(document.getElementById(objectID2).value.length > topLength){ alert(labelName+'不能输入大于'+topLength+'个字符!'); document.getElementById(objectID2).focus(); return false; } } if(document.getElementById(objectID1).value != document.getElementById(objectID2).value){ alert(labelName+'两次输入不相同!'); document.getElementById(objectID1).focus(); return false; }else return true; } /* 比较两个字串的长度和是否相等,一般用在密码比较 * * @param string inputObject1 ← 要比较的对象1 * @param string inputObject2 ← 要比较的对象2 * @param string downLength ← 限定下限长度 * @param string topLength ← 限定上限长度 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param return boolean ← true: 一致 false: 不同 */ function isCompareEN(objectID1,objectID2,labelName,downLength,topLength) { if(labelName == undefined) labelName=''; if(document.getElementById(objectID1).value == ''){ alert(labelName+' should not be empty.'); document.getElementById(objectID1).focus(); return false; } if(downLength != undefined && downLength != 0){ if(document.getElementById(objectID1).value.length < downLength){ alert(labelName+' can not less than '+downLength+' char.'); document.getElementById(objectID1).focus(); return false; } } if(topLength != undefined && topLength != 0){ if(document.getElementById(objectID2).value.length > topLength){ alert(labelName+' can not more than '+topLength+' char.'); document.getElementById(objectID2).focus(); return false; } } if(document.getElementById(objectID1).value != document.getElementById(objectID2).value){ alert(labelName+' input is differece with two times.'); document.getElementById(objectID1).focus(); return false; }else return true; } /* 判断是否为手机号码(包括小灵通,只能进行简单的测试) * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param return boolean ← true: 是空 false: 不为空 */ function isMobile(objectID,labelName) { if(labelName == undefined) labelName=''; var strValue = document.getElementById(objectID).value; if(strValue == ''){ alert(labelName+'不能为空!'); document.getElementById(objectID).focus(); return false; }else if(!strValue.match('^[0-9]{1,}$')){ alert(labelName+'不是数字!'); return false; }else if((strValue.substr(0,2) == "13") || (strValue.substr(0,2) == "15")){ if(strValue.length == 11){ return true; }else{ alert(labelName+'位数不对!'); return false; } }else if(strValue.substring(0,1) == "0"){ if(strValue.length > 9){ return true; }else{ alert(labelName + '位数不对!'); return false; } }else{ alert("请输入正确的" + labelName); return false; } } /* 判断手机号码所属运营商 * * @param string mobile ← 要判断的手机号码 * @param return boolean ← true: 是空 false: 不为空 */ function strCheckMobile(strMobile) { if(strMobile == "") return "em"; //-- 为空 if(strMobile.match("^13[0-3]{1}[0-9]{8}$")){ return "cu"; //-- 联通号码 }else if(strMobile.match("^13[4-9]{1}[0-9]{8}$")){ return "cm"; //-- 移动号码 }else if(strMobile.match("^0[1-9]{1}") && strMobile.length > 9){ return "phs"; //-- 小灵通号码 }else return "no"; //-- 不是手机 } /* 判断输入值是否数字和位数 * * @param string inputObject ← 要判断的对象 * @param string labelName ← 显示要判断的对象的名字相关的信息 * @param string digit ← 限制的位数 * @param return boolean ← true: 输入正确 false: 输入不正确 */ function validFloat(objectID, labelName, digit) { if(isNaN(document.getElementById(objectID).value)){ alert("请输入有效数字"); document.getElementById(objectID).focus(); return false; } if(!checkDecimal(document.getElementById(objectID).value, digit)){ alert("您输入的数据小数位最多为" + digit + "个小数位"); document.getElementById(objectID).focus(); return false; } return true; } /* 检查小数位数 * * @param string num ← 要检查的值 * @param string decimalLen ← 限制的位数 * @param return boolean ← true: 输入正确 false: 输入不正确 */ function checkDecimal(num,decimalLen) { var len = decimalLen*1+1; if(num.indexOf('.')>0){ num=num.substr(num.indexOf('.')+1,num.length-1); if ((num.length)<len){ return true; }else{ return false; } } return true; } function isConfirmOperate(operate) { if(confirm("Your confirm to continue the " + operate + " operation ?")) return true; else return false; } var validDefault = new Validation();
JavaScript
/* Yetii - Yet (E)Another Tab Interface Implementation http://www.kminek.pl/lab/yetii/ Copyright (c) 2007 Grzegorz Wojcik Code licensed under the BSD License: http://www.kminek.pl/bsdlicense.txt */ function Yetii() { this.defaults = { id: null, active: 1, timeout: null, interval: null, tabclass: 'tab', activeclass: 'active' }; for (var n in arguments[0]) { this.defaults[n]=arguments[0][n]; }; this.getTabs = function() { var retnode = []; var elem = document.getElementById(this.defaults.id).getElementsByTagName('*'); var regexp = new RegExp("(^|\\s)" + this.defaults.tabclass.replace(/\-/g, "\\-") + "(\\s|$)"); for (var i = 0; i < elem.length; i++) { if (regexp.test(elem[i].className)) retnode.push(elem[i]); } return retnode; }; this.links = document.getElementById(this.defaults.id + '-nav').getElementsByTagName('a'); this.show = function(number){ for (var i = 0; i < this.tabs.length; i++) { this.tabs[i].style.display = ((i+1)==number) ? 'block' : 'none'; this.links[i].className = ((i+1)==number) ? this.defaults.activeclass : ''; } }; this.rotate = function(interval){ this.show(this.defaults.active); this.defaults.active++; if(this.defaults.active > this.tabs.length) this.defaults.active = 1; var self = this; this.defaults.timeout = setTimeout(function(){self.rotate(interval);}, interval*1000); }; this.tabs = this.getTabs(); this.show(this.defaults.active); var self = this; for (var i = 0; i < this.links.length; i++) { this.links[i].customindex = i+1; this.links[i].onclick = function(){ if (self.defaults.timeout) clearTimeout(self.defaults.timeout); self.show(this.customindex); return false; }; } if (this.defaults.interval) this.rotate(this.defaults.interval); };
JavaScript
// ----------------------------------------------------------------------------------- // // Lightbox v2.03.3 // by Lokesh Dhakar - http://www.huddletogether.com // 5/21/06 // // For more information on this script, visit: // http://huddletogether.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // // Credit also due to those who have helped, inspired, and made their code available to the public. // Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), Thomas Fuchs(mir.aculo.us), and others. // // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Global Variables Extending Built-in Objects - Object.extend(Element) - Array.prototype.removeDuplicates() - Array.prototype.empty() Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Miscellaneous Functions - getPageScroll() - getPageSize() - getKey() - listenKey() - showSelectBoxes() - hideSelectBoxes() - showFlash() - hideFlash() - pause() - initLightbox() Function Calls - addLoadEvent(initLightbox) */ // ----------------------------------------------------------------------------------- // // Configuration // var fileLoadingImage = "images/loading.gif"; var fileBottomNavCloseImage = "images/closelabel.gif"; var overlayOpacity = 0.8; // controls transparency of shadow overlay var animate = true; // toggles resizing animations var resizeSpeed = 7; // controls the speed of the image resizing animations (1=slowest and 10=fastest) var borderSize = 10; //if you adjust the padding in the CSS, you will need to update this variable // ----------------------------------------------------------------------------------- // // Global Variables // var imageArray = new Array; var activeImage; if(animate == true){ overlayDuration = 0.2; // shadow fade in/out duration if(resizeSpeed > 10){ resizeSpeed = 10;} if(resizeSpeed < 1){ resizeSpeed = 1;} resizeDuration = (11 - resizeSpeed) * 0.15; } else { overlayDuration = 0; resizeDuration = 0; } // ----------------------------------------------------------------------------------- // // Additional methods for Element added by SU, Couloir // - further additions by Lokesh Dhakar (huddletogether.com) // Object.extend(Element, { getWidth: function(element) { element = $(element); return element.offsetWidth; }, setWidth: function(element,w) { element = $(element); element.style.width = w +"px"; }, setHeight: function(element,h) { element = $(element); element.style.height = h +"px"; }, setTop: function(element,t) { element = $(element); element.style.top = t +"px"; }, setLeft: function(element,l) { element = $(element); element.style.left = l +"px"; }, setSrc: function(element,src) { element = $(element); element.src = src; }, setHref: function(element,href) { element = $(element); element.href = href; }, setInnerHTML: function(element,content) { element = $(element); element.innerHTML = content; } }); // ----------------------------------------------------------------------------------- // // Extending built-in Array object // - array.removeDuplicates() // - array.empty() // Array.prototype.removeDuplicates = function () { for(i = 0; i < this.length; i++){ for(j = this.length-1; j>i; j--){ if(this[i][0] == this[j][0]){ this.splice(j,1); } } } } // ----------------------------------------------------------------------------------- Array.prototype.empty = function () { for(i = 0; i <= this.length; i++){ this.shift(); } } // ----------------------------------------------------------------------------------- // // Lightbox Class Declaration // - initialize() // - start() // - changeImage() // - resizeImageContainer() // - showImage() // - updateDetails() // - updateNav() // - enableKeyboardNav() // - disableKeyboardNav() // - keyboardNavAction() // - preloadNeighborImages() // - end() // // Structuring of code inspired by Scott Upton (http://www.uptonic.com/) // var Lightbox = Class.create(); Lightbox.prototype = { // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = document.getElementsByTagName("body").item(0); var objOverlay = document.createElement("div"); objOverlay.setAttribute('id','overlay'); objOverlay.style.display = 'none'; objOverlay.onclick = function() { myLightbox.end(); } objBody.appendChild(objOverlay); var objLightbox = document.createElement("div"); objLightbox.setAttribute('id','lightbox'); objLightbox.style.display = 'none'; objLightbox.onclick = function(e) { // close Lightbox is user clicks shadow overlay if (!e) var e = window.event; var clickObj = Event.element(e).id; if ( clickObj == 'lightbox') { myLightbox.end(); } }; objBody.appendChild(objLightbox); var objOuterImageContainer = document.createElement("div"); objOuterImageContainer.setAttribute('id','outerImageContainer'); objLightbox.appendChild(objOuterImageContainer); // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. if(animate){ Element.setWidth('outerImageContainer', 250); Element.setHeight('outerImageContainer', 250); } else { Element.setWidth('outerImageContainer', 1); Element.setHeight('outerImageContainer', 1); } var objImageContainer = document.createElement("div"); objImageContainer.setAttribute('id','imageContainer'); objOuterImageContainer.appendChild(objImageContainer); var objLightboxImage = document.createElement("img"); objLightboxImage.setAttribute('id','lightboxImage'); objImageContainer.appendChild(objLightboxImage); var objHoverNav = document.createElement("div"); objHoverNav.setAttribute('id','hoverNav'); objImageContainer.appendChild(objHoverNav); var objPrevLink = document.createElement("a"); objPrevLink.setAttribute('id','prevLink'); objPrevLink.setAttribute('href','#'); objHoverNav.appendChild(objPrevLink); var objNextLink = document.createElement("a"); objNextLink.setAttribute('id','nextLink'); objNextLink.setAttribute('href','#'); objHoverNav.appendChild(objNextLink); var objLoading = document.createElement("div"); objLoading.setAttribute('id','loading'); objImageContainer.appendChild(objLoading); var objLoadingLink = document.createElement("a"); objLoadingLink.setAttribute('id','loadingLink'); objLoadingLink.setAttribute('href','#'); objLoadingLink.onclick = function() { myLightbox.end(); return false; } objLoading.appendChild(objLoadingLink); var objLoadingImage = document.createElement("img"); objLoadingImage.setAttribute('src', fileLoadingImage); objLoadingLink.appendChild(objLoadingImage); var objImageDataContainer = document.createElement("div"); objImageDataContainer.setAttribute('id','imageDataContainer'); objLightbox.appendChild(objImageDataContainer); var objImageData = document.createElement("div"); objImageData.setAttribute('id','imageData'); objImageDataContainer.appendChild(objImageData); var objImageDetails = document.createElement("div"); objImageDetails.setAttribute('id','imageDetails'); objImageData.appendChild(objImageDetails); var objCaption = document.createElement("span"); objCaption.setAttribute('id','caption'); objImageDetails.appendChild(objCaption); var objNumberDisplay = document.createElement("span"); objNumberDisplay.setAttribute('id','numberDisplay'); objImageDetails.appendChild(objNumberDisplay); var objBottomNav = document.createElement("div"); objBottomNav.setAttribute('id','bottomNav'); objImageData.appendChild(objBottomNav); var objBottomNavCloseLink = document.createElement("a"); objBottomNavCloseLink.setAttribute('id','bottomNavClose'); objBottomNavCloseLink.setAttribute('href','#'); objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; } objBottomNav.appendChild(objBottomNavCloseLink); var objBottomNavCloseImage = document.createElement("img"); objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage); objBottomNavCloseLink.appendChild(objBottomNavCloseImage); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { if (!document.getElementsByTagName){ return; } var anchors = document.getElementsByTagName('a'); var areas = document.getElementsByTagName('area'); // loop through all anchor tags for (var i=0; i<anchors.length; i++){ var anchor = anchors[i]; var relAttribute = String(anchor.getAttribute('rel')); // use the string.match() method to catch 'lightbox' references in the rel attribute if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){ anchor.onclick = function () {myLightbox.start(this); return false;} } } // loop through all area tags // todo: combine anchor & area tag loops for (var i=0; i< areas.length; i++){ var area = areas[i]; var relAttribute = String(area.getAttribute('rel')); // use the string.match() method to catch 'lightbox' references in the rel attribute if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){ area.onclick = function () {myLightbox.start(this); return false;} } } }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { hideSelectBoxes(); hideFlash(); // stretch overlay to fill page and fade in var arrayPageSize = getPageSize(); Element.setWidth('overlay', arrayPageSize[0]); Element.setHeight('overlay', arrayPageSize[1]); new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity }); imageArray = []; imageNum = 0; if (!document.getElementsByTagName){ return; } var anchors = document.getElementsByTagName( imageLink.tagName); // if image is NOT part of a set.. if((imageLink.getAttribute('rel') == 'lightbox')){ // add single image to imageArray imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title'))); } else { // if image is part of a set.. // loop through anchors, find other images in set, and add them to imageArray for (var i=0; i<anchors.length; i++){ var anchor = anchors[i]; if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){ imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title'))); } } imageArray.removeDuplicates(); while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;} } // calculate top and left offset for the lightbox var arrayPageScroll = getPageScroll(); var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10); var lightboxLeft = arrayPageScroll[0]; Element.setTop('lightbox', lightboxTop); Element.setLeft('lightbox', lightboxLeft); Element.show('lightbox'); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { activeImage = imageNum; // update global var // hide elements during transition if(animate){ Element.show('loading');} Element.hide('lightboxImage'); Element.hide('hoverNav'); Element.hide('prevLink'); Element.hide('nextLink'); Element.hide('imageDataContainer'); Element.hide('numberDisplay'); imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload=function(){ Element.setSrc('lightboxImage', imageArray[activeImage][0]); myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height); imgPreloader.onload=function(){}; // clear onLoad, IE behaves irratically with animated gifs otherwise } imgPreloader.src = imageArray[activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function( imgWidth, imgHeight) { // get curren width and height this.widthCurrent = Element.getWidth('outerImageContainer'); this.heightCurrent = Element.getHeight('outerImageContainer'); // get new width and height var widthNew = (imgWidth + (borderSize * 2)); var heightNew = (imgHeight + (borderSize * 2)); // scalars based on change from old to new this.xScale = ( widthNew / this.widthCurrent) * 100; this.yScale = ( heightNew / this.heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary wDiff = this.widthCurrent - widthNew; hDiff = this.heightCurrent - heightNew; if(!( hDiff == 0)){ new Effect.Scale('outerImageContainer', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); } if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); } // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. if((hDiff == 0) && (wDiff == 0)){ if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} } Element.setHeight('prevLink', imgHeight); Element.setHeight('nextLink', imgHeight); Element.setWidth( 'imageDataContainer', widthNew); this.showImage(); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ Element.hide('loading'); new Effect.Appear('lightboxImage', { duration: resizeDuration, queue: 'end', afterFinish: function(){ myLightbox.updateDetails(); } }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { // if caption is not null if(imageArray[activeImage][1]){ Element.show('caption'); Element.setInnerHTML( 'caption', imageArray[activeImage][1]); } // if image is part of set display 'Image x of x' if(imageArray.length > 1){ Element.show('numberDisplay'); Element.setInnerHTML( 'numberDisplay', "Image " + eval(activeImage + 1) + " of " + imageArray.length); } new Effect.Parallel( [ new Effect.SlideDown( 'imageDataContainer', { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear('imageDataContainer', { sync: true, duration: resizeDuration }) ], { duration: resizeDuration, afterFinish: function() { // update overlay size and update nav var arrayPageSize = getPageSize(); Element.setHeight('overlay', arrayPageSize[1]); myLightbox.updateNav(); } } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { Element.show('hoverNav'); // if not first image in set, display prev image button if(activeImage != 0){ Element.show('prevLink'); document.getElementById('prevLink').onclick = function() { myLightbox.changeImage(activeImage - 1); return false; } } // if not last image in set, display next image button if(activeImage != (imageArray.length - 1)){ Element.show('nextLink'); document.getElementById('nextLink').onclick = function() { myLightbox.changeImage(activeImage + 1); return false; } } this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.onkeydown = this.keyboardAction; }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.onkeydown = ''; }, // // keyboardAction() // keyboardAction: function(e) { if (e == null) { // ie keycode = event.keyCode; escapeKey = 27; } else { // mozilla keycode = e.keyCode; escapeKey = e.DOM_VK_ESCAPE; } key = String.fromCharCode(keycode).toLowerCase(); if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox myLightbox.end(); } else if((key == 'p') || (keycode == 37)){ // display previous image if(activeImage != 0){ myLightbox.disableKeyboardNav(); myLightbox.changeImage(activeImage - 1); } } else if((key == 'n') || (keycode == 39)){ // display next image if(activeImage != (imageArray.length - 1)){ myLightbox.disableKeyboardNav(); myLightbox.changeImage(activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ if((imageArray.length - 1) > activeImage){ preloadNextImage = new Image(); preloadNextImage.src = imageArray[activeImage + 1][0]; } if(activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = imageArray[activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); Element.hide('lightbox'); new Effect.Fade('overlay', { duration: overlayDuration}); showSelectBoxes(); showFlash(); } } // ----------------------------------------------------------------------------------- // // getPageScroll() // Returns array with x,y page scroll values. // Core code from - quirksmode.com // function getPageScroll(){ var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) {// all other Explorers yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } arrayPageScroll = new Array(xScroll,yScroll) return arrayPageScroll; } // ----------------------------------------------------------------------------------- // // getPageSize() // Returns array with page width, height and window width, height // Core code from - quirksmode.com // Edit for Firefox by pHaez // function getPageSize(){ var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; // console.log(self.innerWidth); // console.log(document.documentElement.clientWidth); if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // console.log("xScroll " + xScroll) // console.log("windowWidth " + windowWidth) // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } // console.log("pageWidth " + pageWidth) arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) return arrayPageSize; } // ----------------------------------------------------------------------------------- // // getKey(key) // Gets keycode. If 'x' is pressed then it hides the lightbox. // function getKey(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } key = String.fromCharCode(keycode).toLowerCase(); if(key == 'x'){ } } // ----------------------------------------------------------------------------------- // // listenKey() // function listenKey () { document.onkeypress = getKey; } // --------------------------------------------------- function showSelectBoxes(){ var selects = document.getElementsByTagName("select"); for (i = 0; i != selects.length; i++) { selects[i].style.visibility = "visible"; } } // --------------------------------------------------- function hideSelectBoxes(){ var selects = document.getElementsByTagName("select"); for (i = 0; i != selects.length; i++) { selects[i].style.visibility = "hidden"; } } // --------------------------------------------------- function showFlash(){ var flashObjects = document.getElementsByTagName("object"); for (i = 0; i < flashObjects.length; i++) { flashObjects[i].style.visibility = "visible"; } var flashEmbeds = document.getElementsByTagName("embed"); for (i = 0; i < flashEmbeds.length; i++) { flashEmbeds[i].style.visibility = "visible"; } } // --------------------------------------------------- function hideFlash(){ var flashObjects = document.getElementsByTagName("object"); for (i = 0; i < flashObjects.length; i++) { flashObjects[i].style.visibility = "hidden"; } var flashEmbeds = document.getElementsByTagName("embed"); for (i = 0; i < flashEmbeds.length; i++) { flashEmbeds[i].style.visibility = "hidden"; } } // --------------------------------------------------- // // pause(numberMillis) // Pauses code execution for specified time. Uses busy code, not good. // Help from Ran Bar-On [ran2103@gmail.com] // function pause(ms){ var date = new Date(); curDate = null; do{var curDate = new Date();} while( curDate - date < ms); } /* function pause(numberMillis) { var curently = new Date().getTime() + sender; while (new Date().getTime(); } */ // --------------------------------------------------- function initLightbox() { myLightbox = new Lightbox(); } Event.observe(window, 'load', initLightbox, false);
JavaScript
/****************************************************************************** Name: Highslide JS Version: 4.1.8 (October 27 2009) Config: default +inline +ajax +iframe +flash Author: Torstein Hønsi Support: http://highslide.com/support Licence: Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5 License (http://creativecommons.org/licenses/by-nc/2.5/). You are free: * to copy, distribute, display, and perform the work * to make derivative works Under the following conditions: * Attribution. You must attribute the work in the manner specified by the author or licensor. * Noncommercial. You may not use this work for commercial purposes. * For any reuse or distribution, you must make clear to others the license terms of this work. * Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. ******************************************************************************/ if (!hs) { var hs = { // Language strings lang : { cssDirection: 'ltr', loadingText : 'Loading...', loadingTitle : 'Click to cancel', focusTitle : 'Click to bring to front', fullExpandTitle : 'Expand to actual size (f)', creditsText : 'Powered by <i>Highslide JS</i>', creditsTitle : 'Go to the Highslide JS homepage', previousText : 'Previous', nextText : 'Next', moveText : 'Move', closeText : 'Close', closeTitle : 'Close (esc)', resizeTitle : 'Resize', playText : 'Play', playTitle : 'Play slideshow (spacebar)', pauseText : 'Pause', pauseTitle : 'Pause slideshow (spacebar)', previousTitle : 'Previous (arrow left)', nextTitle : 'Next (arrow right)', moveTitle : 'Move', fullExpandText : '1:1', restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.' }, // See http://highslide.com/ref for examples of settings graphicsDir : 'highslide/graphics/', expandCursor : 'zoomin.cur', // null disables restoreCursor : 'zoomout.cur', // null disables expandDuration : 250, // milliseconds restoreDuration : 250, marginLeft : 15, marginRight : 15, marginTop : 15, marginBottom : 15, zIndexCounter : 1001, // adjust to other absolutely positioned elements loadingOpacity : 0.75, allowMultipleInstances: true, numberOfImagesToPreload : 5, outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only outlineStartOffset : 3, // ends at 10 padToMinWidth : false, // pad the popup width to make room for wide caption fullExpandPosition : 'bottom right', fullExpandOpacity : 1, showCredits : true, // you can set this to false if you want creditsHref : 'http://highslide.com/', creditsTarget : '_self', enableKeyListener : true, openerTagNames : ['a'], // Add more to allow slideshow indexing allowWidthReduction : false, allowHeightReduction : true, preserveContent : true, // Preserve changes made to the content and position of HTML popups. objectLoadTime : 'before', // Load iframes 'before' or 'after' expansion. cacheAjax : true, // Cache ajax popups for instant display. Can be overridden for each popup. dragByHeading: true, minWidth: 200, minHeight: 200, allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight outlineType : 'drop-shadow', // set null to disable outlines skin : { contentWrapper: '<div class="highslide-header"><ul>'+ '<li class="highslide-previous">'+ '<a href="#" title="{hs.lang.previousTitle}" onclick="return hs.previous(this)">'+ '<span>{hs.lang.previousText}</span></a>'+ '</li>'+ '<li class="highslide-next">'+ '<a href="#" title="{hs.lang.nextTitle}" onclick="return hs.next(this)">'+ '<span>{hs.lang.nextText}</span></a>'+ '</li>'+ '<li class="highslide-move">'+ '<a href="#" title="{hs.lang.moveTitle}" onclick="return false">'+ '<span>{hs.lang.moveText}</span></a>'+ '</li>'+ '<li class="highslide-close">'+ '<a href="#" title="{hs.lang.closeTitle}" onclick="return hs.close(this)">'+ '<span>{hs.lang.closeText}</span></a>'+ '</li>'+ '</ul></div>'+ '<div class="highslide-body"></div>'+ '<div class="highslide-footer"><div>'+ '<span class="highslide-resize" title="{hs.lang.resizeTitle}"><span></span></span>'+ '</div></div>' }, // END OF YOUR SETTINGS // declare internal properties preloadTheseImages : [], continuePreloading: true, expanders : [], overrides : [ 'allowSizeReduction', 'useBox', 'outlineType', 'outlineWhileAnimating', 'captionId', 'captionText', 'captionEval', 'captionOverlay', 'headingId', 'headingText', 'headingEval', 'headingOverlay', 'creditsPosition', 'dragByHeading', 'width', 'height', 'contentId', 'allowWidthReduction', 'allowHeightReduction', 'preserveContent', 'maincontentId', 'maincontentText', 'maincontentEval', 'objectType', 'cacheAjax', 'objectWidth', 'objectHeight', 'objectLoadTime', 'swfOptions', 'wrapperClassName', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'slideshowGroup', 'easing', 'easingClose', 'fadeInOut', 'src' ], overlays : [], idCounter : 0, oPos : { x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'], y: ['above', 'top', 'middle', 'bottom', 'below'] }, mouse: {}, headingOverlay: {}, captionOverlay: {}, swfOptions: { flashvars: {}, params: {}, attributes: {} }, timers : [], pendingOutlines : {}, sleeping : [], preloadTheseAjax : [], cacheBindings : [], cachedGets : {}, clones : {}, onReady: [], uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 : parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]), ie : (document.all && !window.opera), safari : /Safari/.test(navigator.userAgent), geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent), $ : function (id) { if (id) return document.getElementById(id); }, push : function (arr, val) { arr[arr.length] = val; }, createElement : function (tag, attribs, styles, parent, nopad) { var el = document.createElement(tag); if (attribs) hs.extend(el, attribs); if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0}); if (styles) hs.setStyles(el, styles); if (parent) parent.appendChild(el); return el; }, extend : function (el, attribs) { for (var x in attribs) el[x] = attribs[x]; return el; }, setStyles : function (el, styles) { for (var x in styles) { if (hs.ie && x == 'opacity') { if (styles[x] > 0.99) el.style.removeAttribute('filter'); else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')'; } else el.style[x] = styles[x]; } }, animate: function(el, prop, opt) { var start, end, unit; if (typeof opt != 'object' || opt === null) { var args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (typeof opt.duration != 'number') opt.duration = 250; opt.easing = Math[opt.easing] || Math.easeInQuad; opt.curAnim = hs.extend({}, prop); for (var name in prop) { var e = new hs.fx(el, opt , name ); start = parseFloat(hs.css(el, name)) || 0; end = parseFloat(prop[name]); unit = name != 'opacity' ? 'px' : ''; e.custom( start, end, unit ); } }, css: function(el, prop) { if (document.defaultView) { return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop); } else { if (prop == 'opacity') prop = 'filter'; var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })]; if (prop == 'filter') val = val.replace(/alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100 }); return val === '' ? 1 : val; } }, getPageSize : function () { var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat' ? d.documentElement : d.body; var width = hs.ie ? iebody.clientWidth : (d.documentElement.clientWidth || self.innerWidth), height = hs.ie ? iebody.clientHeight : self.innerHeight; hs.page = { width: width, height: height, scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset, scrollTop: hs.ie ? iebody.scrollTop : pageYOffset } }, getPosition : function(el) { var p = { x: el.offsetLeft, y: el.offsetTop }; while (el.offsetParent) { el = el.offsetParent; p.x += el.offsetLeft; p.y += el.offsetTop; if (el != document.body && el != document.documentElement) { p.x -= el.scrollLeft; p.y -= el.scrollTop; } } return p; }, expand : function(a, params, custom, type) { if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container); if (typeof a.getParams == 'function') return params; if (type == 'html') { for (var i = 0; i < hs.sleeping.length; i++) { if (hs.sleeping[i] && hs.sleeping[i].a == a) { hs.sleeping[i].awake(); hs.sleeping[i] = null; return false; } } hs.hasHtmlExpanders = true; } try { new hs.Expander(a, params, custom, type); return false; } catch (e) { return true; } }, htmlExpand : function(a, params, custom) { return hs.expand(a, params, custom, 'html'); }, getSelfRendered : function() { return hs.createElement('div', { className: 'highslide-html-content', innerHTML: hs.replaceLang(hs.skin.contentWrapper) }); }, getElementByClass : function (el, tagName, className) { var els = el.getElementsByTagName(tagName); for (var i = 0; i < els.length; i++) { if ((new RegExp(className)).test(els[i].className)) { return els[i]; } } return null; }, replaceLang : function(s) { s = s.replace(/\s/g, ' '); var re = /{hs\.lang\.([^}]+)\}/g, matches = s.match(re), lang; if (matches) for (var i = 0; i < matches.length; i++) { lang = matches[i].replace(re, "$1"); if (typeof hs.lang[lang] != 'undefined') s = s.replace(matches[i], hs.lang[lang]); } return s; }, getCacheBinding : function (a) { for (var i = 0; i < hs.cacheBindings.length; i++) { if (hs.cacheBindings[i][0] == a) { var c = hs.cacheBindings[i][1]; hs.cacheBindings[i][1] = c.cloneNode(1); return c; } } return null; }, preloadAjax : function (e) { var arr = hs.getAnchors(); for (var i = 0; i < arr.htmls.length; i++) { var a = arr.htmls[i]; if (hs.getParam(a, 'objectType') == 'ajax' && hs.getParam(a, 'cacheAjax')) hs.push(hs.preloadTheseAjax, a); } hs.preloadAjaxElement(0); }, preloadAjaxElement : function (i) { if (!hs.preloadTheseAjax[i]) return; var a = hs.preloadTheseAjax[i]; var cache = hs.getNode(hs.getParam(a, 'contentId')); if (!cache) cache = hs.getSelfRendered(); var ajax = new hs.Ajax(a, cache, 1); ajax.onError = function () { }; ajax.onLoad = function () { hs.push(hs.cacheBindings, [a, cache]); hs.preloadAjaxElement(i + 1); }; ajax.run(); }, focusTopmost : function() { var topZ = 0, topmostKey = -1, expanders = hs.expanders, exp, zIndex; for (var i = 0; i < expanders.length; i++) { exp = expanders[i]; if (exp) { zIndex = exp.wrapper.style.zIndex; if (zIndex && zIndex > topZ) { topZ = zIndex; topmostKey = i; } } } if (topmostKey == -1) hs.focusKey = -1; else expanders[topmostKey].focus(); }, getParam : function (a, param) { a.getParams = a.onclick; var p = a.getParams ? a.getParams() : null; a.getParams = null; return (p && typeof p[param] != 'undefined') ? p[param] : (typeof hs[param] != 'undefined' ? hs[param] : null); }, getSrc : function (a) { var src = hs.getParam(a, 'src'); if (src) return src; return a.href; }, getNode : function (id) { var node = hs.$(id), clone = hs.clones[id], a = {}; if (!node && !clone) return null; if (!clone) { clone = node.cloneNode(true); clone.id = ''; hs.clones[id] = clone; return node; } else { return clone.cloneNode(true); } }, discardElement : function(d) { if (d) hs.garbageBin.appendChild(d); hs.garbageBin.innerHTML = ''; }, transit : function (adj, exp) { var last = exp = exp || hs.getExpander(); if (hs.upcoming) return false; else hs.last = last; try { hs.upcoming = adj; adj.onclick(); } catch (e){ hs.last = hs.upcoming = null; } try { exp.close(); } catch (e) {} return false; }, previousOrNext : function (el, op) { var exp = hs.getExpander(el); if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp); else return false; }, previous : function (el) { return hs.previousOrNext(el, -1); }, next : function (el) { return hs.previousOrNext(el, 1); }, keyHandler : function(e) { if (!e) e = window.event; if (!e.target) e.target = e.srcElement; // ie if (typeof e.target.form != 'undefined') return true; // form element has focus var exp = hs.getExpander(); var op = null; switch (e.keyCode) { case 70: // f if (exp) exp.doFullExpand(); return true; case 32: // Space case 34: // Page Down case 39: // Arrow right case 40: // Arrow down op = 1; break; case 8: // Backspace case 33: // Page Up case 37: // Arrow left case 38: // Arrow up op = -1; break; case 27: // Escape case 13: // Enter op = 0; } if (op !== null) {hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); if (!hs.enableKeyListener) return true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; if (exp) { if (op == 0) { exp.close(); } else { hs.previousOrNext(exp.key, op); } return false; } } return true; }, registerOverlay : function (overlay) { hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } )); }, getWrapperKey : function (element, expOnly) { var el, re = /^highslide-wrapper-([0-9]+)$/; // 1. look in open expanders el = element; while (el.parentNode) { if (el.id && re.test(el.id)) return el.id.replace(re, "$1"); el = el.parentNode; } // 2. look in thumbnail if (!expOnly) { el = element; while (el.parentNode) { if (el.tagName && hs.isHsAnchor(el)) { for (var key = 0; key < hs.expanders.length; key++) { var exp = hs.expanders[key]; if (exp && exp.a == el) return key; } } el = el.parentNode; } } return null; }, getExpander : function (el, expOnly) { if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null; if (typeof el == 'number') return hs.expanders[el] || null; if (typeof el == 'string') el = hs.$(el); return hs.expanders[hs.getWrapperKey(el, expOnly)] || null; }, isHsAnchor : function (a) { return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/)); }, reOrder : function () { for (var i = 0; i < hs.expanders.length; i++) if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost(); }, mouseClickHandler : function(e) { if (!e) e = window.event; if (e.button > 1) return true; if (!e.target) e.target = e.srcElement; var el = e.target; while (el.parentNode && !(/highslide-(image|move|html|resize)/.test(el.className))) { el = el.parentNode; } var exp = hs.getExpander(el); if (exp && (exp.isClosing || !exp.isExpanded)) return true; if (exp && e.type == 'mousedown') { if (e.target.form) return true; var match = el.className.match(/highslide-(image|move|resize)/); if (match) { hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos, height: exp.y.size, clickX: e.clientX, clickY: e.clientY }; hs.addEventListener(document, 'mousemove', hs.dragHandler); if (e.preventDefault) e.preventDefault(); // FF if (/highslide-(image|html)-blur/.test(exp.content.className)) { exp.focus(); hs.hasFocused = true; } return false; } else if (/highslide-html/.test(el.className) && hs.focusKey != exp.key) { exp.focus(); exp.doShowHide('hidden'); } } else if (e.type == 'mouseup') { hs.removeEventListener(document, 'mousemove', hs.dragHandler); if (hs.dragArgs) { if (hs.styleRestoreCursor && hs.dragArgs.type == 'image') hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor; var hasDragged = hs.dragArgs.hasDragged; if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) { exp.close(); } else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) { hs.dragArgs.exp.doShowHide('hidden'); } if (hs.dragArgs.exp.releaseMask) hs.dragArgs.exp.releaseMask.style.display = 'none'; hs.hasFocused = false; hs.dragArgs = null; } else if (/highslide-image-blur/.test(el.className)) { el.style.cursor = hs.styleRestoreCursor; } } return false; }, dragHandler : function(e) { if (!hs.dragArgs) return true; if (!e) e = window.event; var a = hs.dragArgs, exp = a.exp; if (exp.iframe) { if (!exp.releaseMask) exp.releaseMask = hs.createElement('div', null, { position: 'absolute', width: exp.x.size+'px', height: exp.y.size+'px', left: exp.x.cb+'px', top: exp.y.cb+'px', zIndex: 4, background: (hs.ie ? 'white' : 'none'), opacity: .01 }, exp.wrapper, true); if (exp.releaseMask.style.display == 'none') exp.releaseMask.style.display = ''; } a.dX = e.clientX - a.clickX; a.dY = e.clientY - a.clickY; var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2)); if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0) || (distance > (hs.dragSensitivity || 5)); if (a.hasDragged && e.clientX > 5 && e.clientY > 5) { if (a.type == 'resize') exp.resize(a); else { exp.moveTo(a.left + a.dX, a.top + a.dY); if (a.type == 'image') exp.content.style.cursor = 'move'; } } return false; }, wrapperMouseHandler : function (e) { try { if (!e) e = window.event; var over = /mouseover/i.test(e.type); if (!e.target) e.target = e.srcElement; // ie if (hs.ie) e.relatedTarget = over ? e.fromElement : e.toElement; // ie var exp = hs.getExpander(e.target); if (!exp.isExpanded) return; if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp || hs.dragArgs) return; for (var i = 0; i < exp.overlays.length; i++) (function() { var o = hs.$('hsId'+ exp.overlays[i]); if (o && o.hideOnMouseOut) { if (over) hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur); } })(); } catch (e) {} }, addEventListener : function (el, event, func) { if (el == document && event == 'ready') hs.push(hs.onReady, func); try { el.addEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); el.attachEvent('on'+ event, func); } catch (e) { el['on'+ event] = func; } } }, removeEventListener : function (el, event, func) { try { el.removeEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); } catch (e) { el['on'+ event] = null; } } }, preloadFullImage : function (i) { if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') { var img = document.createElement('img'); img.onload = function() { img = null; hs.preloadFullImage(i + 1); }; img.src = hs.preloadTheseImages[i]; } }, preloadImages : function (number) { if (number && typeof number != 'object') hs.numberOfImagesToPreload = number; var arr = hs.getAnchors(); for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) { hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i])); } // preload outlines if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} ); else hs.preloadFullImage(0); // preload cursor if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor }); }, init : function () { if (!hs.container) { hs.getPageSize(); hs.ieLt7 = hs.ie && hs.uaVersion < 7; hs.ie6SSL = hs.ieLt7 && location.protocol == 'https:'; for (var x in hs.langDefaults) { if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x]; else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined') hs.lang[x] = hs.langDefaults[x]; } hs.container = hs.createElement('div', { className: 'highslide-container' }, { position: 'absolute', left: 0, top: 0, width: '100%', zIndex: hs.zIndexCounter, direction: 'ltr' }, document.body, true ); hs.loading = hs.createElement('a', { className: 'highslide-loading', title: hs.lang.loadingTitle, innerHTML: hs.lang.loadingText, href: 'javascript:;' }, { position: 'absolute', top: '-9999px', opacity: hs.loadingOpacity, zIndex: 1 }, hs.container ); hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container); hs.clearing = hs.createElement('div', null, { clear: 'both', paddingTop: '1px' }, null, true); // http://www.robertpenner.com/easing/ Math.linearTween = function (t, b, c, d) { return c*t/d + b; }; Math.easeInQuad = function (t, b, c, d) { return c*(t/=d)*t + b; }; hs.hideSelects = hs.ieLt7; hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE' || (hs.ie && hs.uaVersion < 5.5)); } }, ready : function() { if (hs.isReady) return; hs.isReady = true; for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i](); }, updateAnchors : function() { var el, els, all = [], images = [], htmls = [],groups = {}, re; for (var i = 0; i < hs.openerTagNames.length; i++) { els = document.getElementsByTagName(hs.openerTagNames[i]); for (var j = 0; j < els.length; j++) { el = els[j]; re = hs.isHsAnchor(el); if (re) { hs.push(all, el); if (re[0] == 'hs.expand') hs.push(images, el); else if (re[0] == 'hs.htmlExpand') hs.push(htmls, el); var g = hs.getParam(el, 'slideshowGroup') || 'none'; if (!groups[g]) groups[g] = []; hs.push(groups[g], el); } } } hs.anchors = { all: all, groups: groups, images: images, htmls: htmls }; return hs.anchors; }, getAnchors : function() { return hs.anchors || hs.updateAnchors(); }, close : function(el) { var exp = hs.getExpander(el); if (exp) exp.close(); return false; } }; // end hs object hs.fx = function( elem, options, prop ){ this.options = options; this.elem = elem; this.prop = prop; if (!options.orig) options.orig = {}; }; hs.fx.prototype = { update: function(){ (hs.fx.step[this.prop] || hs.fx.step._default)(this); if (this.options.step) this.options.step.call(this.elem, this.now, this); }, custom: function(from, to, unit){ this.startTime = (new Date()).getTime(); this.start = from; this.end = to; this.unit = unit;// || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t(gotoEnd){ return self.step(gotoEnd); } t.elem = this.elem; if ( t() && hs.timers.push(t) == 1 ) { hs.timerId = setInterval(function(){ var timers = hs.timers; for ( var i = 0; i < timers.length; i++ ) if ( !timers[i]() ) timers.splice(i--, 1); if ( !timers.length ) { clearInterval(hs.timerId); } }, 13); } }, step: function(gotoEnd){ var t = (new Date()).getTime(); if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; var done = true; for ( var i in this.options.curAnim ) if ( this.options.curAnim[i] !== true ) done = false; if ( done ) { if (this.options.complete) this.options.complete.call(this.elem); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; this.pos = this.options.easing(n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); } return true; } }; hs.extend( hs.fx, { step: { opacity: function(fx){ hs.setStyles(fx.elem, { opacity: fx.now }); }, _default: function(fx){ try { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) fx.elem.style[ fx.prop ] = fx.now + fx.unit; else fx.elem[ fx.prop ] = fx.now; } catch (e) {} } } }); hs.Outline = function (outlineType, onLoad) { this.onLoad = onLoad; this.outlineType = outlineType; var v = hs.uaVersion, tr; this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7; if (!outlineType) { if (onLoad) onLoad(); return; } hs.init(); this.table = hs.createElement( 'table', { cellSpacing: 0 }, { visibility: 'hidden', position: 'absolute', borderCollapse: 'collapse', width: 0 }, hs.container, true ); var tbody = hs.createElement('tbody', null, null, this.table, 1); this.td = []; for (var i = 0; i <= 8; i++) { if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true); this.td[i] = hs.createElement('td', null, null, tr, true); var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' }; hs.setStyles(this.td[i], style); } this.td[4].className = outlineType +' highslide-outline'; this.preloadGraphic(); }; hs.Outline.prototype = { preloadGraphic : function () { var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png"; var appendTo = hs.safari ? hs.container : null; this.graphic = hs.createElement('img', null, { position: 'absolute', top: '-9999px' }, appendTo, true); // for onload trigger var pThis = this; this.graphic.onload = function() { pThis.onGraphicLoad(); }; this.graphic.src = src; }, onGraphicLoad : function () { var o = this.offset = this.graphic.width / 4, pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]], dim = { height: (2*o) +'px', width: (2*o) +'px' }; for (var i = 0; i <= 8; i++) { if (pos[i]) { if (this.hasAlphaImageLoader) { var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px'; var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true); hs.createElement ('div', null, { filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')", position: 'absolute', width: w, height: this.graphic.height +'px', left: (pos[i][0]*o)+'px', top: (pos[i][1]*o)+'px' }, div, true); } else { hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'}); } if (window.opera && (i == 3 || i ==5)) hs.createElement('div', null, dim, this.td[i], true); hs.setStyles (this.td[i], dim); } } this.graphic = null; if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy(); hs.pendingOutlines[this.outlineType] = this; if (this.onLoad) this.onLoad(); }, setPosition : function (pos, offset, vis, dur, easing) { var exp = this.exp, stl = exp.wrapper.style, offset = offset || 0, pos = pos || { x: exp.x.pos + offset, y: exp.y.pos + offset, w: exp.x.get('wsize') - 2 * offset, h: exp.y.get('wsize') - 2 * offset }; if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset) ? 'visible' : 'hidden'; hs.setStyles(this.table, { left: (pos.x - this.offset) +'px', top: (pos.y - this.offset) +'px', width: (pos.w + 2 * this.offset) +'px' }); pos.w -= 2 * this.offset; pos.h -= 2 * this.offset; hs.setStyles (this.td[4], { width: pos.w >= 0 ? pos.w +'px' : 0, height: pos.h >= 0 ? pos.h +'px' : 0 }); if (this.hasAlphaImageLoader) this.td[3].style.height = this.td[5].style.height = this.td[4].style.height; }, destroy : function(hide) { if (hide) this.table.style.visibility = 'hidden'; else hs.discardElement(this.table); } }; hs.Dimension = function(exp, dim) { this.exp = exp; this.dim = dim; this.ucwh = dim == 'x' ? 'Width' : 'Height'; this.wh = this.ucwh.toLowerCase(); this.uclt = dim == 'x' ? 'Left' : 'Top'; this.lt = this.uclt.toLowerCase(); this.ucrb = dim == 'x' ? 'Right' : 'Bottom'; this.rb = this.ucrb.toLowerCase(); this.p1 = this.p2 = 0; }; hs.Dimension.prototype = { get : function(key) { switch (key) { case 'loadingPos': return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2; case 'wsize': return this.size + 2 * this.cb + this.p1 + this.p2; case 'fitsize': return this.clientSize - this.marginMin - this.marginMax; case 'maxsize': return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ; case 'opos': return this.pos - (this.exp.outline ? this.exp.outline.offset : 0); case 'osize': return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0); case 'imgPad': return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0; } }, calcBorders: function() { // correct for borders this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2; this.marginMax = hs['margin'+ this.ucrb]; }, calcThumb: function() { this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) : this.exp.el['offset'+ this.ucwh]; this.tpos = this.exp.tpos[this.dim]; this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2; if (this.tpos == 0 || this.tpos == -1) { this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt]; }; }, calcExpanded: function() { var exp = this.exp; this.justify = 'auto'; // size and position this.pos = this.tpos - this.cb + this.tb; if (this.maxHeight && this.dim == 'x') exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full); this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full); this.minSize = exp.allowSizeReduction ? Math.min(exp['min'+ this.ucwh], this.full) :this.full; if (exp.isImage && exp.useBox) { this.size = exp[this.wh]; this.imgSize = this.full; } if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth; this.marginMin = hs['margin'+ this.uclt]; this.scroll = hs.page['scroll'+ this.uclt]; this.clientSize = hs.page[this.wh]; }, setSize: function(i) { var exp = this.exp; if (exp.isImage && (exp.useBox || hs.padToMinWidth)) { this.imgSize = i; this.size = Math.max(this.size, this.imgSize); exp.content.style[this.lt] = this.get('imgPad')+'px'; } else this.size = i; exp.content.style[this.wh] = i +'px'; exp.wrapper.style[this.wh] = this.get('wsize') +'px'; if (exp.outline) exp.outline.setPosition(); if (exp.releaseMask) exp.releaseMask.style[this.wh] = i +'px'; if (this.dim == 'y' && exp.iDoc && exp.body.style.height != 'auto') try { exp.iDoc.body.style.overflow = 'auto'; } catch (e) {} if (exp.isHtml) { var d = exp.scrollerDiv; if (this.sizeDiff === undefined) this.sizeDiff = exp.innerContent['offset'+ this.ucwh] - d['offset'+ this.ucwh]; d.style[this.wh] = (this.size - this.sizeDiff) +'px'; if (this.dim == 'x') exp.mediumContent.style.width = 'auto'; if (exp.body) exp.body.style[this.wh] = 'auto'; } if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true); }, setPos: function(i) { this.pos = i; this.exp.wrapper.style[this.lt] = i +'px'; if (this.exp.outline) this.exp.outline.setPosition(); } }; hs.Expander = function(a, params, custom, contentType) { if (document.readyState && hs.ie && !hs.isReady) { hs.addEventListener(document, 'ready', function() { new hs.Expander(a, params, custom, contentType); }); return; } this.a = a; this.custom = custom; this.contentType = contentType || 'image'; this.isHtml = (contentType == 'html'); this.isImage = !this.isHtml; hs.continuePreloading = false; this.overlays = []; hs.init(); var key = this.key = hs.expanders.length; // override inline parameters for (var i = 0; i < hs.overrides.length; i++) { var name = hs.overrides[i]; this[name] = params && typeof params[name] != 'undefined' ? params[name] : hs[name]; } if (!this.src) this.src = a.href; // get thumb var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a; el = this.thumb = el.getElementsByTagName('img')[0] || el; this.thumbsUserSetId = el.id || a.id; // check if already open for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].a == a) { hs.expanders[i].focus(); return false; } } // cancel other if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) { hs.expanders[i].cancelLoading(); } } hs.expanders[key] = this; if (!hs.allowMultipleInstances && !hs.upcoming) { if (hs.expanders[key-1]) hs.expanders[key-1].close(); if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey]) hs.expanders[hs.focusKey].close(); } // initiate metrics this.el = el; this.tpos = hs.getPosition(el); hs.getPageSize(); var x = this.x = new hs.Dimension(this, 'x'); x.calcThumb(); var y = this.y = new hs.Dimension(this, 'y'); y.calcThumb(); this.wrapper = hs.createElement( 'div', { id: 'highslide-wrapper-'+ this.key, className: 'highslide-wrapper '+ this.wrapperClassName }, { visibility: 'hidden', position: 'absolute', zIndex: hs.zIndexCounter += 2 }, null, true ); this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler; if (this.contentType == 'image' && this.outlineWhileAnimating == 2) this.outlineWhileAnimating = 0; // get the outline if (!this.outlineType) { this[this.contentType +'Create'](); } else if (hs.pendingOutlines[this.outlineType]) { this.connectOutline(); this[this.contentType +'Create'](); } else { this.showLoading(); var exp = this; new hs.Outline(this.outlineType, function () { exp.connectOutline(); exp[exp.contentType +'Create'](); } ); } return true; }; hs.Expander.prototype = { error : function(e) { // alert ('Line '+ e.lineNumber +': '+ e.message); window.location.href = this.src; }, connectOutline : function() { var outline = this.outline = hs.pendingOutlines[this.outlineType]; outline.exp = this; outline.table.style.zIndex = this.wrapper.style.zIndex - 1; hs.pendingOutlines[this.outlineType] = null; }, showLoading : function() { if (this.onLoadStarted || this.loading) return; this.loading = hs.loading; var exp = this; this.loading.onclick = function() { exp.cancelLoading(); }; var exp = this, l = this.x.get('loadingPos') +'px', t = this.y.get('loadingPos') +'px'; setTimeout(function () { if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })} , 100); }, imageCreate : function() { var exp = this; var img = document.createElement('img'); this.content = img; img.onload = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); }; if (hs.blockRightClick) img.oncontextmenu = function() { return false; }; img.className = 'highslide-image'; hs.setStyles(img, { visibility: 'hidden', display: 'block', position: 'absolute', maxWidth: '9999px', zIndex: 3 }); img.title = hs.lang.restoreTitle; if (hs.safari) hs.container.appendChild(img); if (hs.ie && hs.flushImgSize) img.src = null; img.src = this.src; this.showLoading(); }, htmlCreate : function () { this.content = hs.getCacheBinding(this.a); if (!this.content) this.content = hs.getNode(this.contentId); if (!this.content) this.content = hs.getSelfRendered(); this.getInline(['maincontent']); if (this.maincontent) { var body = hs.getElementByClass(this.content, 'div', 'highslide-body'); if (body) body.appendChild(this.maincontent); this.maincontent.style.display = 'block'; } var innerContent = this.innerContent = this.content; if (/(swf|iframe)/.test(this.objectType)) this.setObjContainerSize(innerContent); // the content tree hs.container.appendChild(this.wrapper); hs.setStyles( this.wrapper, { position: 'static', padding: '0 '+ hs.marginRight +'px 0 '+ hs.marginLeft +'px' }); this.content = hs.createElement( 'div', { className: 'highslide-html' }, { position: 'relative', zIndex: 3, overflow: 'hidden' }, this.wrapper ); this.mediumContent = hs.createElement('div', null, null, this.content, 1); this.mediumContent.appendChild(innerContent); hs.setStyles (innerContent, { position: 'relative', display: 'block', direction: hs.lang.cssDirection || '' }); if (this.width) innerContent.style.width = this.width +'px'; if (this.height) hs.setStyles(innerContent, { height: this.height +'px', overflow: 'hidden' }); if (innerContent.offsetWidth < this.minWidth) innerContent.style.width = this.minWidth +'px'; if (this.objectType == 'ajax' && !hs.getCacheBinding(this.a)) { this.showLoading(); var exp = this; var ajax = new hs.Ajax(this.a, innerContent); ajax.src = this.src; ajax.onLoad = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); }; ajax.onError = function () { location.href = exp.src; }; ajax.run(); } else if (this.objectType == 'iframe' && this.objectLoadTime == 'before') { this.writeExtendedContent(); } else this.contentLoaded(); }, contentLoaded : function() { try { if (!this.content) return; this.content.onload = null; if (this.onLoadStarted) return; else this.onLoadStarted = true; var x = this.x, y = this.y; if (this.loading) { hs.setStyles(this.loading, { top: '-9999px' }); this.loading = null; } if (this.isImage) { x.full = this.content.width; y.full = this.content.height; hs.setStyles(this.content, { width: x.t +'px', height: y.t +'px' }); this.wrapper.appendChild(this.content); hs.container.appendChild(this.wrapper); } else if (this.htmlGetSize) this.htmlGetSize(); x.calcBorders(); y.calcBorders(); hs.setStyles (this.wrapper, { left: (x.tpos + x.tb - x.cb) +'px', top: (y.tpos + x.tb - y.cb) +'px' }); this.getOverlays(); var ratio = x.full / y.full; x.calcExpanded(); this.justify(x); y.calcExpanded(); this.justify(y); if (this.isHtml) this.htmlSizeOperations(); if (this.overlayBox) this.sizeOverlayBox(0, 1); if (this.allowSizeReduction) { if (this.isImage) this.correctRatio(ratio); else this.fitOverlayBox(); if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) { this.createFullExpand(); if (this.overlays.length == 1) this.sizeOverlayBox(); } } this.show(); } catch (e) { this.error(e); } }, setObjContainerSize : function(parent, auto) { var c = hs.getElementByClass(parent, 'DIV', 'highslide-body'); if (/(iframe|swf)/.test(this.objectType)) { if (this.objectWidth) c.style.width = this.objectWidth +'px'; if (this.objectHeight) c.style.height = this.objectHeight +'px'; } }, writeExtendedContent : function () { if (this.hasExtendedContent) return; var exp = this; this.body = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body'); if (this.objectType == 'iframe') { this.showLoading(); var ruler = hs.clearing.cloneNode(1); this.body.appendChild(ruler); this.newWidth = this.innerContent.offsetWidth; if (!this.objectWidth) this.objectWidth = ruler.offsetWidth; var hDiff = this.innerContent.offsetHeight - this.body.offsetHeight, h = this.objectHeight || hs.page.height - hDiff - hs.marginTop - hs.marginBottom, onload = this.objectLoadTime == 'before' ? ' onload="if (hs.expanders['+ this.key +']) hs.expanders['+ this.key +'].contentLoaded()" ' : ''; this.body.innerHTML += '<iframe name="hs'+ (new Date()).getTime() +'" frameborder="0" key="'+ this.key +'" ' +' style="width:'+ this.objectWidth +'px; height:'+ h +'px" ' + onload +' src="'+ this.src +'" ></iframe>'; this.ruler = this.body.getElementsByTagName('div')[0]; this.iframe = this.body.getElementsByTagName('iframe')[0]; if (this.objectLoadTime == 'after') this.correctIframeSize(); } if (this.objectType == 'swf') { this.body.id = this.body.id || 'hs-flash-id-' + this.key; var a = this.swfOptions; if (!a.params) a.params = {}; if (typeof a.params.wmode == 'undefined') a.params.wmode = 'transparent'; if (swfobject) swfobject.embedSWF(this.src, this.body.id, this.objectWidth, this.objectHeight, a.version || '7', a.expressInstallSwfurl, a.flashvars, a.params, a.attributes); } this.hasExtendedContent = true; }, htmlGetSize : function() { if (this.iframe && !this.objectHeight) { // loadtime before this.iframe.style.height = this.body.style.height = this.getIframePageHeight() +'px'; } this.innerContent.appendChild(hs.clearing); if (!this.x.full) this.x.full = this.innerContent.offsetWidth; this.y.full = this.innerContent.offsetHeight; this.innerContent.removeChild(hs.clearing); if (hs.ie && this.newHeight > parseInt(this.innerContent.currentStyle.height)) { // ie css bug this.newHeight = parseInt(this.innerContent.currentStyle.height); } hs.setStyles( this.wrapper, { position: 'absolute', padding: '0'}); hs.setStyles( this.content, { width: this.x.t +'px', height: this.y.t +'px'}); }, getIframePageHeight : function() { var h; try { var doc = this.iDoc = this.iframe.contentDocument || this.iframe.contentWindow.document; var clearing = doc.createElement('div'); clearing.style.clear = 'both'; doc.body.appendChild(clearing); h = clearing.offsetTop; if (hs.ie) h += parseInt(doc.body.currentStyle.marginTop) + parseInt(doc.body.currentStyle.marginBottom) - 1; } catch (e) { // other domain h = 300; } return h; }, correctIframeSize : function () { var wDiff = this.innerContent.offsetWidth - this.ruler.offsetWidth; hs.discardElement(this.ruler); if (wDiff < 0) wDiff = 0; var hDiff = this.innerContent.offsetHeight - this.iframe.offsetHeight; if (this.iDoc && !this.objectHeight && !this.height && this.y.size == this.y.full) try { this.iDoc.body.style.overflow = 'hidden'; } catch (e) {} hs.setStyles(this.iframe, { width: Math.abs(this.x.size - wDiff) +'px', height: Math.abs(this.y.size - hDiff) +'px' }); hs.setStyles(this.body, { width: this.iframe.style.width, height: this.iframe.style.height }); this.scrollingContent = this.iframe; this.scrollerDiv = this.scrollingContent; }, htmlSizeOperations : function () { this.setObjContainerSize(this.innerContent); if (this.objectType == 'swf' && this.objectLoadTime == 'before') this.writeExtendedContent(); // handle minimum size if (this.x.size < this.x.full && !this.allowWidthReduction) this.x.size = this.x.full; if (this.y.size < this.y.full && !this.allowHeightReduction) this.y.size = this.y.full; this.scrollerDiv = this.innerContent; hs.setStyles(this.mediumContent, { position: 'relative', width: this.x.size +'px' }); hs.setStyles(this.innerContent, { border: 'none', width: 'auto', height: 'auto' }); var node = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body'); if (node && !/(iframe|swf)/.test(this.objectType)) { var cNode = node; // wrap to get true size node = hs.createElement(cNode.nodeName, null, {overflow: 'hidden'}, null, true); cNode.parentNode.insertBefore(node, cNode); node.appendChild(hs.clearing); // IE6 node.appendChild(cNode); var wDiff = this.innerContent.offsetWidth - node.offsetWidth; var hDiff = this.innerContent.offsetHeight - node.offsetHeight; node.removeChild(hs.clearing); var kdeBugCorr = hs.safari || navigator.vendor == 'KDE' ? 1 : 0; // KDE repainting bug hs.setStyles(node, { width: (this.x.size - wDiff - kdeBugCorr) +'px', height: (this.y.size - hDiff) +'px', overflow: 'auto', position: 'relative' } ); if (kdeBugCorr && cNode.offsetHeight > node.offsetHeight) { node.style.width = (parseInt(node.style.width) + kdeBugCorr) + 'px'; } this.scrollingContent = node; this.scrollerDiv = this.scrollingContent; } if (this.iframe && this.objectLoadTime == 'before') this.correctIframeSize(); if (!this.scrollingContent && this.y.size < this.mediumContent.offsetHeight) this.scrollerDiv = this.content; if (this.scrollerDiv == this.content && !this.allowWidthReduction && !/(iframe|swf)/.test(this.objectType)) { this.x.size += 17; // room for scrollbars } if (this.scrollerDiv && this.scrollerDiv.offsetHeight > this.scrollerDiv.parentNode.offsetHeight) { setTimeout("try { hs.expanders["+ this.key +"].scrollerDiv.style.overflow = 'auto'; } catch(e) {}", hs.expandDuration); } }, justify : function (p, moveOnly) { var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y'; var hasMovedMin = false; var allowReduce = p.exp.allowSizeReduction; p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2)); if (p.pos < p.scroll + p.marginMin) { p.pos = p.scroll + p.marginMin; hasMovedMin = true; } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) { if (!moveOnly && hasMovedMin && allowReduce) { p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize')); } else if (p.get('wsize') < p.get('fitsize')) { p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize'); } else { // image larger than viewport p.pos = p.scroll + p.marginMin; if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize'); } } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } if (p.pos < p.marginMin) { var tmpMin = p.pos; p.pos = p.marginMin; if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin); } }, correctRatio : function(ratio) { var x = this.x, y = this.y, changed = false, xSize = Math.min(x.full, x.size), ySize = Math.min(y.full, y.size), useBox = (this.useBox || hs.padToMinWidth); if (xSize / ySize > ratio) { // width greater xSize = ySize * ratio; if (xSize < x.minSize) { // below minWidth xSize = x.minSize; ySize = xSize / ratio; } changed = true; } else if (xSize / ySize < ratio) { // height greater ySize = xSize / ratio; changed = true; } if (hs.padToMinWidth && x.full < x.minSize) { x.imgSize = x.full; y.size = y.imgSize = y.full; } else if (this.useBox) { x.imgSize = xSize; y.imgSize = ySize; } else { x.size = xSize; y.size = ySize; } changed = this.fitOverlayBox(useBox ? null : ratio, changed); if (useBox && y.size < y.imgSize) { y.imgSize = y.size; x.imgSize = y.size * ratio; } if (changed || useBox) { x.pos = x.tpos - x.cb + x.tb; x.minSize = x.size; this.justify(x, true); y.pos = y.tpos - y.cb + y.tb; y.minSize = y.size; this.justify(y, true); if (this.overlayBox) this.sizeOverlayBox(); } }, fitOverlayBox : function(ratio, changed) { var x = this.x, y = this.y; if (this.overlayBox && (this.isImage || this.allowHeightReduction)) { while (y.size > this.minHeight && x.size > this.minWidth && y.get('wsize') > y.get('fitsize')) { y.size -= 10; if (ratio) x.size = y.size * ratio; this.sizeOverlayBox(0, 1); changed = true; } } return changed; }, show : function () { var x = this.x, y = this.y; this.doShowHide('hidden'); // Apply size change this.changeSize( 1, { wrapper: { width : x.get('wsize'), height : y.get('wsize'), left: x.pos, top: y.pos }, content: { left: x.p1 + x.get('imgPad'), top: y.p1 + y.get('imgPad'), width:x.imgSize ||x.size, height:y.imgSize ||y.size } }, hs.expandDuration ); }, changeSize : function(up, to, dur) { if (this.outline && !this.outlineWhileAnimating) { if (up) this.outline.setPosition(); else this.outline.destroy( (this.isHtml && this.preserveContent)); } if (!up) this.destroyOverlays(); var exp = this, x = exp.x, y = exp.y, easing = this.easing; if (!up) easing = this.easingClose || easing; var after = up ? function() { if (exp.outline) exp.outline.table.style.visibility = "visible"; setTimeout(function() { exp.afterExpand(); }, 50); } : function() { exp.afterClose(); }; if (up) hs.setStyles( this.wrapper, { width: x.t +'px', height: y.t +'px' }); if (up && this.isHtml) { hs.setStyles(this.wrapper, { left: (x.tpos - x.cb + x.tb) +'px', top: (y.tpos - y.cb + y.tb) +'px' }); } if (this.fadeInOut) { hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 }); hs.extend(to.wrapper, { opacity: up }); } hs.animate( this.wrapper, to.wrapper, { duration: dur, easing: easing, step: function(val, args) { if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') { var fac = up ? args.pos : 1 - args.pos; var pos = { w: x.t + (x.get('wsize') - x.t) * fac, h: y.t + (y.get('wsize') - y.t) * fac, x: x.tpos + (x.pos - x.tpos) * fac, y: y.tpos + (y.pos - y.tpos) * fac }; exp.outline.setPosition(pos, 0, 1); } if (exp.isHtml) { if (args.prop == 'left') exp.mediumContent.style.left = (x.pos - val) +'px'; if (args.prop == 'top') exp.mediumContent.style.top = (y.pos - val) +'px'; } } }); hs.animate( this.content, to.content, dur, easing, after); if (up) { this.wrapper.style.visibility = 'visible'; this.content.style.visibility = 'visible'; if (this.isHtml) this.innerContent.style.visibility = 'visible'; this.a.className += ' highslide-active-anchor'; } }, afterExpand : function() { this.isExpanded = true; this.focus(); if (this.isHtml && this.objectLoadTime == 'after') this.writeExtendedContent(); if (this.iframe) { try { var exp = this, doc = this.iframe.contentDocument || this.iframe.contentWindow.document; hs.addEventListener(doc, 'mousedown', function () { if (hs.focusKey != exp.key) exp.focus(); }); } catch(e) {} if (hs.ie && typeof this.isClosing != 'boolean') // first open this.iframe.style.width = (this.objectWidth - 1) +'px'; // hasLayout } if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null; this.prepareNextOutline(); var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop; this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize') && this.y.pos < mY && mY < this.y.pos + this.y.get('wsize'); if (this.overlayBox) this.showOverlays(); }, prepareNextOutline : function() { var key = this.key; var outlineType = this.outlineType; new hs.Outline(outlineType, function () { try { hs.expanders[key].preloadNext(); } catch (e) {} }); }, preloadNext : function() { var next = this.getAdjacentAnchor(1); if (next && next.onclick.toString().match(/hs\.expand/)) var img = hs.createElement('img', { src: hs.getSrc(next) }); }, getAdjacentAnchor : function(op) { var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none']; /*< ? if ($cfg->slideshow) : ?>s*/ if (!as[current + op] && this.slideshow && this.slideshow.repeat) { if (op == 1) return as[0]; else if (op == -1) return as[as.length-1]; } /*< ? endif ?>s*/ return as[current + op] || null; }, getAnchorIndex : function() { var arr = hs.getAnchors().groups[this.slideshowGroup || 'none']; if (arr) for (var i = 0; i < arr.length; i++) { if (arr[i] == this.a) return i; } return null; }, cancelLoading : function() { hs.discardElement (this.wrapper); hs.expanders[this.key] = null; if (this.loading) hs.loading.style.left = '-9999px'; }, writeCredits : function () { this.credits = hs.createElement('a', { href: hs.creditsHref, target: hs.creditsTarget, className: 'highslide-credits', innerHTML: hs.lang.creditsText, title: hs.lang.creditsTitle }); this.createOverlay({ overlayId: this.credits, position: this.creditsPosition || 'top left' }); }, getInline : function(types, addOverlay) { for (var i = 0; i < types.length; i++) { var type = types[i], s = null; if (!this[type +'Id'] && this.thumbsUserSetId) this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId; if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']); if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try { s = eval(this[type +'Eval']); } catch (e) {} if (!this[type] && this[type +'Text']) { s = this[type +'Text']; } if (!this[type] && !s) { this[type] = hs.getNode(this.a['_'+ type + 'Id']); if (!this[type]) { var next = this.a.nextSibling; while (next && !hs.isHsAnchor(next)) { if ((new RegExp('highslide-'+ type)).test(next.className || null)) { if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++; this[type] = hs.getNode(next.id); break; } next = next.nextSibling; } } } if (!this[type] && s) this[type] = hs.createElement('div', { className: 'highslide-'+ type, innerHTML: s } ); if (addOverlay && this[type]) { var o = { position: (type == 'heading') ? 'above' : 'below' }; for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x]; o.overlayId = this[type]; this.createOverlay(o); } } }, // on end move and resize doShowHide : function(visibility) { if (hs.hideSelects) this.showHideElements('SELECT', visibility); if (hs.hideIframes) this.showHideElements('IFRAME', visibility); if (hs.geckoMac) this.showHideElements('*', visibility); }, showHideElements : function (tagName, visibility) { var els = document.getElementsByTagName(tagName); var prop = tagName == '*' ? 'overflow' : 'visibility'; for (var i = 0; i < els.length; i++) { if (prop == 'visibility' || (document.defaultView.getComputedStyle( els[i], "").getPropertyValue('overflow') == 'auto' || els[i].getAttribute('hidden-by') != null)) { var hiddenBy = els[i].getAttribute('hidden-by'); if (visibility == 'visible' && hiddenBy) { hiddenBy = hiddenBy.replace('['+ this.key +']', ''); els[i].setAttribute('hidden-by', hiddenBy); if (!hiddenBy) els[i].style[prop] = els[i].origProp; } else if (visibility == 'hidden') { // hide if behind var elPos = hs.getPosition(els[i]); elPos.w = els[i].offsetWidth; elPos.h = els[i].offsetHeight; var clearsX = (elPos.x + elPos.w < this.x.get('opos') || elPos.x > this.x.get('opos') + this.x.get('osize')); var clearsY = (elPos.y + elPos.h < this.y.get('opos') || elPos.y > this.y.get('opos') + this.y.get('osize')); var wrapperKey = hs.getWrapperKey(els[i]); if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image if (!hiddenBy) { els[i].setAttribute('hidden-by', '['+ this.key +']'); els[i].origProp = els[i].style[prop]; els[i].style[prop] = 'hidden'; } else if (hiddenBy.indexOf('['+ this.key +']') == -1) { els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']'); } } else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey) && wrapperKey != this.key) { // on move els[i].setAttribute('hidden-by', ''); els[i].style[prop] = els[i].origProp || ''; } else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) { els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', '')); } } } } }, focus : function() { this.wrapper.style.zIndex = hs.zIndexCounter += 2; // blur others for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && i == hs.focusKey) { var blurExp = hs.expanders[i]; blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur'; if (blurExp.isImage) { blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer'; blurExp.content.title = hs.lang.focusTitle; } } } // focus this if (this.outline) this.outline.table.style.zIndex = this.wrapper.style.zIndex - 1; this.content.className = 'highslide-'+ this.contentType; if (this.isImage) { this.content.title = hs.lang.restoreTitle; if (hs.restoreCursor) { hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer'; if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand'; this.content.style.cursor = hs.styleRestoreCursor; } } hs.focusKey = this.key; hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); }, moveTo: function(x, y) { this.x.setPos(x); this.y.setPos(y); }, resize : function (e) { var w, h, r = e.width / e.height; w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full)); if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full; h = this.isHtml ? e.height + e.dY : w / r; if (h < Math.min(this.minHeight, this.y.full)) { h = Math.min(this.minHeight, this.y.full); if (this.isImage) w = h * r; } this.resizeTo(w, h); }, resizeTo: function(w, h) { this.y.setSize(h); this.x.setSize(w); this.wrapper.style.height = this.y.get('wsize') +'px'; }, close : function() { if (this.isClosing || !this.isExpanded) return; this.isClosing = true; hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); try { if (this.isHtml) this.htmlPrepareClose(); this.content.style.cursor = 'default'; this.changeSize( 0, { wrapper: { width : this.x.t, height : this.y.t, left: this.x.tpos - this.x.cb + this.x.tb, top: this.y.tpos - this.y.cb + this.y.tb }, content: { left: 0, top: 0, width: this.x.t, height: this.y.t } }, hs.restoreDuration ); } catch (e) { this.afterClose(); } }, htmlPrepareClose : function() { if (hs.geckoMac) { // bad redraws if (!hs.mask) hs.mask = hs.createElement('div', null, { position: 'absolute' }, hs.container); hs.setStyles(hs.mask, { width: this.x.size +'px', height: this.y.size +'px', left: this.x.pos +'px', top: this.y.pos +'px', display: 'block' }); } if (this.objectType == 'swf') try { hs.$(this.body.id).StopPlay(); } catch (e) {} if (this.objectLoadTime == 'after' && !this.preserveContent) this.destroyObject(); if (this.scrollerDiv && this.scrollerDiv != this.scrollingContent) this.scrollerDiv.style.overflow = 'hidden'; }, destroyObject : function () { if (hs.ie && this.iframe) try { this.iframe.contentWindow.document.body.innerHTML = ''; } catch (e) {} if (this.objectType == 'swf') swfobject.removeSWF(this.body.id); this.body.innerHTML = ''; }, sleep : function() { if (this.outline) this.outline.table.style.display = 'none'; this.releaseMask = null; this.wrapper.style.display = 'none'; hs.push(hs.sleeping, this); }, awake : function() {try { hs.expanders[this.key] = this; if (!hs.allowMultipleInstances &&hs.focusKey != this.key) { try { hs.expanders[hs.focusKey].close(); } catch (e){} } var z = hs.zIndexCounter++, stl = { display: '', zIndex: z }; hs.setStyles (this.wrapper, stl); this.isClosing = false; var o = this.outline || 0; if (o) { if (!this.outlineWhileAnimating) stl.visibility = 'hidden'; hs.setStyles (o.table, stl); } this.show(); } catch (e) {} }, createOverlay : function (o) { var el = o.overlayId; if (typeof el == 'string') el = hs.getNode(el); if (o.html) el = hs.createElement('div', { innerHTML: o.html }); if (!el || typeof el == 'string') return; el.style.display = 'block'; this.genOverlayBox(); var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto'; if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px'; var overlay = hs.createElement( 'div', { id: 'hsId'+ hs.idCounter++, hsId: o.hsId }, { position: 'absolute', visibility: 'hidden', width: width, direction: hs.lang.cssDirection || '', opacity: 0 },this.overlayBox, true ); overlay.appendChild(el); hs.extend(overlay, { opacity: 1, offsetX: 0, offsetY: 0, dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250 }); hs.extend(overlay, o); if (this.gotOverlays) { this.positionOverlay(overlay); if (!overlay.hideOnMouseOut || this.mouseIsOver) hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur); } hs.push(this.overlays, hs.idCounter - 1); }, positionOverlay : function(overlay) { var p = overlay.position || 'middle center', offX = overlay.offsetX, offY = overlay.offsetY; if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay); if (/left$/.test(p)) overlay.style.left = offX +'px'; if (/center$/.test(p)) hs.setStyles (overlay, { left: '50%', marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px' }); if (/right$/.test(p)) overlay.style.right = - offX +'px'; if (/^leftpanel$/.test(p)) { hs.setStyles(overlay, { right: '100%', marginRight: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p1 = overlay.offsetWidth; } else if (/^rightpanel$/.test(p)) { hs.setStyles(overlay, { left: '100%', marginLeft: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p2 = overlay.offsetWidth; } if (/^top/.test(p)) overlay.style.top = offY +'px'; if (/^middle/.test(p)) hs.setStyles (overlay, { top: '50%', marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px' }); if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px'; if (/^above$/.test(p)) { hs.setStyles(overlay, { left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', bottom: '100%', marginBottom: this.y.cb +'px', width: 'auto' }); this.y.p1 = overlay.offsetHeight; } else if (/^below$/.test(p)) { hs.setStyles(overlay, { position: 'relative', left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', top: '100%', marginTop: this.y.cb +'px', width: 'auto' }); this.y.p2 = overlay.offsetHeight; overlay.style.position = 'absolute'; } }, getOverlays : function() { this.getInline(['heading', 'caption'], true); if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move'; if (hs.showCredits) this.writeCredits(); for (var i = 0; i < hs.overlays.length; i++) { var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup; if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId) || (sg && sg === this.slideshowGroup)) { if (this.isImage || (this.isHtml && o.useOnHtml)) this.createOverlay(o); } } var os = []; for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); if (/panel$/.test(o.position)) this.positionOverlay(o); else hs.push(os, o); } for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]); this.gotOverlays = true; }, genOverlayBox : function() { if (!this.overlayBox) this.overlayBox = hs.createElement ( 'div', { className: this.wrapperClassName }, { position : 'absolute', width: (this.x.size || (this.useBox ? this.width : null) || this.x.full) +'px', height: (this.y.size || this.y.full) +'px', visibility : 'hidden', overflow : 'hidden', zIndex : hs.ie ? 4 : 'auto' }, hs.container, true ); }, sizeOverlayBox : function(doWrapper, doPanels) { var overlayBox = this.overlayBox, x = this.x, y = this.y; hs.setStyles( overlayBox, { width: x.size +'px', height: y.size +'px' }); if (doWrapper || doPanels) { for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat'); if (o && /^(above|below)$/.test(o.position)) { if (ie6) { o.style.width = (overlayBox.offsetWidth + 2 * x.cb + x.p1 + x.p2) +'px'; } y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight; } if (o && ie6 && /^(left|right)panel$/.test(o.position)) { o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px'; } } } if (doWrapper) { hs.setStyles(this.content, { top: y.p1 +'px' }); hs.setStyles(overlayBox, { top: (y.p1 + y.cb) +'px' }); } }, showOverlays : function() { var b = this.overlayBox; b.className = ''; hs.setStyles(b, { top: (this.y.p1 + this.y.cb) +'px', left: (this.x.p1 + this.x.cb) +'px', overflow : 'visible' }); if (hs.safari) b.style.visibility = 'visible'; this.wrapper.appendChild (b); for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); o.style.zIndex = 4; if (!o.hideOnMouseOut || this.mouseIsOver) { o.style.visibility = 'visible'; hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: o.opacity }, o.dur); } } }, destroyOverlays : function() { if (!this.overlays.length) return; if (this.isHtml && this.preserveContent) { this.overlayBox.style.top = '-9999px'; hs.container.appendChild(this.overlayBox); } else hs.discardElement(this.overlayBox); }, createFullExpand : function () { this.fullExpandLabel = hs.createElement( 'a', { href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();', title: hs.lang.fullExpandTitle, className: 'highslide-full-expand' } ); this.createOverlay({ overlayId: this.fullExpandLabel, position: hs.fullExpandPosition, hideOnMouseOut: true, opacity: hs.fullExpandOpacity }); }, doFullExpand : function () { try { if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel); this.focus(); var xSize = this.x.size; this.resizeTo(this.x.full, this.y.full); var xpos = this.x.pos - (this.x.size - xSize) / 2; if (xpos < hs.marginLeft) xpos = hs.marginLeft; this.moveTo(xpos, this.y.pos); this.doShowHide('hidden'); } catch (e) { this.error(e); } }, afterClose : function () { this.a.className = this.a.className.replace('highslide-active-anchor', ''); this.doShowHide('visible'); if (this.isHtml && this.preserveContent) { this.sleep(); } else { if (this.outline && this.outlineWhileAnimating) this.outline.destroy(); hs.discardElement(this.wrapper); } if (hs.mask) hs.mask.style.display = 'none'; hs.expanders[this.key] = null; hs.reOrder(); } }; // hs.Ajax object prototype hs.Ajax = function (a, content, pre) { this.a = a; this.content = content; this.pre = pre; }; hs.Ajax.prototype = { run : function () { var xhr; if (!this.src) this.src = hs.getSrc(this.a); if (this.src.match('#')) { var arr = this.src.split('#'); this.src = arr[0]; this.id = arr[1]; } if (hs.cachedGets[this.src]) { this.cachedGet = hs.cachedGets[this.src]; if (this.id) this.getElementContent(); else this.loadHTML(); return; } try { xhr = new XMLHttpRequest(); } catch (e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { this.onError(); } } } var pThis = this; xhr.onreadystatechange = function() { if(pThis.xhr.readyState == 4) { if (pThis.id) pThis.getElementContent(); else pThis.loadHTML(); } }; var src = this.src; this.xhr = xhr; if (hs.forceAjaxReload) src = src.replace(/$/, (/\?/.test(src) ? '&' : '?') +'dummy='+ (new Date()).getTime()); xhr.open('GET', src, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(null); }, getElementContent : function() { hs.init(); var attribs = window.opera || hs.ie6SSL ? { src: 'about:blank' } : null; this.iframe = hs.createElement('iframe', attribs, { position: 'absolute', top: '-9999px' }, hs.container); this.loadHTML(); }, loadHTML : function() { var s = this.cachedGet || this.xhr.responseText, regBody; if (this.pre) hs.cachedGets[this.src] = s; if (!hs.ie || hs.uaVersion >= 5.5) { s = s.replace(new RegExp('<link[^>]*>', 'gi'), '') .replace(new RegExp('<script[^>]*>.*?</script>', 'gi'), ''); if (this.iframe) { var doc = this.iframe.contentDocument; if (!doc && this.iframe.contentWindow) doc = this.iframe.contentWindow.document; if (!doc) { // Opera var pThis = this; setTimeout(function() { pThis.loadHTML(); }, 25); return; } doc.open(); doc.write(s); doc.close(); try { s = doc.getElementById(this.id).innerHTML; } catch (e) { try { s = this.iframe.document.getElementById(this.id).innerHTML; } catch (e) {} // opera } hs.discardElement(this.iframe); } else { regBody = /(<body[^>]*>|<\/body>)/ig; if (regBody.test(s)) s = s.split(regBody)[hs.ie ? 1 : 2]; } } hs.getElementByClass(this.content, 'DIV', 'highslide-body').innerHTML = s; this.onLoad(); for (var x in this) this[x] = null; } }; hs.langDefaults = hs.lang; // history var HsExpander = hs.Expander; if (hs.ie) { (function () { try { document.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } hs.ready(); })(); } hs.addEventListener(document, 'DOMContentLoaded', hs.ready); hs.addEventListener(window, 'load', hs.ready); // set handlers hs.addEventListener(document, 'ready', function() { if (hs.expandCursor) { var style = hs.createElement('style', { type: 'text/css' }, null, document.getElementsByTagName('HEAD')[0]); function addRule(sel, dec) { if (!hs.ie) { style.appendChild(document.createTextNode(sel + " {" + dec + "}")); } else { var last = document.styleSheets[document.styleSheets.length - 1]; if (typeof(last.addRule) == "object") last.addRule(sel, dec); } } function fix(prop) { return 'expression( ( ( ignoreMe = document.documentElement.'+ prop + ' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );'; } if (hs.expandCursor) addRule ('.highslide img', 'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;'); } }); hs.addEventListener(window, 'resize', function() { hs.getPageSize(); }); hs.addEventListener(document, 'mousemove', function(e) { hs.mouse = { x: e.clientX, y: e.clientY }; }); hs.addEventListener(document, 'mousedown', hs.mouseClickHandler); hs.addEventListener(document, 'mouseup', hs.mouseClickHandler); hs.addEventListener(document, 'ready', hs.getAnchors); hs.addEventListener(window, 'load', hs.preloadImages); hs.addEventListener(window, 'load', hs.preloadAjax); }
JavaScript
/****************************************************************************** Name: Highslide JS Version: 4.1.8 (October 27 2009) Config: default +slideshow +positioning +transitions +viewport +thumbstrip Author: Torstein Hønsi Support: http://highslide.com/support Licence: Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5 License (http://creativecommons.org/licenses/by-nc/2.5/). You are free: * to copy, distribute, display, and perform the work * to make derivative works Under the following conditions: * Attribution. You must attribute the work in the manner specified by the author or licensor. * Noncommercial. You may not use this work for commercial purposes. * For any reuse or distribution, you must make clear to others the license terms of this work. * Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. ******************************************************************************/ if (!hs) { var hs = { // Language strings lang : { cssDirection: 'ltr', loadingText : 'Loading...', loadingTitle : 'Click to cancel', focusTitle : 'Click to bring to front', fullExpandTitle : 'Expand to actual size (f)', creditsText : 'Powered by <i>Highslide JS</i>', creditsTitle : 'Go to the Highslide JS homepage', previousText : 'Previous', nextText : 'Next', moveText : 'Move', closeText : 'Close', closeTitle : 'Close (esc)', resizeTitle : 'Resize', playText : 'Play', playTitle : 'Play slideshow (spacebar)', pauseText : 'Pause', pauseTitle : 'Pause slideshow (spacebar)', previousTitle : 'Previous (arrow left)', nextTitle : 'Next (arrow right)', moveTitle : 'Move', fullExpandText : '1:1', number: 'Image %1 of %2', restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.' }, // See http://highslide.com/ref for examples of settings graphicsDir : 'highslide/graphics/', expandCursor : 'zoomin.cur', // null disables restoreCursor : 'zoomout.cur', // null disables expandDuration : 250, // milliseconds restoreDuration : 250, marginLeft : 15, marginRight : 15, marginTop : 15, marginBottom : 15, zIndexCounter : 1001, // adjust to other absolutely positioned elements loadingOpacity : 0.75, allowMultipleInstances: true, numberOfImagesToPreload : 5, outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only outlineStartOffset : 3, // ends at 10 padToMinWidth : false, // pad the popup width to make room for wide caption fullExpandPosition : 'bottom right', fullExpandOpacity : 1, showCredits : true, // you can set this to false if you want creditsHref : 'http://highslide.com/', creditsTarget : '_self', enableKeyListener : true, openerTagNames : ['a'], // Add more to allow slideshow indexing transitions : [], transitionDuration: 250, dimmingOpacity: 0, // Lightbox style dimming background dimmingDuration: 50, // 0 for instant dimming anchor : 'auto', // where the image expands from align : 'auto', // position in the client (overrides anchor) targetX: null, // the id of a target element targetY: null, dragByHeading: true, minWidth: 200, minHeight: 200, allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight outlineType : 'drop-shadow', // set null to disable outlines skin : { controls: '<div class="highslide-controls"><ul>'+ '<li class="highslide-previous">'+ '<a href="#" title="{hs.lang.previousTitle}">'+ '<span>{hs.lang.previousText}</span></a>'+ '</li>'+ '<li class="highslide-play">'+ '<a href="#" title="{hs.lang.playTitle}">'+ '<span>{hs.lang.playText}</span></a>'+ '</li>'+ '<li class="highslide-pause">'+ '<a href="#" title="{hs.lang.pauseTitle}">'+ '<span>{hs.lang.pauseText}</span></a>'+ '</li>'+ '<li class="highslide-next">'+ '<a href="#" title="{hs.lang.nextTitle}">'+ '<span>{hs.lang.nextText}</span></a>'+ '</li>'+ '<li class="highslide-move">'+ '<a href="#" title="{hs.lang.moveTitle}">'+ '<span>{hs.lang.moveText}</span></a>'+ '</li>'+ '<li class="highslide-full-expand">'+ '<a href="#" title="{hs.lang.fullExpandTitle}">'+ '<span>{hs.lang.fullExpandText}</span></a>'+ '</li>'+ '<li class="highslide-close">'+ '<a href="#" title="{hs.lang.closeTitle}" >'+ '<span>{hs.lang.closeText}</span></a>'+ '</li>'+ '</ul></div>' }, // END OF YOUR SETTINGS // declare internal properties preloadTheseImages : [], continuePreloading: true, expanders : [], overrides : [ 'allowSizeReduction', 'useBox', 'anchor', 'align', 'targetX', 'targetY', 'outlineType', 'outlineWhileAnimating', 'captionId', 'captionText', 'captionEval', 'captionOverlay', 'headingId', 'headingText', 'headingEval', 'headingOverlay', 'creditsPosition', 'dragByHeading', 'autoplay', 'numberPosition', 'transitions', 'dimmingOpacity', 'width', 'height', 'wrapperClassName', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'slideshowGroup', 'easing', 'easingClose', 'fadeInOut', 'src' ], overlays : [], idCounter : 0, oPos : { x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'], y: ['above', 'top', 'middle', 'bottom', 'below'] }, mouse: {}, headingOverlay: {}, captionOverlay: {}, timers : [], slideshows : [], pendingOutlines : {}, clones : {}, onReady: [], uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 : parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]), ie : (document.all && !window.opera), safari : /Safari/.test(navigator.userAgent), geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent), $ : function (id) { if (id) return document.getElementById(id); }, push : function (arr, val) { arr[arr.length] = val; }, createElement : function (tag, attribs, styles, parent, nopad) { var el = document.createElement(tag); if (attribs) hs.extend(el, attribs); if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0}); if (styles) hs.setStyles(el, styles); if (parent) parent.appendChild(el); return el; }, extend : function (el, attribs) { for (var x in attribs) el[x] = attribs[x]; return el; }, setStyles : function (el, styles) { for (var x in styles) { if (hs.ie && x == 'opacity') { if (styles[x] > 0.99) el.style.removeAttribute('filter'); else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')'; } else el.style[x] = styles[x]; } }, animate: function(el, prop, opt) { var start, end, unit; if (typeof opt != 'object' || opt === null) { var args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (typeof opt.duration != 'number') opt.duration = 250; opt.easing = Math[opt.easing] || Math.easeInQuad; opt.curAnim = hs.extend({}, prop); for (var name in prop) { var e = new hs.fx(el, opt , name ); start = parseFloat(hs.css(el, name)) || 0; end = parseFloat(prop[name]); unit = name != 'opacity' ? 'px' : ''; e.custom( start, end, unit ); } }, css: function(el, prop) { if (document.defaultView) { return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop); } else { if (prop == 'opacity') prop = 'filter'; var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })]; if (prop == 'filter') val = val.replace(/alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100 }); return val === '' ? 1 : val; } }, getPageSize : function () { var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat' ? d.documentElement : d.body; var width = hs.ie ? iebody.clientWidth : (d.documentElement.clientWidth || self.innerWidth), height = hs.ie ? iebody.clientHeight : self.innerHeight; hs.page = { width: width, height: height, scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset, scrollTop: hs.ie ? iebody.scrollTop : pageYOffset } }, getPosition : function(el) { var p = { x: el.offsetLeft, y: el.offsetTop }; while (el.offsetParent) { el = el.offsetParent; p.x += el.offsetLeft; p.y += el.offsetTop; if (el != document.body && el != document.documentElement) { p.x -= el.scrollLeft; p.y -= el.scrollTop; } } return p; }, expand : function(a, params, custom, type) { if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container); if (typeof a.getParams == 'function') return params; try { new hs.Expander(a, params, custom); return false; } catch (e) { return true; } }, getElementByClass : function (el, tagName, className) { var els = el.getElementsByTagName(tagName); for (var i = 0; i < els.length; i++) { if ((new RegExp(className)).test(els[i].className)) { return els[i]; } } return null; }, replaceLang : function(s) { s = s.replace(/\s/g, ' '); var re = /{hs\.lang\.([^}]+)\}/g, matches = s.match(re), lang; if (matches) for (var i = 0; i < matches.length; i++) { lang = matches[i].replace(re, "$1"); if (typeof hs.lang[lang] != 'undefined') s = s.replace(matches[i], hs.lang[lang]); } return s; }, focusTopmost : function() { var topZ = 0, topmostKey = -1, expanders = hs.expanders, exp, zIndex; for (var i = 0; i < expanders.length; i++) { exp = expanders[i]; if (exp) { zIndex = exp.wrapper.style.zIndex; if (zIndex && zIndex > topZ) { topZ = zIndex; topmostKey = i; } } } if (topmostKey == -1) hs.focusKey = -1; else expanders[topmostKey].focus(); }, getParam : function (a, param) { a.getParams = a.onclick; var p = a.getParams ? a.getParams() : null; a.getParams = null; return (p && typeof p[param] != 'undefined') ? p[param] : (typeof hs[param] != 'undefined' ? hs[param] : null); }, getSrc : function (a) { var src = hs.getParam(a, 'src'); if (src) return src; return a.href; }, getNode : function (id) { var node = hs.$(id), clone = hs.clones[id], a = {}; if (!node && !clone) return null; if (!clone) { clone = node.cloneNode(true); clone.id = ''; hs.clones[id] = clone; return node; } else { return clone.cloneNode(true); } }, discardElement : function(d) { if (d) hs.garbageBin.appendChild(d); hs.garbageBin.innerHTML = ''; }, dim : function(exp) { if (!hs.dimmer) { hs.dimmer = hs.createElement ('div', { className: 'highslide-dimming highslide-viewport-size', owner: '', onclick: function() { hs.close(); } }, { visibility: 'visible', opacity: 0 }, hs.container, true); } hs.dimmer.style.display = ''; hs.dimmer.owner += '|'+ exp.key; if (hs.geckoMac && hs.dimmingGeckoFix) hs.setStyles(hs.dimmer, { background: 'url('+ hs.graphicsDir + 'geckodimmer.png)', opacity: 1 }); else hs.animate(hs.dimmer, { opacity: exp.dimmingOpacity }, hs.dimmingDuration); }, undim : function(key) { if (!hs.dimmer) return; if (typeof key != 'undefined') hs.dimmer.owner = hs.dimmer.owner.replace('|'+ key, ''); if ( (typeof key != 'undefined' && hs.dimmer.owner != '') || (hs.upcoming && hs.getParam(hs.upcoming, 'dimmingOpacity')) ) return; if (hs.geckoMac && hs.dimmingGeckoFix) hs.dimmer.style.display = 'none'; else hs.animate(hs.dimmer, { opacity: 0 }, hs.dimmingDuration, null, function() { hs.dimmer.style.display = 'none'; }); }, transit : function (adj, exp) { var last = exp = exp || hs.getExpander(); if (hs.upcoming) return false; else hs.last = last; try { hs.upcoming = adj; adj.onclick(); } catch (e){ hs.last = hs.upcoming = null; } try { if (!adj || exp.transitions[1] != 'crossfade') exp.close(); } catch (e) {} return false; }, previousOrNext : function (el, op) { var exp = hs.getExpander(el); if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp); else return false; }, previous : function (el) { return hs.previousOrNext(el, -1); }, next : function (el) { return hs.previousOrNext(el, 1); }, keyHandler : function(e) { if (!e) e = window.event; if (!e.target) e.target = e.srcElement; // ie if (typeof e.target.form != 'undefined') return true; // form element has focus var exp = hs.getExpander(); var op = null; switch (e.keyCode) { case 70: // f if (exp) exp.doFullExpand(); return true; case 32: // Space op = 2; break; case 34: // Page Down case 39: // Arrow right case 40: // Arrow down op = 1; break; case 8: // Backspace case 33: // Page Up case 37: // Arrow left case 38: // Arrow up op = -1; break; case 27: // Escape case 13: // Enter op = 0; } if (op !== null) {if (op != 2)hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); if (!hs.enableKeyListener) return true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; if (exp) { if (op == 0) { exp.close(); } else if (op == 2) { if (exp.slideshow) exp.slideshow.hitSpace(); } else { if (exp.slideshow) exp.slideshow.pause(); hs.previousOrNext(exp.key, op); } return false; } } return true; }, registerOverlay : function (overlay) { hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } )); }, addSlideshow : function (options) { var sg = options.slideshowGroup; if (typeof sg == 'object') { for (var i = 0; i < sg.length; i++) { var o = {}; for (var x in options) o[x] = options[x]; o.slideshowGroup = sg[i]; hs.push(hs.slideshows, o); } } else { hs.push(hs.slideshows, options); } }, getWrapperKey : function (element, expOnly) { var el, re = /^highslide-wrapper-([0-9]+)$/; // 1. look in open expanders el = element; while (el.parentNode) { if (el.hsKey !== undefined) return el.hsKey; if (el.id && re.test(el.id)) return el.id.replace(re, "$1"); el = el.parentNode; } // 2. look in thumbnail if (!expOnly) { el = element; while (el.parentNode) { if (el.tagName && hs.isHsAnchor(el)) { for (var key = 0; key < hs.expanders.length; key++) { var exp = hs.expanders[key]; if (exp && exp.a == el) return key; } } el = el.parentNode; } } return null; }, getExpander : function (el, expOnly) { if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null; if (typeof el == 'number') return hs.expanders[el] || null; if (typeof el == 'string') el = hs.$(el); return hs.expanders[hs.getWrapperKey(el, expOnly)] || null; }, isHsAnchor : function (a) { return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/)); }, reOrder : function () { for (var i = 0; i < hs.expanders.length; i++) if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost(); }, mouseClickHandler : function(e) { if (!e) e = window.event; if (e.button > 1) return true; if (!e.target) e.target = e.srcElement; var el = e.target; while (el.parentNode && !(/highslide-(image|move|html|resize)/.test(el.className))) { el = el.parentNode; } var exp = hs.getExpander(el); if (exp && (exp.isClosing || !exp.isExpanded)) return true; if (exp && e.type == 'mousedown') { if (e.target.form) return true; var match = el.className.match(/highslide-(image|move|resize)/); if (match) { hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos, height: exp.y.size, clickX: e.clientX, clickY: e.clientY }; hs.addEventListener(document, 'mousemove', hs.dragHandler); if (e.preventDefault) e.preventDefault(); // FF if (/highslide-(image|html)-blur/.test(exp.content.className)) { exp.focus(); hs.hasFocused = true; } return false; } } else if (e.type == 'mouseup') { hs.removeEventListener(document, 'mousemove', hs.dragHandler); if (hs.dragArgs) { if (hs.styleRestoreCursor && hs.dragArgs.type == 'image') hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor; var hasDragged = hs.dragArgs.hasDragged; if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) { exp.close(); } else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) { hs.dragArgs.exp.doShowHide('hidden'); } hs.hasFocused = false; hs.dragArgs = null; } else if (/highslide-image-blur/.test(el.className)) { el.style.cursor = hs.styleRestoreCursor; } } return false; }, dragHandler : function(e) { if (!hs.dragArgs) return true; if (!e) e = window.event; var a = hs.dragArgs, exp = a.exp; a.dX = e.clientX - a.clickX; a.dY = e.clientY - a.clickY; var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2)); if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0) || (distance > (hs.dragSensitivity || 5)); if (a.hasDragged && e.clientX > 5 && e.clientY > 5) { if (a.type == 'resize') exp.resize(a); else { exp.moveTo(a.left + a.dX, a.top + a.dY); if (a.type == 'image') exp.content.style.cursor = 'move'; } } return false; }, wrapperMouseHandler : function (e) { try { if (!e) e = window.event; var over = /mouseover/i.test(e.type); if (!e.target) e.target = e.srcElement; // ie if (hs.ie) e.relatedTarget = over ? e.fromElement : e.toElement; // ie var exp = hs.getExpander(e.target); if (!exp.isExpanded) return; if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp || hs.dragArgs) return; for (var i = 0; i < exp.overlays.length; i++) (function() { var o = hs.$('hsId'+ exp.overlays[i]); if (o && o.hideOnMouseOut) { if (over) hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur); } })(); } catch (e) {} }, addEventListener : function (el, event, func) { if (el == document && event == 'ready') hs.push(hs.onReady, func); try { el.addEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); el.attachEvent('on'+ event, func); } catch (e) { el['on'+ event] = func; } } }, removeEventListener : function (el, event, func) { try { el.removeEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); } catch (e) { el['on'+ event] = null; } } }, preloadFullImage : function (i) { if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') { var img = document.createElement('img'); img.onload = function() { img = null; hs.preloadFullImage(i + 1); }; img.src = hs.preloadTheseImages[i]; } }, preloadImages : function (number) { if (number && typeof number != 'object') hs.numberOfImagesToPreload = number; var arr = hs.getAnchors(); for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) { hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i])); } // preload outlines if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} ); else hs.preloadFullImage(0); // preload cursor if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor }); }, init : function () { if (!hs.container) { hs.getPageSize(); hs.ieLt7 = hs.ie && hs.uaVersion < 7; for (var x in hs.langDefaults) { if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x]; else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined') hs.lang[x] = hs.langDefaults[x]; } hs.container = hs.createElement('div', { className: 'highslide-container' }, { position: 'absolute', left: 0, top: 0, width: '100%', zIndex: hs.zIndexCounter, direction: 'ltr' }, document.body, true ); hs.loading = hs.createElement('a', { className: 'highslide-loading', title: hs.lang.loadingTitle, innerHTML: hs.lang.loadingText, href: 'javascript:;' }, { position: 'absolute', top: '-9999px', opacity: hs.loadingOpacity, zIndex: 1 }, hs.container ); hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container); hs.viewport = hs.createElement('div', { className: 'highslide-viewport highslide-viewport-size' }, { visibility: (hs.safari && hs.uaVersion < 525) ? 'visible' : 'hidden' }, hs.container, 1 ); // http://www.robertpenner.com/easing/ Math.linearTween = function (t, b, c, d) { return c*t/d + b; }; Math.easeInQuad = function (t, b, c, d) { return c*(t/=d)*t + b; }; Math.easeOutQuad = function (t, b, c, d) { return -c *(t/=d)*(t-2) + b; }; hs.hideSelects = hs.ieLt7; hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE' || (hs.ie && hs.uaVersion < 5.5)); } }, ready : function() { if (hs.isReady) return; hs.isReady = true; for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i](); }, updateAnchors : function() { var el, els, all = [], images = [],groups = {}, re; for (var i = 0; i < hs.openerTagNames.length; i++) { els = document.getElementsByTagName(hs.openerTagNames[i]); for (var j = 0; j < els.length; j++) { el = els[j]; re = hs.isHsAnchor(el); if (re) { hs.push(all, el); if (re[0] == 'hs.expand') hs.push(images, el); var g = hs.getParam(el, 'slideshowGroup') || 'none'; if (!groups[g]) groups[g] = []; hs.push(groups[g], el); } } } hs.anchors = { all: all, groups: groups, images: images }; return hs.anchors; }, getAnchors : function() { return hs.anchors || hs.updateAnchors(); }, close : function(el) { var exp = hs.getExpander(el); if (exp) exp.close(); return false; } }; // end hs object hs.fx = function( elem, options, prop ){ this.options = options; this.elem = elem; this.prop = prop; if (!options.orig) options.orig = {}; }; hs.fx.prototype = { update: function(){ (hs.fx.step[this.prop] || hs.fx.step._default)(this); if (this.options.step) this.options.step.call(this.elem, this.now, this); }, custom: function(from, to, unit){ this.startTime = (new Date()).getTime(); this.start = from; this.end = to; this.unit = unit;// || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t(gotoEnd){ return self.step(gotoEnd); } t.elem = this.elem; if ( t() && hs.timers.push(t) == 1 ) { hs.timerId = setInterval(function(){ var timers = hs.timers; for ( var i = 0; i < timers.length; i++ ) if ( !timers[i]() ) timers.splice(i--, 1); if ( !timers.length ) { clearInterval(hs.timerId); } }, 13); } }, step: function(gotoEnd){ var t = (new Date()).getTime(); if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; var done = true; for ( var i in this.options.curAnim ) if ( this.options.curAnim[i] !== true ) done = false; if ( done ) { if (this.options.complete) this.options.complete.call(this.elem); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; this.pos = this.options.easing(n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); } return true; } }; hs.extend( hs.fx, { step: { opacity: function(fx){ hs.setStyles(fx.elem, { opacity: fx.now }); }, _default: function(fx){ try { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) fx.elem.style[ fx.prop ] = fx.now + fx.unit; else fx.elem[ fx.prop ] = fx.now; } catch (e) {} } } }); hs.Outline = function (outlineType, onLoad) { this.onLoad = onLoad; this.outlineType = outlineType; var v = hs.uaVersion, tr; this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7; if (!outlineType) { if (onLoad) onLoad(); return; } hs.init(); this.table = hs.createElement( 'table', { cellSpacing: 0 }, { visibility: 'hidden', position: 'absolute', borderCollapse: 'collapse', width: 0 }, hs.container, true ); var tbody = hs.createElement('tbody', null, null, this.table, 1); this.td = []; for (var i = 0; i <= 8; i++) { if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true); this.td[i] = hs.createElement('td', null, null, tr, true); var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' }; hs.setStyles(this.td[i], style); } this.td[4].className = outlineType +' highslide-outline'; this.preloadGraphic(); }; hs.Outline.prototype = { preloadGraphic : function () { var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png"; var appendTo = hs.safari ? hs.container : null; this.graphic = hs.createElement('img', null, { position: 'absolute', top: '-9999px' }, appendTo, true); // for onload trigger var pThis = this; this.graphic.onload = function() { pThis.onGraphicLoad(); }; this.graphic.src = src; }, onGraphicLoad : function () { var o = this.offset = this.graphic.width / 4, pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]], dim = { height: (2*o) +'px', width: (2*o) +'px' }; for (var i = 0; i <= 8; i++) { if (pos[i]) { if (this.hasAlphaImageLoader) { var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px'; var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true); hs.createElement ('div', null, { filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')", position: 'absolute', width: w, height: this.graphic.height +'px', left: (pos[i][0]*o)+'px', top: (pos[i][1]*o)+'px' }, div, true); } else { hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'}); } if (window.opera && (i == 3 || i ==5)) hs.createElement('div', null, dim, this.td[i], true); hs.setStyles (this.td[i], dim); } } this.graphic = null; if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy(); hs.pendingOutlines[this.outlineType] = this; if (this.onLoad) this.onLoad(); }, setPosition : function (pos, offset, vis, dur, easing) { var exp = this.exp, stl = exp.wrapper.style, offset = offset || 0, pos = pos || { x: exp.x.pos + offset, y: exp.y.pos + offset, w: exp.x.get('wsize') - 2 * offset, h: exp.y.get('wsize') - 2 * offset }; if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset) ? 'visible' : 'hidden'; hs.setStyles(this.table, { left: (pos.x - this.offset) +'px', top: (pos.y - this.offset) +'px', width: (pos.w + 2 * this.offset) +'px' }); pos.w -= 2 * this.offset; pos.h -= 2 * this.offset; hs.setStyles (this.td[4], { width: pos.w >= 0 ? pos.w +'px' : 0, height: pos.h >= 0 ? pos.h +'px' : 0 }); if (this.hasAlphaImageLoader) this.td[3].style.height = this.td[5].style.height = this.td[4].style.height; }, destroy : function(hide) { if (hide) this.table.style.visibility = 'hidden'; else hs.discardElement(this.table); } }; hs.Dimension = function(exp, dim) { this.exp = exp; this.dim = dim; this.ucwh = dim == 'x' ? 'Width' : 'Height'; this.wh = this.ucwh.toLowerCase(); this.uclt = dim == 'x' ? 'Left' : 'Top'; this.lt = this.uclt.toLowerCase(); this.ucrb = dim == 'x' ? 'Right' : 'Bottom'; this.rb = this.ucrb.toLowerCase(); this.p1 = this.p2 = 0; }; hs.Dimension.prototype = { get : function(key) { switch (key) { case 'loadingPos': return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2; case 'loadingPosXfade': return this.pos + this.cb+ this.p1 + (this.size - hs.loading['offset'+ this.ucwh]) / 2; case 'wsize': return this.size + 2 * this.cb + this.p1 + this.p2; case 'fitsize': return this.clientSize - this.marginMin - this.marginMax; case 'maxsize': return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ; case 'opos': return this.pos - (this.exp.outline ? this.exp.outline.offset : 0); case 'osize': return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0); case 'imgPad': return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0; } }, calcBorders: function() { // correct for borders this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2; this.marginMax = hs['margin'+ this.ucrb]; }, calcThumb: function() { this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) : this.exp.el['offset'+ this.ucwh]; this.tpos = this.exp.tpos[this.dim]; this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2; if (this.tpos == 0 || this.tpos == -1) { this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt]; }; }, calcExpanded: function() { var exp = this.exp; this.justify = 'auto'; // get alignment if (exp.align == 'center') this.justify = 'center'; else if (new RegExp(this.lt).test(exp.anchor)) this.justify = null; else if (new RegExp(this.rb).test(exp.anchor)) this.justify = 'max'; // size and position this.pos = this.tpos - this.cb + this.tb; if (this.maxHeight && this.dim == 'x') exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full); this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full); this.minSize = exp.allowSizeReduction ? Math.min(exp['min'+ this.ucwh], this.full) :this.full; if (exp.isImage && exp.useBox) { this.size = exp[this.wh]; this.imgSize = this.full; } if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth; this.target = exp['target'+ this.dim.toUpperCase()]; this.marginMin = hs['margin'+ this.uclt]; this.scroll = hs.page['scroll'+ this.uclt]; this.clientSize = hs.page[this.wh]; }, setSize: function(i) { var exp = this.exp; if (exp.isImage && (exp.useBox || hs.padToMinWidth)) { this.imgSize = i; this.size = Math.max(this.size, this.imgSize); exp.content.style[this.lt] = this.get('imgPad')+'px'; } else this.size = i; exp.content.style[this.wh] = i +'px'; exp.wrapper.style[this.wh] = this.get('wsize') +'px'; if (exp.outline) exp.outline.setPosition(); if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true); if (this.dim == 'x' && exp.slideshow && exp.isImage) { if (i == this.full) exp.slideshow.disable('full-expand'); else exp.slideshow.enable('full-expand'); } }, setPos: function(i) { this.pos = i; this.exp.wrapper.style[this.lt] = i +'px'; if (this.exp.outline) this.exp.outline.setPosition(); } }; hs.Expander = function(a, params, custom, contentType) { if (document.readyState && hs.ie && !hs.isReady) { hs.addEventListener(document, 'ready', function() { new hs.Expander(a, params, custom, contentType); }); return; } this.a = a; this.custom = custom; this.contentType = contentType || 'image'; this.isImage = !this.isHtml; hs.continuePreloading = false; this.overlays = []; this.last = hs.last; hs.last = null; hs.init(); var key = this.key = hs.expanders.length; // override inline parameters for (var i = 0; i < hs.overrides.length; i++) { var name = hs.overrides[i]; this[name] = params && typeof params[name] != 'undefined' ? params[name] : hs[name]; } if (!this.src) this.src = a.href; // get thumb var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a; el = this.thumb = el.getElementsByTagName('img')[0] || el; this.thumbsUserSetId = el.id || a.id; // check if already open for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].a == a && !(this.last && this.transitions[1] == 'crossfade')) { hs.expanders[i].focus(); return false; } } // cancel other if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) { hs.expanders[i].cancelLoading(); } } hs.expanders[key] = this; if (!hs.allowMultipleInstances && !hs.upcoming) { if (hs.expanders[key-1]) hs.expanders[key-1].close(); if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey]) hs.expanders[hs.focusKey].close(); } // initiate metrics this.el = el; this.tpos = hs.getPosition(el); hs.getPageSize(); var x = this.x = new hs.Dimension(this, 'x'); x.calcThumb(); var y = this.y = new hs.Dimension(this, 'y'); y.calcThumb(); this.wrapper = hs.createElement( 'div', { id: 'highslide-wrapper-'+ this.key, className: 'highslide-wrapper '+ this.wrapperClassName }, { visibility: 'hidden', position: 'absolute', zIndex: hs.zIndexCounter += 2 }, null, true ); this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler; if (this.contentType == 'image' && this.outlineWhileAnimating == 2) this.outlineWhileAnimating = 0; // get the outline if (!this.outlineType || (this.last && this.isImage && this.transitions[1] == 'crossfade')) { this[this.contentType +'Create'](); } else if (hs.pendingOutlines[this.outlineType]) { this.connectOutline(); this[this.contentType +'Create'](); } else { this.showLoading(); var exp = this; new hs.Outline(this.outlineType, function () { exp.connectOutline(); exp[exp.contentType +'Create'](); } ); } return true; }; hs.Expander.prototype = { error : function(e) { // alert ('Line '+ e.lineNumber +': '+ e.message); window.location.href = this.src; }, connectOutline : function() { var outline = this.outline = hs.pendingOutlines[this.outlineType]; outline.exp = this; outline.table.style.zIndex = this.wrapper.style.zIndex - 1; hs.pendingOutlines[this.outlineType] = null; }, showLoading : function() { if (this.onLoadStarted || this.loading) return; this.loading = hs.loading; var exp = this; this.loading.onclick = function() { exp.cancelLoading(); }; var exp = this, l = this.x.get('loadingPos') +'px', t = this.y.get('loadingPos') +'px'; if (!tgt && this.last && this.transitions[1] == 'crossfade') var tgt = this.last; if (tgt) { l = tgt.x.get('loadingPosXfade') +'px'; t = tgt.y.get('loadingPosXfade') +'px'; this.loading.style.zIndex = hs.zIndexCounter++; } setTimeout(function () { if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })} , 100); }, imageCreate : function() { var exp = this; var img = document.createElement('img'); this.content = img; img.onload = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); }; if (hs.blockRightClick) img.oncontextmenu = function() { return false; }; img.className = 'highslide-image'; hs.setStyles(img, { visibility: 'hidden', display: 'block', position: 'absolute', maxWidth: '9999px', zIndex: 3 }); img.title = hs.lang.restoreTitle; if (hs.safari) hs.container.appendChild(img); if (hs.ie && hs.flushImgSize) img.src = null; img.src = this.src; this.showLoading(); }, contentLoaded : function() { try { if (!this.content) return; this.content.onload = null; if (this.onLoadStarted) return; else this.onLoadStarted = true; var x = this.x, y = this.y; if (this.loading) { hs.setStyles(this.loading, { top: '-9999px' }); this.loading = null; } x.full = this.content.width; y.full = this.content.height; hs.setStyles(this.content, { width: x.t +'px', height: y.t +'px' }); this.wrapper.appendChild(this.content); hs.container.appendChild(this.wrapper); x.calcBorders(); y.calcBorders(); hs.setStyles (this.wrapper, { left: (x.tpos + x.tb - x.cb) +'px', top: (y.tpos + x.tb - y.cb) +'px' }); this.initSlideshow(); this.getOverlays(); var ratio = x.full / y.full; x.calcExpanded(); this.justify(x); y.calcExpanded(); this.justify(y); if (this.overlayBox) this.sizeOverlayBox(0, 1); if (this.allowSizeReduction) { this.correctRatio(ratio); var ss = this.slideshow; if (ss && this.last && ss.controls && ss.fixedControls) { var pos = ss.overlayOptions.position || '', p; for (var dim in hs.oPos) for (var i = 0; i < 5; i++) { p = this[dim]; if (pos.match(hs.oPos[dim][i])) { p.pos = this.last[dim].pos + (this.last[dim].p1 - p.p1) + (this.last[dim].size - p.size) * [0, 0, .5, 1, 1][i]; if (ss.fixedControls == 'fit') { if (p.pos + p.size + p.p1 + p.p2 > p.scroll + p.clientSize - p.marginMax) p.pos = p.scroll + p.clientSize - p.size - p.marginMin - p.marginMax - p.p1 - p.p2; if (p.pos < p.scroll + p.marginMin) p.pos = p.scroll + p.marginMin; } } } } if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) { this.createFullExpand(); if (this.overlays.length == 1) this.sizeOverlayBox(); } } this.show(); } catch (e) { this.error(e); } }, justify : function (p, moveOnly) { var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y'; if (tgt && tgt.match(/ /)) { tgtArr = tgt.split(' '); tgt = tgtArr[0]; } if (tgt && hs.$(tgt)) { p.pos = hs.getPosition(hs.$(tgt))[dim]; if (tgtArr && tgtArr[1] && tgtArr[1].match(/^[-]?[0-9]+px$/)) p.pos += parseInt(tgtArr[1]); if (p.size < p.minSize) p.size = p.minSize; } else if (p.justify == 'auto' || p.justify == 'center') { var hasMovedMin = false; var allowReduce = p.exp.allowSizeReduction; if (p.justify == 'center') p.pos = Math.round(p.scroll + (p.clientSize + p.marginMin - p.marginMax - p.get('wsize')) / 2); else p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2)); if (p.pos < p.scroll + p.marginMin) { p.pos = p.scroll + p.marginMin; hasMovedMin = true; } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) { if (!moveOnly && hasMovedMin && allowReduce) { p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize')); } else if (p.get('wsize') < p.get('fitsize')) { p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize'); } else { // image larger than viewport p.pos = p.scroll + p.marginMin; if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize'); } } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } } else if (p.justify == 'max') { p.pos = Math.floor(p.pos - p.size + p.t); } if (p.pos < p.marginMin) { var tmpMin = p.pos; p.pos = p.marginMin; if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin); } }, correctRatio : function(ratio) { var x = this.x, y = this.y, changed = false, xSize = Math.min(x.full, x.size), ySize = Math.min(y.full, y.size), useBox = (this.useBox || hs.padToMinWidth); if (xSize / ySize > ratio) { // width greater xSize = ySize * ratio; if (xSize < x.minSize) { // below minWidth xSize = x.minSize; ySize = xSize / ratio; } changed = true; } else if (xSize / ySize < ratio) { // height greater ySize = xSize / ratio; changed = true; } if (hs.padToMinWidth && x.full < x.minSize) { x.imgSize = x.full; y.size = y.imgSize = y.full; } else if (this.useBox) { x.imgSize = xSize; y.imgSize = ySize; } else { x.size = xSize; y.size = ySize; } changed = this.fitOverlayBox(useBox ? null : ratio, changed); if (useBox && y.size < y.imgSize) { y.imgSize = y.size; x.imgSize = y.size * ratio; } if (changed || useBox) { x.pos = x.tpos - x.cb + x.tb; x.minSize = x.size; this.justify(x, true); y.pos = y.tpos - y.cb + y.tb; y.minSize = y.size; this.justify(y, true); if (this.overlayBox) this.sizeOverlayBox(); } }, fitOverlayBox : function(ratio, changed) { var x = this.x, y = this.y; if (this.overlayBox) { while (y.size > this.minHeight && x.size > this.minWidth && y.get('wsize') > y.get('fitsize')) { y.size -= 10; if (ratio) x.size = y.size * ratio; this.sizeOverlayBox(0, 1); changed = true; } } return changed; }, show : function () { var x = this.x, y = this.y; this.doShowHide('hidden'); if (this.slideshow && this.slideshow.thumbstrip) this.slideshow.thumbstrip.selectThumb(); // Apply size change this.changeSize( 1, { wrapper: { width : x.get('wsize'), height : y.get('wsize'), left: x.pos, top: y.pos }, content: { left: x.p1 + x.get('imgPad'), top: y.p1 + y.get('imgPad'), width:x.imgSize ||x.size, height:y.imgSize ||y.size } }, hs.expandDuration ); }, changeSize : function(up, to, dur) { // transition var trans = this.transitions, other = up ? (this.last ? this.last.a : null) : hs.upcoming, t = (trans[1] && other && hs.getParam(other, 'transitions')[1] == trans[1]) ? trans[1] : trans[0]; if (this[t] && t != 'expand') { this[t](up, to); return; } if (this.outline && !this.outlineWhileAnimating) { if (up) this.outline.setPosition(); else this.outline.destroy(); } if (!up) this.destroyOverlays(); var exp = this, x = exp.x, y = exp.y, easing = this.easing; if (!up) easing = this.easingClose || easing; var after = up ? function() { if (exp.outline) exp.outline.table.style.visibility = "visible"; setTimeout(function() { exp.afterExpand(); }, 50); } : function() { exp.afterClose(); }; if (up) hs.setStyles( this.wrapper, { width: x.t +'px', height: y.t +'px' }); if (this.fadeInOut) { hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 }); hs.extend(to.wrapper, { opacity: up }); } hs.animate( this.wrapper, to.wrapper, { duration: dur, easing: easing, step: function(val, args) { if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') { var fac = up ? args.pos : 1 - args.pos; var pos = { w: x.t + (x.get('wsize') - x.t) * fac, h: y.t + (y.get('wsize') - y.t) * fac, x: x.tpos + (x.pos - x.tpos) * fac, y: y.tpos + (y.pos - y.tpos) * fac }; exp.outline.setPosition(pos, 0, 1); } } }); hs.animate( this.content, to.content, dur, easing, after); if (up) { this.wrapper.style.visibility = 'visible'; this.content.style.visibility = 'visible'; this.a.className += ' highslide-active-anchor'; } }, fade : function(up, to) { this.outlineWhileAnimating = false; var exp = this, t = up ? hs.expandDuration : 0; if (up) { hs.animate(this.wrapper, to.wrapper, 0); hs.setStyles(this.wrapper, { opacity: 0, visibility: 'visible' }); hs.animate(this.content, to.content, 0); this.content.style.visibility = 'visible'; hs.animate(this.wrapper, { opacity: 1 }, t, null, function() { exp.afterExpand(); }); } if (this.outline) { this.outline.table.style.zIndex = this.wrapper.style.zIndex; var dir = up || -1, offset = this.outline.offset, startOff = up ? 3 : offset, endOff = up? offset : 3; for (var i = startOff; dir * i <= dir * endOff; i += dir, t += 25) { (function() { var o = up ? endOff - i : startOff - i; setTimeout(function() { exp.outline.setPosition(0, o, 1); }, t); })(); } } if (up) {}//setTimeout(function() { exp.afterExpand(); }, t+50); else { setTimeout( function() { if (exp.outline) exp.outline.destroy(exp.preserveContent); exp.destroyOverlays(); hs.animate( exp.wrapper, { opacity: 0 }, hs.restoreDuration, null, function(){ exp.afterClose(); }); }, t); } }, crossfade : function (up, to, from) { if (!up) return; var exp = this, last = this.last, x = this.x, y = this.y, lastX = last.x, lastY = last.y, wrapper = this.wrapper, content = this.content, overlayBox = this.overlayBox; hs.removeEventListener(document, 'mousemove', hs.dragHandler); hs.setStyles(content, { width: (x.imgSize || x.size) +'px', height: (y.imgSize || y.size) +'px' }); if (overlayBox) overlayBox.style.overflow = 'visible'; this.outline = last.outline; if (this.outline) this.outline.exp = exp; last.outline = null; var fadeBox = hs.createElement('div', { className: 'highslide-image' }, { position: 'absolute', zIndex: 4, overflow: 'hidden', display: 'none' } ); var names = { oldImg: last, newImg: this }; for (var n in names) { this[n] = names[n].content.cloneNode(1); hs.setStyles(this[n], { position: 'absolute', border: 0, visibility: 'visible' }); fadeBox.appendChild(this[n]); } wrapper.appendChild(fadeBox); if (overlayBox) { overlayBox.className = ''; wrapper.appendChild(overlayBox); } fadeBox.style.display = ''; last.content.style.display = 'none'; if (hs.safari) { var match = navigator.userAgent.match(/Safari\/([0-9]{3})/); if (match && parseInt(match[1]) < 525) this.wrapper.style.visibility = 'visible'; } hs.animate(wrapper, { width: x.size }, { duration: hs.transitionDuration, step: function(val, args) { var pos = args.pos, invPos = 1 - pos; var prop, size = {}, props = ['pos', 'size', 'p1', 'p2']; for (var n in props) { prop = props[n]; size['x'+ prop] = Math.round(invPos * lastX[prop] + pos * x[prop]); size['y'+ prop] = Math.round(invPos * lastY[prop] + pos * y[prop]); size.ximgSize = Math.round( invPos * (lastX.imgSize || lastX.size) + pos * (x.imgSize || x.size)); size.ximgPad = Math.round(invPos * lastX.get('imgPad') + pos * x.get('imgPad')); size.yimgSize = Math.round( invPos * (lastY.imgSize || lastY.size) + pos * (y.imgSize || y.size)); size.yimgPad = Math.round(invPos * lastY.get('imgPad') + pos * y.get('imgPad')); } if (exp.outline) exp.outline.setPosition({ x: size.xpos, y: size.ypos, w: size.xsize + size.xp1 + size.xp2 + 2 * x.cb, h: size.ysize + size.yp1 + size.yp2 + 2 * y.cb }); last.wrapper.style.clip = 'rect(' + (size.ypos - lastY.pos)+'px, ' + (size.xsize + size.xp1 + size.xp2 + size.xpos + 2 * lastX.cb - lastX.pos) +'px, ' + (size.ysize + size.yp1 + size.yp2 + size.ypos + 2 * lastY.cb - lastY.pos) +'px, ' + (size.xpos - lastX.pos)+'px)'; hs.setStyles(content, { top: (size.yp1 + y.get('imgPad')) +'px', left: (size.xp1 + x.get('imgPad')) +'px', marginTop: (y.pos - size.ypos) +'px', marginLeft: (x.pos - size.xpos) +'px' }); hs.setStyles(wrapper, { top: size.ypos +'px', left: size.xpos +'px', width: (size.xp1 + size.xp2 + size.xsize + 2 * x.cb)+ 'px', height: (size.yp1 + size.yp2 + size.ysize + 2 * y.cb) + 'px' }); hs.setStyles(fadeBox, { width: (size.ximgSize || size.xsize) + 'px', height: (size.yimgSize || size.ysize) +'px', left: (size.xp1 + size.ximgPad) +'px', top: (size.yp1 + size.yimgPad) +'px', visibility: 'visible' }); hs.setStyles(exp.oldImg, { top: (lastY.pos - size.ypos + lastY.p1 - size.yp1 + lastY.get('imgPad') - size.yimgPad)+'px', left: (lastX.pos - size.xpos + lastX.p1 - size.xp1 + lastX.get('imgPad') - size.ximgPad)+'px' }); hs.setStyles(exp.newImg, { opacity: pos, top: (y.pos - size.ypos + y.p1 - size.yp1 + y.get('imgPad') - size.yimgPad) +'px', left: (x.pos - size.xpos + x.p1 - size.xp1 + x.get('imgPad') - size.ximgPad) +'px' }); if (overlayBox) hs.setStyles(overlayBox, { width: size.xsize + 'px', height: size.ysize +'px', left: (size.xp1 + x.cb) +'px', top: (size.yp1 + y.cb) +'px' }); }, complete: function () { wrapper.style.visibility = content.style.visibility = 'visible'; content.style.display = 'block'; fadeBox.style.display = 'none'; exp.a.className += ' highslide-active-anchor'; exp.afterExpand(); last.afterClose(); exp.last = null; } }); }, reuseOverlay : function(o, el) { if (!this.last) return false; for (var i = 0; i < this.last.overlays.length; i++) { var oDiv = hs.$('hsId'+ this.last.overlays[i]); if (oDiv && oDiv.hsId == o.hsId) { this.genOverlayBox(); oDiv.reuse = this.key; hs.push(this.overlays, this.last.overlays[i]); return true; } } return false; }, afterExpand : function() { this.isExpanded = true; this.focus(); if (this.dimmingOpacity) hs.dim(this); if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null; this.prepareNextOutline(); var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop; this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize') && this.y.pos < mY && mY < this.y.pos + this.y.get('wsize'); if (this.overlayBox) this.showOverlays(); }, prepareNextOutline : function() { var key = this.key; var outlineType = this.outlineType; new hs.Outline(outlineType, function () { try { hs.expanders[key].preloadNext(); } catch (e) {} }); }, preloadNext : function() { var next = this.getAdjacentAnchor(1); if (next && next.onclick.toString().match(/hs\.expand/)) var img = hs.createElement('img', { src: hs.getSrc(next) }); }, getAdjacentAnchor : function(op) { var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none']; /*< ? if ($cfg->slideshow) : ?>s*/ if (!as[current + op] && this.slideshow && this.slideshow.repeat) { if (op == 1) return as[0]; else if (op == -1) return as[as.length-1]; } /*< ? endif ?>s*/ return as[current + op] || null; }, getAnchorIndex : function() { var arr = hs.getAnchors().groups[this.slideshowGroup || 'none']; if (arr) for (var i = 0; i < arr.length; i++) { if (arr[i] == this.a) return i; } return null; }, getNumber : function() { if (this[this.numberPosition]) { var arr = hs.anchors.groups[this.slideshowGroup || 'none']; if (arr) { var s = hs.lang.number.replace('%1', this.getAnchorIndex() + 1).replace('%2', arr.length); this[this.numberPosition].innerHTML = '<div class="highslide-number">'+ s +'</div>'+ this[this.numberPosition].innerHTML; } } }, initSlideshow : function() { if (!this.last) { for (var i = 0; i < hs.slideshows.length; i++) { var ss = hs.slideshows[i], sg = ss.slideshowGroup; if (typeof sg == 'undefined' || sg === null || sg === this.slideshowGroup) this.slideshow = new hs.Slideshow(this.key, ss); } } else { this.slideshow = this.last.slideshow; } var ss = this.slideshow; if (!ss) return; var key = ss.expKey = this.key; ss.checkFirstAndLast(); ss.disable('full-expand'); if (ss.controls) { var o = ss.overlayOptions || {}; o.overlayId = ss.controls; o.hsId = 'controls'; this.createOverlay(o); } if (ss.thumbstrip) ss.thumbstrip.add(this); if (!this.last && this.autoplay) ss.play(true); if (ss.autoplay) { ss.autoplay = setTimeout(function() { hs.next(key); }, (ss.interval || 500)); } }, cancelLoading : function() { hs.discardElement (this.wrapper); hs.expanders[this.key] = null; if (hs.upcoming == this.a) hs.upcoming = null; hs.undim(this.key); if (this.loading) hs.loading.style.left = '-9999px'; }, writeCredits : function () { if (this.credits) return; this.credits = hs.createElement('a', { href: hs.creditsHref, target: hs.creditsTarget, className: 'highslide-credits', innerHTML: hs.lang.creditsText, title: hs.lang.creditsTitle }); this.createOverlay({ overlayId: this.credits, position: this.creditsPosition || 'top left', hsId: 'credits' }); }, getInline : function(types, addOverlay) { for (var i = 0; i < types.length; i++) { var type = types[i], s = null; if (!this[type +'Id'] && this.thumbsUserSetId) this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId; if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']); if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try { s = eval(this[type +'Eval']); } catch (e) {} if (!this[type] && this[type +'Text']) { s = this[type +'Text']; } if (!this[type] && !s) { this[type] = hs.getNode(this.a['_'+ type + 'Id']); if (!this[type]) { var next = this.a.nextSibling; while (next && !hs.isHsAnchor(next)) { if ((new RegExp('highslide-'+ type)).test(next.className || null)) { if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++; this[type] = hs.getNode(next.id); break; } next = next.nextSibling; } } } if (!this[type] && !s && this.numberPosition == type) s = '\n'; if (!this[type] && s) this[type] = hs.createElement('div', { className: 'highslide-'+ type, innerHTML: s } ); if (addOverlay && this[type]) { var o = { position: (type == 'heading') ? 'above' : 'below' }; for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x]; o.overlayId = this[type]; this.createOverlay(o); } } }, // on end move and resize doShowHide : function(visibility) { if (hs.hideSelects) this.showHideElements('SELECT', visibility); if (hs.hideIframes) this.showHideElements('IFRAME', visibility); if (hs.geckoMac) this.showHideElements('*', visibility); }, showHideElements : function (tagName, visibility) { var els = document.getElementsByTagName(tagName); var prop = tagName == '*' ? 'overflow' : 'visibility'; for (var i = 0; i < els.length; i++) { if (prop == 'visibility' || (document.defaultView.getComputedStyle( els[i], "").getPropertyValue('overflow') == 'auto' || els[i].getAttribute('hidden-by') != null)) { var hiddenBy = els[i].getAttribute('hidden-by'); if (visibility == 'visible' && hiddenBy) { hiddenBy = hiddenBy.replace('['+ this.key +']', ''); els[i].setAttribute('hidden-by', hiddenBy); if (!hiddenBy) els[i].style[prop] = els[i].origProp; } else if (visibility == 'hidden') { // hide if behind var elPos = hs.getPosition(els[i]); elPos.w = els[i].offsetWidth; elPos.h = els[i].offsetHeight; if (!this.dimmingOpacity) { // hide all if dimming var clearsX = (elPos.x + elPos.w < this.x.get('opos') || elPos.x > this.x.get('opos') + this.x.get('osize')); var clearsY = (elPos.y + elPos.h < this.y.get('opos') || elPos.y > this.y.get('opos') + this.y.get('osize')); } var wrapperKey = hs.getWrapperKey(els[i]); if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image if (!hiddenBy) { els[i].setAttribute('hidden-by', '['+ this.key +']'); els[i].origProp = els[i].style[prop]; els[i].style[prop] = 'hidden'; } else if (hiddenBy.indexOf('['+ this.key +']') == -1) { els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']'); } } else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey) && wrapperKey != this.key) { // on move els[i].setAttribute('hidden-by', ''); els[i].style[prop] = els[i].origProp || ''; } else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) { els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', '')); } } } } }, focus : function() { this.wrapper.style.zIndex = hs.zIndexCounter += 2; // blur others for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && i == hs.focusKey) { var blurExp = hs.expanders[i]; blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur'; blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer'; blurExp.content.title = hs.lang.focusTitle; } } // focus this if (this.outline) this.outline.table.style.zIndex = this.wrapper.style.zIndex - 1; this.content.className = 'highslide-'+ this.contentType; this.content.title = hs.lang.restoreTitle; if (hs.restoreCursor) { hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer'; if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand'; this.content.style.cursor = hs.styleRestoreCursor; } hs.focusKey = this.key; hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); }, moveTo: function(x, y) { this.x.setPos(x); this.y.setPos(y); }, resize : function (e) { var w, h, r = e.width / e.height; w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full)); if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full; h = w / r; if (h < Math.min(this.minHeight, this.y.full)) { h = Math.min(this.minHeight, this.y.full); if (this.isImage) w = h * r; } this.resizeTo(w, h); }, resizeTo: function(w, h) { this.y.setSize(h); this.x.setSize(w); this.wrapper.style.height = this.y.get('wsize') +'px'; }, close : function() { if (this.isClosing || !this.isExpanded) return; if (this.transitions[1] == 'crossfade' && hs.upcoming) { hs.getExpander(hs.upcoming).cancelLoading(); hs.upcoming = null; } this.isClosing = true; if (this.slideshow && !hs.upcoming) this.slideshow.pause(); hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); try { this.content.style.cursor = 'default'; this.changeSize( 0, { wrapper: { width : this.x.t, height : this.y.t, left: this.x.tpos - this.x.cb + this.x.tb, top: this.y.tpos - this.y.cb + this.y.tb }, content: { left: 0, top: 0, width: this.x.t, height: this.y.t } }, hs.restoreDuration ); } catch (e) { this.afterClose(); } }, createOverlay : function (o) { var el = o.overlayId, relToVP = (o.relativeTo == 'viewport' && !/panel$/.test(o.position)); if (typeof el == 'string') el = hs.getNode(el); if (o.html) el = hs.createElement('div', { innerHTML: o.html }); if (!el || typeof el == 'string') return; el.style.display = 'block'; o.hsId = o.hsId || o.overlayId; if (this.transitions[1] == 'crossfade' && this.reuseOverlay(o, el)) return; this.genOverlayBox(); var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto'; if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px'; var overlay = hs.createElement( 'div', { id: 'hsId'+ hs.idCounter++, hsId: o.hsId }, { position: 'absolute', visibility: 'hidden', width: width, direction: hs.lang.cssDirection || '', opacity: 0 }, relToVP ? hs.viewport :this.overlayBox, true ); if (relToVP) overlay.hsKey = this.key; overlay.appendChild(el); hs.extend(overlay, { opacity: 1, offsetX: 0, offsetY: 0, dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250 }); hs.extend(overlay, o); if (this.gotOverlays) { this.positionOverlay(overlay); if (!overlay.hideOnMouseOut || this.mouseIsOver) hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur); } hs.push(this.overlays, hs.idCounter - 1); }, positionOverlay : function(overlay) { var p = overlay.position || 'middle center', relToVP = (overlay.relativeTo == 'viewport'), offX = overlay.offsetX, offY = overlay.offsetY; if (relToVP) { hs.viewport.style.display = 'block'; overlay.hsKey = this.key; if (overlay.offsetWidth > overlay.parentNode.offsetWidth) overlay.style.width = '100%'; } else if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay); if (/left$/.test(p)) overlay.style.left = offX +'px'; if (/center$/.test(p)) hs.setStyles (overlay, { left: '50%', marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px' }); if (/right$/.test(p)) overlay.style.right = - offX +'px'; if (/^leftpanel$/.test(p)) { hs.setStyles(overlay, { right: '100%', marginRight: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p1 = overlay.offsetWidth; } else if (/^rightpanel$/.test(p)) { hs.setStyles(overlay, { left: '100%', marginLeft: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p2 = overlay.offsetWidth; } var parOff = overlay.parentNode.offsetHeight; overlay.style.height = 'auto'; if (relToVP && overlay.offsetHeight > parOff) overlay.style.height = hs.ieLt7 ? parOff +'px' : '100%'; if (/^top/.test(p)) overlay.style.top = offY +'px'; if (/^middle/.test(p)) hs.setStyles (overlay, { top: '50%', marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px' }); if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px'; if (/^above$/.test(p)) { hs.setStyles(overlay, { left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', bottom: '100%', marginBottom: this.y.cb +'px', width: 'auto' }); this.y.p1 = overlay.offsetHeight; } else if (/^below$/.test(p)) { hs.setStyles(overlay, { position: 'relative', left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', top: '100%', marginTop: this.y.cb +'px', width: 'auto' }); this.y.p2 = overlay.offsetHeight; overlay.style.position = 'absolute'; } }, getOverlays : function() { this.getInline(['heading', 'caption'], true); this.getNumber(); if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move'; if (hs.showCredits) this.writeCredits(); for (var i = 0; i < hs.overlays.length; i++) { var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup; if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId) || (sg && sg === this.slideshowGroup)) { this.createOverlay(o); } } var os = []; for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); if (/panel$/.test(o.position)) this.positionOverlay(o); else hs.push(os, o); } for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]); this.gotOverlays = true; }, genOverlayBox : function() { if (!this.overlayBox) this.overlayBox = hs.createElement ( 'div', { className: this.wrapperClassName }, { position : 'absolute', width: (this.x.size || (this.useBox ? this.width : null) || this.x.full) +'px', height: (this.y.size || this.y.full) +'px', visibility : 'hidden', overflow : 'hidden', zIndex : hs.ie ? 4 : 'auto' }, hs.container, true ); }, sizeOverlayBox : function(doWrapper, doPanels) { var overlayBox = this.overlayBox, x = this.x, y = this.y; hs.setStyles( overlayBox, { width: x.size +'px', height: y.size +'px' }); if (doWrapper || doPanels) { for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat'); if (o && /^(above|below)$/.test(o.position)) { if (ie6) { o.style.width = (overlayBox.offsetWidth + 2 * x.cb + x.p1 + x.p2) +'px'; } y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight; } if (o && ie6 && /^(left|right)panel$/.test(o.position)) { o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px'; } } } if (doWrapper) { hs.setStyles(this.content, { top: y.p1 +'px' }); hs.setStyles(overlayBox, { top: (y.p1 + y.cb) +'px' }); } }, showOverlays : function() { var b = this.overlayBox; b.className = ''; hs.setStyles(b, { top: (this.y.p1 + this.y.cb) +'px', left: (this.x.p1 + this.x.cb) +'px', overflow : 'visible' }); if (hs.safari) b.style.visibility = 'visible'; this.wrapper.appendChild (b); for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); o.style.zIndex = o.hsId == 'controls' ? 5 : 4; if (!o.hideOnMouseOut || this.mouseIsOver) { o.style.visibility = 'visible'; hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: o.opacity }, o.dur); } } }, destroyOverlays : function() { if (!this.overlays.length) return; if (this.slideshow) { var c = this.slideshow.controls; if (c && hs.getExpander(c) == this) c.parentNode.removeChild(c); } for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); if (o && o.parentNode == hs.viewport && hs.getExpander(o) == this) hs.discardElement(o); } hs.discardElement(this.overlayBox); }, createFullExpand : function () { if (this.slideshow && this.slideshow.controls) { this.slideshow.enable('full-expand'); return; } this.fullExpandLabel = hs.createElement( 'a', { href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();', title: hs.lang.fullExpandTitle, className: 'highslide-full-expand' } ); this.createOverlay({ overlayId: this.fullExpandLabel, position: hs.fullExpandPosition, hideOnMouseOut: true, opacity: hs.fullExpandOpacity }); }, doFullExpand : function () { try { if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel); this.focus(); var xSize = this.x.size; this.resizeTo(this.x.full, this.y.full); var xpos = this.x.pos - (this.x.size - xSize) / 2; if (xpos < hs.marginLeft) xpos = hs.marginLeft; this.moveTo(xpos, this.y.pos); this.doShowHide('hidden'); } catch (e) { this.error(e); } }, afterClose : function () { this.a.className = this.a.className.replace('highslide-active-anchor', ''); this.doShowHide('visible'); if (this.outline && this.outlineWhileAnimating) this.outline.destroy(); hs.discardElement(this.wrapper); this.destroyOverlays(); if (!hs.viewport.childNodes.length) hs.viewport.style.display = 'none'; if (this.dimmingOpacity) hs.undim(this.key); hs.expanders[this.key] = null; hs.reOrder(); } }; hs.Slideshow = function (expKey, options) { if (hs.dynamicallyUpdateAnchors !== false) hs.updateAnchors(); this.expKey = expKey; for (var x in options) this[x] = options[x]; if (this.useControls) this.getControls(); if (this.thumbstrip) this.thumbstrip = hs.Thumbstrip(this); }; hs.Slideshow.prototype = { getControls: function() { this.controls = hs.createElement('div', { innerHTML: hs.replaceLang(hs.skin.controls) }, null, hs.container); var buttons = ['play', 'pause', 'previous', 'next', 'move', 'full-expand', 'close']; this.btn = {}; var pThis = this; for (var i = 0; i < buttons.length; i++) { this.btn[buttons[i]] = hs.getElementByClass(this.controls, 'li', 'highslide-'+ buttons[i]); this.enable(buttons[i]); } this.btn.pause.style.display = 'none'; //this.disable('full-expand'); }, checkFirstAndLast: function() { if (this.repeat || !this.controls) return; var exp = hs.expanders[this.expKey], cur = exp.getAnchorIndex(), re = /disabled$/; if (cur == 0) this.disable('previous'); else if (re.test(this.btn.previous.getElementsByTagName('a')[0].className)) this.enable('previous'); if (cur + 1 == hs.anchors.groups[exp.slideshowGroup || 'none'].length) { this.disable('next'); this.disable('play'); } else if (re.test(this.btn.next.getElementsByTagName('a')[0].className)) { this.enable('next'); this.enable('play'); } }, enable: function(btn) { if (!this.btn) return; var sls = this, a = this.btn[btn].getElementsByTagName('a')[0], re = /disabled$/; a.onclick = function() { sls[btn](); return false; }; if (re.test(a.className)) a.className = a.className.replace(re, ''); }, disable: function(btn) { if (!this.btn) return; var a = this.btn[btn].getElementsByTagName('a')[0]; a.onclick = function() { return false; }; if (!/disabled$/.test(a.className)) a.className += ' disabled'; }, hitSpace: function() { if (this.autoplay) this.pause(); else this.play(); }, play: function(wait) { if (this.btn) { this.btn.play.style.display = 'none'; this.btn.pause.style.display = ''; } this.autoplay = true; if (!wait) hs.next(this.expKey); }, pause: function() { if (this.btn) { this.btn.pause.style.display = 'none'; this.btn.play.style.display = ''; } clearTimeout(this.autoplay); this.autoplay = null; }, previous: function() { this.pause(); hs.previous(this.btn.previous); }, next: function() { this.pause(); hs.next(this.btn.next); }, move: function() {}, 'full-expand': function() { hs.getExpander().doFullExpand(); }, close: function() { hs.close(this.btn.close); } }; hs.Thumbstrip = function(slideshow) { function add (exp) { hs.extend(options || {}, { overlayId: dom, hsId: 'thumbstrip', className: 'highslide-thumbstrip-'+ mode +'-overlay ' + (options.className || '') }); if (hs.ieLt7) options.fade = 0; exp.createOverlay(options); hs.setStyles(dom.parentNode, { overflow: 'hidden' }); }; function scroll (delta) { selectThumb(undefined, Math.round(delta * dom[isX ? 'offsetWidth' : 'offsetHeight'] * 0.7)); }; function selectThumb (i, scrollBy) { if (i === undefined) for (var j = 0; j < group.length; j++) { if (group[j] == hs.expanders[slideshow.expKey].a) { i = j; break; } } if (i === undefined) return; var as = dom.getElementsByTagName('a'), active = as[i], cell = active.parentNode, left = isX ? 'Left' : 'Top', right = isX ? 'Right' : 'Bottom', width = isX ? 'Width' : 'Height', offsetLeft = 'offset' + left, offsetWidth = 'offset' + width, overlayWidth = div.parentNode.parentNode[offsetWidth], minTblPos = overlayWidth - table[offsetWidth], curTblPos = parseInt(table.style[isX ? 'left' : 'top']) || 0, tblPos = curTblPos, mgnRight = 20; if (scrollBy !== undefined) { tblPos = curTblPos - scrollBy; if (minTblPos > 0) minTblPos = 0; if (tblPos > 0) tblPos = 0; if (tblPos < minTblPos) tblPos = minTblPos; } else { for (var j = 0; j < as.length; j++) as[j].className = ''; active.className = 'highslide-active-anchor'; var activeLeft = i > 0 ? as[i - 1].parentNode[offsetLeft] : cell[offsetLeft], activeRight = cell[offsetLeft] + cell[offsetWidth] + (as[i + 1] ? as[i + 1].parentNode[offsetWidth] : 0); if (activeRight > overlayWidth - curTblPos) tblPos = overlayWidth - activeRight; else if (activeLeft < -curTblPos) tblPos = -activeLeft; } var markerPos = cell[offsetLeft] + (cell[offsetWidth] - marker[offsetWidth]) / 2 + tblPos; hs.animate(table, isX ? { left: tblPos } : { top: tblPos }, null, 'easeOutQuad'); hs.animate(marker, isX ? { left: markerPos } : { top: markerPos }, null, 'easeOutQuad'); scrollUp.style.display = tblPos < 0 ? 'block' : 'none'; scrollDown.style.display = (tblPos > minTblPos) ? 'block' : 'none'; }; // initialize var group = hs.anchors.groups[hs.expanders[slideshow.expKey].slideshowGroup || 'none'], options = slideshow.thumbstrip, mode = options.mode || 'horizontal', floatMode = (mode == 'float'), tree = floatMode ? ['div', 'ul', 'li', 'span'] : ['table', 'tbody', 'tr', 'td'], isX = (mode == 'horizontal'), dom = hs.createElement('div', { className: 'highslide-thumbstrip highslide-thumbstrip-'+ mode, innerHTML: '<div class="highslide-thumbstrip-inner">'+ '<'+ tree[0] +'><'+ tree[1] +'></'+ tree[1] +'></'+ tree[0] +'></div>'+ '<div class="highslide-scroll-up"><div></div></div>'+ '<div class="highslide-scroll-down"><div></div></div>'+ '<div class="highslide-marker"><div></div></div>' }, { display: 'none' }, hs.container), domCh = dom.childNodes, div = domCh[0], scrollUp = domCh[1], scrollDown = domCh[2], marker = domCh[3], table = div.firstChild, tbody = dom.getElementsByTagName(tree[1])[0], tr; for (var i = 0; i < group.length; i++) { if (i == 0 || !isX) tr = hs.createElement(tree[2], null, null, tbody); (function(){ var a = group[i], cell = hs.createElement(tree[3], null, null, tr), pI = i; hs.createElement('a', { href: a.href, onclick: function() { hs.getExpander(this).focus(); return hs.transit(a); }, innerHTML: hs.stripItemFormatter ? hs.stripItemFormatter(a) : a.innerHTML }, null, cell); })(); } if (!floatMode) { scrollUp.onclick = function () { scroll(-1); }; scrollDown.onclick = function() { scroll(1); }; hs.addEventListener(tbody, document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll', function(e) { var delta = 0; e = e || window.event; if (e.wheelDelta) { delta = e.wheelDelta/120; if (hs.opera) delta = -delta; } else if (e.detail) { delta = -e.detail/3; } if (delta) scroll(-delta * 0.2); if (e.preventDefault) e.preventDefault(); e.returnValue = false; }); } return { add: add, selectThumb: selectThumb } }; hs.langDefaults = hs.lang; // history var HsExpander = hs.Expander; if (hs.ie) { (function () { try { document.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } hs.ready(); })(); } hs.addEventListener(document, 'DOMContentLoaded', hs.ready); hs.addEventListener(window, 'load', hs.ready); // set handlers hs.addEventListener(document, 'ready', function() { if (hs.expandCursor || hs.dimmingOpacity) { var style = hs.createElement('style', { type: 'text/css' }, null, document.getElementsByTagName('HEAD')[0]); function addRule(sel, dec) { if (!hs.ie) { style.appendChild(document.createTextNode(sel + " {" + dec + "}")); } else { var last = document.styleSheets[document.styleSheets.length - 1]; if (typeof(last.addRule) == "object") last.addRule(sel, dec); } } function fix(prop) { return 'expression( ( ( ignoreMe = document.documentElement.'+ prop + ' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );'; } if (hs.expandCursor) addRule ('.highslide img', 'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;'); addRule ('.highslide-viewport-size', hs.ie && (hs.uaVersion < 7 || document.compatMode == 'BackCompat') ? 'position: absolute; '+ 'left:'+ fix('scrollLeft') + 'top:'+ fix('scrollTop') + 'width:'+ fix('clientWidth') + 'height:'+ fix('clientHeight') : 'position: fixed; width: 100%; height: 100%; left: 0; top: 0'); } }); hs.addEventListener(window, 'resize', function() { hs.getPageSize(); if (hs.viewport) for (var i = 0; i < hs.viewport.childNodes.length; i++) { var node = hs.viewport.childNodes[i], exp = hs.getExpander(node); exp.positionOverlay(node); if (node.hsId == 'thumbstrip') exp.slideshow.thumbstrip.selectThumb(); } }); hs.addEventListener(document, 'mousemove', function(e) { hs.mouse = { x: e.clientX, y: e.clientY }; }); hs.addEventListener(document, 'mousedown', hs.mouseClickHandler); hs.addEventListener(document, 'mouseup', hs.mouseClickHandler); hs.addEventListener(document, 'ready', hs.getAnchors); hs.addEventListener(window, 'load', hs.preloadImages); }
JavaScript
/****************************************************************************** Name: Highslide JS Version: 4.1.8 (October 27 2009) Config: default Author: Torstein Hønsi Support: http://highslide.com/support Licence: Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5 License (http://creativecommons.org/licenses/by-nc/2.5/). You are free: * to copy, distribute, display, and perform the work * to make derivative works Under the following conditions: * Attribution. You must attribute the work in the manner specified by the author or licensor. * Noncommercial. You may not use this work for commercial purposes. * For any reuse or distribution, you must make clear to others the license terms of this work. * Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. ******************************************************************************/ if (!hs) { var hs = { // Language strings lang : { cssDirection: 'ltr', loadingText : 'Loading...', loadingTitle : 'Click to cancel', focusTitle : 'Click to bring to front', fullExpandTitle : 'Expand to actual size (f)', creditsText : 'Powered by <i>Highslide JS</i>', creditsTitle : 'Go to the Highslide JS homepage', restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.' }, // See http://highslide.com/ref for examples of settings graphicsDir : 'highslide/graphics/', expandCursor : 'zoomin.cur', // null disables restoreCursor : 'zoomout.cur', // null disables expandDuration : 250, // milliseconds restoreDuration : 250, marginLeft : 15, marginRight : 15, marginTop : 15, marginBottom : 15, zIndexCounter : 1001, // adjust to other absolutely positioned elements loadingOpacity : 0.75, allowMultipleInstances: true, numberOfImagesToPreload : 5, outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only outlineStartOffset : 3, // ends at 10 padToMinWidth : false, // pad the popup width to make room for wide caption fullExpandPosition : 'bottom right', fullExpandOpacity : 1, showCredits : true, // you can set this to false if you want creditsHref : 'http://highslide.com/', creditsTarget : '_self', enableKeyListener : true, openerTagNames : ['a'], // Add more to allow slideshow indexing dragByHeading: true, minWidth: 200, minHeight: 200, allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight outlineType : 'drop-shadow', // set null to disable outlines // END OF YOUR SETTINGS // declare internal properties preloadTheseImages : [], continuePreloading: true, expanders : [], overrides : [ 'allowSizeReduction', 'useBox', 'outlineType', 'outlineWhileAnimating', 'captionId', 'captionText', 'captionEval', 'captionOverlay', 'headingId', 'headingText', 'headingEval', 'headingOverlay', 'creditsPosition', 'dragByHeading', 'width', 'height', 'wrapperClassName', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'slideshowGroup', 'easing', 'easingClose', 'fadeInOut', 'src' ], overlays : [], idCounter : 0, oPos : { x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'], y: ['above', 'top', 'middle', 'bottom', 'below'] }, mouse: {}, headingOverlay: {}, captionOverlay: {}, timers : [], pendingOutlines : {}, clones : {}, onReady: [], uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 : parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]), ie : (document.all && !window.opera), safari : /Safari/.test(navigator.userAgent), geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent), $ : function (id) { if (id) return document.getElementById(id); }, push : function (arr, val) { arr[arr.length] = val; }, createElement : function (tag, attribs, styles, parent, nopad) { var el = document.createElement(tag); if (attribs) hs.extend(el, attribs); if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0}); if (styles) hs.setStyles(el, styles); if (parent) parent.appendChild(el); return el; }, extend : function (el, attribs) { for (var x in attribs) el[x] = attribs[x]; return el; }, setStyles : function (el, styles) { for (var x in styles) { if (hs.ie && x == 'opacity') { if (styles[x] > 0.99) el.style.removeAttribute('filter'); else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')'; } else el.style[x] = styles[x]; } }, animate: function(el, prop, opt) { var start, end, unit; if (typeof opt != 'object' || opt === null) { var args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (typeof opt.duration != 'number') opt.duration = 250; opt.easing = Math[opt.easing] || Math.easeInQuad; opt.curAnim = hs.extend({}, prop); for (var name in prop) { var e = new hs.fx(el, opt , name ); start = parseFloat(hs.css(el, name)) || 0; end = parseFloat(prop[name]); unit = name != 'opacity' ? 'px' : ''; e.custom( start, end, unit ); } }, css: function(el, prop) { if (document.defaultView) { return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop); } else { if (prop == 'opacity') prop = 'filter'; var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })]; if (prop == 'filter') val = val.replace(/alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100 }); return val === '' ? 1 : val; } }, getPageSize : function () { var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat' ? d.documentElement : d.body; var width = hs.ie ? iebody.clientWidth : (d.documentElement.clientWidth || self.innerWidth), height = hs.ie ? iebody.clientHeight : self.innerHeight; hs.page = { width: width, height: height, scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset, scrollTop: hs.ie ? iebody.scrollTop : pageYOffset } }, getPosition : function(el) { var p = { x: el.offsetLeft, y: el.offsetTop }; while (el.offsetParent) { el = el.offsetParent; p.x += el.offsetLeft; p.y += el.offsetTop; if (el != document.body && el != document.documentElement) { p.x -= el.scrollLeft; p.y -= el.scrollTop; } } return p; }, expand : function(a, params, custom, type) { if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container); if (typeof a.getParams == 'function') return params; try { new hs.Expander(a, params, custom); return false; } catch (e) { return true; } }, focusTopmost : function() { var topZ = 0, topmostKey = -1, expanders = hs.expanders, exp, zIndex; for (var i = 0; i < expanders.length; i++) { exp = expanders[i]; if (exp) { zIndex = exp.wrapper.style.zIndex; if (zIndex && zIndex > topZ) { topZ = zIndex; topmostKey = i; } } } if (topmostKey == -1) hs.focusKey = -1; else expanders[topmostKey].focus(); }, getParam : function (a, param) { a.getParams = a.onclick; var p = a.getParams ? a.getParams() : null; a.getParams = null; return (p && typeof p[param] != 'undefined') ? p[param] : (typeof hs[param] != 'undefined' ? hs[param] : null); }, getSrc : function (a) { var src = hs.getParam(a, 'src'); if (src) return src; return a.href; }, getNode : function (id) { var node = hs.$(id), clone = hs.clones[id], a = {}; if (!node && !clone) return null; if (!clone) { clone = node.cloneNode(true); clone.id = ''; hs.clones[id] = clone; return node; } else { return clone.cloneNode(true); } }, discardElement : function(d) { if (d) hs.garbageBin.appendChild(d); hs.garbageBin.innerHTML = ''; }, transit : function (adj, exp) { var last = exp = exp || hs.getExpander(); if (hs.upcoming) return false; else hs.last = last; try { hs.upcoming = adj; adj.onclick(); } catch (e){ hs.last = hs.upcoming = null; } try { exp.close(); } catch (e) {} return false; }, previousOrNext : function (el, op) { var exp = hs.getExpander(el); if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp); else return false; }, previous : function (el) { return hs.previousOrNext(el, -1); }, next : function (el) { return hs.previousOrNext(el, 1); }, keyHandler : function(e) { if (!e) e = window.event; if (!e.target) e.target = e.srcElement; // ie if (typeof e.target.form != 'undefined') return true; // form element has focus var exp = hs.getExpander(); var op = null; switch (e.keyCode) { case 70: // f if (exp) exp.doFullExpand(); return true; case 32: // Space case 34: // Page Down case 39: // Arrow right case 40: // Arrow down op = 1; break; case 8: // Backspace case 33: // Page Up case 37: // Arrow left case 38: // Arrow up op = -1; break; case 27: // Escape case 13: // Enter op = 0; } if (op !== null) {hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); if (!hs.enableKeyListener) return true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; if (exp) { if (op == 0) { exp.close(); } else { hs.previousOrNext(exp.key, op); } return false; } } return true; }, registerOverlay : function (overlay) { hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } )); }, getWrapperKey : function (element, expOnly) { var el, re = /^highslide-wrapper-([0-9]+)$/; // 1. look in open expanders el = element; while (el.parentNode) { if (el.id && re.test(el.id)) return el.id.replace(re, "$1"); el = el.parentNode; } // 2. look in thumbnail if (!expOnly) { el = element; while (el.parentNode) { if (el.tagName && hs.isHsAnchor(el)) { for (var key = 0; key < hs.expanders.length; key++) { var exp = hs.expanders[key]; if (exp && exp.a == el) return key; } } el = el.parentNode; } } return null; }, getExpander : function (el, expOnly) { if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null; if (typeof el == 'number') return hs.expanders[el] || null; if (typeof el == 'string') el = hs.$(el); return hs.expanders[hs.getWrapperKey(el, expOnly)] || null; }, isHsAnchor : function (a) { return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/)); }, reOrder : function () { for (var i = 0; i < hs.expanders.length; i++) if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost(); }, mouseClickHandler : function(e) { if (!e) e = window.event; if (e.button > 1) return true; if (!e.target) e.target = e.srcElement; var el = e.target; while (el.parentNode && !(/highslide-(image|move|html|resize)/.test(el.className))) { el = el.parentNode; } var exp = hs.getExpander(el); if (exp && (exp.isClosing || !exp.isExpanded)) return true; if (exp && e.type == 'mousedown') { if (e.target.form) return true; var match = el.className.match(/highslide-(image|move|resize)/); if (match) { hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos, height: exp.y.size, clickX: e.clientX, clickY: e.clientY }; hs.addEventListener(document, 'mousemove', hs.dragHandler); if (e.preventDefault) e.preventDefault(); // FF if (/highslide-(image|html)-blur/.test(exp.content.className)) { exp.focus(); hs.hasFocused = true; } return false; } } else if (e.type == 'mouseup') { hs.removeEventListener(document, 'mousemove', hs.dragHandler); if (hs.dragArgs) { if (hs.styleRestoreCursor && hs.dragArgs.type == 'image') hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor; var hasDragged = hs.dragArgs.hasDragged; if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) { exp.close(); } else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) { hs.dragArgs.exp.doShowHide('hidden'); } hs.hasFocused = false; hs.dragArgs = null; } else if (/highslide-image-blur/.test(el.className)) { el.style.cursor = hs.styleRestoreCursor; } } return false; }, dragHandler : function(e) { if (!hs.dragArgs) return true; if (!e) e = window.event; var a = hs.dragArgs, exp = a.exp; a.dX = e.clientX - a.clickX; a.dY = e.clientY - a.clickY; var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2)); if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0) || (distance > (hs.dragSensitivity || 5)); if (a.hasDragged && e.clientX > 5 && e.clientY > 5) { if (a.type == 'resize') exp.resize(a); else { exp.moveTo(a.left + a.dX, a.top + a.dY); if (a.type == 'image') exp.content.style.cursor = 'move'; } } return false; }, wrapperMouseHandler : function (e) { try { if (!e) e = window.event; var over = /mouseover/i.test(e.type); if (!e.target) e.target = e.srcElement; // ie if (hs.ie) e.relatedTarget = over ? e.fromElement : e.toElement; // ie var exp = hs.getExpander(e.target); if (!exp.isExpanded) return; if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp || hs.dragArgs) return; for (var i = 0; i < exp.overlays.length; i++) (function() { var o = hs.$('hsId'+ exp.overlays[i]); if (o && o.hideOnMouseOut) { if (over) hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur); } })(); } catch (e) {} }, addEventListener : function (el, event, func) { if (el == document && event == 'ready') hs.push(hs.onReady, func); try { el.addEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); el.attachEvent('on'+ event, func); } catch (e) { el['on'+ event] = func; } } }, removeEventListener : function (el, event, func) { try { el.removeEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); } catch (e) { el['on'+ event] = null; } } }, preloadFullImage : function (i) { if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') { var img = document.createElement('img'); img.onload = function() { img = null; hs.preloadFullImage(i + 1); }; img.src = hs.preloadTheseImages[i]; } }, preloadImages : function (number) { if (number && typeof number != 'object') hs.numberOfImagesToPreload = number; var arr = hs.getAnchors(); for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) { hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i])); } // preload outlines if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} ); else hs.preloadFullImage(0); // preload cursor if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor }); }, init : function () { if (!hs.container) { hs.getPageSize(); hs.ieLt7 = hs.ie && hs.uaVersion < 7; for (var x in hs.langDefaults) { if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x]; else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined') hs.lang[x] = hs.langDefaults[x]; } hs.container = hs.createElement('div', { className: 'highslide-container' }, { position: 'absolute', left: 0, top: 0, width: '100%', zIndex: hs.zIndexCounter, direction: 'ltr' }, document.body, true ); hs.loading = hs.createElement('a', { className: 'highslide-loading', title: hs.lang.loadingTitle, innerHTML: hs.lang.loadingText, href: 'javascript:;' }, { position: 'absolute', top: '-9999px', opacity: hs.loadingOpacity, zIndex: 1 }, hs.container ); hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container); // http://www.robertpenner.com/easing/ Math.linearTween = function (t, b, c, d) { return c*t/d + b; }; Math.easeInQuad = function (t, b, c, d) { return c*(t/=d)*t + b; }; hs.hideSelects = hs.ieLt7; hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE' || (hs.ie && hs.uaVersion < 5.5)); } }, ready : function() { if (hs.isReady) return; hs.isReady = true; for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i](); }, updateAnchors : function() { var el, els, all = [], images = [],groups = {}, re; for (var i = 0; i < hs.openerTagNames.length; i++) { els = document.getElementsByTagName(hs.openerTagNames[i]); for (var j = 0; j < els.length; j++) { el = els[j]; re = hs.isHsAnchor(el); if (re) { hs.push(all, el); if (re[0] == 'hs.expand') hs.push(images, el); var g = hs.getParam(el, 'slideshowGroup') || 'none'; if (!groups[g]) groups[g] = []; hs.push(groups[g], el); } } } hs.anchors = { all: all, groups: groups, images: images }; return hs.anchors; }, getAnchors : function() { return hs.anchors || hs.updateAnchors(); }, close : function(el) { var exp = hs.getExpander(el); if (exp) exp.close(); return false; } }; // end hs object hs.fx = function( elem, options, prop ){ this.options = options; this.elem = elem; this.prop = prop; if (!options.orig) options.orig = {}; }; hs.fx.prototype = { update: function(){ (hs.fx.step[this.prop] || hs.fx.step._default)(this); if (this.options.step) this.options.step.call(this.elem, this.now, this); }, custom: function(from, to, unit){ this.startTime = (new Date()).getTime(); this.start = from; this.end = to; this.unit = unit;// || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t(gotoEnd){ return self.step(gotoEnd); } t.elem = this.elem; if ( t() && hs.timers.push(t) == 1 ) { hs.timerId = setInterval(function(){ var timers = hs.timers; for ( var i = 0; i < timers.length; i++ ) if ( !timers[i]() ) timers.splice(i--, 1); if ( !timers.length ) { clearInterval(hs.timerId); } }, 13); } }, step: function(gotoEnd){ var t = (new Date()).getTime(); if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; var done = true; for ( var i in this.options.curAnim ) if ( this.options.curAnim[i] !== true ) done = false; if ( done ) { if (this.options.complete) this.options.complete.call(this.elem); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; this.pos = this.options.easing(n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); } return true; } }; hs.extend( hs.fx, { step: { opacity: function(fx){ hs.setStyles(fx.elem, { opacity: fx.now }); }, _default: function(fx){ try { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) fx.elem.style[ fx.prop ] = fx.now + fx.unit; else fx.elem[ fx.prop ] = fx.now; } catch (e) {} } } }); hs.Outline = function (outlineType, onLoad) { this.onLoad = onLoad; this.outlineType = outlineType; var v = hs.uaVersion, tr; this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7; if (!outlineType) { if (onLoad) onLoad(); return; } hs.init(); this.table = hs.createElement( 'table', { cellSpacing: 0 }, { visibility: 'hidden', position: 'absolute', borderCollapse: 'collapse', width: 0 }, hs.container, true ); var tbody = hs.createElement('tbody', null, null, this.table, 1); this.td = []; for (var i = 0; i <= 8; i++) { if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true); this.td[i] = hs.createElement('td', null, null, tr, true); var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' }; hs.setStyles(this.td[i], style); } this.td[4].className = outlineType +' highslide-outline'; this.preloadGraphic(); }; hs.Outline.prototype = { preloadGraphic : function () { var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png"; var appendTo = hs.safari ? hs.container : null; this.graphic = hs.createElement('img', null, { position: 'absolute', top: '-9999px' }, appendTo, true); // for onload trigger var pThis = this; this.graphic.onload = function() { pThis.onGraphicLoad(); }; this.graphic.src = src; }, onGraphicLoad : function () { var o = this.offset = this.graphic.width / 4, pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]], dim = { height: (2*o) +'px', width: (2*o) +'px' }; for (var i = 0; i <= 8; i++) { if (pos[i]) { if (this.hasAlphaImageLoader) { var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px'; var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true); hs.createElement ('div', null, { filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')", position: 'absolute', width: w, height: this.graphic.height +'px', left: (pos[i][0]*o)+'px', top: (pos[i][1]*o)+'px' }, div, true); } else { hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'}); } if (window.opera && (i == 3 || i ==5)) hs.createElement('div', null, dim, this.td[i], true); hs.setStyles (this.td[i], dim); } } this.graphic = null; if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy(); hs.pendingOutlines[this.outlineType] = this; if (this.onLoad) this.onLoad(); }, setPosition : function (pos, offset, vis, dur, easing) { var exp = this.exp, stl = exp.wrapper.style, offset = offset || 0, pos = pos || { x: exp.x.pos + offset, y: exp.y.pos + offset, w: exp.x.get('wsize') - 2 * offset, h: exp.y.get('wsize') - 2 * offset }; if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset) ? 'visible' : 'hidden'; hs.setStyles(this.table, { left: (pos.x - this.offset) +'px', top: (pos.y - this.offset) +'px', width: (pos.w + 2 * this.offset) +'px' }); pos.w -= 2 * this.offset; pos.h -= 2 * this.offset; hs.setStyles (this.td[4], { width: pos.w >= 0 ? pos.w +'px' : 0, height: pos.h >= 0 ? pos.h +'px' : 0 }); if (this.hasAlphaImageLoader) this.td[3].style.height = this.td[5].style.height = this.td[4].style.height; }, destroy : function(hide) { if (hide) this.table.style.visibility = 'hidden'; else hs.discardElement(this.table); } }; hs.Dimension = function(exp, dim) { this.exp = exp; this.dim = dim; this.ucwh = dim == 'x' ? 'Width' : 'Height'; this.wh = this.ucwh.toLowerCase(); this.uclt = dim == 'x' ? 'Left' : 'Top'; this.lt = this.uclt.toLowerCase(); this.ucrb = dim == 'x' ? 'Right' : 'Bottom'; this.rb = this.ucrb.toLowerCase(); this.p1 = this.p2 = 0; }; hs.Dimension.prototype = { get : function(key) { switch (key) { case 'loadingPos': return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2; case 'wsize': return this.size + 2 * this.cb + this.p1 + this.p2; case 'fitsize': return this.clientSize - this.marginMin - this.marginMax; case 'maxsize': return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ; case 'opos': return this.pos - (this.exp.outline ? this.exp.outline.offset : 0); case 'osize': return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0); case 'imgPad': return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0; } }, calcBorders: function() { // correct for borders this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2; this.marginMax = hs['margin'+ this.ucrb]; }, calcThumb: function() { this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) : this.exp.el['offset'+ this.ucwh]; this.tpos = this.exp.tpos[this.dim]; this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2; if (this.tpos == 0 || this.tpos == -1) { this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt]; }; }, calcExpanded: function() { var exp = this.exp; this.justify = 'auto'; // size and position this.pos = this.tpos - this.cb + this.tb; if (this.maxHeight && this.dim == 'x') exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full); this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full); this.minSize = exp.allowSizeReduction ? Math.min(exp['min'+ this.ucwh], this.full) :this.full; if (exp.isImage && exp.useBox) { this.size = exp[this.wh]; this.imgSize = this.full; } if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth; this.marginMin = hs['margin'+ this.uclt]; this.scroll = hs.page['scroll'+ this.uclt]; this.clientSize = hs.page[this.wh]; }, setSize: function(i) { var exp = this.exp; if (exp.isImage && (exp.useBox || hs.padToMinWidth)) { this.imgSize = i; this.size = Math.max(this.size, this.imgSize); exp.content.style[this.lt] = this.get('imgPad')+'px'; } else this.size = i; exp.content.style[this.wh] = i +'px'; exp.wrapper.style[this.wh] = this.get('wsize') +'px'; if (exp.outline) exp.outline.setPosition(); if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true); }, setPos: function(i) { this.pos = i; this.exp.wrapper.style[this.lt] = i +'px'; if (this.exp.outline) this.exp.outline.setPosition(); } }; hs.Expander = function(a, params, custom, contentType) { if (document.readyState && hs.ie && !hs.isReady) { hs.addEventListener(document, 'ready', function() { new hs.Expander(a, params, custom, contentType); }); return; } this.a = a; this.custom = custom; this.contentType = contentType || 'image'; this.isImage = !this.isHtml; hs.continuePreloading = false; this.overlays = []; hs.init(); var key = this.key = hs.expanders.length; // override inline parameters for (var i = 0; i < hs.overrides.length; i++) { var name = hs.overrides[i]; this[name] = params && typeof params[name] != 'undefined' ? params[name] : hs[name]; } if (!this.src) this.src = a.href; // get thumb var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a; el = this.thumb = el.getElementsByTagName('img')[0] || el; this.thumbsUserSetId = el.id || a.id; // check if already open for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].a == a) { hs.expanders[i].focus(); return false; } } // cancel other if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) { hs.expanders[i].cancelLoading(); } } hs.expanders[key] = this; if (!hs.allowMultipleInstances && !hs.upcoming) { if (hs.expanders[key-1]) hs.expanders[key-1].close(); if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey]) hs.expanders[hs.focusKey].close(); } // initiate metrics this.el = el; this.tpos = hs.getPosition(el); hs.getPageSize(); var x = this.x = new hs.Dimension(this, 'x'); x.calcThumb(); var y = this.y = new hs.Dimension(this, 'y'); y.calcThumb(); this.wrapper = hs.createElement( 'div', { id: 'highslide-wrapper-'+ this.key, className: 'highslide-wrapper '+ this.wrapperClassName }, { visibility: 'hidden', position: 'absolute', zIndex: hs.zIndexCounter += 2 }, null, true ); this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler; if (this.contentType == 'image' && this.outlineWhileAnimating == 2) this.outlineWhileAnimating = 0; // get the outline if (!this.outlineType) { this[this.contentType +'Create'](); } else if (hs.pendingOutlines[this.outlineType]) { this.connectOutline(); this[this.contentType +'Create'](); } else { this.showLoading(); var exp = this; new hs.Outline(this.outlineType, function () { exp.connectOutline(); exp[exp.contentType +'Create'](); } ); } return true; }; hs.Expander.prototype = { error : function(e) { // alert ('Line '+ e.lineNumber +': '+ e.message); window.location.href = this.src; }, connectOutline : function() { var outline = this.outline = hs.pendingOutlines[this.outlineType]; outline.exp = this; outline.table.style.zIndex = this.wrapper.style.zIndex - 1; hs.pendingOutlines[this.outlineType] = null; }, showLoading : function() { if (this.onLoadStarted || this.loading) return; this.loading = hs.loading; var exp = this; this.loading.onclick = function() { exp.cancelLoading(); }; var exp = this, l = this.x.get('loadingPos') +'px', t = this.y.get('loadingPos') +'px'; setTimeout(function () { if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })} , 100); }, imageCreate : function() { var exp = this; var img = document.createElement('img'); this.content = img; img.onload = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); }; if (hs.blockRightClick) img.oncontextmenu = function() { return false; }; img.className = 'highslide-image'; hs.setStyles(img, { visibility: 'hidden', display: 'block', position: 'absolute', maxWidth: '9999px', zIndex: 3 }); img.title = hs.lang.restoreTitle; if (hs.safari) hs.container.appendChild(img); if (hs.ie && hs.flushImgSize) img.src = null; img.src = this.src; this.showLoading(); }, contentLoaded : function() { try { if (!this.content) return; this.content.onload = null; if (this.onLoadStarted) return; else this.onLoadStarted = true; var x = this.x, y = this.y; if (this.loading) { hs.setStyles(this.loading, { top: '-9999px' }); this.loading = null; } x.full = this.content.width; y.full = this.content.height; hs.setStyles(this.content, { width: x.t +'px', height: y.t +'px' }); this.wrapper.appendChild(this.content); hs.container.appendChild(this.wrapper); x.calcBorders(); y.calcBorders(); hs.setStyles (this.wrapper, { left: (x.tpos + x.tb - x.cb) +'px', top: (y.tpos + x.tb - y.cb) +'px' }); this.getOverlays(); var ratio = x.full / y.full; x.calcExpanded(); this.justify(x); y.calcExpanded(); this.justify(y); if (this.overlayBox) this.sizeOverlayBox(0, 1); if (this.allowSizeReduction) { this.correctRatio(ratio); if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) { this.createFullExpand(); if (this.overlays.length == 1) this.sizeOverlayBox(); } } this.show(); } catch (e) { this.error(e); } }, justify : function (p, moveOnly) { var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y'; var hasMovedMin = false; var allowReduce = p.exp.allowSizeReduction; p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2)); if (p.pos < p.scroll + p.marginMin) { p.pos = p.scroll + p.marginMin; hasMovedMin = true; } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) { if (!moveOnly && hasMovedMin && allowReduce) { p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize')); } else if (p.get('wsize') < p.get('fitsize')) { p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize'); } else { // image larger than viewport p.pos = p.scroll + p.marginMin; if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize'); } } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } if (p.pos < p.marginMin) { var tmpMin = p.pos; p.pos = p.marginMin; if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin); } }, correctRatio : function(ratio) { var x = this.x, y = this.y, changed = false, xSize = Math.min(x.full, x.size), ySize = Math.min(y.full, y.size), useBox = (this.useBox || hs.padToMinWidth); if (xSize / ySize > ratio) { // width greater xSize = ySize * ratio; if (xSize < x.minSize) { // below minWidth xSize = x.minSize; ySize = xSize / ratio; } changed = true; } else if (xSize / ySize < ratio) { // height greater ySize = xSize / ratio; changed = true; } if (hs.padToMinWidth && x.full < x.minSize) { x.imgSize = x.full; y.size = y.imgSize = y.full; } else if (this.useBox) { x.imgSize = xSize; y.imgSize = ySize; } else { x.size = xSize; y.size = ySize; } changed = this.fitOverlayBox(useBox ? null : ratio, changed); if (useBox && y.size < y.imgSize) { y.imgSize = y.size; x.imgSize = y.size * ratio; } if (changed || useBox) { x.pos = x.tpos - x.cb + x.tb; x.minSize = x.size; this.justify(x, true); y.pos = y.tpos - y.cb + y.tb; y.minSize = y.size; this.justify(y, true); if (this.overlayBox) this.sizeOverlayBox(); } }, fitOverlayBox : function(ratio, changed) { var x = this.x, y = this.y; if (this.overlayBox) { while (y.size > this.minHeight && x.size > this.minWidth && y.get('wsize') > y.get('fitsize')) { y.size -= 10; if (ratio) x.size = y.size * ratio; this.sizeOverlayBox(0, 1); changed = true; } } return changed; }, show : function () { var x = this.x, y = this.y; this.doShowHide('hidden'); // Apply size change this.changeSize( 1, { wrapper: { width : x.get('wsize'), height : y.get('wsize'), left: x.pos, top: y.pos }, content: { left: x.p1 + x.get('imgPad'), top: y.p1 + y.get('imgPad'), width:x.imgSize ||x.size, height:y.imgSize ||y.size } }, hs.expandDuration ); }, changeSize : function(up, to, dur) { if (this.outline && !this.outlineWhileAnimating) { if (up) this.outline.setPosition(); else this.outline.destroy(); } if (!up) this.destroyOverlays(); var exp = this, x = exp.x, y = exp.y, easing = this.easing; if (!up) easing = this.easingClose || easing; var after = up ? function() { if (exp.outline) exp.outline.table.style.visibility = "visible"; setTimeout(function() { exp.afterExpand(); }, 50); } : function() { exp.afterClose(); }; if (up) hs.setStyles( this.wrapper, { width: x.t +'px', height: y.t +'px' }); if (this.fadeInOut) { hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 }); hs.extend(to.wrapper, { opacity: up }); } hs.animate( this.wrapper, to.wrapper, { duration: dur, easing: easing, step: function(val, args) { if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') { var fac = up ? args.pos : 1 - args.pos; var pos = { w: x.t + (x.get('wsize') - x.t) * fac, h: y.t + (y.get('wsize') - y.t) * fac, x: x.tpos + (x.pos - x.tpos) * fac, y: y.tpos + (y.pos - y.tpos) * fac }; exp.outline.setPosition(pos, 0, 1); } } }); hs.animate( this.content, to.content, dur, easing, after); if (up) { this.wrapper.style.visibility = 'visible'; this.content.style.visibility = 'visible'; this.a.className += ' highslide-active-anchor'; } }, afterExpand : function() { this.isExpanded = true; this.focus(); if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null; this.prepareNextOutline(); var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop; this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize') && this.y.pos < mY && mY < this.y.pos + this.y.get('wsize'); if (this.overlayBox) this.showOverlays(); }, prepareNextOutline : function() { var key = this.key; var outlineType = this.outlineType; new hs.Outline(outlineType, function () { try { hs.expanders[key].preloadNext(); } catch (e) {} }); }, preloadNext : function() { var next = this.getAdjacentAnchor(1); if (next && next.onclick.toString().match(/hs\.expand/)) var img = hs.createElement('img', { src: hs.getSrc(next) }); }, getAdjacentAnchor : function(op) { var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none']; /*< ? if ($cfg->slideshow) : ?>s*/ if (!as[current + op] && this.slideshow && this.slideshow.repeat) { if (op == 1) return as[0]; else if (op == -1) return as[as.length-1]; } /*< ? endif ?>s*/ return as[current + op] || null; }, getAnchorIndex : function() { var arr = hs.getAnchors().groups[this.slideshowGroup || 'none']; if (arr) for (var i = 0; i < arr.length; i++) { if (arr[i] == this.a) return i; } return null; }, cancelLoading : function() { hs.discardElement (this.wrapper); hs.expanders[this.key] = null; if (this.loading) hs.loading.style.left = '-9999px'; }, writeCredits : function () { this.credits = hs.createElement('a', { href: hs.creditsHref, target: hs.creditsTarget, className: 'highslide-credits', innerHTML: hs.lang.creditsText, title: hs.lang.creditsTitle }); this.createOverlay({ overlayId: this.credits, position: this.creditsPosition || 'top left' }); }, getInline : function(types, addOverlay) { for (var i = 0; i < types.length; i++) { var type = types[i], s = null; if (!this[type +'Id'] && this.thumbsUserSetId) this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId; if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']); if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try { s = eval(this[type +'Eval']); } catch (e) {} if (!this[type] && this[type +'Text']) { s = this[type +'Text']; } if (!this[type] && !s) { this[type] = hs.getNode(this.a['_'+ type + 'Id']); if (!this[type]) { var next = this.a.nextSibling; while (next && !hs.isHsAnchor(next)) { if ((new RegExp('highslide-'+ type)).test(next.className || null)) { if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++; this[type] = hs.getNode(next.id); break; } next = next.nextSibling; } } } if (!this[type] && s) this[type] = hs.createElement('div', { className: 'highslide-'+ type, innerHTML: s } ); if (addOverlay && this[type]) { var o = { position: (type == 'heading') ? 'above' : 'below' }; for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x]; o.overlayId = this[type]; this.createOverlay(o); } } }, // on end move and resize doShowHide : function(visibility) { if (hs.hideSelects) this.showHideElements('SELECT', visibility); if (hs.hideIframes) this.showHideElements('IFRAME', visibility); if (hs.geckoMac) this.showHideElements('*', visibility); }, showHideElements : function (tagName, visibility) { var els = document.getElementsByTagName(tagName); var prop = tagName == '*' ? 'overflow' : 'visibility'; for (var i = 0; i < els.length; i++) { if (prop == 'visibility' || (document.defaultView.getComputedStyle( els[i], "").getPropertyValue('overflow') == 'auto' || els[i].getAttribute('hidden-by') != null)) { var hiddenBy = els[i].getAttribute('hidden-by'); if (visibility == 'visible' && hiddenBy) { hiddenBy = hiddenBy.replace('['+ this.key +']', ''); els[i].setAttribute('hidden-by', hiddenBy); if (!hiddenBy) els[i].style[prop] = els[i].origProp; } else if (visibility == 'hidden') { // hide if behind var elPos = hs.getPosition(els[i]); elPos.w = els[i].offsetWidth; elPos.h = els[i].offsetHeight; var clearsX = (elPos.x + elPos.w < this.x.get('opos') || elPos.x > this.x.get('opos') + this.x.get('osize')); var clearsY = (elPos.y + elPos.h < this.y.get('opos') || elPos.y > this.y.get('opos') + this.y.get('osize')); var wrapperKey = hs.getWrapperKey(els[i]); if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image if (!hiddenBy) { els[i].setAttribute('hidden-by', '['+ this.key +']'); els[i].origProp = els[i].style[prop]; els[i].style[prop] = 'hidden'; } else if (hiddenBy.indexOf('['+ this.key +']') == -1) { els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']'); } } else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey) && wrapperKey != this.key) { // on move els[i].setAttribute('hidden-by', ''); els[i].style[prop] = els[i].origProp || ''; } else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) { els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', '')); } } } } }, focus : function() { this.wrapper.style.zIndex = hs.zIndexCounter += 2; // blur others for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && i == hs.focusKey) { var blurExp = hs.expanders[i]; blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur'; blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer'; blurExp.content.title = hs.lang.focusTitle; } } // focus this if (this.outline) this.outline.table.style.zIndex = this.wrapper.style.zIndex - 1; this.content.className = 'highslide-'+ this.contentType; this.content.title = hs.lang.restoreTitle; if (hs.restoreCursor) { hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer'; if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand'; this.content.style.cursor = hs.styleRestoreCursor; } hs.focusKey = this.key; hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); }, moveTo: function(x, y) { this.x.setPos(x); this.y.setPos(y); }, resize : function (e) { var w, h, r = e.width / e.height; w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full)); if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full; h = w / r; if (h < Math.min(this.minHeight, this.y.full)) { h = Math.min(this.minHeight, this.y.full); if (this.isImage) w = h * r; } this.resizeTo(w, h); }, resizeTo: function(w, h) { this.y.setSize(h); this.x.setSize(w); this.wrapper.style.height = this.y.get('wsize') +'px'; }, close : function() { if (this.isClosing || !this.isExpanded) return; this.isClosing = true; hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); try { this.content.style.cursor = 'default'; this.changeSize( 0, { wrapper: { width : this.x.t, height : this.y.t, left: this.x.tpos - this.x.cb + this.x.tb, top: this.y.tpos - this.y.cb + this.y.tb }, content: { left: 0, top: 0, width: this.x.t, height: this.y.t } }, hs.restoreDuration ); } catch (e) { this.afterClose(); } }, createOverlay : function (o) { var el = o.overlayId; if (typeof el == 'string') el = hs.getNode(el); if (o.html) el = hs.createElement('div', { innerHTML: o.html }); if (!el || typeof el == 'string') return; el.style.display = 'block'; this.genOverlayBox(); var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto'; if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px'; var overlay = hs.createElement( 'div', { id: 'hsId'+ hs.idCounter++, hsId: o.hsId }, { position: 'absolute', visibility: 'hidden', width: width, direction: hs.lang.cssDirection || '', opacity: 0 },this.overlayBox, true ); overlay.appendChild(el); hs.extend(overlay, { opacity: 1, offsetX: 0, offsetY: 0, dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250 }); hs.extend(overlay, o); if (this.gotOverlays) { this.positionOverlay(overlay); if (!overlay.hideOnMouseOut || this.mouseIsOver) hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur); } hs.push(this.overlays, hs.idCounter - 1); }, positionOverlay : function(overlay) { var p = overlay.position || 'middle center', offX = overlay.offsetX, offY = overlay.offsetY; if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay); if (/left$/.test(p)) overlay.style.left = offX +'px'; if (/center$/.test(p)) hs.setStyles (overlay, { left: '50%', marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px' }); if (/right$/.test(p)) overlay.style.right = - offX +'px'; if (/^leftpanel$/.test(p)) { hs.setStyles(overlay, { right: '100%', marginRight: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p1 = overlay.offsetWidth; } else if (/^rightpanel$/.test(p)) { hs.setStyles(overlay, { left: '100%', marginLeft: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p2 = overlay.offsetWidth; } if (/^top/.test(p)) overlay.style.top = offY +'px'; if (/^middle/.test(p)) hs.setStyles (overlay, { top: '50%', marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px' }); if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px'; if (/^above$/.test(p)) { hs.setStyles(overlay, { left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', bottom: '100%', marginBottom: this.y.cb +'px', width: 'auto' }); this.y.p1 = overlay.offsetHeight; } else if (/^below$/.test(p)) { hs.setStyles(overlay, { position: 'relative', left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', top: '100%', marginTop: this.y.cb +'px', width: 'auto' }); this.y.p2 = overlay.offsetHeight; overlay.style.position = 'absolute'; } }, getOverlays : function() { this.getInline(['heading', 'caption'], true); if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move'; if (hs.showCredits) this.writeCredits(); for (var i = 0; i < hs.overlays.length; i++) { var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup; if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId) || (sg && sg === this.slideshowGroup)) { this.createOverlay(o); } } var os = []; for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); if (/panel$/.test(o.position)) this.positionOverlay(o); else hs.push(os, o); } for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]); this.gotOverlays = true; }, genOverlayBox : function() { if (!this.overlayBox) this.overlayBox = hs.createElement ( 'div', { className: this.wrapperClassName }, { position : 'absolute', width: (this.x.size || (this.useBox ? this.width : null) || this.x.full) +'px', height: (this.y.size || this.y.full) +'px', visibility : 'hidden', overflow : 'hidden', zIndex : hs.ie ? 4 : 'auto' }, hs.container, true ); }, sizeOverlayBox : function(doWrapper, doPanels) { var overlayBox = this.overlayBox, x = this.x, y = this.y; hs.setStyles( overlayBox, { width: x.size +'px', height: y.size +'px' }); if (doWrapper || doPanels) { for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat'); if (o && /^(above|below)$/.test(o.position)) { if (ie6) { o.style.width = (overlayBox.offsetWidth + 2 * x.cb + x.p1 + x.p2) +'px'; } y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight; } if (o && ie6 && /^(left|right)panel$/.test(o.position)) { o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px'; } } } if (doWrapper) { hs.setStyles(this.content, { top: y.p1 +'px' }); hs.setStyles(overlayBox, { top: (y.p1 + y.cb) +'px' }); } }, showOverlays : function() { var b = this.overlayBox; b.className = ''; hs.setStyles(b, { top: (this.y.p1 + this.y.cb) +'px', left: (this.x.p1 + this.x.cb) +'px', overflow : 'visible' }); if (hs.safari) b.style.visibility = 'visible'; this.wrapper.appendChild (b); for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); o.style.zIndex = 4; if (!o.hideOnMouseOut || this.mouseIsOver) { o.style.visibility = 'visible'; hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: o.opacity }, o.dur); } } }, destroyOverlays : function() { if (!this.overlays.length) return; hs.discardElement(this.overlayBox); }, createFullExpand : function () { this.fullExpandLabel = hs.createElement( 'a', { href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();', title: hs.lang.fullExpandTitle, className: 'highslide-full-expand' } ); this.createOverlay({ overlayId: this.fullExpandLabel, position: hs.fullExpandPosition, hideOnMouseOut: true, opacity: hs.fullExpandOpacity }); }, doFullExpand : function () { try { if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel); this.focus(); var xSize = this.x.size; this.resizeTo(this.x.full, this.y.full); var xpos = this.x.pos - (this.x.size - xSize) / 2; if (xpos < hs.marginLeft) xpos = hs.marginLeft; this.moveTo(xpos, this.y.pos); this.doShowHide('hidden'); } catch (e) { this.error(e); } }, afterClose : function () { this.a.className = this.a.className.replace('highslide-active-anchor', ''); this.doShowHide('visible'); if (this.outline && this.outlineWhileAnimating) this.outline.destroy(); hs.discardElement(this.wrapper); hs.expanders[this.key] = null; hs.reOrder(); } }; hs.langDefaults = hs.lang; // history var HsExpander = hs.Expander; if (hs.ie) { (function () { try { document.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } hs.ready(); })(); } hs.addEventListener(document, 'DOMContentLoaded', hs.ready); hs.addEventListener(window, 'load', hs.ready); // set handlers hs.addEventListener(document, 'ready', function() { if (hs.expandCursor) { var style = hs.createElement('style', { type: 'text/css' }, null, document.getElementsByTagName('HEAD')[0]); function addRule(sel, dec) { if (!hs.ie) { style.appendChild(document.createTextNode(sel + " {" + dec + "}")); } else { var last = document.styleSheets[document.styleSheets.length - 1]; if (typeof(last.addRule) == "object") last.addRule(sel, dec); } } function fix(prop) { return 'expression( ( ( ignoreMe = document.documentElement.'+ prop + ' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );'; } if (hs.expandCursor) addRule ('.highslide img', 'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;'); } }); hs.addEventListener(window, 'resize', function() { hs.getPageSize(); }); hs.addEventListener(document, 'mousemove', function(e) { hs.mouse = { x: e.clientX, y: e.clientY }; }); hs.addEventListener(document, 'mousedown', hs.mouseClickHandler); hs.addEventListener(document, 'mouseup', hs.mouseClickHandler); hs.addEventListener(document, 'ready', hs.getAnchors); hs.addEventListener(window, 'load', hs.preloadImages); }
JavaScript
/****************************************************************************** Name: Highslide JS Version: 4.1.8 (October 27 2009) Config: default +events +unobtrusive +imagemap +slideshow +positioning +transitions +viewport +thumbstrip +inline +ajax +iframe +flash Author: Torstein Hønsi Support: http://highslide.com/support Licence: Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5 License (http://creativecommons.org/licenses/by-nc/2.5/). You are free: * to copy, distribute, display, and perform the work * to make derivative works Under the following conditions: * Attribution. You must attribute the work in the manner specified by the author or licensor. * Noncommercial. You may not use this work for commercial purposes. * For any reuse or distribution, you must make clear to others the license terms of this work. * Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. ******************************************************************************/ if (!hs) { var hs = { // Language strings lang : { cssDirection: 'ltr', loadingText : 'Loading...', loadingTitle : 'Click to cancel', focusTitle : 'Click to bring to front', fullExpandTitle : 'Expand to actual size (f)', creditsText : 'Powered by <i>Highslide JS</i>', creditsTitle : 'Go to the Highslide JS homepage', previousText : 'Previous', nextText : 'Next', moveText : 'Move', closeText : 'Close', closeTitle : 'Close (esc)', resizeTitle : 'Resize', playText : 'Play', playTitle : 'Play slideshow (spacebar)', pauseText : 'Pause', pauseTitle : 'Pause slideshow (spacebar)', previousTitle : 'Previous (arrow left)', nextTitle : 'Next (arrow right)', moveTitle : 'Move', fullExpandText : '1:1', number: 'Image %1 of %2', restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.' }, // See http://highslide.com/ref for examples of settings graphicsDir : 'highslide/graphics/', expandCursor : 'zoomin.cur', // null disables restoreCursor : 'zoomout.cur', // null disables expandDuration : 250, // milliseconds restoreDuration : 250, marginLeft : 15, marginRight : 15, marginTop : 15, marginBottom : 15, zIndexCounter : 1001, // adjust to other absolutely positioned elements loadingOpacity : 0.75, allowMultipleInstances: true, numberOfImagesToPreload : 5, outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only outlineStartOffset : 3, // ends at 10 padToMinWidth : false, // pad the popup width to make room for wide caption fullExpandPosition : 'bottom right', fullExpandOpacity : 1, showCredits : true, // you can set this to false if you want creditsHref : 'http://highslide.com/', creditsTarget : '_self', enableKeyListener : true, openerTagNames : ['a', 'area'], // Add more to allow slideshow indexing transitions : [], transitionDuration: 250, dimmingOpacity: 0, // Lightbox style dimming background dimmingDuration: 50, // 0 for instant dimming allowWidthReduction : false, allowHeightReduction : true, preserveContent : true, // Preserve changes made to the content and position of HTML popups. objectLoadTime : 'before', // Load iframes 'before' or 'after' expansion. cacheAjax : true, // Cache ajax popups for instant display. Can be overridden for each popup. anchor : 'auto', // where the image expands from align : 'auto', // position in the client (overrides anchor) targetX: null, // the id of a target element targetY: null, dragByHeading: true, minWidth: 200, minHeight: 200, allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight outlineType : 'drop-shadow', // set null to disable outlines skin : { controls: '<div class="highslide-controls"><ul>'+ '<li class="highslide-previous">'+ '<a href="#" title="{hs.lang.previousTitle}">'+ '<span>{hs.lang.previousText}</span></a>'+ '</li>'+ '<li class="highslide-play">'+ '<a href="#" title="{hs.lang.playTitle}">'+ '<span>{hs.lang.playText}</span></a>'+ '</li>'+ '<li class="highslide-pause">'+ '<a href="#" title="{hs.lang.pauseTitle}">'+ '<span>{hs.lang.pauseText}</span></a>'+ '</li>'+ '<li class="highslide-next">'+ '<a href="#" title="{hs.lang.nextTitle}">'+ '<span>{hs.lang.nextText}</span></a>'+ '</li>'+ '<li class="highslide-move">'+ '<a href="#" title="{hs.lang.moveTitle}">'+ '<span>{hs.lang.moveText}</span></a>'+ '</li>'+ '<li class="highslide-full-expand">'+ '<a href="#" title="{hs.lang.fullExpandTitle}">'+ '<span>{hs.lang.fullExpandText}</span></a>'+ '</li>'+ '<li class="highslide-close">'+ '<a href="#" title="{hs.lang.closeTitle}" >'+ '<span>{hs.lang.closeText}</span></a>'+ '</li>'+ '</ul></div>' , contentWrapper: '<div class="highslide-header"><ul>'+ '<li class="highslide-previous">'+ '<a href="#" title="{hs.lang.previousTitle}" onclick="return hs.previous(this)">'+ '<span>{hs.lang.previousText}</span></a>'+ '</li>'+ '<li class="highslide-next">'+ '<a href="#" title="{hs.lang.nextTitle}" onclick="return hs.next(this)">'+ '<span>{hs.lang.nextText}</span></a>'+ '</li>'+ '<li class="highslide-move">'+ '<a href="#" title="{hs.lang.moveTitle}" onclick="return false">'+ '<span>{hs.lang.moveText}</span></a>'+ '</li>'+ '<li class="highslide-close">'+ '<a href="#" title="{hs.lang.closeTitle}" onclick="return hs.close(this)">'+ '<span>{hs.lang.closeText}</span></a>'+ '</li>'+ '</ul></div>'+ '<div class="highslide-body"></div>'+ '<div class="highslide-footer"><div>'+ '<span class="highslide-resize" title="{hs.lang.resizeTitle}"><span></span></span>'+ '</div></div>' }, // END OF YOUR SETTINGS // declare internal properties preloadTheseImages : [], continuePreloading: true, expanders : [], overrides : [ 'allowSizeReduction', 'useBox', 'anchor', 'align', 'targetX', 'targetY', 'outlineType', 'outlineWhileAnimating', 'captionId', 'captionText', 'captionEval', 'captionOverlay', 'headingId', 'headingText', 'headingEval', 'headingOverlay', 'creditsPosition', 'dragByHeading', 'autoplay', 'numberPosition', 'transitions', 'dimmingOpacity', 'width', 'height', 'contentId', 'allowWidthReduction', 'allowHeightReduction', 'preserveContent', 'maincontentId', 'maincontentText', 'maincontentEval', 'objectType', 'cacheAjax', 'objectWidth', 'objectHeight', 'objectLoadTime', 'swfOptions', 'wrapperClassName', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'slideshowGroup', 'easing', 'easingClose', 'fadeInOut', 'src' ], overlays : [], idCounter : 0, oPos : { x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'], y: ['above', 'top', 'middle', 'bottom', 'below'] }, mouse: {}, headingOverlay: {}, captionOverlay: {}, swfOptions: { flashvars: {}, params: {}, attributes: {} }, timers : [], slideshows : [], pendingOutlines : {}, sleeping : [], preloadTheseAjax : [], cacheBindings : [], cachedGets : {}, clones : {}, onReady: [], uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 : parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]), ie : (document.all && !window.opera), safari : /Safari/.test(navigator.userAgent), geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent), $ : function (id) { if (id) return document.getElementById(id); }, push : function (arr, val) { arr[arr.length] = val; }, createElement : function (tag, attribs, styles, parent, nopad) { var el = document.createElement(tag); if (attribs) hs.extend(el, attribs); if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0}); if (styles) hs.setStyles(el, styles); if (parent) parent.appendChild(el); return el; }, extend : function (el, attribs) { for (var x in attribs) el[x] = attribs[x]; return el; }, setStyles : function (el, styles) { for (var x in styles) { if (hs.ie && x == 'opacity') { if (styles[x] > 0.99) el.style.removeAttribute('filter'); else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')'; } else el.style[x] = styles[x]; } }, animate: function(el, prop, opt) { var start, end, unit; if (typeof opt != 'object' || opt === null) { var args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (typeof opt.duration != 'number') opt.duration = 250; opt.easing = Math[opt.easing] || Math.easeInQuad; opt.curAnim = hs.extend({}, prop); for (var name in prop) { var e = new hs.fx(el, opt , name ); start = parseFloat(hs.css(el, name)) || 0; end = parseFloat(prop[name]); unit = name != 'opacity' ? 'px' : ''; e.custom( start, end, unit ); } }, css: function(el, prop) { if (document.defaultView) { return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop); } else { if (prop == 'opacity') prop = 'filter'; var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })]; if (prop == 'filter') val = val.replace(/alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100 }); return val === '' ? 1 : val; } }, getPageSize : function () { var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat' ? d.documentElement : d.body; var width = hs.ie ? iebody.clientWidth : (d.documentElement.clientWidth || self.innerWidth), height = hs.ie ? iebody.clientHeight : self.innerHeight; hs.page = { width: width, height: height, scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset, scrollTop: hs.ie ? iebody.scrollTop : pageYOffset } }, getPosition : function(el) { if (/area/i.test(el.tagName)) { var imgs = document.getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { var u = imgs[i].useMap; if (u && u.replace(/^.*?#/, '') == el.parentNode.name) { el = imgs[i]; break; } } } var p = { x: el.offsetLeft, y: el.offsetTop }; while (el.offsetParent) { el = el.offsetParent; p.x += el.offsetLeft; p.y += el.offsetTop; if (el != document.body && el != document.documentElement) { p.x -= el.scrollLeft; p.y -= el.scrollTop; } } return p; }, expand : function(a, params, custom, type) { if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container); if (typeof a.getParams == 'function') return params; if (type == 'html') { for (var i = 0; i < hs.sleeping.length; i++) { if (hs.sleeping[i] && hs.sleeping[i].a == a) { hs.sleeping[i].awake(); hs.sleeping[i] = null; return false; } } hs.hasHtmlExpanders = true; } try { new hs.Expander(a, params, custom, type); return false; } catch (e) { return true; } }, htmlExpand : function(a, params, custom) { return hs.expand(a, params, custom, 'html'); }, getSelfRendered : function() { return hs.createElement('div', { className: 'highslide-html-content', innerHTML: hs.replaceLang(hs.skin.contentWrapper) }); }, getElementByClass : function (el, tagName, className) { var els = el.getElementsByTagName(tagName); for (var i = 0; i < els.length; i++) { if ((new RegExp(className)).test(els[i].className)) { return els[i]; } } return null; }, replaceLang : function(s) { s = s.replace(/\s/g, ' '); var re = /{hs\.lang\.([^}]+)\}/g, matches = s.match(re), lang; if (matches) for (var i = 0; i < matches.length; i++) { lang = matches[i].replace(re, "$1"); if (typeof hs.lang[lang] != 'undefined') s = s.replace(matches[i], hs.lang[lang]); } return s; }, setClickEvents : function () { var els = document.getElementsByTagName('a'); for (var i = 0; i < els.length; i++) { var type = hs.isUnobtrusiveAnchor(els[i]); if (type && !els[i].hsHasSetClick) { (function(){ var t = type; if (hs.fireEvent(hs, 'onSetClickEvent', { element: els[i], type: t })) { els[i].onclick =(type == 'image') ?function() { return hs.expand(this) }: function() { return hs.htmlExpand(this, { objectType: t } );}; } })(); els[i].hsHasSetClick = true; } } hs.getAnchors(); }, isUnobtrusiveAnchor: function(el) { if (el.rel == 'highslide') return 'image'; else if (el.rel == 'highslide-ajax') return 'ajax'; else if (el.rel == 'highslide-iframe') return 'iframe'; else if (el.rel == 'highslide-swf') return 'swf'; }, getCacheBinding : function (a) { for (var i = 0; i < hs.cacheBindings.length; i++) { if (hs.cacheBindings[i][0] == a) { var c = hs.cacheBindings[i][1]; hs.cacheBindings[i][1] = c.cloneNode(1); return c; } } return null; }, preloadAjax : function (e) { var arr = hs.getAnchors(); for (var i = 0; i < arr.htmls.length; i++) { var a = arr.htmls[i]; if (hs.getParam(a, 'objectType') == 'ajax' && hs.getParam(a, 'cacheAjax')) hs.push(hs.preloadTheseAjax, a); } hs.preloadAjaxElement(0); }, preloadAjaxElement : function (i) { if (!hs.preloadTheseAjax[i]) return; var a = hs.preloadTheseAjax[i]; var cache = hs.getNode(hs.getParam(a, 'contentId')); if (!cache) cache = hs.getSelfRendered(); var ajax = new hs.Ajax(a, cache, 1); ajax.onError = function () { }; ajax.onLoad = function () { hs.push(hs.cacheBindings, [a, cache]); hs.preloadAjaxElement(i + 1); }; ajax.run(); }, focusTopmost : function() { var topZ = 0, topmostKey = -1, expanders = hs.expanders, exp, zIndex; for (var i = 0; i < expanders.length; i++) { exp = expanders[i]; if (exp) { zIndex = exp.wrapper.style.zIndex; if (zIndex && zIndex > topZ) { topZ = zIndex; topmostKey = i; } } } if (topmostKey == -1) hs.focusKey = -1; else expanders[topmostKey].focus(); }, getParam : function (a, param) { a.getParams = a.onclick; var p = a.getParams ? a.getParams() : null; a.getParams = null; return (p && typeof p[param] != 'undefined') ? p[param] : (typeof hs[param] != 'undefined' ? hs[param] : null); }, getSrc : function (a) { var src = hs.getParam(a, 'src'); if (src) return src; return a.href; }, getNode : function (id) { var node = hs.$(id), clone = hs.clones[id], a = {}; if (!node && !clone) return null; if (!clone) { clone = node.cloneNode(true); clone.id = ''; hs.clones[id] = clone; return node; } else { return clone.cloneNode(true); } }, discardElement : function(d) { if (d) hs.garbageBin.appendChild(d); hs.garbageBin.innerHTML = ''; }, dim : function(exp) { if (!hs.dimmer) { hs.dimmer = hs.createElement ('div', { className: 'highslide-dimming highslide-viewport-size', owner: '', onclick: function() { if (hs.fireEvent(hs, 'onDimmerClick')) hs.close(); } }, { visibility: 'visible', opacity: 0 }, hs.container, true); } hs.dimmer.style.display = ''; hs.dimmer.owner += '|'+ exp.key; if (hs.geckoMac && hs.dimmingGeckoFix) hs.setStyles(hs.dimmer, { background: 'url('+ hs.graphicsDir + 'geckodimmer.png)', opacity: 1 }); else hs.animate(hs.dimmer, { opacity: exp.dimmingOpacity }, hs.dimmingDuration); }, undim : function(key) { if (!hs.dimmer) return; if (typeof key != 'undefined') hs.dimmer.owner = hs.dimmer.owner.replace('|'+ key, ''); if ( (typeof key != 'undefined' && hs.dimmer.owner != '') || (hs.upcoming && hs.getParam(hs.upcoming, 'dimmingOpacity')) ) return; if (hs.geckoMac && hs.dimmingGeckoFix) hs.dimmer.style.display = 'none'; else hs.animate(hs.dimmer, { opacity: 0 }, hs.dimmingDuration, null, function() { hs.dimmer.style.display = 'none'; }); }, transit : function (adj, exp) { var last = exp = exp || hs.getExpander(); if (hs.upcoming) return false; else hs.last = last; try { hs.upcoming = adj; adj.onclick(); } catch (e){ hs.last = hs.upcoming = null; } try { if (!adj || exp.transitions[1] != 'crossfade') exp.close(); } catch (e) {} return false; }, previousOrNext : function (el, op) { var exp = hs.getExpander(el); if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp); else return false; }, previous : function (el) { return hs.previousOrNext(el, -1); }, next : function (el) { return hs.previousOrNext(el, 1); }, keyHandler : function(e) { if (!e) e = window.event; if (!e.target) e.target = e.srcElement; // ie if (typeof e.target.form != 'undefined') return true; // form element has focus if (!hs.fireEvent(hs, 'onKeyDown', e)) return true; var exp = hs.getExpander(); var op = null; switch (e.keyCode) { case 70: // f if (exp) exp.doFullExpand(); return true; case 32: // Space op = 2; break; case 34: // Page Down case 39: // Arrow right case 40: // Arrow down op = 1; break; case 8: // Backspace case 33: // Page Up case 37: // Arrow left case 38: // Arrow up op = -1; break; case 27: // Escape case 13: // Enter op = 0; } if (op !== null) {if (op != 2)hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); if (!hs.enableKeyListener) return true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; if (exp) { if (op == 0) { exp.close(); } else if (op == 2) { if (exp.slideshow) exp.slideshow.hitSpace(); } else { if (exp.slideshow) exp.slideshow.pause(); hs.previousOrNext(exp.key, op); } return false; } } return true; }, registerOverlay : function (overlay) { hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } )); }, addSlideshow : function (options) { var sg = options.slideshowGroup; if (typeof sg == 'object') { for (var i = 0; i < sg.length; i++) { var o = {}; for (var x in options) o[x] = options[x]; o.slideshowGroup = sg[i]; hs.push(hs.slideshows, o); } } else { hs.push(hs.slideshows, options); } }, getWrapperKey : function (element, expOnly) { var el, re = /^highslide-wrapper-([0-9]+)$/; // 1. look in open expanders el = element; while (el.parentNode) { if (el.hsKey !== undefined) return el.hsKey; if (el.id && re.test(el.id)) return el.id.replace(re, "$1"); el = el.parentNode; } // 2. look in thumbnail if (!expOnly) { el = element; while (el.parentNode) { if (el.tagName && hs.isHsAnchor(el)) { for (var key = 0; key < hs.expanders.length; key++) { var exp = hs.expanders[key]; if (exp && exp.a == el) return key; } } el = el.parentNode; } } return null; }, getExpander : function (el, expOnly) { if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null; if (typeof el == 'number') return hs.expanders[el] || null; if (typeof el == 'string') el = hs.$(el); return hs.expanders[hs.getWrapperKey(el, expOnly)] || null; }, isHsAnchor : function (a) { return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/)); }, reOrder : function () { for (var i = 0; i < hs.expanders.length; i++) if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost(); }, fireEvent : function (obj, evt, args) { return obj && obj[evt] ? (obj[evt](obj, args) !== false) : true; }, mouseClickHandler : function(e) { if (!e) e = window.event; if (e.button > 1) return true; if (!e.target) e.target = e.srcElement; var el = e.target; while (el.parentNode && !(/highslide-(image|move|html|resize)/.test(el.className))) { el = el.parentNode; } var exp = hs.getExpander(el); if (exp && (exp.isClosing || !exp.isExpanded)) return true; if (exp && e.type == 'mousedown') { if (e.target.form) return true; var match = el.className.match(/highslide-(image|move|resize)/); if (match) { hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos, height: exp.y.size, clickX: e.clientX, clickY: e.clientY }; hs.addEventListener(document, 'mousemove', hs.dragHandler); if (e.preventDefault) e.preventDefault(); // FF if (/highslide-(image|html)-blur/.test(exp.content.className)) { exp.focus(); hs.hasFocused = true; } return false; } else if (/highslide-html/.test(el.className) && hs.focusKey != exp.key) { exp.focus(); exp.doShowHide('hidden'); } } else if (e.type == 'mouseup') { hs.removeEventListener(document, 'mousemove', hs.dragHandler); if (hs.dragArgs) { if (hs.styleRestoreCursor && hs.dragArgs.type == 'image') hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor; var hasDragged = hs.dragArgs.hasDragged; if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) { if (hs.fireEvent(exp, 'onImageClick')) exp.close(); } else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) { hs.dragArgs.exp.doShowHide('hidden'); } if (hs.dragArgs.exp.releaseMask) hs.dragArgs.exp.releaseMask.style.display = 'none'; if (hasDragged) hs.fireEvent(hs.dragArgs.exp, 'onDrop', hs.dragArgs); hs.hasFocused = false; hs.dragArgs = null; } else if (/highslide-image-blur/.test(el.className)) { el.style.cursor = hs.styleRestoreCursor; } } return false; }, dragHandler : function(e) { if (!hs.dragArgs) return true; if (!e) e = window.event; var a = hs.dragArgs, exp = a.exp; if (exp.iframe) { if (!exp.releaseMask) exp.releaseMask = hs.createElement('div', null, { position: 'absolute', width: exp.x.size+'px', height: exp.y.size+'px', left: exp.x.cb+'px', top: exp.y.cb+'px', zIndex: 4, background: (hs.ie ? 'white' : 'none'), opacity: .01 }, exp.wrapper, true); if (exp.releaseMask.style.display == 'none') exp.releaseMask.style.display = ''; } a.dX = e.clientX - a.clickX; a.dY = e.clientY - a.clickY; var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2)); if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0) || (distance > (hs.dragSensitivity || 5)); if (a.hasDragged && e.clientX > 5 && e.clientY > 5) { if (!hs.fireEvent(exp, 'onDrag', a)) return false; if (a.type == 'resize') exp.resize(a); else { exp.moveTo(a.left + a.dX, a.top + a.dY); if (a.type == 'image') exp.content.style.cursor = 'move'; } } return false; }, wrapperMouseHandler : function (e) { try { if (!e) e = window.event; var over = /mouseover/i.test(e.type); if (!e.target) e.target = e.srcElement; // ie if (hs.ie) e.relatedTarget = over ? e.fromElement : e.toElement; // ie var exp = hs.getExpander(e.target); if (!exp.isExpanded) return; if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp || hs.dragArgs) return; hs.fireEvent(exp, over ? 'onMouseOver' : 'onMouseOut', e); for (var i = 0; i < exp.overlays.length; i++) (function() { var o = hs.$('hsId'+ exp.overlays[i]); if (o && o.hideOnMouseOut) { if (over) hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur); } })(); } catch (e) {} }, addEventListener : function (el, event, func) { if (el == document && event == 'ready') hs.push(hs.onReady, func); try { el.addEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); el.attachEvent('on'+ event, func); } catch (e) { el['on'+ event] = func; } } }, removeEventListener : function (el, event, func) { try { el.removeEventListener(event, func, false); } catch (e) { try { el.detachEvent('on'+ event, func); } catch (e) { el['on'+ event] = null; } } }, preloadFullImage : function (i) { if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') { var img = document.createElement('img'); img.onload = function() { img = null; hs.preloadFullImage(i + 1); }; img.src = hs.preloadTheseImages[i]; } }, preloadImages : function (number) { if (number && typeof number != 'object') hs.numberOfImagesToPreload = number; var arr = hs.getAnchors(); for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) { hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i])); } // preload outlines if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} ); else hs.preloadFullImage(0); // preload cursor if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor }); }, init : function () { if (!hs.container) { hs.getPageSize(); hs.ieLt7 = hs.ie && hs.uaVersion < 7; hs.ie6SSL = hs.ieLt7 && location.protocol == 'https:'; for (var x in hs.langDefaults) { if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x]; else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined') hs.lang[x] = hs.langDefaults[x]; } hs.container = hs.createElement('div', { className: 'highslide-container' }, { position: 'absolute', left: 0, top: 0, width: '100%', zIndex: hs.zIndexCounter, direction: 'ltr' }, document.body, true ); hs.loading = hs.createElement('a', { className: 'highslide-loading', title: hs.lang.loadingTitle, innerHTML: hs.lang.loadingText, href: 'javascript:;' }, { position: 'absolute', top: '-9999px', opacity: hs.loadingOpacity, zIndex: 1 }, hs.container ); hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container); hs.viewport = hs.createElement('div', { className: 'highslide-viewport highslide-viewport-size' }, { visibility: (hs.safari && hs.uaVersion < 525) ? 'visible' : 'hidden' }, hs.container, 1 ); hs.clearing = hs.createElement('div', null, { clear: 'both', paddingTop: '1px' }, null, true); // http://www.robertpenner.com/easing/ Math.linearTween = function (t, b, c, d) { return c*t/d + b; }; Math.easeInQuad = function (t, b, c, d) { return c*(t/=d)*t + b; }; Math.easeOutQuad = function (t, b, c, d) { return -c *(t/=d)*(t-2) + b; }; hs.hideSelects = hs.ieLt7; hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE' || (hs.ie && hs.uaVersion < 5.5)); hs.fireEvent(this, 'onActivate'); } }, ready : function() { if (hs.isReady) return; hs.isReady = true; for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i](); }, updateAnchors : function() { var el, els, all = [], images = [], htmls = [],groups = {}, re; for (var i = 0; i < hs.openerTagNames.length; i++) { els = document.getElementsByTagName(hs.openerTagNames[i]); for (var j = 0; j < els.length; j++) { el = els[j]; re = hs.isHsAnchor(el); if (re) { hs.push(all, el); if (re[0] == 'hs.expand') hs.push(images, el); else if (re[0] == 'hs.htmlExpand') hs.push(htmls, el); var g = hs.getParam(el, 'slideshowGroup') || 'none'; if (!groups[g]) groups[g] = []; hs.push(groups[g], el); } } } hs.anchors = { all: all, groups: groups, images: images, htmls: htmls }; return hs.anchors; }, getAnchors : function() { return hs.anchors || hs.updateAnchors(); }, close : function(el) { var exp = hs.getExpander(el); if (exp) exp.close(); return false; } }; // end hs object hs.fx = function( elem, options, prop ){ this.options = options; this.elem = elem; this.prop = prop; if (!options.orig) options.orig = {}; }; hs.fx.prototype = { update: function(){ (hs.fx.step[this.prop] || hs.fx.step._default)(this); if (this.options.step) this.options.step.call(this.elem, this.now, this); }, custom: function(from, to, unit){ this.startTime = (new Date()).getTime(); this.start = from; this.end = to; this.unit = unit;// || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t(gotoEnd){ return self.step(gotoEnd); } t.elem = this.elem; if ( t() && hs.timers.push(t) == 1 ) { hs.timerId = setInterval(function(){ var timers = hs.timers; for ( var i = 0; i < timers.length; i++ ) if ( !timers[i]() ) timers.splice(i--, 1); if ( !timers.length ) { clearInterval(hs.timerId); } }, 13); } }, step: function(gotoEnd){ var t = (new Date()).getTime(); if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; var done = true; for ( var i in this.options.curAnim ) if ( this.options.curAnim[i] !== true ) done = false; if ( done ) { if (this.options.complete) this.options.complete.call(this.elem); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; this.pos = this.options.easing(n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); } return true; } }; hs.extend( hs.fx, { step: { opacity: function(fx){ hs.setStyles(fx.elem, { opacity: fx.now }); }, _default: function(fx){ try { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) fx.elem.style[ fx.prop ] = fx.now + fx.unit; else fx.elem[ fx.prop ] = fx.now; } catch (e) {} } } }); hs.Outline = function (outlineType, onLoad) { this.onLoad = onLoad; this.outlineType = outlineType; var v = hs.uaVersion, tr; this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7; if (!outlineType) { if (onLoad) onLoad(); return; } hs.init(); this.table = hs.createElement( 'table', { cellSpacing: 0 }, { visibility: 'hidden', position: 'absolute', borderCollapse: 'collapse', width: 0 }, hs.container, true ); var tbody = hs.createElement('tbody', null, null, this.table, 1); this.td = []; for (var i = 0; i <= 8; i++) { if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true); this.td[i] = hs.createElement('td', null, null, tr, true); var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' }; hs.setStyles(this.td[i], style); } this.td[4].className = outlineType +' highslide-outline'; this.preloadGraphic(); }; hs.Outline.prototype = { preloadGraphic : function () { var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png"; var appendTo = hs.safari ? hs.container : null; this.graphic = hs.createElement('img', null, { position: 'absolute', top: '-9999px' }, appendTo, true); // for onload trigger var pThis = this; this.graphic.onload = function() { pThis.onGraphicLoad(); }; this.graphic.src = src; }, onGraphicLoad : function () { var o = this.offset = this.graphic.width / 4, pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]], dim = { height: (2*o) +'px', width: (2*o) +'px' }; for (var i = 0; i <= 8; i++) { if (pos[i]) { if (this.hasAlphaImageLoader) { var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px'; var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true); hs.createElement ('div', null, { filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')", position: 'absolute', width: w, height: this.graphic.height +'px', left: (pos[i][0]*o)+'px', top: (pos[i][1]*o)+'px' }, div, true); } else { hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'}); } if (window.opera && (i == 3 || i ==5)) hs.createElement('div', null, dim, this.td[i], true); hs.setStyles (this.td[i], dim); } } this.graphic = null; if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy(); hs.pendingOutlines[this.outlineType] = this; if (this.onLoad) this.onLoad(); }, setPosition : function (pos, offset, vis, dur, easing) { var exp = this.exp, stl = exp.wrapper.style, offset = offset || 0, pos = pos || { x: exp.x.pos + offset, y: exp.y.pos + offset, w: exp.x.get('wsize') - 2 * offset, h: exp.y.get('wsize') - 2 * offset }; if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset) ? 'visible' : 'hidden'; hs.setStyles(this.table, { left: (pos.x - this.offset) +'px', top: (pos.y - this.offset) +'px', width: (pos.w + 2 * this.offset) +'px' }); pos.w -= 2 * this.offset; pos.h -= 2 * this.offset; hs.setStyles (this.td[4], { width: pos.w >= 0 ? pos.w +'px' : 0, height: pos.h >= 0 ? pos.h +'px' : 0 }); if (this.hasAlphaImageLoader) this.td[3].style.height = this.td[5].style.height = this.td[4].style.height; }, destroy : function(hide) { if (hide) this.table.style.visibility = 'hidden'; else hs.discardElement(this.table); } }; hs.Dimension = function(exp, dim) { this.exp = exp; this.dim = dim; this.ucwh = dim == 'x' ? 'Width' : 'Height'; this.wh = this.ucwh.toLowerCase(); this.uclt = dim == 'x' ? 'Left' : 'Top'; this.lt = this.uclt.toLowerCase(); this.ucrb = dim == 'x' ? 'Right' : 'Bottom'; this.rb = this.ucrb.toLowerCase(); this.p1 = this.p2 = 0; }; hs.Dimension.prototype = { get : function(key) { switch (key) { case 'loadingPos': return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2; case 'loadingPosXfade': return this.pos + this.cb+ this.p1 + (this.size - hs.loading['offset'+ this.ucwh]) / 2; case 'wsize': return this.size + 2 * this.cb + this.p1 + this.p2; case 'fitsize': return this.clientSize - this.marginMin - this.marginMax; case 'maxsize': return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ; case 'opos': return this.pos - (this.exp.outline ? this.exp.outline.offset : 0); case 'osize': return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0); case 'imgPad': return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0; } }, calcBorders: function() { // correct for borders this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2; this.marginMax = hs['margin'+ this.ucrb]; }, calcThumb: function() { this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) : this.exp.el['offset'+ this.ucwh]; this.tpos = this.exp.tpos[this.dim]; this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2; if (this.tpos == 0 || this.tpos == -1) { this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt]; }; }, calcExpanded: function() { var exp = this.exp; this.justify = 'auto'; // get alignment if (exp.align == 'center') this.justify = 'center'; else if (new RegExp(this.lt).test(exp.anchor)) this.justify = null; else if (new RegExp(this.rb).test(exp.anchor)) this.justify = 'max'; // size and position this.pos = this.tpos - this.cb + this.tb; if (this.maxHeight && this.dim == 'x') exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full); this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full); this.minSize = exp.allowSizeReduction ? Math.min(exp['min'+ this.ucwh], this.full) :this.full; if (exp.isImage && exp.useBox) { this.size = exp[this.wh]; this.imgSize = this.full; } if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth; this.target = exp['target'+ this.dim.toUpperCase()]; this.marginMin = hs['margin'+ this.uclt]; this.scroll = hs.page['scroll'+ this.uclt]; this.clientSize = hs.page[this.wh]; }, setSize: function(i) { var exp = this.exp; if (exp.isImage && (exp.useBox || hs.padToMinWidth)) { this.imgSize = i; this.size = Math.max(this.size, this.imgSize); exp.content.style[this.lt] = this.get('imgPad')+'px'; } else this.size = i; exp.content.style[this.wh] = i +'px'; exp.wrapper.style[this.wh] = this.get('wsize') +'px'; if (exp.outline) exp.outline.setPosition(); if (exp.releaseMask) exp.releaseMask.style[this.wh] = i +'px'; if (this.dim == 'y' && exp.iDoc && exp.body.style.height != 'auto') try { exp.iDoc.body.style.overflow = 'auto'; } catch (e) {} if (exp.isHtml) { var d = exp.scrollerDiv; if (this.sizeDiff === undefined) this.sizeDiff = exp.innerContent['offset'+ this.ucwh] - d['offset'+ this.ucwh]; d.style[this.wh] = (this.size - this.sizeDiff) +'px'; if (this.dim == 'x') exp.mediumContent.style.width = 'auto'; if (exp.body) exp.body.style[this.wh] = 'auto'; } if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true); if (this.dim == 'x' && exp.slideshow && exp.isImage) { if (i == this.full) exp.slideshow.disable('full-expand'); else exp.slideshow.enable('full-expand'); } }, setPos: function(i) { this.pos = i; this.exp.wrapper.style[this.lt] = i +'px'; if (this.exp.outline) this.exp.outline.setPosition(); } }; hs.Expander = function(a, params, custom, contentType) { if (document.readyState && hs.ie && !hs.isReady) { hs.addEventListener(document, 'ready', function() { new hs.Expander(a, params, custom, contentType); }); return; } this.a = a; this.custom = custom; this.contentType = contentType || 'image'; this.isHtml = (contentType == 'html'); this.isImage = !this.isHtml; hs.continuePreloading = false; this.overlays = []; this.last = hs.last; hs.last = null; hs.init(); var key = this.key = hs.expanders.length; // override inline parameters for (var i = 0; i < hs.overrides.length; i++) { var name = hs.overrides[i]; this[name] = params && typeof params[name] != 'undefined' ? params[name] : hs[name]; } if (!this.src) this.src = a.href; // get thumb var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a; el = this.thumb = el.getElementsByTagName('img')[0] || el; this.thumbsUserSetId = el.id || a.id; if (!hs.fireEvent(this, 'onInit')) return true; // check if already open for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].a == a && !(this.last && this.transitions[1] == 'crossfade')) { hs.expanders[i].focus(); return false; } } // cancel other if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) { hs.expanders[i].cancelLoading(); } } hs.expanders[key] = this; if (!hs.allowMultipleInstances && !hs.upcoming) { if (hs.expanders[key-1]) hs.expanders[key-1].close(); if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey]) hs.expanders[hs.focusKey].close(); } // initiate metrics this.el = el; this.tpos = hs.getPosition(el); hs.getPageSize(); var x = this.x = new hs.Dimension(this, 'x'); x.calcThumb(); var y = this.y = new hs.Dimension(this, 'y'); y.calcThumb(); if (/area/i.test(el.tagName)) this.getImageMapAreaCorrection(el); this.wrapper = hs.createElement( 'div', { id: 'highslide-wrapper-'+ this.key, className: 'highslide-wrapper '+ this.wrapperClassName }, { visibility: 'hidden', position: 'absolute', zIndex: hs.zIndexCounter += 2 }, null, true ); this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler; if (this.contentType == 'image' && this.outlineWhileAnimating == 2) this.outlineWhileAnimating = 0; // get the outline if (!this.outlineType || (this.last && this.isImage && this.transitions[1] == 'crossfade')) { this[this.contentType +'Create'](); } else if (hs.pendingOutlines[this.outlineType]) { this.connectOutline(); this[this.contentType +'Create'](); } else { this.showLoading(); var exp = this; new hs.Outline(this.outlineType, function () { exp.connectOutline(); exp[exp.contentType +'Create'](); } ); } return true; }; hs.Expander.prototype = { error : function(e) { // alert ('Line '+ e.lineNumber +': '+ e.message); window.location.href = this.src; }, connectOutline : function() { var outline = this.outline = hs.pendingOutlines[this.outlineType]; outline.exp = this; outline.table.style.zIndex = this.wrapper.style.zIndex - 1; hs.pendingOutlines[this.outlineType] = null; }, showLoading : function() { if (this.onLoadStarted || this.loading) return; this.loading = hs.loading; var exp = this; this.loading.onclick = function() { exp.cancelLoading(); }; if (!hs.fireEvent(this, 'onShowLoading')) return; var exp = this, l = this.x.get('loadingPos') +'px', t = this.y.get('loadingPos') +'px'; if (!tgt && this.last && this.transitions[1] == 'crossfade') var tgt = this.last; if (tgt) { l = tgt.x.get('loadingPosXfade') +'px'; t = tgt.y.get('loadingPosXfade') +'px'; this.loading.style.zIndex = hs.zIndexCounter++; } setTimeout(function () { if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })} , 100); }, imageCreate : function() { var exp = this; var img = document.createElement('img'); this.content = img; img.onload = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); }; if (hs.blockRightClick) img.oncontextmenu = function() { return false; }; img.className = 'highslide-image'; hs.setStyles(img, { visibility: 'hidden', display: 'block', position: 'absolute', maxWidth: '9999px', zIndex: 3 }); img.title = hs.lang.restoreTitle; if (hs.safari) hs.container.appendChild(img); if (hs.ie && hs.flushImgSize) img.src = null; img.src = this.src; this.showLoading(); }, htmlCreate : function () { if (!hs.fireEvent(this, 'onBeforeGetContent')) return; this.content = hs.getCacheBinding(this.a); if (!this.content) this.content = hs.getNode(this.contentId); if (!this.content) this.content = hs.getSelfRendered(); this.getInline(['maincontent']); if (this.maincontent) { var body = hs.getElementByClass(this.content, 'div', 'highslide-body'); if (body) body.appendChild(this.maincontent); this.maincontent.style.display = 'block'; } hs.fireEvent(this, 'onAfterGetContent'); var innerContent = this.innerContent = this.content; if (/(swf|iframe)/.test(this.objectType)) this.setObjContainerSize(innerContent); // the content tree hs.container.appendChild(this.wrapper); hs.setStyles( this.wrapper, { position: 'static', padding: '0 '+ hs.marginRight +'px 0 '+ hs.marginLeft +'px' }); this.content = hs.createElement( 'div', { className: 'highslide-html' }, { position: 'relative', zIndex: 3, overflow: 'hidden' }, this.wrapper ); this.mediumContent = hs.createElement('div', null, null, this.content, 1); this.mediumContent.appendChild(innerContent); hs.setStyles (innerContent, { position: 'relative', display: 'block', direction: hs.lang.cssDirection || '' }); if (this.width) innerContent.style.width = this.width +'px'; if (this.height) hs.setStyles(innerContent, { height: this.height +'px', overflow: 'hidden' }); if (innerContent.offsetWidth < this.minWidth) innerContent.style.width = this.minWidth +'px'; if (this.objectType == 'ajax' && !hs.getCacheBinding(this.a)) { this.showLoading(); var exp = this; var ajax = new hs.Ajax(this.a, innerContent); ajax.src = this.src; ajax.onLoad = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); }; ajax.onError = function () { location.href = exp.src; }; ajax.run(); } else if (this.objectType == 'iframe' && this.objectLoadTime == 'before') { this.writeExtendedContent(); } else this.contentLoaded(); }, contentLoaded : function() { try { if (!this.content) return; this.content.onload = null; if (this.onLoadStarted) return; else this.onLoadStarted = true; var x = this.x, y = this.y; if (this.loading) { hs.setStyles(this.loading, { top: '-9999px' }); this.loading = null; hs.fireEvent(this, 'onHideLoading'); } if (this.isImage) { x.full = this.content.width; y.full = this.content.height; hs.setStyles(this.content, { width: x.t +'px', height: y.t +'px' }); this.wrapper.appendChild(this.content); hs.container.appendChild(this.wrapper); } else if (this.htmlGetSize) this.htmlGetSize(); x.calcBorders(); y.calcBorders(); hs.setStyles (this.wrapper, { left: (x.tpos + x.tb - x.cb) +'px', top: (y.tpos + x.tb - y.cb) +'px' }); this.initSlideshow(); this.getOverlays(); var ratio = x.full / y.full; x.calcExpanded(); this.justify(x); y.calcExpanded(); this.justify(y); if (this.isHtml) this.htmlSizeOperations(); if (this.overlayBox) this.sizeOverlayBox(0, 1); if (this.allowSizeReduction) { if (this.isImage) this.correctRatio(ratio); else this.fitOverlayBox(); var ss = this.slideshow; if (ss && this.last && ss.controls && ss.fixedControls) { var pos = ss.overlayOptions.position || '', p; for (var dim in hs.oPos) for (var i = 0; i < 5; i++) { p = this[dim]; if (pos.match(hs.oPos[dim][i])) { p.pos = this.last[dim].pos + (this.last[dim].p1 - p.p1) + (this.last[dim].size - p.size) * [0, 0, .5, 1, 1][i]; if (ss.fixedControls == 'fit') { if (p.pos + p.size + p.p1 + p.p2 > p.scroll + p.clientSize - p.marginMax) p.pos = p.scroll + p.clientSize - p.size - p.marginMin - p.marginMax - p.p1 - p.p2; if (p.pos < p.scroll + p.marginMin) p.pos = p.scroll + p.marginMin; } } } } if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) { this.createFullExpand(); if (this.overlays.length == 1) this.sizeOverlayBox(); } } this.show(); } catch (e) { this.error(e); } }, setObjContainerSize : function(parent, auto) { var c = hs.getElementByClass(parent, 'DIV', 'highslide-body'); if (/(iframe|swf)/.test(this.objectType)) { if (this.objectWidth) c.style.width = this.objectWidth +'px'; if (this.objectHeight) c.style.height = this.objectHeight +'px'; } }, writeExtendedContent : function () { if (this.hasExtendedContent) return; var exp = this; this.body = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body'); if (this.objectType == 'iframe') { this.showLoading(); var ruler = hs.clearing.cloneNode(1); this.body.appendChild(ruler); this.newWidth = this.innerContent.offsetWidth; if (!this.objectWidth) this.objectWidth = ruler.offsetWidth; var hDiff = this.innerContent.offsetHeight - this.body.offsetHeight, h = this.objectHeight || hs.page.height - hDiff - hs.marginTop - hs.marginBottom, onload = this.objectLoadTime == 'before' ? ' onload="if (hs.expanders['+ this.key +']) hs.expanders['+ this.key +'].contentLoaded()" ' : ''; this.body.innerHTML += '<iframe name="hs'+ (new Date()).getTime() +'" frameborder="0" key="'+ this.key +'" ' +' style="width:'+ this.objectWidth +'px; height:'+ h +'px" ' + onload +' src="'+ this.src +'" ></iframe>'; this.ruler = this.body.getElementsByTagName('div')[0]; this.iframe = this.body.getElementsByTagName('iframe')[0]; if (this.objectLoadTime == 'after') this.correctIframeSize(); } if (this.objectType == 'swf') { this.body.id = this.body.id || 'hs-flash-id-' + this.key; var a = this.swfOptions; if (!a.params) a.params = {}; if (typeof a.params.wmode == 'undefined') a.params.wmode = 'transparent'; if (swfobject) swfobject.embedSWF(this.src, this.body.id, this.objectWidth, this.objectHeight, a.version || '7', a.expressInstallSwfurl, a.flashvars, a.params, a.attributes); } this.hasExtendedContent = true; }, htmlGetSize : function() { if (this.iframe && !this.objectHeight) { // loadtime before this.iframe.style.height = this.body.style.height = this.getIframePageHeight() +'px'; } this.innerContent.appendChild(hs.clearing); if (!this.x.full) this.x.full = this.innerContent.offsetWidth; this.y.full = this.innerContent.offsetHeight; this.innerContent.removeChild(hs.clearing); if (hs.ie && this.newHeight > parseInt(this.innerContent.currentStyle.height)) { // ie css bug this.newHeight = parseInt(this.innerContent.currentStyle.height); } hs.setStyles( this.wrapper, { position: 'absolute', padding: '0'}); hs.setStyles( this.content, { width: this.x.t +'px', height: this.y.t +'px'}); }, getIframePageHeight : function() { var h; try { var doc = this.iDoc = this.iframe.contentDocument || this.iframe.contentWindow.document; var clearing = doc.createElement('div'); clearing.style.clear = 'both'; doc.body.appendChild(clearing); h = clearing.offsetTop; if (hs.ie) h += parseInt(doc.body.currentStyle.marginTop) + parseInt(doc.body.currentStyle.marginBottom) - 1; } catch (e) { // other domain h = 300; } return h; }, correctIframeSize : function () { var wDiff = this.innerContent.offsetWidth - this.ruler.offsetWidth; hs.discardElement(this.ruler); if (wDiff < 0) wDiff = 0; var hDiff = this.innerContent.offsetHeight - this.iframe.offsetHeight; if (this.iDoc && !this.objectHeight && !this.height && this.y.size == this.y.full) try { this.iDoc.body.style.overflow = 'hidden'; } catch (e) {} hs.setStyles(this.iframe, { width: Math.abs(this.x.size - wDiff) +'px', height: Math.abs(this.y.size - hDiff) +'px' }); hs.setStyles(this.body, { width: this.iframe.style.width, height: this.iframe.style.height }); this.scrollingContent = this.iframe; this.scrollerDiv = this.scrollingContent; }, htmlSizeOperations : function () { this.setObjContainerSize(this.innerContent); if (this.objectType == 'swf' && this.objectLoadTime == 'before') this.writeExtendedContent(); // handle minimum size if (this.x.size < this.x.full && !this.allowWidthReduction) this.x.size = this.x.full; if (this.y.size < this.y.full && !this.allowHeightReduction) this.y.size = this.y.full; this.scrollerDiv = this.innerContent; hs.setStyles(this.mediumContent, { position: 'relative', width: this.x.size +'px' }); hs.setStyles(this.innerContent, { border: 'none', width: 'auto', height: 'auto' }); var node = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body'); if (node && !/(iframe|swf)/.test(this.objectType)) { var cNode = node; // wrap to get true size node = hs.createElement(cNode.nodeName, null, {overflow: 'hidden'}, null, true); cNode.parentNode.insertBefore(node, cNode); node.appendChild(hs.clearing); // IE6 node.appendChild(cNode); var wDiff = this.innerContent.offsetWidth - node.offsetWidth; var hDiff = this.innerContent.offsetHeight - node.offsetHeight; node.removeChild(hs.clearing); var kdeBugCorr = hs.safari || navigator.vendor == 'KDE' ? 1 : 0; // KDE repainting bug hs.setStyles(node, { width: (this.x.size - wDiff - kdeBugCorr) +'px', height: (this.y.size - hDiff) +'px', overflow: 'auto', position: 'relative' } ); if (kdeBugCorr && cNode.offsetHeight > node.offsetHeight) { node.style.width = (parseInt(node.style.width) + kdeBugCorr) + 'px'; } this.scrollingContent = node; this.scrollerDiv = this.scrollingContent; } if (this.iframe && this.objectLoadTime == 'before') this.correctIframeSize(); if (!this.scrollingContent && this.y.size < this.mediumContent.offsetHeight) this.scrollerDiv = this.content; if (this.scrollerDiv == this.content && !this.allowWidthReduction && !/(iframe|swf)/.test(this.objectType)) { this.x.size += 17; // room for scrollbars } if (this.scrollerDiv && this.scrollerDiv.offsetHeight > this.scrollerDiv.parentNode.offsetHeight) { setTimeout("try { hs.expanders["+ this.key +"].scrollerDiv.style.overflow = 'auto'; } catch(e) {}", hs.expandDuration); } }, getImageMapAreaCorrection : function(area) { var c = area.coords.split(','); for (var i = 0; i < c.length; i++) c[i] = parseInt(c[i]); if (area.shape.toLowerCase() == 'circle') { this.x.tpos += c[0] - c[2]; this.y.tpos += c[1] - c[2]; this.x.t = this.y.t = 2 * c[2]; } else { var maxX, maxY, minX = maxX = c[0], minY = maxY = c[1]; for (var i = 0; i < c.length; i++) { if (i % 2 == 0) { minX = Math.min(minX, c[i]); maxX = Math.max(maxX, c[i]); } else { minY = Math.min(minY, c[i]); maxY = Math.max(maxY, c[i]); } } this.x.tpos += minX; this.x.t = maxX - minX; this.y.tpos += minY; this.y.t = maxY - minY; } }, justify : function (p, moveOnly) { var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y'; if (tgt && tgt.match(/ /)) { tgtArr = tgt.split(' '); tgt = tgtArr[0]; } if (tgt && hs.$(tgt)) { p.pos = hs.getPosition(hs.$(tgt))[dim]; if (tgtArr && tgtArr[1] && tgtArr[1].match(/^[-]?[0-9]+px$/)) p.pos += parseInt(tgtArr[1]); if (p.size < p.minSize) p.size = p.minSize; } else if (p.justify == 'auto' || p.justify == 'center') { var hasMovedMin = false; var allowReduce = p.exp.allowSizeReduction; if (p.justify == 'center') p.pos = Math.round(p.scroll + (p.clientSize + p.marginMin - p.marginMax - p.get('wsize')) / 2); else p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2)); if (p.pos < p.scroll + p.marginMin) { p.pos = p.scroll + p.marginMin; hasMovedMin = true; } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) { if (!moveOnly && hasMovedMin && allowReduce) { p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize')); } else if (p.get('wsize') < p.get('fitsize')) { p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize'); } else { // image larger than viewport p.pos = p.scroll + p.marginMin; if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize'); } } if (!moveOnly && p.size < p.minSize) { p.size = p.minSize; allowReduce = false; } } else if (p.justify == 'max') { p.pos = Math.floor(p.pos - p.size + p.t); } if (p.pos < p.marginMin) { var tmpMin = p.pos; p.pos = p.marginMin; if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin); } }, correctRatio : function(ratio) { var x = this.x, y = this.y, changed = false, xSize = Math.min(x.full, x.size), ySize = Math.min(y.full, y.size), useBox = (this.useBox || hs.padToMinWidth); if (xSize / ySize > ratio) { // width greater xSize = ySize * ratio; if (xSize < x.minSize) { // below minWidth xSize = x.minSize; ySize = xSize / ratio; } changed = true; } else if (xSize / ySize < ratio) { // height greater ySize = xSize / ratio; changed = true; } if (hs.padToMinWidth && x.full < x.minSize) { x.imgSize = x.full; y.size = y.imgSize = y.full; } else if (this.useBox) { x.imgSize = xSize; y.imgSize = ySize; } else { x.size = xSize; y.size = ySize; } changed = this.fitOverlayBox(useBox ? null : ratio, changed); if (useBox && y.size < y.imgSize) { y.imgSize = y.size; x.imgSize = y.size * ratio; } if (changed || useBox) { x.pos = x.tpos - x.cb + x.tb; x.minSize = x.size; this.justify(x, true); y.pos = y.tpos - y.cb + y.tb; y.minSize = y.size; this.justify(y, true); if (this.overlayBox) this.sizeOverlayBox(); } }, fitOverlayBox : function(ratio, changed) { var x = this.x, y = this.y; if (this.overlayBox && (this.isImage || this.allowHeightReduction)) { while (y.size > this.minHeight && x.size > this.minWidth && y.get('wsize') > y.get('fitsize')) { y.size -= 10; if (ratio) x.size = y.size * ratio; this.sizeOverlayBox(0, 1); changed = true; } } return changed; }, reflow : function () { if (this.scrollerDiv) { var h = /iframe/i.test(this.scrollerDiv.tagName) ? (this.getIframePageHeight() + 1) +'px' : 'auto'; if (this.body) this.body.style.height = h; this.scrollerDiv.style.height = h; this.y.setSize(this.innerContent.offsetHeight); } }, show : function () { var x = this.x, y = this.y; this.doShowHide('hidden'); hs.fireEvent(this, 'onBeforeExpand'); if (this.slideshow && this.slideshow.thumbstrip) this.slideshow.thumbstrip.selectThumb(); // Apply size change this.changeSize( 1, { wrapper: { width : x.get('wsize'), height : y.get('wsize'), left: x.pos, top: y.pos }, content: { left: x.p1 + x.get('imgPad'), top: y.p1 + y.get('imgPad'), width:x.imgSize ||x.size, height:y.imgSize ||y.size } }, hs.expandDuration ); }, changeSize : function(up, to, dur) { // transition var trans = this.transitions, other = up ? (this.last ? this.last.a : null) : hs.upcoming, t = (trans[1] && other && hs.getParam(other, 'transitions')[1] == trans[1]) ? trans[1] : trans[0]; if (this[t] && t != 'expand') { this[t](up, to); return; } if (this.outline && !this.outlineWhileAnimating) { if (up) this.outline.setPosition(); else this.outline.destroy( (this.isHtml && this.preserveContent)); } if (!up) this.destroyOverlays(); var exp = this, x = exp.x, y = exp.y, easing = this.easing; if (!up) easing = this.easingClose || easing; var after = up ? function() { if (exp.outline) exp.outline.table.style.visibility = "visible"; setTimeout(function() { exp.afterExpand(); }, 50); } : function() { exp.afterClose(); }; if (up) hs.setStyles( this.wrapper, { width: x.t +'px', height: y.t +'px' }); if (up && this.isHtml) { hs.setStyles(this.wrapper, { left: (x.tpos - x.cb + x.tb) +'px', top: (y.tpos - y.cb + y.tb) +'px' }); } if (this.fadeInOut) { hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 }); hs.extend(to.wrapper, { opacity: up }); } hs.animate( this.wrapper, to.wrapper, { duration: dur, easing: easing, step: function(val, args) { if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') { var fac = up ? args.pos : 1 - args.pos; var pos = { w: x.t + (x.get('wsize') - x.t) * fac, h: y.t + (y.get('wsize') - y.t) * fac, x: x.tpos + (x.pos - x.tpos) * fac, y: y.tpos + (y.pos - y.tpos) * fac }; exp.outline.setPosition(pos, 0, 1); } if (exp.isHtml) { if (args.prop == 'left') exp.mediumContent.style.left = (x.pos - val) +'px'; if (args.prop == 'top') exp.mediumContent.style.top = (y.pos - val) +'px'; } } }); hs.animate( this.content, to.content, dur, easing, after); if (up) { this.wrapper.style.visibility = 'visible'; this.content.style.visibility = 'visible'; if (this.isHtml) this.innerContent.style.visibility = 'visible'; this.a.className += ' highslide-active-anchor'; } }, fade : function(up, to) { this.outlineWhileAnimating = false; var exp = this, t = up ? hs.expandDuration : 0; if (up) { hs.animate(this.wrapper, to.wrapper, 0); hs.setStyles(this.wrapper, { opacity: 0, visibility: 'visible' }); hs.animate(this.content, to.content, 0); this.content.style.visibility = 'visible'; hs.animate(this.wrapper, { opacity: 1 }, t, null, function() { exp.afterExpand(); }); } if (this.outline) { this.outline.table.style.zIndex = this.wrapper.style.zIndex; var dir = up || -1, offset = this.outline.offset, startOff = up ? 3 : offset, endOff = up? offset : 3; for (var i = startOff; dir * i <= dir * endOff; i += dir, t += 25) { (function() { var o = up ? endOff - i : startOff - i; setTimeout(function() { exp.outline.setPosition(0, o, 1); }, t); })(); } } if (up) {}//setTimeout(function() { exp.afterExpand(); }, t+50); else { setTimeout( function() { if (exp.outline) exp.outline.destroy(exp.preserveContent); exp.destroyOverlays(); hs.animate( exp.wrapper, { opacity: 0 }, hs.restoreDuration, null, function(){ exp.afterClose(); }); }, t); } }, crossfade : function (up, to, from) { if (!up) return; var exp = this, last = this.last, x = this.x, y = this.y, lastX = last.x, lastY = last.y, wrapper = this.wrapper, content = this.content, overlayBox = this.overlayBox; hs.removeEventListener(document, 'mousemove', hs.dragHandler); hs.setStyles(content, { width: (x.imgSize || x.size) +'px', height: (y.imgSize || y.size) +'px' }); if (overlayBox) overlayBox.style.overflow = 'visible'; this.outline = last.outline; if (this.outline) this.outline.exp = exp; last.outline = null; var fadeBox = hs.createElement('div', { className: 'highslide-image' }, { position: 'absolute', zIndex: 4, overflow: 'hidden', display: 'none' } ); var names = { oldImg: last, newImg: this }; for (var n in names) { this[n] = names[n].content.cloneNode(1); hs.setStyles(this[n], { position: 'absolute', border: 0, visibility: 'visible' }); fadeBox.appendChild(this[n]); } wrapper.appendChild(fadeBox); if (this.isHtml) hs.setStyles(this.mediumContent, { left: 0, top: 0 }); if (overlayBox) { overlayBox.className = ''; wrapper.appendChild(overlayBox); } fadeBox.style.display = ''; last.content.style.display = 'none'; if (hs.safari) { var match = navigator.userAgent.match(/Safari\/([0-9]{3})/); if (match && parseInt(match[1]) < 525) this.wrapper.style.visibility = 'visible'; } hs.animate(wrapper, { width: x.size }, { duration: hs.transitionDuration, step: function(val, args) { var pos = args.pos, invPos = 1 - pos; var prop, size = {}, props = ['pos', 'size', 'p1', 'p2']; for (var n in props) { prop = props[n]; size['x'+ prop] = Math.round(invPos * lastX[prop] + pos * x[prop]); size['y'+ prop] = Math.round(invPos * lastY[prop] + pos * y[prop]); size.ximgSize = Math.round( invPos * (lastX.imgSize || lastX.size) + pos * (x.imgSize || x.size)); size.ximgPad = Math.round(invPos * lastX.get('imgPad') + pos * x.get('imgPad')); size.yimgSize = Math.round( invPos * (lastY.imgSize || lastY.size) + pos * (y.imgSize || y.size)); size.yimgPad = Math.round(invPos * lastY.get('imgPad') + pos * y.get('imgPad')); } if (exp.outline) exp.outline.setPosition({ x: size.xpos, y: size.ypos, w: size.xsize + size.xp1 + size.xp2 + 2 * x.cb, h: size.ysize + size.yp1 + size.yp2 + 2 * y.cb }); last.wrapper.style.clip = 'rect(' + (size.ypos - lastY.pos)+'px, ' + (size.xsize + size.xp1 + size.xp2 + size.xpos + 2 * lastX.cb - lastX.pos) +'px, ' + (size.ysize + size.yp1 + size.yp2 + size.ypos + 2 * lastY.cb - lastY.pos) +'px, ' + (size.xpos - lastX.pos)+'px)'; hs.setStyles(content, { top: (size.yp1 + y.get('imgPad')) +'px', left: (size.xp1 + x.get('imgPad')) +'px', marginTop: (y.pos - size.ypos) +'px', marginLeft: (x.pos - size.xpos) +'px' }); hs.setStyles(wrapper, { top: size.ypos +'px', left: size.xpos +'px', width: (size.xp1 + size.xp2 + size.xsize + 2 * x.cb)+ 'px', height: (size.yp1 + size.yp2 + size.ysize + 2 * y.cb) + 'px' }); hs.setStyles(fadeBox, { width: (size.ximgSize || size.xsize) + 'px', height: (size.yimgSize || size.ysize) +'px', left: (size.xp1 + size.ximgPad) +'px', top: (size.yp1 + size.yimgPad) +'px', visibility: 'visible' }); hs.setStyles(exp.oldImg, { top: (lastY.pos - size.ypos + lastY.p1 - size.yp1 + lastY.get('imgPad') - size.yimgPad)+'px', left: (lastX.pos - size.xpos + lastX.p1 - size.xp1 + lastX.get('imgPad') - size.ximgPad)+'px' }); hs.setStyles(exp.newImg, { opacity: pos, top: (y.pos - size.ypos + y.p1 - size.yp1 + y.get('imgPad') - size.yimgPad) +'px', left: (x.pos - size.xpos + x.p1 - size.xp1 + x.get('imgPad') - size.ximgPad) +'px' }); if (overlayBox) hs.setStyles(overlayBox, { width: size.xsize + 'px', height: size.ysize +'px', left: (size.xp1 + x.cb) +'px', top: (size.yp1 + y.cb) +'px' }); }, complete: function () { wrapper.style.visibility = content.style.visibility = 'visible'; content.style.display = 'block'; fadeBox.style.display = 'none'; exp.a.className += ' highslide-active-anchor'; exp.afterExpand(); last.afterClose(); exp.last = null; } }); }, reuseOverlay : function(o, el) { if (!this.last) return false; for (var i = 0; i < this.last.overlays.length; i++) { var oDiv = hs.$('hsId'+ this.last.overlays[i]); if (oDiv && oDiv.hsId == o.hsId) { this.genOverlayBox(); oDiv.reuse = this.key; hs.push(this.overlays, this.last.overlays[i]); return true; } } return false; }, afterExpand : function() { this.isExpanded = true; this.focus(); if (this.isHtml && this.objectLoadTime == 'after') this.writeExtendedContent(); if (this.iframe) { try { var exp = this, doc = this.iframe.contentDocument || this.iframe.contentWindow.document; hs.addEventListener(doc, 'mousedown', function () { if (hs.focusKey != exp.key) exp.focus(); }); } catch(e) {} if (hs.ie && typeof this.isClosing != 'boolean') // first open this.iframe.style.width = (this.objectWidth - 1) +'px'; // hasLayout } if (this.dimmingOpacity) hs.dim(this); if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null; this.prepareNextOutline(); var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop; this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize') && this.y.pos < mY && mY < this.y.pos + this.y.get('wsize'); if (this.overlayBox) this.showOverlays(); hs.fireEvent(this, 'onAfterExpand'); }, prepareNextOutline : function() { var key = this.key; var outlineType = this.outlineType; new hs.Outline(outlineType, function () { try { hs.expanders[key].preloadNext(); } catch (e) {} }); }, preloadNext : function() { var next = this.getAdjacentAnchor(1); if (next && next.onclick.toString().match(/hs\.expand/)) var img = hs.createElement('img', { src: hs.getSrc(next) }); }, getAdjacentAnchor : function(op) { var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none']; /*< ? if ($cfg->slideshow) : ?>s*/ if (!as[current + op] && this.slideshow && this.slideshow.repeat) { if (op == 1) return as[0]; else if (op == -1) return as[as.length-1]; } /*< ? endif ?>s*/ return as[current + op] || null; }, getAnchorIndex : function() { var arr = hs.getAnchors().groups[this.slideshowGroup || 'none']; if (arr) for (var i = 0; i < arr.length; i++) { if (arr[i] == this.a) return i; } return null; }, getNumber : function() { if (this[this.numberPosition]) { var arr = hs.anchors.groups[this.slideshowGroup || 'none']; if (arr) { var s = hs.lang.number.replace('%1', this.getAnchorIndex() + 1).replace('%2', arr.length); this[this.numberPosition].innerHTML = '<div class="highslide-number">'+ s +'</div>'+ this[this.numberPosition].innerHTML; } } }, initSlideshow : function() { if (!this.last) { for (var i = 0; i < hs.slideshows.length; i++) { var ss = hs.slideshows[i], sg = ss.slideshowGroup; if (typeof sg == 'undefined' || sg === null || sg === this.slideshowGroup) this.slideshow = new hs.Slideshow(this.key, ss); } } else { this.slideshow = this.last.slideshow; } var ss = this.slideshow; if (!ss) return; var key = ss.expKey = this.key; ss.checkFirstAndLast(); ss.disable('full-expand'); if (ss.controls) { var o = ss.overlayOptions || {}; o.overlayId = ss.controls; o.hsId = 'controls'; this.createOverlay(o); } if (ss.thumbstrip) ss.thumbstrip.add(this); if (!this.last && this.autoplay) ss.play(true); if (ss.autoplay) { ss.autoplay = setTimeout(function() { hs.next(key); }, (ss.interval || 500)); } }, cancelLoading : function() { hs.discardElement (this.wrapper); hs.expanders[this.key] = null; if (hs.upcoming == this.a) hs.upcoming = null; hs.undim(this.key); if (this.loading) hs.loading.style.left = '-9999px'; hs.fireEvent(this, 'onHideLoading'); }, writeCredits : function () { if (this.credits) return; this.credits = hs.createElement('a', { href: hs.creditsHref, target: hs.creditsTarget, className: 'highslide-credits', innerHTML: hs.lang.creditsText, title: hs.lang.creditsTitle }); this.createOverlay({ overlayId: this.credits, position: this.creditsPosition || 'top left', hsId: 'credits' }); }, getInline : function(types, addOverlay) { for (var i = 0; i < types.length; i++) { var type = types[i], s = null; if (type == 'caption' && !hs.fireEvent(this, 'onBeforeGetCaption')) return; else if (type == 'heading' && !hs.fireEvent(this, 'onBeforeGetHeading')) return; if (!this[type +'Id'] && this.thumbsUserSetId) this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId; if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']); if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try { s = eval(this[type +'Eval']); } catch (e) {} if (!this[type] && this[type +'Text']) { s = this[type +'Text']; } if (!this[type] && !s) { this[type] = hs.getNode(this.a['_'+ type + 'Id']); if (!this[type]) { var next = this.a.nextSibling; while (next && !hs.isHsAnchor(next)) { if ((new RegExp('highslide-'+ type)).test(next.className || null)) { if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++; this[type] = hs.getNode(next.id); break; } next = next.nextSibling; } } } if (!this[type] && !s && this.numberPosition == type) s = '\n'; if (!this[type] && s) this[type] = hs.createElement('div', { className: 'highslide-'+ type, innerHTML: s } ); if (addOverlay && this[type]) { var o = { position: (type == 'heading') ? 'above' : 'below' }; for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x]; o.overlayId = this[type]; this.createOverlay(o); } } }, // on end move and resize doShowHide : function(visibility) { if (hs.hideSelects) this.showHideElements('SELECT', visibility); if (hs.hideIframes) this.showHideElements('IFRAME', visibility); if (hs.geckoMac) this.showHideElements('*', visibility); }, showHideElements : function (tagName, visibility) { var els = document.getElementsByTagName(tagName); var prop = tagName == '*' ? 'overflow' : 'visibility'; for (var i = 0; i < els.length; i++) { if (prop == 'visibility' || (document.defaultView.getComputedStyle( els[i], "").getPropertyValue('overflow') == 'auto' || els[i].getAttribute('hidden-by') != null)) { var hiddenBy = els[i].getAttribute('hidden-by'); if (visibility == 'visible' && hiddenBy) { hiddenBy = hiddenBy.replace('['+ this.key +']', ''); els[i].setAttribute('hidden-by', hiddenBy); if (!hiddenBy) els[i].style[prop] = els[i].origProp; } else if (visibility == 'hidden') { // hide if behind var elPos = hs.getPosition(els[i]); elPos.w = els[i].offsetWidth; elPos.h = els[i].offsetHeight; if (!this.dimmingOpacity) { // hide all if dimming var clearsX = (elPos.x + elPos.w < this.x.get('opos') || elPos.x > this.x.get('opos') + this.x.get('osize')); var clearsY = (elPos.y + elPos.h < this.y.get('opos') || elPos.y > this.y.get('opos') + this.y.get('osize')); } var wrapperKey = hs.getWrapperKey(els[i]); if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image if (!hiddenBy) { els[i].setAttribute('hidden-by', '['+ this.key +']'); els[i].origProp = els[i].style[prop]; els[i].style[prop] = 'hidden'; } else if (hiddenBy.indexOf('['+ this.key +']') == -1) { els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']'); } } else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey) && wrapperKey != this.key) { // on move els[i].setAttribute('hidden-by', ''); els[i].style[prop] = els[i].origProp || ''; } else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) { els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', '')); } } } } }, focus : function() { this.wrapper.style.zIndex = hs.zIndexCounter += 2; // blur others for (var i = 0; i < hs.expanders.length; i++) { if (hs.expanders[i] && i == hs.focusKey) { var blurExp = hs.expanders[i]; blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur'; if (blurExp.isImage) { blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer'; blurExp.content.title = hs.lang.focusTitle; } hs.fireEvent(blurExp, 'onBlur'); } } // focus this if (this.outline) this.outline.table.style.zIndex = this.wrapper.style.zIndex - 1; this.content.className = 'highslide-'+ this.contentType; if (this.isImage) { this.content.title = hs.lang.restoreTitle; if (hs.restoreCursor) { hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer'; if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand'; this.content.style.cursor = hs.styleRestoreCursor; } } hs.focusKey = this.key; hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); hs.fireEvent(this, 'onFocus'); }, moveTo: function(x, y) { this.x.setPos(x); this.y.setPos(y); }, resize : function (e) { var w, h, r = e.width / e.height; w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full)); if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full; h = this.isHtml ? e.height + e.dY : w / r; if (h < Math.min(this.minHeight, this.y.full)) { h = Math.min(this.minHeight, this.y.full); if (this.isImage) w = h * r; } this.resizeTo(w, h); }, resizeTo: function(w, h) { this.y.setSize(h); this.x.setSize(w); this.wrapper.style.height = this.y.get('wsize') +'px'; }, close : function() { if (this.isClosing || !this.isExpanded) return; if (this.transitions[1] == 'crossfade' && hs.upcoming) { hs.getExpander(hs.upcoming).cancelLoading(); hs.upcoming = null; } if (!hs.fireEvent(this, 'onBeforeClose')) return; this.isClosing = true; if (this.slideshow && !hs.upcoming) this.slideshow.pause(); hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler); try { if (this.isHtml) this.htmlPrepareClose(); this.content.style.cursor = 'default'; this.changeSize( 0, { wrapper: { width : this.x.t, height : this.y.t, left: this.x.tpos - this.x.cb + this.x.tb, top: this.y.tpos - this.y.cb + this.y.tb }, content: { left: 0, top: 0, width: this.x.t, height: this.y.t } }, hs.restoreDuration ); } catch (e) { this.afterClose(); } }, htmlPrepareClose : function() { if (hs.geckoMac) { // bad redraws if (!hs.mask) hs.mask = hs.createElement('div', null, { position: 'absolute' }, hs.container); hs.setStyles(hs.mask, { width: this.x.size +'px', height: this.y.size +'px', left: this.x.pos +'px', top: this.y.pos +'px', display: 'block' }); } if (this.objectType == 'swf') try { hs.$(this.body.id).StopPlay(); } catch (e) {} if (this.objectLoadTime == 'after' && !this.preserveContent) this.destroyObject(); if (this.scrollerDiv && this.scrollerDiv != this.scrollingContent) this.scrollerDiv.style.overflow = 'hidden'; }, destroyObject : function () { if (hs.ie && this.iframe) try { this.iframe.contentWindow.document.body.innerHTML = ''; } catch (e) {} if (this.objectType == 'swf') swfobject.removeSWF(this.body.id); this.body.innerHTML = ''; }, sleep : function() { if (this.outline) this.outline.table.style.display = 'none'; this.releaseMask = null; this.wrapper.style.display = 'none'; hs.push(hs.sleeping, this); }, awake : function() {try { hs.expanders[this.key] = this; if (!hs.allowMultipleInstances &&hs.focusKey != this.key) { try { hs.expanders[hs.focusKey].close(); } catch (e){} } var z = hs.zIndexCounter++, stl = { display: '', zIndex: z }; hs.setStyles (this.wrapper, stl); this.isClosing = false; var o = this.outline || 0; if (o) { if (!this.outlineWhileAnimating) stl.visibility = 'hidden'; hs.setStyles (o.table, stl); } if (this.slideshow) { this.initSlideshow(); } this.show(); } catch (e) {} }, createOverlay : function (o) { var el = o.overlayId, relToVP = (o.relativeTo == 'viewport' && !/panel$/.test(o.position)); if (typeof el == 'string') el = hs.getNode(el); if (o.html) el = hs.createElement('div', { innerHTML: o.html }); if (!el || typeof el == 'string') return; if (!hs.fireEvent(this, 'onCreateOverlay', { overlay: el })) return; el.style.display = 'block'; o.hsId = o.hsId || o.overlayId; if (this.transitions[1] == 'crossfade' && this.reuseOverlay(o, el)) return; this.genOverlayBox(); var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto'; if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px'; var overlay = hs.createElement( 'div', { id: 'hsId'+ hs.idCounter++, hsId: o.hsId }, { position: 'absolute', visibility: 'hidden', width: width, direction: hs.lang.cssDirection || '', opacity: 0 }, relToVP ? hs.viewport :this.overlayBox, true ); if (relToVP) overlay.hsKey = this.key; overlay.appendChild(el); hs.extend(overlay, { opacity: 1, offsetX: 0, offsetY: 0, dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250 }); hs.extend(overlay, o); if (this.gotOverlays) { this.positionOverlay(overlay); if (!overlay.hideOnMouseOut || this.mouseIsOver) hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur); } hs.push(this.overlays, hs.idCounter - 1); }, positionOverlay : function(overlay) { var p = overlay.position || 'middle center', relToVP = (overlay.relativeTo == 'viewport'), offX = overlay.offsetX, offY = overlay.offsetY; if (relToVP) { hs.viewport.style.display = 'block'; overlay.hsKey = this.key; if (overlay.offsetWidth > overlay.parentNode.offsetWidth) overlay.style.width = '100%'; } else if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay); if (/left$/.test(p)) overlay.style.left = offX +'px'; if (/center$/.test(p)) hs.setStyles (overlay, { left: '50%', marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px' }); if (/right$/.test(p)) overlay.style.right = - offX +'px'; if (/^leftpanel$/.test(p)) { hs.setStyles(overlay, { right: '100%', marginRight: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p1 = overlay.offsetWidth; } else if (/^rightpanel$/.test(p)) { hs.setStyles(overlay, { left: '100%', marginLeft: this.x.cb +'px', top: - this.y.cb +'px', bottom: - this.y.cb +'px', overflow: 'auto' }); this.x.p2 = overlay.offsetWidth; } var parOff = overlay.parentNode.offsetHeight; overlay.style.height = 'auto'; if (relToVP && overlay.offsetHeight > parOff) overlay.style.height = hs.ieLt7 ? parOff +'px' : '100%'; if (/^top/.test(p)) overlay.style.top = offY +'px'; if (/^middle/.test(p)) hs.setStyles (overlay, { top: '50%', marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px' }); if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px'; if (/^above$/.test(p)) { hs.setStyles(overlay, { left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', bottom: '100%', marginBottom: this.y.cb +'px', width: 'auto' }); this.y.p1 = overlay.offsetHeight; } else if (/^below$/.test(p)) { hs.setStyles(overlay, { position: 'relative', left: (- this.x.p1 - this.x.cb) +'px', right: (- this.x.p2 - this.x.cb) +'px', top: '100%', marginTop: this.y.cb +'px', width: 'auto' }); this.y.p2 = overlay.offsetHeight; overlay.style.position = 'absolute'; } }, getOverlays : function() { this.getInline(['heading', 'caption'], true); this.getNumber(); if (this.caption) hs.fireEvent(this, 'onAfterGetCaption'); if (this.heading) hs.fireEvent(this, 'onAfterGetHeading'); if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move'; if (hs.showCredits) this.writeCredits(); for (var i = 0; i < hs.overlays.length; i++) { var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup; if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId) || (sg && sg === this.slideshowGroup)) { if (this.isImage || (this.isHtml && o.useOnHtml)) this.createOverlay(o); } } var os = []; for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); if (/panel$/.test(o.position)) this.positionOverlay(o); else hs.push(os, o); } for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]); this.gotOverlays = true; }, genOverlayBox : function() { if (!this.overlayBox) this.overlayBox = hs.createElement ( 'div', { className: this.wrapperClassName }, { position : 'absolute', width: (this.x.size || (this.useBox ? this.width : null) || this.x.full) +'px', height: (this.y.size || this.y.full) +'px', visibility : 'hidden', overflow : 'hidden', zIndex : hs.ie ? 4 : 'auto' }, hs.container, true ); }, sizeOverlayBox : function(doWrapper, doPanels) { var overlayBox = this.overlayBox, x = this.x, y = this.y; hs.setStyles( overlayBox, { width: x.size +'px', height: y.size +'px' }); if (doWrapper || doPanels) { for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat'); if (o && /^(above|below)$/.test(o.position)) { if (ie6) { o.style.width = (overlayBox.offsetWidth + 2 * x.cb + x.p1 + x.p2) +'px'; } y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight; } if (o && ie6 && /^(left|right)panel$/.test(o.position)) { o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px'; } } } if (doWrapper) { hs.setStyles(this.content, { top: y.p1 +'px' }); hs.setStyles(overlayBox, { top: (y.p1 + y.cb) +'px' }); } }, showOverlays : function() { var b = this.overlayBox; b.className = ''; hs.setStyles(b, { top: (this.y.p1 + this.y.cb) +'px', left: (this.x.p1 + this.x.cb) +'px', overflow : 'visible' }); if (hs.safari) b.style.visibility = 'visible'; this.wrapper.appendChild (b); for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); o.style.zIndex = o.hsId == 'controls' ? 5 : 4; if (!o.hideOnMouseOut || this.mouseIsOver) { o.style.visibility = 'visible'; hs.setStyles(o, { visibility: 'visible', display: '' }); hs.animate(o, { opacity: o.opacity }, o.dur); } } }, destroyOverlays : function() { if (!this.overlays.length) return; if (this.slideshow) { var c = this.slideshow.controls; if (c && hs.getExpander(c) == this) c.parentNode.removeChild(c); } for (var i = 0; i < this.overlays.length; i++) { var o = hs.$('hsId'+ this.overlays[i]); if (o && o.parentNode == hs.viewport && hs.getExpander(o) == this) hs.discardElement(o); } if (this.isHtml && this.preserveContent) { this.overlayBox.style.top = '-9999px'; hs.container.appendChild(this.overlayBox); } else hs.discardElement(this.overlayBox); }, createFullExpand : function () { if (this.slideshow && this.slideshow.controls) { this.slideshow.enable('full-expand'); return; } this.fullExpandLabel = hs.createElement( 'a', { href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();', title: hs.lang.fullExpandTitle, className: 'highslide-full-expand' } ); if (!hs.fireEvent(this, 'onCreateFullExpand')) return; this.createOverlay({ overlayId: this.fullExpandLabel, position: hs.fullExpandPosition, hideOnMouseOut: true, opacity: hs.fullExpandOpacity }); }, doFullExpand : function () { try { if (!hs.fireEvent(this, 'onDoFullExpand')) return; if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel); this.focus(); var xSize = this.x.size; this.resizeTo(this.x.full, this.y.full); var xpos = this.x.pos - (this.x.size - xSize) / 2; if (xpos < hs.marginLeft) xpos = hs.marginLeft; this.moveTo(xpos, this.y.pos); this.doShowHide('hidden'); } catch (e) { this.error(e); } }, afterClose : function () { this.a.className = this.a.className.replace('highslide-active-anchor', ''); this.doShowHide('visible'); if (this.isHtml && this.preserveContent && this.transitions[1] != 'crossfade') { this.sleep(); } else { if (this.outline && this.outlineWhileAnimating) this.outline.destroy(); hs.discardElement(this.wrapper); } if (hs.mask) hs.mask.style.display = 'none'; this.destroyOverlays(); if (!hs.viewport.childNodes.length) hs.viewport.style.display = 'none'; if (this.dimmingOpacity) hs.undim(this.key); hs.fireEvent(this, 'onAfterClose'); hs.expanders[this.key] = null; hs.reOrder(); } }; // hs.Ajax object prototype hs.Ajax = function (a, content, pre) { this.a = a; this.content = content; this.pre = pre; }; hs.Ajax.prototype = { run : function () { var xhr; if (!this.src) this.src = hs.getSrc(this.a); if (this.src.match('#')) { var arr = this.src.split('#'); this.src = arr[0]; this.id = arr[1]; } if (hs.cachedGets[this.src]) { this.cachedGet = hs.cachedGets[this.src]; if (this.id) this.getElementContent(); else this.loadHTML(); return; } try { xhr = new XMLHttpRequest(); } catch (e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { this.onError(); } } } var pThis = this; xhr.onreadystatechange = function() { if(pThis.xhr.readyState == 4) { if (pThis.id) pThis.getElementContent(); else pThis.loadHTML(); } }; var src = this.src; this.xhr = xhr; if (hs.forceAjaxReload) src = src.replace(/$/, (/\?/.test(src) ? '&' : '?') +'dummy='+ (new Date()).getTime()); xhr.open('GET', src, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(null); }, getElementContent : function() { hs.init(); var attribs = window.opera || hs.ie6SSL ? { src: 'about:blank' } : null; this.iframe = hs.createElement('iframe', attribs, { position: 'absolute', top: '-9999px' }, hs.container); this.loadHTML(); }, loadHTML : function() { var s = this.cachedGet || this.xhr.responseText, regBody; if (this.pre) hs.cachedGets[this.src] = s; if (!hs.ie || hs.uaVersion >= 5.5) { s = s.replace(new RegExp('<link[^>]*>', 'gi'), '') .replace(new RegExp('<script[^>]*>.*?</script>', 'gi'), ''); if (this.iframe) { var doc = this.iframe.contentDocument; if (!doc && this.iframe.contentWindow) doc = this.iframe.contentWindow.document; if (!doc) { // Opera var pThis = this; setTimeout(function() { pThis.loadHTML(); }, 25); return; } doc.open(); doc.write(s); doc.close(); try { s = doc.getElementById(this.id).innerHTML; } catch (e) { try { s = this.iframe.document.getElementById(this.id).innerHTML; } catch (e) {} // opera } hs.discardElement(this.iframe); } else { regBody = /(<body[^>]*>|<\/body>)/ig; if (regBody.test(s)) s = s.split(regBody)[hs.ie ? 1 : 2]; } } hs.getElementByClass(this.content, 'DIV', 'highslide-body').innerHTML = s; this.onLoad(); for (var x in this) this[x] = null; } }; hs.Slideshow = function (expKey, options) { if (hs.dynamicallyUpdateAnchors !== false) hs.updateAnchors(); this.expKey = expKey; for (var x in options) this[x] = options[x]; if (this.useControls) this.getControls(); if (this.thumbstrip) this.thumbstrip = hs.Thumbstrip(this); }; hs.Slideshow.prototype = { getControls: function() { this.controls = hs.createElement('div', { innerHTML: hs.replaceLang(hs.skin.controls) }, null, hs.container); var buttons = ['play', 'pause', 'previous', 'next', 'move', 'full-expand', 'close']; this.btn = {}; var pThis = this; for (var i = 0; i < buttons.length; i++) { this.btn[buttons[i]] = hs.getElementByClass(this.controls, 'li', 'highslide-'+ buttons[i]); this.enable(buttons[i]); } this.btn.pause.style.display = 'none'; //this.disable('full-expand'); }, checkFirstAndLast: function() { if (this.repeat || !this.controls) return; var exp = hs.expanders[this.expKey], cur = exp.getAnchorIndex(), re = /disabled$/; if (cur == 0) this.disable('previous'); else if (re.test(this.btn.previous.getElementsByTagName('a')[0].className)) this.enable('previous'); if (cur + 1 == hs.anchors.groups[exp.slideshowGroup || 'none'].length) { this.disable('next'); this.disable('play'); } else if (re.test(this.btn.next.getElementsByTagName('a')[0].className)) { this.enable('next'); this.enable('play'); } }, enable: function(btn) { if (!this.btn) return; var sls = this, a = this.btn[btn].getElementsByTagName('a')[0], re = /disabled$/; a.onclick = function() { sls[btn](); return false; }; if (re.test(a.className)) a.className = a.className.replace(re, ''); }, disable: function(btn) { if (!this.btn) return; var a = this.btn[btn].getElementsByTagName('a')[0]; a.onclick = function() { return false; }; if (!/disabled$/.test(a.className)) a.className += ' disabled'; }, hitSpace: function() { if (this.autoplay) this.pause(); else this.play(); }, play: function(wait) { if (this.btn) { this.btn.play.style.display = 'none'; this.btn.pause.style.display = ''; } this.autoplay = true; if (!wait) hs.next(this.expKey); }, pause: function() { if (this.btn) { this.btn.pause.style.display = 'none'; this.btn.play.style.display = ''; } clearTimeout(this.autoplay); this.autoplay = null; }, previous: function() { this.pause(); hs.previous(this.btn.previous); }, next: function() { this.pause(); hs.next(this.btn.next); }, move: function() {}, 'full-expand': function() { hs.getExpander().doFullExpand(); }, close: function() { hs.close(this.btn.close); } }; hs.Thumbstrip = function(slideshow) { function add (exp) { hs.extend(options || {}, { overlayId: dom, hsId: 'thumbstrip', className: 'highslide-thumbstrip-'+ mode +'-overlay ' + (options.className || '') }); if (hs.ieLt7) options.fade = 0; exp.createOverlay(options); hs.setStyles(dom.parentNode, { overflow: 'hidden' }); }; function scroll (delta) { selectThumb(undefined, Math.round(delta * dom[isX ? 'offsetWidth' : 'offsetHeight'] * 0.7)); }; function selectThumb (i, scrollBy) { if (i === undefined) for (var j = 0; j < group.length; j++) { if (group[j] == hs.expanders[slideshow.expKey].a) { i = j; break; } } if (i === undefined) return; var as = dom.getElementsByTagName('a'), active = as[i], cell = active.parentNode, left = isX ? 'Left' : 'Top', right = isX ? 'Right' : 'Bottom', width = isX ? 'Width' : 'Height', offsetLeft = 'offset' + left, offsetWidth = 'offset' + width, overlayWidth = div.parentNode.parentNode[offsetWidth], minTblPos = overlayWidth - table[offsetWidth], curTblPos = parseInt(table.style[isX ? 'left' : 'top']) || 0, tblPos = curTblPos, mgnRight = 20; if (scrollBy !== undefined) { tblPos = curTblPos - scrollBy; if (minTblPos > 0) minTblPos = 0; if (tblPos > 0) tblPos = 0; if (tblPos < minTblPos) tblPos = minTblPos; } else { for (var j = 0; j < as.length; j++) as[j].className = ''; active.className = 'highslide-active-anchor'; var activeLeft = i > 0 ? as[i - 1].parentNode[offsetLeft] : cell[offsetLeft], activeRight = cell[offsetLeft] + cell[offsetWidth] + (as[i + 1] ? as[i + 1].parentNode[offsetWidth] : 0); if (activeRight > overlayWidth - curTblPos) tblPos = overlayWidth - activeRight; else if (activeLeft < -curTblPos) tblPos = -activeLeft; } var markerPos = cell[offsetLeft] + (cell[offsetWidth] - marker[offsetWidth]) / 2 + tblPos; hs.animate(table, isX ? { left: tblPos } : { top: tblPos }, null, 'easeOutQuad'); hs.animate(marker, isX ? { left: markerPos } : { top: markerPos }, null, 'easeOutQuad'); scrollUp.style.display = tblPos < 0 ? 'block' : 'none'; scrollDown.style.display = (tblPos > minTblPos) ? 'block' : 'none'; }; // initialize var group = hs.anchors.groups[hs.expanders[slideshow.expKey].slideshowGroup || 'none'], options = slideshow.thumbstrip, mode = options.mode || 'horizontal', floatMode = (mode == 'float'), tree = floatMode ? ['div', 'ul', 'li', 'span'] : ['table', 'tbody', 'tr', 'td'], isX = (mode == 'horizontal'), dom = hs.createElement('div', { className: 'highslide-thumbstrip highslide-thumbstrip-'+ mode, innerHTML: '<div class="highslide-thumbstrip-inner">'+ '<'+ tree[0] +'><'+ tree[1] +'></'+ tree[1] +'></'+ tree[0] +'></div>'+ '<div class="highslide-scroll-up"><div></div></div>'+ '<div class="highslide-scroll-down"><div></div></div>'+ '<div class="highslide-marker"><div></div></div>' }, { display: 'none' }, hs.container), domCh = dom.childNodes, div = domCh[0], scrollUp = domCh[1], scrollDown = domCh[2], marker = domCh[3], table = div.firstChild, tbody = dom.getElementsByTagName(tree[1])[0], tr; for (var i = 0; i < group.length; i++) { if (i == 0 || !isX) tr = hs.createElement(tree[2], null, null, tbody); (function(){ var a = group[i], cell = hs.createElement(tree[3], null, null, tr), pI = i; hs.createElement('a', { href: a.href, onclick: function() { hs.getExpander(this).focus(); return hs.transit(a); }, innerHTML: hs.stripItemFormatter ? hs.stripItemFormatter(a) : a.innerHTML }, null, cell); })(); } if (!floatMode) { scrollUp.onclick = function () { scroll(-1); }; scrollDown.onclick = function() { scroll(1); }; hs.addEventListener(tbody, document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll', function(e) { var delta = 0; e = e || window.event; if (e.wheelDelta) { delta = e.wheelDelta/120; if (hs.opera) delta = -delta; } else if (e.detail) { delta = -e.detail/3; } if (delta) scroll(-delta * 0.2); if (e.preventDefault) e.preventDefault(); e.returnValue = false; }); } return { add: add, selectThumb: selectThumb } }; hs.langDefaults = hs.lang; // history var HsExpander = hs.Expander; if (hs.ie) { (function () { try { document.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } hs.ready(); })(); } hs.addEventListener(document, 'DOMContentLoaded', hs.ready); hs.addEventListener(window, 'load', hs.ready); // set handlers hs.addEventListener(document, 'ready', function() { if (hs.expandCursor || hs.dimmingOpacity) { var style = hs.createElement('style', { type: 'text/css' }, null, document.getElementsByTagName('HEAD')[0]); function addRule(sel, dec) { if (!hs.ie) { style.appendChild(document.createTextNode(sel + " {" + dec + "}")); } else { var last = document.styleSheets[document.styleSheets.length - 1]; if (typeof(last.addRule) == "object") last.addRule(sel, dec); } } function fix(prop) { return 'expression( ( ( ignoreMe = document.documentElement.'+ prop + ' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );'; } if (hs.expandCursor) addRule ('.highslide img', 'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;'); addRule ('.highslide-viewport-size', hs.ie && (hs.uaVersion < 7 || document.compatMode == 'BackCompat') ? 'position: absolute; '+ 'left:'+ fix('scrollLeft') + 'top:'+ fix('scrollTop') + 'width:'+ fix('clientWidth') + 'height:'+ fix('clientHeight') : 'position: fixed; width: 100%; height: 100%; left: 0; top: 0'); } }); hs.addEventListener(window, 'resize', function() { hs.getPageSize(); if (hs.viewport) for (var i = 0; i < hs.viewport.childNodes.length; i++) { var node = hs.viewport.childNodes[i], exp = hs.getExpander(node); exp.positionOverlay(node); if (node.hsId == 'thumbstrip') exp.slideshow.thumbstrip.selectThumb(); } }); hs.addEventListener(document, 'mousemove', function(e) { hs.mouse = { x: e.clientX, y: e.clientY }; }); hs.addEventListener(document, 'mousedown', hs.mouseClickHandler); hs.addEventListener(document, 'mouseup', hs.mouseClickHandler); hs.addEventListener(document, 'ready', hs.setClickEvents); hs.addEventListener(window, 'load', hs.preloadImages); hs.addEventListener(window, 'load', hs.preloadAjax); }
JavaScript
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. var Scriptaculous = { Version: '1.5.1', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"></script>'); }, load: function() { if((typeof Prototype=='undefined') || parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) < 1.4) throw("script.aculo.us requires the Prototype JavaScript framework >= 1.4.0"); $A(document.getElementsByTagName("script")).findAll( function(s) { return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/)) }).each( function(s) { var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,''); var includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } } Scriptaculous.load();
JavaScript
module.exports = function( grunt ) { "use strict"; var // files coreFiles = [ "jquery.ui.core.js", "jquery.ui.widget.js", "jquery.ui.mouse.js", "jquery.ui.draggable.js", "jquery.ui.droppable.js", "jquery.ui.resizable.js", "jquery.ui.selectable.js", "jquery.ui.sortable.js", "jquery.ui.effect.js" ], uiFiles = coreFiles.map(function( file ) { return "ui/" + file; }).concat( grunt.file.expandFiles( "ui/*.js" ).filter(function( file ) { return coreFiles.indexOf( file.substring(3) ) === -1; })), allI18nFiles = grunt.file.expandFiles( "ui/i18n/*.js" ), cssFiles = [ "core", "accordion", "autocomplete", "button", "datepicker", "dialog", "menu", "progressbar", "resizable", "selectable", "slider", "spinner", "tabs", "tooltip", "theme" ].map(function( component ) { return "themes/base/jquery.ui." + component + ".css"; }), // minified files minify = { "dist/jquery-ui.min.js": [ "<banner:meta.bannerAll>", "dist/jquery-ui.js" ], "dist/i18n/jquery-ui-i18n.min.js": [ "<banner:meta.bannerI18n>", "dist/i18n/jquery-ui-i18n.js" ] }, minifyCSS = { "dist/jquery-ui.min.css": "dist/jquery-ui.css" }, compareFiles = { all: [ "dist/jquery-ui.js", "dist/jquery-ui.min.js" ] }; function mapMinFile( file ) { return "dist/" + file.replace( /\.js$/, ".min.js" ).replace( /ui\//, "minified/" ); } uiFiles.concat( allI18nFiles ).forEach(function( file ) { minify[ mapMinFile( file ) ] = [ "<banner>", file ]; }); cssFiles.forEach(function( file ) { minifyCSS[ "dist/" + file.replace( /\.css$/, ".min.css" ).replace( /themes\/base\//, "themes/base/minified/" ) ] = [ "<banner>", "<strip_all_banners:" + file + ">" ]; }); uiFiles.forEach(function( file ) { compareFiles[ file ] = [ file, mapMinFile( file ) ]; }); // grunt plugins grunt.loadNpmTasks( "grunt-css" ); grunt.loadNpmTasks( "grunt-html" ); grunt.loadNpmTasks( "grunt-compare-size" ); grunt.loadNpmTasks( "grunt-junit" ); grunt.loadNpmTasks( "grunt-git-authors" ); // local testswarm and build tasks grunt.loadTasks( "build/tasks" ); grunt.registerHelper( "strip_all_banners", function( filepath ) { return grunt.file.read( filepath ).replace( /^\s*\/\*[\s\S]*?\*\/\s*/g, "" ); }); function stripBanner( files ) { return files.map(function( file ) { return "<strip_all_banners:" + file + ">"; }); } function stripDirectory( file ) { // TODO: we're receiving the directive, so we need to strip the trailing > // we should be receving a clean path without the directive return file.replace( /.+\/(.+?)>?$/, "$1" ); } // allow access from banner template global.stripDirectory = stripDirectory; function createBanner( files ) { // strip folders var fileNames = files && files.map( stripDirectory ); return "/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - " + "<%= grunt.template.today('isoDate') %>\n" + "<%= pkg.homepage ? '* ' + pkg.homepage + '\n' : '' %>" + "* Includes: " + (files ? fileNames.join(", ") : "<%= stripDirectory(grunt.task.current.file.src[1]) %>") + "\n" + "* Copyright <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>;" + " Licensed <%= _.pluck(pkg.licenses, 'type').join(', ') %> */"; } grunt.initConfig({ pkg: "<json:package.json>", files: { dist: "<%= pkg.name %>-<%= pkg.version %>", cdn: "<%= pkg.name %>-<%= pkg.version %>-cdn", themes: "<%= pkg.name %>-themes-<%= pkg.version %>" }, meta: { banner: createBanner(), bannerAll: createBanner( uiFiles ), bannerI18n: createBanner( allI18nFiles ), bannerCSS: createBanner( cssFiles ) }, compare_size: compareFiles, concat: { ui: { src: [ "<banner:meta.bannerAll>", stripBanner( uiFiles ) ], dest: "dist/jquery-ui.js" }, i18n: { src: [ "<banner:meta.bannerI18n>", allI18nFiles ], dest: "dist/i18n/jquery-ui-i18n.js" }, css: { src: [ "<banner:meta.bannerCSS>", stripBanner( cssFiles ) ], dest: "dist/jquery-ui.css" } }, min: minify, cssmin: minifyCSS, htmllint: { // ignore files that contain invalid html, used only for ajax content testing all: grunt.file.expand( [ "demos/**/*.html", "tests/**/*.html" ] ).filter(function( file ) { return !/(?:ajax\/content\d\.html|tabs\/data\/test\.html|tests\/unit\/core\/core\.html)/.test( file ); }) }, copy: { dist: { src: [ "AUTHORS.txt", "jquery-*.js", "MIT-LICENSE.txt", "README.md", "grunt.js", "package.json", "*.jquery.json", "ui/**/*", "ui/.jshintrc", "demos/**/*", "themes/**/*", "external/**/*", "tests/**/*" ], renames: { "dist/jquery-ui.js": "ui/jquery-ui.js", "dist/jquery-ui.min.js": "ui/minified/jquery-ui.min.js", "dist/i18n/jquery-ui-i18n.js": "ui/i18n/jquery-ui-i18n.js", "dist/i18n/jquery-ui-i18n.min.js": "ui/minified/i18n/jquery-ui-i18n.min.js", "dist/jquery-ui.css": "themes/base/jquery-ui.css", "dist/jquery-ui.min.css": "themes/base/minified/jquery-ui.min.css" }, dest: "dist/<%= files.dist %>" }, dist_min: { src: "dist/minified/**/*", strip: /^dist/, dest: "dist/<%= files.dist %>/ui" }, dist_css_min: { src: "dist/themes/base/minified/*.css", strip: /^dist/, dest: "dist/<%= files.dist %>" }, dist_units_images: { src: "themes/base/images/*", strip: /^themes\/base\//, dest: "dist/" }, dist_min_images: { src: "themes/base/images/*", strip: /^themes\/base\//, dest: "dist/<%= files.dist %>/themes/base/minified" }, cdn: { src: [ "AUTHORS.txt", "MIT-LICENSE.txt", "ui/*.js", "package.json" ], renames: { "dist/jquery-ui.js": "jquery-ui.js", "dist/jquery-ui.min.js": "jquery-ui.min.js", "dist/i18n/jquery-ui-i18n.js": "i18n/jquery-ui-i18n.js", "dist/i18n/jquery-ui-i18n.min.js": "i18n/jquery-ui-i18n.min.js", "dist/jquery-ui.css": "themes/base/jquery-ui.css", "dist/jquery-ui.min.css": "themes/base/minified/jquery-ui.min.css" }, dest: "dist/<%= files.cdn %>" }, cdn_i18n: { src: "ui/i18n/jquery.ui.datepicker-*.js", strip: "ui/", dest: "dist/<%= files.cdn %>" }, cdn_i18n_min: { src: "dist/minified/i18n/jquery.ui.datepicker-*.js", strip: "dist/minified", dest: "dist/<%= files.cdn %>" }, cdn_min: { src: "dist/minified/*.js", strip: /^dist\/minified/, dest: "dist/<%= files.cdn %>/ui" }, cdn_min_images: { src: "themes/base/images/*", strip: /^themes\/base\//, dest: "dist/<%= files.cdn %>/themes/base/minified" }, cdn_themes: { src: "dist/<%= files.themes %>/themes/**/*", strip: "dist/<%= files.themes %>", dest: "dist/<%= files.cdn %>" }, themes: { src: [ "AUTHORS.txt", "MIT-LICENSE.txt", "package.json" ], dest: "dist/<%= files.themes %>" } }, zip: { dist: { src: "<%= files.dist %>", dest: "<%= files.dist %>.zip" }, cdn: { src: "<%= files.cdn %>", dest: "<%= files.cdn %>.zip" }, themes: { src: "<%= files.themes %>", dest: "<%= files.themes %>.zip" } }, md5: { dist: { src: "dist/<%= files.dist %>", dest: "dist/<%= files.dist %>/MANIFEST" }, cdn: { src: "dist/<%= files.cdn %>", dest: "dist/<%= files.cdn %>/MANIFEST" }, themes: { src: "dist/<%= files.themes %>", dest: "dist/<%= files.themes %>/MANIFEST" } }, qunit: { files: grunt.file.expandFiles( "tests/unit/**/*.html" ).filter(function( file ) { // disabling everything that doesn't (quite) work with PhantomJS for now // TODO except for all|index|test, try to include more as we go return !( /(all|all-active|index|test|draggable|droppable|selectable|resizable|sortable|dialog|slider|datepicker|tabs|tabs_deprecated|tooltip)\.html$/ ).test( file ); }) }, lint: { ui: grunt.file.expandFiles( "ui/*.js" ).filter(function( file ) { // TODO remove items from this list once rewritten return !( /(mouse|datepicker|draggable|droppable|resizable|selectable|sortable)\.js$/ ).test( file ); }), grunt: [ "grunt.js", "build/**/*.js" ], tests: "tests/unit/**/*.js" }, csslint: { // nothing: [] // TODO figure out what to check for, then fix and enable base_theme: { src: grunt.file.expandFiles( "themes/base/*.css" ).filter(function( file ) { // TODO remove items from this list once rewritten return !( /(button|datepicker|core|dialog|theme)\.css$/ ).test( file ); }), // TODO consider reenabling some of these rules rules: { "import": false, "important": false, "outline-none": false, // especially this one "overqualified-elements": false, "compatible-vendor-prefixes": false } } }, jshint: (function() { function parserc( path ) { var rc = grunt.file.readJSON( (path || "") + ".jshintrc" ), settings = { options: rc, globals: {} }; (rc.predef || []).forEach(function( prop ) { settings.globals[ prop ] = true; }); delete rc.predef; return settings; } return { grunt: parserc(), ui: parserc( "ui/" ), // TODO: `evil: true` is only for document.write() https://github.com/jshint/jshint/issues/519 // TODO: don't create so many globals in tests tests: parserc( "tests/" ) }; })() }); grunt.registerTask( "default", "lint csslint htmllint qunit" ); grunt.registerTask( "sizer", "concat:ui min:dist/jquery-ui.min.js compare_size:all" ); grunt.registerTask( "sizer_all", "concat:ui min compare_size" ); grunt.registerTask( "build", "concat min cssmin copy:dist_units_images" ); grunt.registerTask( "release", "clean build copy:dist copy:dist_min copy:dist_min_images copy:dist_css_min md5:dist zip:dist" ); grunt.registerTask( "release_themes", "release generate_themes copy:themes md5:themes zip:themes" ); grunt.registerTask( "release_cdn", "release_themes copy:cdn copy:cdn_min copy:cdn_i18n copy:cdn_i18n_min copy:cdn_min_images copy:cdn_themes md5:cdn zip:cdn" ); };
JavaScript
var Flasher = { /* * This function takes the id of an element and animates it's background colour from * black to white. Once the color is white, the animation is stopped and the original * colour of the element is restored. * * NOTE: Several things need to be fixed before it works... */ flash: function(id, original_colour) { var e = document.getElementById(id); var colour = 0; id = setInterval(function() { colour += 5; e.style.backgroundColor = "#"+ colour.toString(16) + colour.toString(16) + colour.toString(16); if (colour == 250) { clearInterval(id); e.style.backgroundColor = original_colour; } }, 5); } }
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ $(document).ready(function() { MenuBar.enableHover(); //Menu.showMenu(param); }); /* * Inspect the ihtml/ directory in the ria.zip archive and then add it to the project. When initializing the menu, you should dynamically add the content of each drop- down_* le into one of the above div's. To do this, you can use: a) $.ajax() b) $(*).load() - Simpler to use, but $.ajax() gives you additional control. * * For each entry in the drop down, you need to register a click event. Whenever the user clicks on an item in the drop down menu, you should populate the bottom div with an appropriate text from the ihtml/ directory by using one of the calls described in {6.4}. This time around though, a problem exists. Because the div's we added are populated dynamically using AJAX, there is no guarantee that the newly loaded content has been added to the DOM when we call $(*).click(). The solution to this problem is to use $(*).live(). Refer to the JQuery documentation for more information. * */ var shownDropDown = 0; var timeout = 200; var closetimer = 0; var MenuBar = { enableHover:function() { /* * Load contents of dropdowns into respective menus */ $('#fruits_dropdown').load('ihtml/dropdown_fruits.ihtml'); $('#vegetables_dropdown').load('ihtml/dropdown_vegetables.ihtml'); $('#nuts_dropdown').load('ihtml/dropdown_nuts.ihtml'); /* * Register onclick for all the buttons */ $('ul.dropdown #apple').live('click', function() { registerClick("apple"); }); $('ul.dropdown #banana').live('click', function() { registerClick("banana"); }); $('ul.dropdown #cashew').live('click', function() { registerClick("cashew"); }); $('ul.dropdown #pecan').live('click', function() { registerClick("pecan"); }); $('ul.dropdown #lettuce').live('click', function() { registerClick("lettuce"); }); $('ul.dropdown #tomato').live('click', function() { registerClick("tomato"); }); /* * Register hover for menu buttons */ $("#fruits_button").hover(function() { placeDropDown("#fruits_button", "#fruits_dropdown"); showDropDown("#fruits_dropdown"); }, function() { startCloseTimer(); }); $("#vegetables_button").hover(function() { placeDropDown("#vegetables_button", "#vegetables_dropdown"); showDropDown("#vegetables_dropdown"); }, function() { startCloseTimer(); }); $("#nuts_button").hover(function() { placeDropDown("#nuts_button", "#nuts_dropdown"); showDropDown("#nuts_dropdown"); }, function() { startCloseTimer(); }); } } var registerClick = function(param) { $('#content').load("/EncylopediaServlet", {what: param}); } var showDropDown = function(dropdown) { cancelCloseTimer(); closeDropDown(); shownDropDown = $(dropdown); shownDropDown.css("visibility", "visible"); shownDropDown.mouseenter(cancelCloseTimer); shownDropDown.mouseleave(startCloseTimer); } var placeDropDown = function(button,dropdown) { var pos = $(button).offset(); var height = $(button).height(); $(dropdown).css( {"left": (pos.left ) + "px", "top" : (pos.top + height) + "px"} ); }; // closes drop down function closeDropDown() { if(shownDropDown) shownDropDown.css("visibility", "hidden"); } // go close timer function startCloseTimer() { closetimer = window.setTimeout(closeDropDown, timeout); } // cancel close timer function cancelCloseTimer() { if(closetimer) { window.clearTimeout(closetimer); closetimer = null; } } var Menu = { showMenu:function(param) { $(param).load(); } }
JavaScript
/* Here, you should not change anything else than the argument in the call below */ addLoadEvent(function() { Lighten.lightenElement('bottom'); }) var Lighten = { /* * Takes an id to an element and brightens its colour a notch... * You should implement the lightenElement(id) function. */ lightenElement: function(id) { var element = document.getElementById(id); var color = new RGB(window.getComputedStyle(element,null) .backgroundColor); element.onmouseout = function() { element.style.backgroundColor = color.getHex(); } element.onmouseover = function() { color2 = new RGB(window.getComputedStyle(element,null) .backgroundColor); color2.addRGB(30, 30, 30); element.style.backgroundColor = color2.getHex(); } } }
JavaScript
/* * Taken from * http://developer.expressionz.in/blogs/2009/03/07/calling-multiple-windows-onload-functions-in-javascript/ */ function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func } else { window.onload = function() { if (oldonload) { oldonload() } func() } } } /* * A working solution, but * not very good... */ //window.onload = function() { // Darken.darkenElement('topleft'); // Lighten.lightenElement('bottom'); //} /* * To change this template, choose Tools | Templates * and open the template in the editor. */
JavaScript
/* Here, you should not change anything else than the argument in the call below */ $(document).ready(function(){ Lighten.lightenElement('#bottom'); }); var Lighten = { /* * Takes an id to an element and brightens its colour a notch... * You should implement the lightenElement(id) function. */ lightenElement: function(id) { var color = $(id).css('backgroundColor'); var color2 = new RGB(color); color2.addRGB(30, 30, 30); $(id).hover( function(){$(id).css("backgroundColor",color2.getHex());}, function(){$(id).css("backgroundColor",color);} ); } }
JavaScript
/* Here, you should not change anything else than the argument in the call below */ /* * The problem with darken and lighten is: * window.onload can't be executed in both * */ $(document).ready(function() { Darken.darkenElement('#topleft'); }); var Darken = { /* * Takes an id to an element and darkens its colour a notch... * You should implement the darkenElement(id) function. */ darkenElement: function(id) { var color = $(id).css('backgroundColor'); var color2 = new RGB(color); color2.subRGB(30, 30, 30); $(id).hover( function(){$(id).css("backgroundColor",color2.getHex());}, function(){$(id).css("backgroundColor",color);} ); } }
JavaScript