code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 )
{
iterator.EnforceRealBlocks = true ;
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() ;
}
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 = [] ;
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 ;
}
if ( bqParent && bqChild )
moveOutNodes.push( bqChild ) ;
}
var movedNodes = [] ;
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 ) ;
if ( ! bqBlock.firstChild )
bqBlock.parentNode.removeChild( bqBlock ) ;
}
else if ( node == node.parentNode.lastChild )
{
bqBlock.parentNode.insertBefore( bqBlock.removeChild( node ), bqBlock.nextSibling ) ;
if ( ! bqBlock.firstChild )
bqBlock.parentNode.removeChild( bqBlock ) ;
}
else
FCKDomTools.BreakParent( node, node.parentNode, range ) ;
movedNodes.push( node ) ;
}
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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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, null, 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, 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"> </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 ;
}
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( ' ' ) ;
},
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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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.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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 = new FCKDomRange( FCK.EditorWindow ) ;
oRange.MoveToSelection() ;
var oEditorScrollPos = FCKTools.GetScrollPosition( FCK.EditorWindow ) ;
// 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.
oRange.Select() ;
FCK.EditorWindow.scrollTo( oEditorScrollPos.X, oEditorScrollPos.Y ) ;
}
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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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
innerHTML = innerHTML.replace( /^[ \t]+|[ \t]+$/g, function( match, offset, s )
{
if ( match.length == 1 ) // one space, preserve it
return ' ' ;
else if ( offset == 0 ) // beginning of block
return new Array( match.length ).join( ' ' ) + ' ' ;
else // end of block
return ' ' + new Array( match.length ).join( ' ' ) ;
} ) ;
// 2. Convert \n to <BR>.
// 3. Convert contiguous (i.e. non-singular) spaces or tabs to
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( ' ' ) + ' ' ;
} ) ;
}
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 to spaces since 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]+| )/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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 ) ;
}
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 ( this.IsRTL )
{
if ( this.IsContextMenu )
x = x - iMainWidth + 1 ;
else if ( relElement )
x = ( x * -1 ) + relElement.offsetWidth - iMainWidth ;
}
// 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 ;
FCKTools.RunFunction( this.OnHide, this ) ;
}
}
function FCKPanel_Cleanup()
{
this._Popup = null ;
this._Window = null ;
this.Document = null ;
this.MainNode = null ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 = ' ' ;
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 ) ? ' ' : 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> </label></td><td class="SC_FieldButton"> </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;"> </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;"> </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> </label></td>
<td class="SC_FieldButton"> </td>
</tr>
</tbody>
</table>
</div>
*/
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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.
' ' +
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 )
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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 )
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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This 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 ) ;
}
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 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 = ' ' ;
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 = ' ' ;
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 && addrStart.nodeType == 3 )
{
bookmark.Start[0] += curStart.length ;
addrStart = curStart ;
curStart = curStart.previousSibling ;
}
while ( curEnd && 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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 bIsStartMakerAlone ;
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
{
bIsStartMakerAlone = ( forceExpand || !eStartMarker.previousSibling || eStartMarker.previousSibling.nodeName.toLowerCase() == 'br' ) && !eStartMarker.nextSibing ;
// Append a temporary <span></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 = '' ; // Zero Width No-Break Space (U+FEFF). See #1359.
eStartMarker.parentNode.insertBefore( dummySpan, eStartMarker ) ;
if ( bIsStartMakerAlone )
{
// 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 ( bIsStartMakerAlone )
{
// Move the selection start to include the temporary .
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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Editor configuration settings.
*
* Follow this link for more information:
* http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options
*/
FCKConfig.CustomConfigurationsPath = '' ;
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;
FCKConfig.EditorAreaStyles = '' ;
FCKConfig.ToolbarComboPreviewCSS = '' ;
FCKConfig.DocType = '' ;
FCKConfig.BaseHref = '' ;
FCKConfig.FullPage = false ;
// The following option determines whether the "Show Blocks" feature is enabled or not at startup.
FCKConfig.StartupShowBlocks = false ;
FCKConfig.Debug = false ;
FCKConfig.AllowQueryStringDebug = true ;
FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/silver/' ;
FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ;
FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ;
// FCKConfig.Plugins.Add( 'autogrow' ) ;
// FCKConfig.Plugins.Add( 'dragresizetable' );
FCKConfig.AutoGrowMax = 400 ;
// FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // 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 = 'encode' ; // 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["HSCMS"] = [
['Cut','Copy','Paste','PasteText','PasteWord','RemoveFormat'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
['Link','Unlink','Anchor'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['TextColor','BGColor'],
'/',
['Style','FontFormat','FontName','FontSize'],
['Source','Preview'] // No comma for the last row.
] ;
FCKConfig.ToolbarSets["HSCMS_Basic"] = [
['Cut','Copy','PasteText'],
['Bold','Italic','Underline'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','TextColor','BGColor'],
['Style','FontFormat','FontName','FontSize'],['Source','Preview']
];
FCKConfig.ToolbarSets["HSCMS_Small"] = [
['Bold','Italic','Underline'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','TextColor','BGColor'],
['FontFormat','FontName','FontSize']
];
FCKConfig.ToolbarSets["Basic"] = [
['-','Superscript','-']
] ;
FCKConfig.EnterMode = 'p' ; // p | div | br
FCKConfig.ShiftEnterMode = 'br' ; // p | div | br
//var proto = FCKEnterKey.prototype;
//FCKEnterKey = function( targetWindow, enterMode, shiftEnterMode, tabSpaces )
//{
// this.Window = targetWindow ;
// this.EnterMode = 'p' ;
// this.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 ) ;
//}
//FCKEnterKey.prototype = proto;
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 = '8px;9px;10px;11px;12px;14px;16px' ;
//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 = 'ieSpell' ; // 'ieSpell' | 'SpellerPages'
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.RemoveAttributes = '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 = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage = 'aspx' ; // 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 ;
//FCKConfig.LinkBrowser = false;
//FCKConfig.ImageBrowser = false;
//FCKConfig.LinkUpload = false;
//FCKConfig.ImageUpload = false;
if( window.console ) window.console.log( 'Config is loaded!' ) ; // @Packager.Compactor.RemoveLine | JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the integration file for JavaScript.
*
* It defines the FCKeditor class that can be used to create editor
* instances in a HTML page in the client side. For server side
* operations, use the specific integration system.
*/
// FCKeditor Class
var FCKeditor = function( instanceName, width, height, toolbarSet, value )
{
// Properties
this.InstanceName = instanceName ;
this.Width = width || '100%' ;
this.Height = height || '200' ;
this.ToolbarSet = toolbarSet || 'Default' ;
this.Value = value || '' ;
this.BasePath = FCKeditor.BasePath ;
this.CheckBrowser = true ;
this.DisplayErrors = true ;
this.Config = new Object() ;
// Events
this.OnError = null ; // function( source, errorNumber, errorDescription )
}
/**
* This is the default BasePath used by all editor instances.
*/
FCKeditor.BasePath = '/fckeditor/' ;
/**
* The minimum height used when replacing textareas.
*/
FCKeditor.MinHeight = 200 ;
/**
* The minimum width used when replacing textareas.
*/
FCKeditor.MinWidth = 750 ;
FCKeditor.prototype.Version = '2.6.3' ;
FCKeditor.prototype.VersionBuild = '19836' ;
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 ( !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 += '&' ;
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 += '&Toolbar=' + this.ToolbarSet ;
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, "&").replace(
/"/g, """).replace(
/</g, "<").replace(
/>/g, ">") ;
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 |
/*
=============================
jQuery Scroll Path Plugin
v1.1.1
Demo and Documentation:
http://joelb.me/scrollpath
=============================
A jQuery plugin for defining a custom path that the browser
follows when scrolling. Comes with a custom scrollbar,
which is styled in scrollpath.css.
Author: Joel Besada (http://www.joelb.me)
Date: 2012-02-01
Copyright 2012, Joel Besada
MIT Licensed (http://www.opensource.org/licenses/mit-license.php)
*/
( function ( $, window, document, undefined ) {
var PREFIX = "-" + getVendorPrefix().toLowerCase() + "-",
HAS_TRANSFORM_SUPPORT = supportsTransforms(),
HAS_CANVAS_SUPPORT = supportsCanvas(),
FPS = 60,
STEP_SIZE = 50, // Number of actual path steps per scroll steps.
// The extra steps are needed to make animations look smooth.
BIG_STEP_SIZE = STEP_SIZE * 5, // Step size for space, page down/up
isInitialized = false,
isDragging = false,
isAnimating = false,
step,
pathObject,
pathList,
element,
scrollBar,
scrollHandle,
// Default speeds for scrolling and rotating (with path.rotate())
speeds = {
scrollSpeed: 50,
rotationSpeed: Math.PI/15
},
// Default plugin settings
settings = {
wrapAround: false,
drawPath: false,
scrollBar: true
},
methods = {
/* Initializes the plugin */
init: function( options ) {
if ( this.length > 1 || isInitialized ) $.error( "jQuery.scrollPath can only be initialized on *one* element *once*" );
$.extend( settings, options );
isInitialized = true;
element = this;
pathList = pathObject.getPath();
initCanvas();
initScrollBar();
scrollToStep( 0 ); // Go to the first step immediately
element.css( "position", "relative" );
$( document ).on({
"mousewheel": scrollHandler,
"DOMMouseScroll": ("onmousewheel" in document) ? null : scrollHandler, // Firefox
"keydown": keyHandler,
"mousedown": function( e ) {
if( e.button === 1 ) {
e.preventDefault();
return false;
}
}
});
$( window ).on( "resize", function() { scrollToStep( step ); } ); // Re-centers the screen
return this;
},
getPath: function( options ) {
$.extend( speeds, options );
return pathObject || ( pathObject = new Path( speeds.scrollSpeed, speeds.rotationSpeed ));
},
scrollTo: function( name, duration, easing, callback ) {
var destination = findStep( name );
if ( destination === undefined ) $.error( "jQuery.scrollPath could not find scroll target with name '" + name + "'" );
var distance = destination - step;
if ( settings.wrapAround && Math.abs( distance ) > pathList.length / 2) {
if ( destination > step) {
distance = -step - pathList.length + destination;
} else {
distance = pathList.length - step + destination;
}
}
animateSteps( distance, duration, easing, callback );
return this;
}
};
/* The Path object serves as a context to "draw" the scroll path
on before initializing the plugin */
function Path( scrollS, rotateS ) {
var PADDING = 40,
scrollSpeed = scrollS,
rotationSpeed = rotateS,
xPos = 0,
yPos = 0,
rotation = 0,
width = 0,
height = 0,
offsetX = 0,
offsetY = 0,
canvasPath = [{ method: "moveTo", args: [ 0, 0 ] }], // Needed if first path operation isn't a moveTo
path = [],
nameMap = {},
defaults = {
rotate: null,
callback: null,
name: null
};
/* Rotates the screen while staying in place */
this.rotate = function( radians, options ) {
var settings = $.extend( {}, defaults, options ),
rotDistance = Math.abs( radians - rotation ),
steps = Math.round( rotDistance / rotationSpeed ) * STEP_SIZE,
rotStep = ( radians - rotation ) / steps,
i = 1;
if ( !HAS_TRANSFORM_SUPPORT ) {
if ( settings.name || settings.callback ) {
// In case there was a name or callback set to this path, we add an extra step with those
// so they don't get lost in browsers without rotation support
this.moveTo(xPos, yPos, {
callback: settings.callback,
name: settings.name
});
}
return this;
}
for( ; i <= steps; i++ ) {
path.push({ x: xPos,
y: yPos,
rotate: rotation + rotStep * i,
callback: i === steps ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
rotation = radians % ( Math.PI*2 );
return this;
};
/* Moves (jumps) directly to the given point */
this.moveTo = function( x, y, options ) {
var settings = $.extend( {}, defaults, options ),
steps = path.length ? STEP_SIZE : 1;
i = 0;
for( ; i < steps; i++ ) {
path.push({ x: x,
y: y,
rotate: settings.rotate !== null ? settings.rotate : rotation,
callback: i === steps - 1 ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
setPos( x, y );
updateCanvas( x, y );
canvasPath.push({ method: "moveTo", args: arguments });
return this;
};
/* Draws a straight path to the given point */
this.lineTo = function( x, y, options ) {
var settings = $.extend( {}, defaults, options ),
relX = x - xPos,
relY = y - yPos,
distance = hypotenuse( relX, relY ),
steps = Math.round( distance/scrollSpeed ) * STEP_SIZE,
xStep = relX / steps,
yStep = relY / steps,
canRotate = settings.rotate !== null && HAS_TRANSFORM_SUPPORT,
rotStep = ( canRotate ? ( settings.rotate - rotation ) / steps : 0 ),
i = 1;
for ( ; i <= steps; i++ ) {
path.push({ x: xPos + xStep * i,
y: yPos + yStep * i,
rotate: rotation + rotStep * i,
callback: i === steps ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
rotation = ( canRotate ? settings.rotate : rotation );
setPos( x, y );
updateCanvas( x, y );
canvasPath.push({ method: "lineTo", args: arguments });
return this;
};
/* Draws an arced path with a given circle center, radius, start and end angle. */
this.arc = function( centerX, centerY, radius, startAngle, endAngle, counterclockwise, options ) {
var settings = $.extend( {}, defaults, options ),
startX = centerX + Math.cos( startAngle ) * radius,
startY = centerY + Math.sin( startAngle ) * radius,
endX = centerX + Math.cos( endAngle ) * radius,
endY = centerY + Math.sin( endAngle ) * radius,
angleDistance = sectorAngle( startAngle, endAngle, counterclockwise ),
distance = radius * angleDistance,
steps = Math.round( distance/scrollSpeed ) * STEP_SIZE,
radStep = angleDistance / steps * ( counterclockwise ? -1 : 1 ),
canRotate = settings.rotate !== null && HAS_TRANSFORM_SUPPORT,
rotStep = ( canRotate ? (settings.rotate - rotation) / steps : 0 ),
i = 1;
// If the arc starting point isn't the same as the end point of the preceding path,
// prepend a line to the starting point. This is the default behavior when drawing on
// a canvas.
if ( xPos !== startX || yPos !== startY ) {
this.lineTo( startX, startY );
}
for ( ; i <= steps; i++ ) {
path.push({ x: centerX + radius * Math.cos( startAngle + radStep*i ),
y: centerY + radius * Math.sin( startAngle + radStep*i ),
rotate: rotation + rotStep * i,
callback: i === steps ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
rotation = ( canRotate ? settings.rotate : rotation );
setPos( endX, endY );
updateCanvas( centerX + radius, centerY + radius );
updateCanvas( centerX - radius, centerY - radius );
canvasPath.push({ method: "arc", args: arguments });
return this;
};
this.getPath = function() {
return path;
};
this.getNameMap = function() {
return nameMap;
};
/* Appends offsets to all x and y coordinates before returning the canvas path */
this.getCanvasPath = function() {
var i = 0;
for( ; i < canvasPath.length; i++ ) {
canvasPath[ i ].args[ 0 ] -= this.getPathOffsetX();
canvasPath[ i ].args[ 1 ] -= this.getPathOffsetY();
}
return canvasPath;
};
this.getPathWidth = function() {
return width - offsetX + PADDING;
};
this.getPathHeight = function() {
return height - offsetY + PADDING;
};
this.getPathOffsetX = function() {
return offsetX - PADDING / 2;
};
this.getPathOffsetY = function() {
return offsetY - PADDING / 2;
};
/* Sets the current position */
function setPos( x, y ) {
xPos = x;
yPos = y;
}
/* Updates width and height, if needed */
function updateCanvas( x, y ) {
offsetX = Math.min( x, offsetX );
offsetY = Math.min( y, offsetY );
width = Math.max( x, width );
height = Math.max( y, height );
}
}
/* Plugin wrapper, handles method calling */
$.fn.scrollPath = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) );
} else if ( typeof method === "object" || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error( "Method " + method + " does not exist on jQuery.scrollPath" );
}
};
/* Initialize the scroll bar */
function initScrollBar() {
if ( !settings.scrollBar ) return;
// TODO: Holding down the mouse on the bar should "rapidfire", like holding down space
scrollBar = $( "<div>" ).
addClass( "sp-scroll-bar" ).
on( "mousedown", function( e ) {
var clickStep = Math.round( (e.offsetY || e.clientY) / scrollBar.height() * ( pathList.length - 1) );
// Close in on the clicked part instead of jumping directly to it.
// This mimics the default browser scroll bar behavior.
if ( Math.abs(clickStep - step) > BIG_STEP_SIZE) {
clickStep = step + ( 5 * STEP_SIZE * ( clickStep > step ? 1 : -1 ) );
}
scrollToStep(clickStep);
e.preventDefault();
return false;
});
scrollHandle = $( "<div>" ).
addClass( "sp-scroll-handle" ).
on({
click: function( e ) {
e.preventDefault();
return false;
},
mousedown: function( e ) {
if ( e.button !== 0 ) return;
isDragging = true;
e.preventDefault();
return false;
}
});
$( document ).on({
mouseup: function( e ) { isDragging = false; },
mousemove: function( e ) { if( isDragging ) dragScrollHandler( e ); }
});
$( "body" ).prepend( scrollBar.append( scrollHandle ) );
}
/* Initializes the path canvas */
function initCanvas() {
if ( !settings.drawPath || !HAS_CANVAS_SUPPORT ) return;
var canvas,
style = {
position: "absolute",
"z-index": 9998,
left: pathObject.getPathOffsetX(),
top: pathObject.getPathOffsetY(),
"pointer-events": "none"
};
applyPrefix( style, "user-select", "none" );
applyPrefix( style, "user-drag", "none" );
canvas = $( "<canvas>" ).
addClass( "sp-canvas" ).
css( style ).
prependTo( element );
canvas[ 0 ].width = pathObject.getPathWidth();
canvas[ 0 ].height = pathObject.getPathHeight();
drawCanvasPath( canvas[ 0 ].getContext( "2d" ), pathObject.getCanvasPath() );
}
/* Sets the canvas path styles and draws the path */
function drawCanvasPath( context, path ) {
var i = 0;
context.shadowBlur = 15;
context.shadowColor = "black";
context.strokeStyle = "white";
context.lineJoin = "round";
context.lineCap = "round";
context.lineWidth = 10;
for( ; i < path.length; i++ ) {
context[ path[ i ].method ].apply( context, path[ i ].args );
}
context.stroke();
}
/* Handles mousewheel scrolling */
function scrollHandler( e ) {
var scrollDelta = e.originalEvent.wheelDelta || -e.originalEvent.detail,
dir = scrollDelta / ( Math.abs( scrollDelta ) );
e.preventDefault();
$( window ).scrollTop( 0 ).scrollLeft( 0 );
scrollSteps( -dir * STEP_SIZE );
}
/* Handles key scrolling (arrows and space) */
function keyHandler( e ) {
// Disable scrolling with keys when user has focus on text input elements
if ( /^text/.test( e.target.type ) ) return;
switch ( e.keyCode ) {
case 40: // Down Arrow
scrollSteps( STEP_SIZE );
break;
case 38: // Up Arrow
scrollSteps( -STEP_SIZE );
break;
case 34: //Page Down
scrollSteps( BIG_STEP_SIZE );
break;
case 33: //Page Up
scrollSteps( -BIG_STEP_SIZE );
break;
case 32: // Spacebar
scrollSteps( BIG_STEP_SIZE * ( e.shiftKey ? -1 : 1 ) );
break;
case 35: // End
scrollToStep( pathList.length - 1 );
break;
case 36: //Home
scrollToStep( 0 );
break;
}
}
/* Handles scrollbar scrolling */
function dragScrollHandler( e ) {
var dragStep,
y = e.clientY - scrollBar.offset().top;
dragStep = limitWithin( Math.round( y / scrollBar.height() * ( pathList.length - 1 ) ), 0, pathList.length - 1 );
scrollToStep( snap(dragStep, STEP_SIZE) );
}
/* Scrolls forward the given amount of steps. Negative values scroll backward. */
function scrollSteps( steps ) {
scrollToStep( wrapStep( step + steps ) );
}
/* Animates forward the given amount of steps over the set duration. Negative values scroll backward */
function animateSteps ( steps, duration, easing, callback ) {
if( steps === 0 || isAnimating ) return;
if( !duration || typeof duration !== "number" ) {
if ( typeof duration === "function" ) duration();
return scrollSteps( steps );
}
isAnimating = true;
var frames = ( duration / 1000 ) * FPS,
startStep = step,
currentFrame = 0,
easedSteps,
nextStep,
interval = setInterval(function() {
easedSteps = Math.round( ($.easing[easing] || $.easing.swing)( ++currentFrame / frames, duration / frames * currentFrame, 0, steps, duration) );
nextStep = wrapStep( startStep + easedSteps);
if (currentFrame === frames) {
clearInterval( interval );
if ( typeof easing === "function" ) {
easing();
} else if ( callback ) {
callback();
}
isAnimating = false;
}
scrollToStep( nextStep, true );
}, duration / frames);
}
/* Scrolls to a specified step */
function scrollToStep( stepParam, fromAnimation ) {
if ( isAnimating && !fromAnimation ) return;
var cb;
if (pathList[ stepParam ] ){
cb = pathList[ stepParam ].callback;
element.css( makeCSS( pathList[ stepParam ] ) );
}
if( scrollHandle ) scrollHandle.css( "top", stepParam / (pathList.length - 1 ) * ( scrollBar.height() - scrollHandle.height() ) + "px" );
if ( cb && stepParam !== step && !isAnimating ) cb();
step = stepParam;
}
/* Finds the step number of a given name */
function findStep( name ) {
return pathObject.getNameMap()[ name ];
}
/* Wraps a step around the path, or limits it, depending on the wrapAround setting */
function wrapStep( wStep ) {
if ( settings.wrapAround ) {
if( isAnimating ) {
while ( wStep < 0 ) wStep += pathList.length;
while ( wStep >= pathList.length ) wStep -= pathList.length;
} else {
if ( wStep < 0 ) wStep = pathList.length - 1;
if ( wStep >= pathList.length ) wStep = 0;
}
} else {
wStep = limitWithin( wStep, 0, pathList.length - 1 );
}
return wStep;
}
/* Translates a given node in the path to CSS styles */
function makeCSS( node ) {
var centeredX = node.x - $( window ).width() / 2,
centeredY = node.y - $( window ).height() / 2,
style = {};
// Only use transforms when page is rotated
if ( normalizeAngle(node.rotate) === 0 ) {
style.left = -centeredX;
style.top = -centeredY;
applyPrefix( style, "transform-origin", "" );
applyPrefix( style, "transform", "" );
} else {
style.left = style.top = "";
applyPrefix( style, "transform-origin", node.x + "px " + node.y + "px" );
applyPrefix( style, "transform", "translate(" + -centeredX + "px, " + -centeredY + "px) rotate(" + node.rotate + "rad)" );
}
return style;
}
/* Determine the vendor prefix of the visitor's browser,
http://lea.verou.me/2009/02/find-the-vendor-prefix-of-the-current-browser/
*/
function getVendorPrefix() {
var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/,
someScript = document.getElementsByTagName( "script" )[ 0 ];
for ( var prop in someScript.style ) {
if ( regex.test(prop) ) {
return prop.match( regex )[ 0 ];
}
}
if ( "WebkitOpacity" in someScript.style ) return "Webkit";
if ( "KhtmlOpacity" in someScript.style ) return "Khtml";
return "";
}
/* Applied prefixed and unprefixed css values of a given property to a given object*/
function applyPrefix( style, prop, value ) {
style[ PREFIX + prop ] = style[ prop ] = value;
}
/* Checks for CSS transform support */
function supportsTransforms() {
var testStyle = document.createElement( "dummy" ).style,
testProps = [ "transform",
"WebkitTransform",
"MozTransform",
"OTransform",
"msTransform",
"KhtmlTransform" ],
i = 0;
for ( ; i < testProps.length; i++ ) {
if ( testStyle[testProps[ i ]] !== undefined ) {
return true;
}
}
return false;
}
/* Checks for canvas support */
function supportsCanvas() {
return !!document.createElement( "canvas" ).getContext;
}
/* Calculates the angle distance between two angles */
function sectorAngle( start, end, ccw ) {
var nStart = normalizeAngle( start ),
nEnd = normalizeAngle( end ),
diff = Math.abs( nStart - nEnd ),
invDiff = Math.PI * 2 - diff;
if ( ( ccw && nStart < nEnd ) ||
( !ccw && nStart > nEnd ) ||
( nStart === nEnd && start !== end ) // Special case *
) {
return invDiff;
}
// *: In the case of a full circle, say from 0 to 2 * Math.PI (0 to 360 degrees),
// the normalized angles would be the same, which means the sector angle is 0.
// To allow full circles, we set this special case.
return diff;
}
/* Limits a given value between a lower and upper limit */
function limitWithin( value, lowerLimit, upperLimit ) {
if ( value > upperLimit ) {
return upperLimit;
} else if ( value < lowerLimit ) {
return lowerLimit;
}
return value;
}
/* 'Snaps' a value to be a multiple of a given snap value */
function snap( value, snapValue ) {
var mod = value % snapValue;
if( mod > snapValue / 2) return value + snapValue - mod;
return value - mod;
}
/* Normalizes a given angle (sets it between 0 and 2 * Math.PI) */
function normalizeAngle( angle ) {
while( angle < 0 ) {
angle += Math.PI * 2;
}
return angle % ( Math.PI * 2 );
}
/* Calculates the hypotenuse of a right triangle with sides x and y */
function hypotenuse( x, y ) {
return Math.sqrt( x * x + y * y );
}
})( jQuery, window, document );
| JavaScript |
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/ | JavaScript |
$(document).ready(init);
function init() {
/* ========== DRAWING THE PATH AND INITIATING THE PLUGIN ============= */
$.fn.scrollPath("getPath")
// Move to 'start' element
.moveTo(400, 50, {name: "start"})
// Line to 'description' element
.lineTo(400, 800, {name: "myself"})
// Arc down and line to 'syntax'
.arc(200, 1200, 400, -Math.PI/2, Math.PI/2, true)
.lineTo(600, 1600, {
// callback: function() {
// highlight($(".settings"));
// },
name: "description"
})
// Continue line to 'scrollbar'
.lineTo(1750, 1600, {
callback: function() {
highlight($(".sp-scroll-handle"));
},
name: "thinking"
})
// Arc up while rotating
.arc(1800, 1000, 600, Math.PI/2, 0, true, {rotate: Math.PI/2 })
// Line to 'rotations'
.lineTo(2400, 750, {
name: "job"
})
// Rotate in place
.rotate(3*Math.PI/2, {
name: "discovery"
})
// Continue upwards to 'source'
.lineTo(2400, -700, {
name: "other"
})
// Small arc downwards
.arc(2250, -700, 150, 0, -Math.PI/2, true)
//Line to 'follow'
.lineTo(1350, -850, {
name: "thank"
})
// Arc and rotate back to the beginning.
.arc(1300, 50, 900, -Math.PI/2, -Math.PI, true, {rotate: Math.PI*2, name: "end"});
// We're done with the path, let's initate the plugin on our wrapper element
$(".wrapper").scrollPath({drawPath: true, wrapAround: true});
// Add scrollTo on click on the navigation anchors
$("nav").find("a").each(function() {
var target = $(this).attr("href").replace("#", "");
$(this).click(function(e) {
e.preventDefault();
// Include the jQuery easing plugin (http://gsgd.co.uk/sandbox/jquery/easing/)
// for extra easing functions like the one below
$.fn.scrollPath("scrollTo", target, 1000, "easeInOutSine");
});
});
/* ===================================================================== */
$(".settings .show-path").click(function(e) {
e.preventDefault();
$(".sp-canvas").toggle();
}).toggle(function() {
$(this).text("Hide Path");
}, function() {
$(this).text("Show Path");
});
}
function highlight(element) {
if(!element.hasClass("highlight")) {
element.addClass("highlight");
setTimeout(function() { element.removeClass("highlight"); }, 2000);
}
}
function ordinal(num) {
return num + (
(num % 10 == 1 && num % 100 != 11) ? 'st' :
(num % 10 == 2 && num % 100 != 12) ? 'nd' :
(num % 10 == 3 && num % 100 != 13) ? 'rd' : 'th'
);
}
| JavaScript |
alert('plugin one nested js file'); | JavaScript |
alert('win sauce'); | JavaScript |
alert('I am a root level file!'); | JavaScript |
alert("Test App"); | JavaScript |
nested theme js file | JavaScript |
root theme js file | JavaScript |
var cellShown;
var lineSegmentIdsShown;
function hidePath(cell)
{
if (lineSegmentIdsShown) {
setOutlines('none');
cellShown.style.outlineWidth = 'thin';
lineSegmentIdsShown = null;
var sameCell = cell == cellShown;
cellShown = null;
return sameCell;
}
return false;
}
function setOutlines(outlineStyle)
{
for (var i = 0; i < lineSegmentIdsShown.length; i++) {
var item = document.getElementById(lineSegmentIdsShown[i]);
if (item) item.style.outline = outlineStyle;
}
}
function showPath(cell, lineSegmentIdsStr)
{
if (hidePath(cell)) return;
lineSegmentIdsShown = lineSegmentIdsStr.split(' ');
setOutlines('thin dashed #0000FF');
cell.style.outlineWidth = 'medium';
cellShown = cell;
}
function showHide(callPoints, listIndex)
{
var tableCell = callPoints.parentNode;
if (listIndex >= 0) {
tableCell = tableCell.parentNode;
}
else {
listIndex = 0;
}
var list = tableCell.getElementsByTagName('ol')[listIndex].style;
list.display = list.display == 'none' ? 'block' : 'none';
}
var filesShown = true;
function showHideAllFiles(header)
{
var table = header.parentNode.parentNode;
filesShown = !filesShown;
var newDisplay = filesShown ? 'block' : 'none';
var rows = table.rows;
rows[0].cells[1].style.display = newDisplay;
for (var i = 1; i < rows.length; i++) {
rows[i].cells[1].style.display = newDisplay;
}
}
function showHideFiles(files)
{
var table = files.parentNode.cells[1].getElementsByTagName('table')[0];
table.style.display = table.style.display == 'none' ? 'block' : 'none';
}
function showHideLines(cell)
{
var content = cell.children;
var expanded = content[0].style;
var collapsed = content[1].style;
var showingExpanded = expanded.display == 'block';
expanded.display = showingExpanded ? 'none' : 'block';
collapsed.display = showingExpanded ? 'block' : 'none';
}
var metricCol;
function rowOrder(r1, r2)
{
var c1 = r1.cells[metricCol];
var c2 = r2.cells[metricCol];
if (!c1 || !c2) {
return -1;
}
var t1 = c1.title;
var t2 = c2.title;
if (t1 && t2) {
var s1 = t1.split('/')[1];
var s2 = t2.split('/')[1];
return s1 - s2;
}
return t1 ? 1 : -1;
}
function sortRows(tbl, metric)
{
var startRow = 0;
var endRow = tbl.rows.length;
if (tbl.id == 'packages') {
metricCol = 1 + metric;
startRow = 1;
endRow--;
}
else {
metricCol = metric;
}
var rs = new Array();
for (var i = startRow; i < endRow; i++) {
rs[i - startRow] = tbl.rows[i];
}
rs.sort(rowOrder);
for (var i = 0; i < rs.length; i++) {
rs[i] = rs[i].innerHTML;
}
for (var i = 0; i < rs.length; i++) {
tbl.rows[startRow + i].innerHTML = rs[i];
}
}
function sortTables(metric)
{
var tables = document.getElementsByTagName("table");
for (var i = 0; i < tables.length; i++) {
sortRows(tables[i], metric);
}
} | JavaScript |
/*
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @fileoverview Bookmark bubble library. This is meant to be included in the
* main JavaScript binary of a mobile web application.
*
* Supported browsers: iPhone / iPod / iPad Safari 3.0+
*/
var google = google || {};
google.bookmarkbubble = google.bookmarkbubble || {};
/**
* Binds a context object to the function.
* @param {Function} fn The function to bind to.
* @param {Object} context The "this" object to use when the function is run.
* @return {Function} A partially-applied form of fn.
*/
google.bind = function(fn, context) {
return function() {
return fn.apply(context, arguments);
};
};
/**
* Function used to define an abstract method in a base class. If a subclass
* fails to override the abstract method, then an error will be thrown whenever
* that method is invoked.
*/
google.abstractMethod = function() {
throw Error('Unimplemented abstract method.');
};
/**
* The bubble constructor. Instantiating an object does not cause anything to
* be rendered yet, so if necessary you can set instance properties before
* showing the bubble.
* @constructor
*/
google.bookmarkbubble.Bubble = function() {
/**
* Handler for the scroll event. Keep a reference to it here, so it can be
* unregistered when the bubble is destroyed.
* @type {function()}
* @private
*/
this.boundScrollHandler_ = google.bind(this.setPosition, this);
/**
* The bubble element.
* @type {Element}
* @private
*/
this.element_ = null;
/**
* Whether the bubble has been destroyed.
* @type {boolean}
* @private
*/
this.hasBeenDestroyed_ = false;
};
/**
* Shows the bubble if allowed. It is not allowed if:
* - The browser is not Mobile Safari, or
* - The user has dismissed it too often already, or
* - The hash parameter is present in the location hash, or
* - The application is in fullscreen mode, which means it was already loaded
* from a homescreen bookmark.
* @return {boolean} True if the bubble is being shown, false if it is not
* allowed to show for one of the aforementioned reasons.
*/
google.bookmarkbubble.Bubble.prototype.showIfAllowed = function() {
if (!this.isAllowedToShow_()) {
return false;
}
this.show_();
return true;
};
/**
* Shows the bubble if allowed after loading the icon image. This method creates
* an image element to load the image into the browser's cache before showing
* the bubble to ensure that the image isn't blank. Use this instead of
* showIfAllowed if the image url is http and cacheable.
* This hack is necessary because Mobile Safari does not properly render
* image elements with border-radius CSS.
* @param {function()} opt_callback Closure to be called if and when the bubble
* actually shows.
* @return {boolean} True if the bubble is allowed to show.
*/
google.bookmarkbubble.Bubble.prototype.showIfAllowedWhenLoaded =
function(opt_callback) {
if (!this.isAllowedToShow_()) {
return false;
}
var self = this;
// Attach to self to avoid garbage collection.
var img = self.loadImg_ = document.createElement('img');
img.src = self.getIconUrl_();
img.onload = function() {
if (img.complete) {
delete self.loadImg_;
img.onload = null; // Break the circular reference.
self.show_();
opt_callback && opt_callback();
}
};
img.onload();
return true;
};
/**
* Sets the parameter in the location hash. As it is
* unpredictable what hash scheme is to be used, this method must be
* implemented by the host application.
*
* This gets called automatically when the bubble is shown. The idea is that if
* the user then creates a bookmark, we can later recognize on application
* startup whether it was from a bookmark suggested with this bubble.
*
* NOTE: Using a hash parameter to track whether the bubble has been shown
* conflicts with the navigation system in jQuery Mobile. If you are using that
* library, you should implement this function to track the bubble's status in
* a different way, e.g. using window.localStorage in HTML5.
*/
google.bookmarkbubble.Bubble.prototype.setHashParameter = google.abstractMethod;
/**
* Whether the parameter is present in the location hash. As it is
* unpredictable what hash scheme is to be used, this method must be
* implemented by the host application.
*
* Call this method during application startup if you want to log whether the
* application was loaded from a bookmark with the bookmark bubble promotion
* parameter in it.
*
* @return {boolean} Whether the bookmark bubble parameter is present in the
* location hash.
*/
google.bookmarkbubble.Bubble.prototype.hasHashParameter = google.abstractMethod;
/**
* The number of times the user must dismiss the bubble before we stop showing
* it. This is a public property and can be changed by the host application if
* necessary.
* @type {number}
*/
google.bookmarkbubble.Bubble.prototype.NUMBER_OF_TIMES_TO_DISMISS = 2;
/**
* Time in milliseconds. If the user does not dismiss the bubble, it will auto
* destruct after this amount of time.
* @type {number}
*/
google.bookmarkbubble.Bubble.prototype.TIME_UNTIL_AUTO_DESTRUCT = 15000;
/**
* The prefix for keys in local storage. This is a public property and can be
* changed by the host application if necessary.
* @type {string}
*/
google.bookmarkbubble.Bubble.prototype.LOCAL_STORAGE_PREFIX = 'BOOKMARK_';
/**
* The key name for the dismissed state.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.DISMISSED_ = 'DISMISSED_COUNT';
/**
* The arrow image in base64 data url format.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IMAGE_ARROW_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAMAAABSrFY3AAABKVBMVEUAAAD///8AAAAAAAAAAAAAAAAAAADf398AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD09PQAAAAAAAAAAAC9vb0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD19fUAAAAAAAAAAAAAAADq6uoAAAAAAAAAAAC8vLzU1NTT09MAAADg4OAAAADs7OwAAAAAAAAAAAD///+cueenwerA0vC1y+3a5fb5+/3t8vr4+v3w9PuwyOy3zO3h6vfh6vjq8Pqkv+mat+fE1fHB0/Cduuifu+iuxuuivemrxOvC1PDz9vzJ2fKpwuqmwOrb5vapw+q/0vDf6ffK2vLN3PPprJISAAAAQHRSTlMAAAEGExES7FM+JhUoQSxIRwMbNfkJUgXXBE4kDQIMHSA0Tw4xIToeTSc4Chz4OyIjPfI3QD/X5OZR6zzwLSUPrm1y3gAAAQZJREFUeF5lzsVyw0AURNE3IMsgmZmZgszQZoeZOf//EYlG5Yrhbs+im4Dj7slM5wBJ4OJ+undAUr68gK/Hyb6Bcp5yBR/w8jreNeAr5Eg2XE7g6e2/0z6cGw1JQhpmHP3u5aiPPnTTkIK48Hj9Op7bD3btAXTfgUdwYjwSDCVXMbizO0O4uDY/x4kYC5SWFnfC6N1a9RCO7i2XEmQJj2mHK1Hgp9Vq3QBRl9shuBLGhcNtHexcdQCnDUoUGetxDD+H2DQNG2xh6uAWgG2/17o1EmLqYH0Xej0UjHAaFxZIV6rJ/WK1kg7QZH8HU02zmdJinKZJaDV3TVMjM5Q9yiqYpUwiMwa/1apDXTNESjsAAAAASUVORK5CYII=';
/**
* The close image in base64 data url format.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IMAGE_CLOSE_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAALVBMVEXM3fm+1Pfb5/rF2fjw9f23z/aavPOhwfTp8PyTt/L3+v7T4vqMs/K7zP////+qRWzhAAAAXElEQVQIW2O4CwUM996BwVskxtOqd++2rwMyPI+ve31GD8h4Madqz2mwms5jZ/aBGS/mHIDoen3m+DowY8/hOVUgxusz+zqPg7SvPA1UxQfSvu/du0YUK2AMmDMA5H1qhVX33T8AAAAASUVORK5CYII=';
/**
* The link used to locate the application's home screen icon to display inside
* the bubble. The default link used here is for an iPhone home screen icon
* without gloss. If your application uses a glossy icon, change this to
* 'apple-touch-icon'.
* @type {string}
* @private
*/
google.bookmarkbubble.Bubble.prototype.REL_ICON_ =
'apple-touch-icon-precomposed';
/**
* Regular expression for detecting an iPhone or iPod or iPad.
* @type {!RegExp}
* @private
*/
google.bookmarkbubble.Bubble.prototype.MOBILE_SAFARI_USERAGENT_REGEX_ =
/iPhone|iPod|iPad/;
/**
* Regular expression for detecting an iPad.
* @type {!RegExp}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IPAD_USERAGENT_REGEX_ = /iPad/;
/**
* Regular expression for extracting the iOS version. Only matches 2.0 and up.
* @type {!RegExp}
* @private
*/
google.bookmarkbubble.Bubble.prototype.IOS_VERSION_USERAGENT_REGEX_ =
/OS (\d)_(\d)(?:_(\d))?/;
/**
* Determines whether the bubble should be shown or not.
* @return {boolean} Whether the bubble should be shown or not.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isAllowedToShow_ = function() {
return this.isMobileSafari_() &&
!this.hasBeenDismissedTooManyTimes_() &&
!this.isFullscreen_() &&
!this.hasHashParameter();
};
/**
* Builds and shows the bubble.
* @private
*/
google.bookmarkbubble.Bubble.prototype.show_ = function() {
this.element_ = this.build_();
document.body.appendChild(this.element_);
this.element_.style.WebkitTransform =
'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)';
this.setHashParameter();
window.setTimeout(this.boundScrollHandler_, 1);
window.addEventListener('scroll', this.boundScrollHandler_, false);
// If the user does not dismiss the bubble, slide out and destroy it after
// some time.
window.setTimeout(google.bind(this.autoDestruct_, this),
this.TIME_UNTIL_AUTO_DESTRUCT);
};
/**
* Destroys the bubble by removing its DOM nodes from the document.
*/
google.bookmarkbubble.Bubble.prototype.destroy = function() {
if (this.hasBeenDestroyed_) {
return;
}
window.removeEventListener('scroll', this.boundScrollHandler_, false);
if (this.element_ && this.element_.parentNode == document.body) {
document.body.removeChild(this.element_);
this.element_ = null;
}
this.hasBeenDestroyed_ = true;
};
/**
* Remember that the user has dismissed the bubble once more.
* @private
*/
google.bookmarkbubble.Bubble.prototype.rememberDismissal_ = function() {
if (window.localStorage) {
try {
var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_;
var value = Number(window.localStorage[key]) || 0;
window.localStorage[key] = String(value + 1);
} catch (ex) {
// Looks like we've hit the storage size limit. Currently we have no
// fallback for this scenario, but we could use cookie storage instead.
// This would increase the code bloat though.
}
}
};
/**
* Whether the user has dismissed the bubble often enough that we will not
* show it again.
* @return {boolean} Whether the user has dismissed the bubble often enough
* that we will not show it again.
* @private
*/
google.bookmarkbubble.Bubble.prototype.hasBeenDismissedTooManyTimes_ =
function() {
if (!window.localStorage) {
// If we can not use localStorage to remember how many times the user has
// dismissed the bubble, assume he has dismissed it. Otherwise we might end
// up showing it every time the host application loads, into eternity.
return true;
}
try {
var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_;
// If the key has never been set, localStorage yields undefined, which
// Number() turns into NaN. In that case we'll fall back to zero for
// clarity's sake.
var value = Number(window.localStorage[key]) || 0;
return value >= this.NUMBER_OF_TIMES_TO_DISMISS;
} catch (ex) {
// If we got here, something is wrong with the localStorage. Make the same
// assumption as when it does not exist at all. Exceptions should only
// occur when setting a value (due to storage limitations) but let's be
// extra careful.
return true;
}
};
/**
* Whether the application is running in fullscreen mode.
* @return {boolean} Whether the application is running in fullscreen mode.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isFullscreen_ = function() {
return !!window.navigator.standalone;
};
/**
* Whether the application is running inside Mobile Safari.
* @return {boolean} True if the current user agent looks like Mobile Safari.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isMobileSafari_ = function() {
return this.MOBILE_SAFARI_USERAGENT_REGEX_.test(window.navigator.userAgent);
};
/**
* Whether the application is running on an iPad.
* @return {boolean} True if the current user agent looks like an iPad.
* @private
*/
google.bookmarkbubble.Bubble.prototype.isIpad_ = function() {
return this.IPAD_USERAGENT_REGEX_.test(window.navigator.userAgent);
};
/**
* Creates a version number from 4 integer pieces between 0 and 127 (inclusive).
* @param {*=} opt_a The major version.
* @param {*=} opt_b The minor version.
* @param {*=} opt_c The revision number.
* @param {*=} opt_d The build number.
* @return {number} A representation of the version.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getVersion_ = function(opt_a, opt_b,
opt_c, opt_d) {
// We want to allow implicit conversion of any type to number while avoiding
// compiler warnings about the type.
return /** @type {number} */ (opt_a) << 21 |
/** @type {number} */ (opt_b) << 14 |
/** @type {number} */ (opt_c) << 7 |
/** @type {number} */ (opt_d);
};
/**
* Gets the iOS version of the device. Only works for 2.0+.
* @return {number} The iOS version.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getIosVersion_ = function() {
var groups = this.IOS_VERSION_USERAGENT_REGEX_.exec(
window.navigator.userAgent) || [];
groups.shift();
return this.getVersion_.apply(this, groups);
};
/**
* Positions the bubble at the bottom of the viewport using an animated
* transition.
*/
google.bookmarkbubble.Bubble.prototype.setPosition = function() {
this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-out';
this.element_.style.WebkitTransform =
'translate3d(0,' + this.getVisibleYPosition_() + 'px,0)';
};
/**
* Destroys the bubble by removing its DOM nodes from the document, and
* remembers that it was dismissed.
* @private
*/
google.bookmarkbubble.Bubble.prototype.closeClickHandler_ = function() {
this.destroy();
this.rememberDismissal_();
};
/**
* Gets called after a while if the user ignores the bubble.
* @private
*/
google.bookmarkbubble.Bubble.prototype.autoDestruct_ = function() {
if (this.hasBeenDestroyed_) {
return;
}
this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-in';
this.element_.style.WebkitTransform =
'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)';
window.setTimeout(google.bind(this.destroy, this), 700);
};
/**
* Gets the y offset used to show the bubble (i.e., position it on-screen).
* @return {number} The y offset.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getVisibleYPosition_ = function() {
return this.isIpad_() ? window.pageYOffset + 17 :
window.pageYOffset - this.element_.offsetHeight + window.innerHeight - 17;
};
/**
* Gets the y offset used to hide the bubble (i.e., position it off-screen).
* @return {number} The y offset.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getHiddenYPosition_ = function() {
return this.isIpad_() ? window.pageYOffset - this.element_.offsetHeight :
window.pageYOffset + window.innerHeight;
};
/**
* The url of the app's bookmark icon.
* @type {string|undefined}
* @private
*/
google.bookmarkbubble.Bubble.prototype.iconUrl_;
/**
* Scrapes the document for a link element that specifies an Apple favicon and
* returns the icon url. Returns an empty data url if nothing can be found.
* @return {string} A url string.
* @private
*/
google.bookmarkbubble.Bubble.prototype.getIconUrl_ = function() {
if (!this.iconUrl_) {
var link = this.getLink(this.REL_ICON_);
if (!link || !(this.iconUrl_ = link.href)) {
this.iconUrl_ = 'data:image/png;base64,';
}
}
return this.iconUrl_;
};
/**
* Gets the requested link tag if it exists.
* @param {string} rel The rel attribute of the link tag to get.
* @return {Element} The requested link tag or null.
*/
google.bookmarkbubble.Bubble.prototype.getLink = function(rel) {
rel = rel.toLowerCase();
var links = document.getElementsByTagName('link');
for (var i = 0; i < links.length; ++i) {
var currLink = /** @type {Element} */ (links[i]);
if (currLink.getAttribute('rel').toLowerCase() == rel) {
return currLink;
}
}
return null;
};
/**
* Creates the bubble and appends it to the document.
* @return {Element} The bubble element.
* @private
*/
google.bookmarkbubble.Bubble.prototype.build_ = function() {
var bubble = document.createElement('div');
var isIpad = this.isIpad_();
bubble.style.position = 'absolute';
bubble.style.zIndex = 1000;
bubble.style.width = '100%';
bubble.style.left = '0';
bubble.style.top = '0';
var bubbleInner = document.createElement('div');
bubbleInner.style.position = 'relative';
bubbleInner.style.width = '214px';
bubbleInner.style.margin = isIpad ? '0 0 0 82px' : '0 auto';
bubbleInner.style.border = '2px solid #fff';
bubbleInner.style.padding = '20px 20px 20px 10px';
bubbleInner.style.WebkitBorderRadius = '8px';
bubbleInner.style.WebkitBoxShadow = '0 0 8px rgba(0, 0, 0, 0.7)';
bubbleInner.style.WebkitBackgroundSize = '100% 8px';
bubbleInner.style.backgroundColor = '#b0c8ec';
bubbleInner.style.background = '#cddcf3 -webkit-gradient(linear, ' +
'left bottom, left top, ' + isIpad ?
'from(#cddcf3), to(#b3caed)) no-repeat top' :
'from(#b3caed), to(#cddcf3)) no-repeat bottom';
bubbleInner.style.font = '13px/17px sans-serif';
bubble.appendChild(bubbleInner);
// The "Add to Home Screen" text is intended to be the exact same text
// that is displayed in the menu of Mobile Safari.
if (this.getIosVersion_() >= this.getVersion_(4, 2)) {
bubbleInner.innerHTML = 'Install this web app on your phone: ' +
'tap on the arrow and then <b>\'Add to Home Screen\'</b>';
} else {
bubbleInner.innerHTML = 'Install this web app on your phone: ' +
'tap <b style="font-size:15px">+</b> and then ' +
'<b>\'Add to Home Screen\'</b>';
}
var icon = document.createElement('div');
icon.style['float'] = 'left';
icon.style.width = '55px';
icon.style.height = '55px';
icon.style.margin = '-2px 7px 3px 5px';
icon.style.background =
'#fff url(' + this.getIconUrl_() + ') no-repeat -1px -1px';
icon.style.WebkitBackgroundSize = '57px';
icon.style.WebkitBorderRadius = '10px';
icon.style.WebkitBoxShadow = '0 2px 5px rgba(0, 0, 0, 0.4)';
bubbleInner.insertBefore(icon, bubbleInner.firstChild);
var arrow = document.createElement('div');
arrow.style.backgroundImage = 'url(' + this.IMAGE_ARROW_DATA_URL_ + ')';
arrow.style.width = '25px';
arrow.style.height = '19px';
arrow.style.position = 'absolute';
arrow.style.left = '111px';
if (isIpad) {
arrow.style.WebkitTransform = 'rotate(180deg)';
arrow.style.top = '-19px';
} else {
arrow.style.bottom = '-19px';
}
bubbleInner.appendChild(arrow);
var close = document.createElement('a');
close.onclick = google.bind(this.closeClickHandler_, this);
close.style.position = 'absolute';
close.style.display = 'block';
close.style.top = '-3px';
close.style.right = '-3px';
close.style.width = '16px';
close.style.height = '16px';
close.style.border = '10px solid transparent';
close.style.background =
'url(' + this.IMAGE_CLOSE_DATA_URL_ + ') no-repeat';
bubbleInner.appendChild(close);
return bubble;
};
| JavaScript |
/*
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/** @fileoverview Example of how to use the bookmark bubble. */
window.addEventListener('load', function() {
window.setTimeout(function() {
var bubble = new google.bookmarkbubble.Bubble();
var parameter = 'bmb=1';
bubble.hasHashParameter = function() {
return window.location.hash.indexOf(parameter) != -1;
};
bubble.setHashParameter = function() {
if (!this.hasHashParameter()) {
window.location.hash += parameter;
}
};
bubble.getViewportHeight = function() {
window.console.log('Example of how to override getViewportHeight.');
return window.innerHeight;
};
bubble.getViewportScrollY = function() {
window.console.log('Example of how to override getViewportScrollY.');
return window.pageYOffset;
};
bubble.registerScrollHandler = function(handler) {
window.console.log('Example of how to override registerScrollHandler.');
window.addEventListener('scroll', handler, false);
};
bubble.deregisterScrollHandler = function(handler) {
window.console.log('Example of how to override deregisterScrollHandler.');
window.removeEventListener('scroll', handler, false);
};
bubble.showIfAllowed();
}, 1000);
}, false);
| JavaScript |
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var canvas, context;
var gameStage;
var preloadQ;
var logoScreenImage, logoScreenBitmap;
var newGame = true;
var player;
var floorImage, floorBitmap;
var playerIdleImage, playerIdleBitmap;
var scaleW = window.innerWidth / 1366;
var scaleH = window.innerHeight / 768;
var ghosts = [];
var ghostSpeed = 1.0;
var ghostImage;
var timeToAddNewGhost = 0;
var isGameOver = false;
var scoreText;
var playerScore = 0;
var playerSpeed = 10;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
function initialize() {
canvas = document.getElementById("gameCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context = canvas.getContext("2d");
gameStage = new createjs.Stage(canvas);
canvas.addEventListener("MSPointerUp", pointerUp, false);
canvas.addEventListener("MSPointerMove", pointerMove, false);
canvas.addEventListener("MSPointerDown", pointerDown, false);
gameStage = new createjs.Stage(canvas);
loadContent();
}
function pointerUp(event) {
if (newGame) {
newGame = false;
}
else {
player.targetX = event.x;
player.targetY = event.y;
}
}
function pointerMove(event) {
if (newGame) {
}
else {
player.targetX = event.x;
player.targetY = event.y;
}
}
function pointerDown(event) {
if (newGame) {
}
else {
player.targetX = event.x;
player.targetY = event.y;
}
}
function loadContent() {
preloadQ = new createjs.LoadQueue();
preloadQ.on("complete", prepareStage, this);
preloadQ.loadManifest([
{ id: "logoScreen", src: "images/GFX/LogoScreen.png" },
{ id: "floor", src: "images/GFX/floor.png" },
{ id: "ghost", src: "images/GFX/Ghost.png" },
{ id: "playerIdle", src: "images/GFX/PlayerIdle.png" }
]);
}
function prepareStage() {
logoScreenImage = preloadQ.getResult("logoScreen");
logoScreenBitmap = new createjs.Bitmap(logoScreenImage);
logoScreenBitmap.scaleX = scaleW;
logoScreenBitmap.scaleY = scaleH;
gameStage.addChild(logoScreenBitmap);
floorImage = preloadQ.getResult("floor");
floorBitmap = new createjs.Bitmap(floorImage);
floorBitmap.visible = false;
floorBitmap.scaleX = scaleW;
floorBitmap.scaleY = scaleH;
gameStage.addChild(floorBitmap);
playerIdleImage = preloadQ.getResult("playerIdle");
playerIdleBitmap = new createjs.Bitmap(playerIdleImage);
playerIdleBitmap.visible = false;
gameStage.addChild(playerIdleBitmap);
scoreText = new createjs.Text("Score: " + playerScore, "30px sans-serif", "yellow");
scoreText.x = canvas.width / 2 - (scoreText.getMeasuredWidth() * scaleW / 2);
scoreText.scaleX = scaleW;
scoreText.scaleY = scaleH;
scoreText.y = 30 * scaleH;
scoreText.visible = false;
gameStage.addChild(scoreText);
player = new Player();
ghostImage = preloadQ.getResult("ghost");
createjs.Ticker.setInterval(window.requestAnimationFrame);
createjs.Ticker.addEventListener("tick", gameLoop);
}
function gameLoop() {
update();
draw();
}
function update() {
if (newGame) {
logoScreenBitmap.visible = true;
playerIdleBitmap.visible = false;
floorBitmap.visible = false;
}
else {
if (isGameOver) {
isGameOver = false;
ghosts.length = 0;
gameStage.clear();
gameStage.addChild(logoScreenBitmap);
gameStage.addChild(floorBitmap);
gameStage.addChild(playerIdleBitmap);
gameStage.addChild(scoreText);
playerScore = 0;
gameStage.update();
}
logoScreenBitmap.visible = false;
playerIdleBitmap.visible = true;
floorBitmap.visible = true;
scoreText.visible = true;
playerScore += 1;
scoreText.text = ("Score: " + playerScore);
if (player.targetX > player.positionX) {
player.positionX += playerSpeed;
}
if (player.targetX < player.positionX) {
player.positionX -= playerSpeed;
}
if (player.targetY > player.positionY) {
player.positionY += playerSpeed;
}
if (player.targetY < player.positionY) {
player.positionY -= playerSpeed;
}
playerIdleBitmap.x = player.positionX - (player.width / 2);
playerIdleBitmap.y = player.positionY - (player.height / 2);
timeToAddNewGhost -= 1;
if (timeToAddNewGhost < 0) {
timeToAddNewGhost = 1000
ghosts.push(new Ghost(new createjs.Bitmap(ghostImage)));
ghosts[ghosts.length - 1].setStartPosition();
gameStage.addChild(ghosts[ghosts.length - 1].ghostBitmap);
}
for (var i = 0; i < ghosts.length; i++) {
ghosts[i].ghostBitmap.x = ghosts[i].positionX;
ghosts[i].ghostBitmap.y = ghosts[i].positionY;
ghosts[i].ghostBitmap.visible = true;
ghosts[i].move(player.positionX, player.positionY);
isGameOver = ghosts[i].isCollision(player.positionX, player.positionY, player.width, player.height);
if (isGameOver) {
break;
}
}
}
}
function draw() {
gameStage.update();
}
function Player() {
this.positionX = window.innerWidth / 2;
this.positionY = window.innerHeight / 2;
this.targetX = this.positionX;
this.targetY = this.positionY;
this.width = playerIdleBitmap.image.width * scaleW;
this.height = playerIdleBitmap.image.height * scaleH;
}
function Ghost(gfx) {
this.positionX = Math.random() * 5000 - 2500;
this.positionY = Math.random() * 3000 - 1500;
this.setStartPosition = function () {
if (this.positionX >= 0 && this.positionX <= window.innerWidth) {
this.positionX = -500;
}
if (this.positionY >= 0 && this.positionY <= window.innerHeight) {
this.positionY = -500;
}
}
this.targetX = 0;
this.targetY = 0;
this.move = function (tX, tY) {
this.targetX = tX;
this.targetY = tY;
if (this.targetX > this.positionX) {
this.positionX += ghostSpeed;
}
if (this.targetX < this.positionX) {
this.positionX -= ghostSpeed;
}
if (this.targetY > this.positionY) {
this.positionY += ghostSpeed;
}
if (this.targetY < this.positionY) {
this.positionY -= ghostSpeed;
}
}
this.isCollision = function (playerX, playerY, playerW, playerH) {
var centerX = this.positionX + (this.ghostBitmap.image.width * scaleW / 2);
var centerY = this.positionY + (this.ghostBitmap.image.height * scaleH / 2);
if ((centerX >= playerX - playerW / 2) && (centerX < playerX + playerW / 2)) {
if ((centerY >= playerY - playerH / 2) && (centerY < playerY + playerH / 2)) {
return true;
}
}
return false;
}
this.ghostBitmap = gfx;
}
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
document.addEventListener("DOMContentLoaded", initialize, false);
app.start();
})();
| JavaScript |
/// <reference path="jquery-1.7.1.js" />
/// <reference path="jquery-ui-1.8.20.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="knockout-2.1.0.debug.js" />
/// <reference path="modernizr-2.5.3.js" /> | JavaScript |
/// <reference path="UserModel.js" />
function taskModel(serverTaskModel) {
var self = this;
self.id = serverTaskModel != null ? ko.observable(serverTaskModel.Id) : ko.observable('unknown');
self.description = serverTaskModel != null ? ko.observable(serverTaskModel.Description) : ko.observable('unknown');
self.creationTime = serverTaskModel != null ? ko.observable(serverTaskModel.CreationTime) : ko.observable('unknown');
self.dueDate = serverTaskModel != null ? ko.observable(serverTaskModel.DueDate) : ko.observable('unknown');
self.originator = serverTaskModel != null ? ko.observable(new userModel(serverTaskModel.Originator)) : ko.observable('unknown');
return (serverTaskModel != null) ? self : 'unknown';
} | JavaScript |
function userModel(serverUserModel) {
var self = this;
self.id = serverUserModel != null ? ko.observable(serverUserModel.id) : ko.observable('unknown');
self.userName = serverUserModel != null ? ko.observable(serverUserModel.UserName) : ko.observable('unknown');
self.password = serverUserModel != null ? ko.observable(serverUserModel.Password) : ko.observable('unknown');
self.userType = serverUserModel != null ? ko.observable(serverUserModel.userType) : ko.observable(0);
return (serverUserModel != null) ? self : 'unknown';
} | JavaScript |
// JavaScript Document
function promptConfirm(){
var r = confirm("Are you sure about the entries?");
if (r==true){
return true;
}else{
return false;
}
}
function promptConfirmDelete(){
var r = confirm("Are you sure you want to delete this category?");
if (r==true){
return true;
}else{
return false;
}
} | JavaScript |
// Change product
function changeSupplies(partner){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(partner===''){
//Reset
var limit = $('#order_item_wrap .supplies_dropdown').length;
for(var i=0 ; i<limit ; i++){
document.getElementsByClassName("supplies_dropdown")[i].innerHTML = "<select name='supplies[]' style='width: 100%;'><option value=''>----SELECT----</option></select>";
}
}else{
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//var result_json = xmlhttp.responseText;
//var result_array = Json.parse(result_json);
var limit = $('#order_item_wrap .supplies_dropdown').length;
for(var i = 0 ; i<limit;i++){
//document.getElementById("supplies_dropdown").innerHTML = xmlhttp.responseText;
//document.getElementById("supplies_dropdown").innerHTML = xmlhttp.responseText;
document.getElementsByClassName("supplies_dropdown")[i].innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","helper/getsupplies.php?partner="+partner,true);
xmlhttp.send();
}
}
// Change product
function changePartner(partner){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(partner===''){
//Reset
document.document.getElementById("supplies_dropdown").innerHTML = "<select name='supplies' style='width: 90%;'><option value=''>----SELECT----</option></select>";
}else{
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("supplies_dropdown").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","helper/getsupplies2.php?partner="+partner,true);
xmlhttp.send();
}
}
// Add field
function getSum(){
var cost =document.getElementsByName("cost[]");
//alert(cost.length);
var sum = 0;
for(var i=0;i<cost.length;i++){
if(cost[i].value != ''){
sum += parseInt(cost[i].value, 10);
}
}
document.getElementById("estimated_total_cost").innerHTML = sum;
}
// get item list
function getOrderItem(field_id,order_id){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(order_id===''){
//Reset
var str = "order_item_";
var div_id = str.concat(field_id);
document.getElementById(div_id).innerHTML = "<select name='order_item[]' style='width: 100%;'><option value=''>----SELECT----</option></select>";
}else{
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var str = "order_item_";
var div_id = str.concat(field_id);
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","helper/getorderitem.php?invoice_id="+order_id,true);
xmlhttp.send();
}
}
// get sales batch list
// get item list
function getProductBatch(field_id,product_id){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(product_id===''){
//Reset
var div_id = "product_batch_"+field_id;
document.getElementById(div_id).innerHTML = "<select name='product_batch[]' style='width: 100%;'><option value=''>----SELECT----</option></select>";
}else{
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var str = "product_batch_";
var div_id = str.concat(field_id);
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","helper/getproductbatch.php?product_id="+product_id,true);
xmlhttp.send();
}
}
function updatePrice(field_id){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//get user input
var product_div = "product_"+field_id;
var product_id = document.getElementById(product_div).value;
var cal_quantity = "cal_quantity_"+field_id;
var product_quantity = document.getElementById(cal_quantity).value;
if(product_id!=='' && product_quantity!==''){
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var cal_single = "cal_single_"+field_id;
var cal_sub_total = "cal_sub_total_"+field_id;
document.getElementById(cal_single).innerHTML = xmlhttp.responseText;
document.getElementById(cal_sub_total).innerHTML = xmlhttp.responseText * product_quantity;
}
}
xmlhttp.open("GET","helper/getprice.php?product_id="+product_id,true);
xmlhttp.send();
}else{
//Reset
var cal_single = "cal_single_"+field_id;
var cal_sub_total = "cal_sub_total_"+field_id;
document.getElementById(cal_single).innerHTML = "";
document.getElementById(cal_sub_total).innerHTML = "";
}
}
function updateSales(num){
for(var i=0;i<num;i++){
updatePrice(i);
}
var total = 0;
for(var i=0;i<num;i++){
field_id = "cal_sub_total_" + i;
value = document.getElementById(field_id).innerHTML;
if(value !== ''){
subtotal = parseInt(value);
total = total + subtotal;
}
}
document.getElementById("cal_total").innerHTML = total;
} | JavaScript |
window.onload = function() {
myHeight = new fx.Height('nav', {duration: 400});
myHeight.hide();
} | JavaScript |
/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
10/24/2005
v(1.0.2)
*/
//base
var fx = new Object();
fx.Base = function(){};
fx.Base.prototype = {
setOptions: function(options) {
this.options = {
duration: 500,
onComplete: ''
}
Object.extend(this.options, options || {});
},
go: function() {
this.duration = this.options.duration;
this.startTime = (new Date).getTime();
this.timer = setInterval (this.step.bind(this), 13);
},
step: function() {
var time = (new Date).getTime();
var Tpos = (time - this.startTime) / (this.duration);
if (time >= this.duration+this.startTime) {
this.now = this.to;
clearInterval (this.timer);
this.timer = null;
if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
}
else {
this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;
//this time-position, sinoidal transition thing is from script.aculo.us
}
this.increase();
},
custom: function(from, to) {
if (this.timer != null) return;
this.from = from;
this.to = to;
this.go();
},
hide: function() {
this.now = 0;
this.increase();
},
clearTimer: function() {
clearInterval(this.timer);
this.timer = null;
}
}
//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.el.style.overflow = "hidden";
this.el.iniWidth = this.el.offsetWidth;
this.el.iniHeight = this.el.offsetHeight;
this.setOptions(options);
}
});
fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {
increase: function() {
this.el.style.height = this.now + "px";
},
toggle: function() {
if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
else this.custom(0, this.el.scrollHeight);
}
});
| JavaScript |
function create_menu(basepath)
{
var base = (basepath == 'null') ? '' : basepath;
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<ul>' +
'<li><a href="'+base+'index.html">User Guide Home</a></li>' +
'<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' +
'</ul>' +
'<h3>Basic Info</h3>' +
'<ul>' +
'<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' +
'<li><a href="'+base+'license.html">License Agreement</a></li>' +
'<li><a href="'+base+'changelog.html">Change Log</a></li>' +
'<li><a href="'+base+'general/credits.html">Credits</a></li>' +
'</ul>' +
'<h3>Installation</h3>' +
'<ul>' +
'<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' +
'<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' +
'<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' +
'<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' +
'</ul>' +
'<h3>Introduction</h3>' +
'<ul>' +
'<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' +
'<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' +
'<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' +
'<li><a href="'+base+'overview/features.html">Supported Features</a></li>' +
'<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' +
'<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' +
'<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' +
'</ul>' +
'<h3>Tutorial</h3>' +
'<ul>' +
'<li><a href="'+base+'tutorial/index.html">Introduction</a></li>' +
'<li><a href="'+base+'tutorial/static_pages.html">Static pages</a></li>' +
'<li><a href="'+base+'tutorial/news_section.html">News section</a></li>' +
'<li><a href="'+base+'tutorial/create_news_items.html">Create news items</a></li>' +
'<li><a href="'+base+'tutorial/conclusion.html">Conclusion</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>General Topics</h3>' +
'<ul>' +
'<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' +
'<li><a href="'+base+'general/controllers.html">Controllers</a></li>' +
'<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' +
'<li><a href="'+base+'general/views.html">Views</a></li>' +
'<li><a href="'+base+'general/models.html">Models</a></li>' +
'<li><a href="'+base+'general/helpers.html">Helpers</a></li>' +
'<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' +
'<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' +
'<li><a href="'+base+'general/drivers.html">Using CodeIgniter Drivers</a></li>' +
'<li><a href="'+base+'general/creating_drivers.html">Creating Your Own Drivers</a></li>' +
'<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' +
'<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' +
'<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' +
'<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' +
'<li><a href="'+base+'general/routing.html">URI Routing</a></li>' +
'<li><a href="'+base+'general/errors.html">Error Handling</a></li>' +
'<li><a href="'+base+'general/caching.html">Caching</a></li>' +
'<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' +
'<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' +
'<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' +
'<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' +
'<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' +
'<li><a href="'+base+'general/security.html">Security</a></li>' +
'<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' +
'<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' +
'</ul>' +
'<h3>Additional Resources</h3>' +
'<ul>' +
'<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' +
'<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Class Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' +
'<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' +
'<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' +
'<li><a href="'+base+'libraries/config.html">Config Class</a></li>' +
'<li><a href="'+base+'libraries/email.html">Email Class</a></li>' +
'<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' +
'<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' +
'<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' +
'<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' +
'<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' +
'<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' +
'<li><a href="'+base+'libraries/input.html">Input Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' +
'<li><a href="'+base+'libraries/language.html">Language Class</a></li>' +
'<li><a href="'+base+'libraries/migration.html">Migration Class</a></li>' +
'<li><a href="'+base+'libraries/output.html">Output Class</a></li>' +
'<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' +
'<li><a href="'+base+'libraries/security.html">Security Class</a></li>' +
'<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' +
'<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' +
'<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' +
'<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' +
'<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' +
'<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' +
'<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' +
'<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' +
'<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Driver Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' +
'<li><a href="'+base+'database/index.html">Database Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'</ul>' +
'<h3>Helper Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' +
'<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' +
'<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' +
'<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' +
'<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' +
'<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' +
'<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' +
'<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' +
'<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' +
'<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' +
'<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' +
'<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' +
'<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' +
'<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' +
'<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' +
'<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' +
'<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' +
'<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' +
'<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' +
'<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' +
'<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' +
'</ul>' +
'</td></tr></table>');
} | JavaScript |
/*$(document).ready(function(){
$("#resultScore").click(function(){
alert("기능이 준비중 입니다");
});
});*/
$(document).ready(function(){
$("#resultScore").click(function(){
var q1 = parseInt($("input[name='q1']:checked").val());
var q2 = parseInt($("input[name='q2']:checked").val());
var q3 = parseInt($("input[name='q3']:checked").val());
var q4 = parseInt($("input[name='q4']:checked").val());
var q5 = parseInt($("input[name='q5']:checked").val());
var q6 = parseInt($("input[name='q6']:checked").val());
var q7 = parseInt($("input[name='q7']:checked").val());
var q8 = parseInt($("input[name='q8']:checked").val());
var q9 = parseInt($("input[name='q9']:checked").val());
var q10 = parseInt($("input[name='q10']:checked").val());
var sum;
sum = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10;
if(100>=sum && sum>=80){
alert(sum+"점 : 와우~ 너무도 잘 알고 있는 스마트한 당신! 앞으로도 윤리경영실천에 더욱 앞장서 주세요.");
} else if(70>=sum && sum >=40) {
alert(sum+"점 : 나쁘지는 않지만 한 번 더 생각해보면 어떨까요? 그렇다면 당신의 윤리의식은 UP! UP! UP!");
} else if(30>=sum && sum >=0) {
alert(sum+"점 : 안돼요! 안돼! 윤리적 위기상태입니다 윤리경영실천! 생각보다 어렵지 않아요~ 시작이 반입니다. 작은 것부터 바꿔보세요");
} else {
alert("모든 질문에 답변해 주셔야 합니다.");
}
});
});
| JavaScript |
//pdf popup size 정의
function Pop_info1(url) {
var maxThisX = screen.width - 10;
var maxThisY = screen.height - 50;
window.open(url,"info","left=0,top=0,width="+maxThisX+",height="+maxThisY+",toolbar=no,scrollbars=yes,status=yes");
}
function Pop_info2(url) {
var maxThisX = screen.width - 10;
var maxThisY = screen.height - 50;
window.open(url,"info","left=0,top=0,width="+900+",height="+650+",toolbar=no,scrollbars=yes,status=yes").focus();
}
function Pop_info3(url) {
var maxThisX = screen.width - 10;
var maxThisY = screen.height - 50;
window.open(url,"info","left=0,top=0,width="+900+",height="+750+",toolbar=no,scrollbars=yes,status=yes").focus();
}
function Pop_info4(url) {
var maxThisX = screen.width - 10;
var maxThisY = screen.height - 50;
window.open(url,"info","left=0,top=0,width="+1000+",height="+750+",toolbar=no,scrollbars=yes,status=yes").focus();
}
function Pop_info5(url) {
var maxThisX = screen.width - 10;
var maxThisY = screen.height - 50;
/*location.href="/admin/caseAddpop.hcom?case_seq="+$("boardBean.case_seq ").val()+"&court_step="+$("1");*/
window.open(url,"info","left=0,top=0,width="+550+",height="+600+",toolbar=no,scrollbars=no,status=yes").focus();
}
function Pop_info6(url) {
var maxThisX = screen.width - 10;
var maxThisY = screen.height - 50;
window.open(url,"info","left=0,top=0,width="+850+",height="+930+",toolbar=no,scrollbars=yes,status=yes").focus();
}
| JavaScript |
$(document).ready(function(){
//########### jquery UI DatePicker 캘린더 호출 및 설정 시작. ##############
$(".datepicker").datepicker({
showOn: "both", // 버튼과 텍스트 필드 모두 캘린더를 보여준다.
buttonImage: "/images/admin/icon_calendar.png", // 버튼 이미지
buttonImageOnly: true, // 버튼에 있는 이미지만 표시한다.
changeMonth: true, // 월을 바꿀수 있는 셀렉트 박스를 표시한다.
changeYear: true, // 년을 바꿀 수 있는 셀렉트 박스를 표시한다.
minDate: '-100y', // 현재날짜로부터 100년이전까지 년을 표시한다.
nextText: '다음 달', // next 아이콘의 툴팁.
prevText: '이전 달', // prev 아이콘의 툴팁.
numberOfMonths: [1,1], // 한번에 얼마나 많은 월을 표시할것인가. [2,3] 일 경우, 2(행) x 3(열) = 6개의 월을 표시한다.
//stepMonths: 3, // next, prev 버튼을 클릭했을때 얼마나 많은 월을 이동하여 표시하는가.
yearRange: 'c-100:c+10', // 년도 선택 셀렉트박스를 현재 년도에서 이전, 이후로 얼마의 범위를 표시할것인가.
showButtonPanel: true, // 캘린더 하단에 버튼 패널을 표시한다.
currentText: '오늘 날짜' , // 오늘 날짜로 이동하는 버튼 패널
closeText: '닫기', // 닫기 버튼 패널
dateFormat: "yymmdd", // 텍스트 필드에 입력되는 날짜 형식.
showAnim: "slide", //애니메이션을 적용한다.
showMonthAfterYear: true , // 월, 년순의 셀렉트 박스를 년,월 순으로 바꿔준다.
dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'], // 요일의 한글 형식.
monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'] // 월의 한글 형식.
});
//########### jquery UI DatePicker 캘린더 호출 및 설정 끝. ##############
}); | JavaScript |
$(".openpw").click(function(){
//var pw = $(this).children().text();
var auth = $("#auth").val().toUpperCase();
auth = $.trim(auth);
/*alert$("#pw").val(pw);*/
if(auth == 'ADMIN' || auth == 'LEADER'){
location.href = $(this).children().attr('id');
}else{
var pw = $(this).attr('id');
pw = $.trim(pw);
//$("#url").val($(this).children().attr('id', 'empPw').);
$("#pw").val(pw);
if(pw == ''){
location.href = $(this).children().attr('id');
}else{
$("#url").val($(this).children().attr('id'));
$("#pwPop").center();
$("#pwPop").css('display','');
}
}
});
$("#btn_close").click(function(){
$("#pw_confirm").val('');
$("#pwPop").css('display','none');
});
$("#btn_confirm").click(function(){
var str = $("#pw_confirm").val();
if(str == null){
alert('비밀번호를 입력하세요.');
}else{
if($("#pw").val() == str){
location.href = $("#url").val();
}else{
alert('비밀번호가 틀렸습니다.');
$("#pw_confirm").val('');
$("#pw_confirm").focus();
}
}
});
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
} | JavaScript |
// JavaScript Document
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}
//동영상
function aviPlay(src,w,h) {
document.write('<embed src="'+src+'" width='+w+' height='+h+'>')
}
/*png 투명이미지 처리*/
function setPng24(obj) {
obj.width=obj.height=1;
obj.className=obj.className.replace(/\bpng24\b/i,'');
obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ obj.src +"',sizingMethod='image');"
obj.src='';
return '';
}
/*IE6 Background Flicker 버그 수정*/
(function(){
var m = document.uniqueID
&& document.compatMode
&& !window.XMLHttpRequest
&& document.execCommand;
try{
if(!!m){
m("BackgroundImageCache",false,true)
}
}catch(oh){};
})();
/*IE6 Background Flicker 버그 수정*/
/* 플래시 처리*/
function insertFlash(swf, width, height, bgcolor, id, flashvars, title)
{
var strFlashTag = new String();
if (navigator.appName.indexOf("Microsoft") != -1)
{
strFlashTag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
strFlashTag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=version=8,0,0,0" ';
strFlashTag += 'id="' + id + '" title="' + title + '" width="' + width + '" height="' + height + '">';
strFlashTag += '<param name="movie" value="' + swf + '"/>';
if(flashvars != null) {strFlashTag += '<param name="flashvars" value="' + flashvars + '"/>'};
strFlashTag += '<param name="quality" value="best"/>';
strFlashTag += '<param name="bgcolor" value="' + bgcolor + '"/>';
strFlashTag += '<param name="menu" value="false"/>';
strFlashTag += '<param name="salign" value="LT"/>';
strFlashTag += '<param name="scale" value="noscale"/>';
strFlashTag += '<param name="wmode" value="transparent"/>';
strFlashTag += '<param name="allowScriptAccess" value="sameDomain"/>';
strFlashTag += '</object>';
}
else
{
strFlashTag += '<embed src="' + swf + '" ';
strFlashTag += 'quality="best" ';
strFlashTag += 'bgcolor="' + bgcolor + '" ';
strFlashTag += 'width="' + width + '" ';
strFlashTag += 'height="' + height + '" ';
strFlashTag += 'menu="false" ';
strFlashTag += 'scale="noscale" ';
strFlashTag += 'id="' + id + '" ';
strFlashTag += 'salign="LT" ';
strFlashTag += 'wmode="transparent" ';
strFlashTag += 'allowScriptAccess="sameDomain" ';
if(flashvars != null) {strFlashTag += 'flashvars="' + flashvars + '" '};
strFlashTag += 'type="application/x-shockwave-flash" ';
strFlashTag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
strFlashTag += '</embed>';
}
document.write(strFlashTag);
}
function insertFlash2(swf, width, height, bgcolor, id, flashvars, title,noobj)
{
var strFlashTag = new String();
strFlashTag += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" id="' + id + '" title="' + title + '" width="' + width + '" height="' + height + '" align="middle">';
strFlashTag += '<param name="movie" value="' + swf + '" />';
strFlashTag += '<param name="quality" value="best"/>';
strFlashTag += '<param name="flashvars" value="'+flashvars+'" />';
strFlashTag += '<param name="allowFullScreen" value="false" />';
strFlashTag += '<param name="quality" value="high" />';
strFlashTag += '<param name="wmode" value="transparent" />';
strFlashTag += '<param name="scale" value="noscale"/>';
strFlashTag += '<param name="bgcolor" value="#ffffff" />';
strFlashTag += '<object type="application/x-shockwave-flash" data="' + swf + '" id="' + id + '_noobj" title="' + title + '" width="' + width + '" height="' + height + '">';
strFlashTag += '<param name="flashvars" value="'+flashvars+'" />';
strFlashTag += '<param name="quality" value="best"/>';
strFlashTag += '<param name="menu" value="false"/>';
strFlashTag += '<param name="salign" value="LT"/>';
strFlashTag += '<param name="scale" value="noscale"/>';
strFlashTag += '<param name="wmode" value="transparent"/>';
strFlashTag += '<param name="allowScriptAccess" value="sameDomain"/>';
strFlashTag += noobj.innerHTML;
strFlashTag += '</object>';
strFlashTag += '</object>';
document.write(strFlashTag);
}
/* 플래시 처리*/
/* 웹접근성에 이용할 플래시 로더 스크립트*/
function SWFLoader() {
var obj = new String;
var parameter = new String;
var embed = new String;
var classId = new String;
var codeBase = new String;
var pluginSpage = new String;
var embedType = new String;
var allParameter = new String;
var src = new String;
var width = new String;
var height = new String;
var id = new String;
var title = new String;
var layer = new String;
var arg = new String;
var altText = new String;
var wmode = new String;
this.init = function ( w, h, s, a ) {
width = w;
height = h;
src = s;
arg = a;
wmode = 'transparent';
classId = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';
codeBase = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0';
pluginSpage = 'http://www.macromedia.com/go/getflashplayer';
embedType = 'application/x-shockwave-flash';
parameter += "<param name='allowScriptAccess' value='always'>\n";
parameter += "<param name='allowFullScreen' value='false'\n>";
parameter += "<param name='movie' value='"+ s + "'>\n";
parameter += "<param name='quality' value='best'/>\n";
parameter += "<param name='base' value='.'>\n";
parameter += "<param name='scale' value='noscale'/>\n";
parameter += "<param name='expressinstall' value='Scripts/expressInstall.swf' />\n";
}
this.parameter = function ( param, value ) {
parameter += "<param name='"+param +"' value='"+ value + "'>\n";
}
this.wmode = function ( value ) {
wmode = value;
}
this.id = function ( value ) {
id = value;
}
this.title = function ( value ) {
title = value;
}
this.shocknone = function ( value ) {
altText = value;
}
this.layer = function ( value ) {
if(value == undefined) {
layer = "";
} else {
layer = value;
}
}
this.show = function () {
obj = '<object id="'+id+'" width="'+width+'" height="'+height+'" title="'+title+'" classid="'+classId+'" codebase="'+codeBase+'">\n'+
parameter +
'<param name="wmode" value="'+wmode+'">\n'+
'<!--[if !IE]>-->\n' +
'<object type="application/x-shockwave-flash" data="' + src + '" width="' + width + '" height="' + height + '" name="' + id + '">\n' +
parameter +
'<param name="wmode" value="'+wmode+'">\n'+
'<!--<![endif]-->\n' +
'<div class="alt-content alt-' + id + '2">' + altText + '</div>\n' +
'<!--[if !IE]>-->\n' +
'</object>\n' +
'<!--<![endif]-->\n' +
'</object>';
if(layer == "") {
document.write(obj);
}else{
var div = document.getElementById( layer);
div.style.display = "";
div.innerHTML = obj;
}
}
}
/* 웹접근성에 이용할 플래시 로더 스크립트*/
/* font 사이즈 */
var ttsenv_fontRate = 2;
var ttsenv_fontmaxRate = 19;
var ttsenv_fontminRate = 10;
var ttsenv_fontDefault = '';
var ttsenv_mustadjustfont = true;
var ttsenv_fontcolor = new Array();
var tts_curRate;
var tts_fontcolorindex;
var tts_bgcolorindex;
var tts_curfontsize;
var ttsenv_bgcolor = new Array();
ttsenv_fontcolor[0] = "";
ttsenv_fontcolor[1] = "#000000";
ttsenv_fontcolor[2] = "#ffff00";
ttsenv_fontcolor[3] = "#ffffff";
ttsenv_fontcolor[4] = "#6666ff";
ttsenv_fontcolor[5] = "#ff6666";
ttsenv_fontcolor[6] = "#ff66ff";
ttsenv_fontcolor[7] = "#66ff66";
ttsenv_bgcolor[0] = "";
ttsenv_bgcolor[1] = "#ffffff";
ttsenv_bgcolor[2] = "#000000";
ttsenv_bgcolor[3] = "#6666ff";
ttsenv_bgcolor[4] = "#ff6666";
ttsenv_bgcolor[5] = "#ff66ff";
ttsenv_bgcolor[6] = "#66ff66";
function f_scalescreen(mode)
{
if((document.body.style.zoom==null)||(ttsenv_mustadjustfont==true)) {
if(mode==1) {
if(tts_curfontsize==null) {
tts_curfontsize=ttsenv_fontminRate;
} else if(tts_curfontsize=='') {
tts_curfontsize=ttsenv_fontminRate;
} else {
tts_curfontsize=tts_curfontsize-(-ttsenv_fontRate);
if(tts_curfontsize>ttsenv_fontmaxRate) {
tts_curfontsize=ttsenv_fontmaxRate;
}
}
} else if(mode==-1) {
if(tts_curfontsize!=null) {
if(tts_curfontsize!='') {
tts_curfontsize=tts_curfontsize-ttsenv_fontRate;
if(tts_curfontsize<ttsenv_fontminRate) {
tts_curfontsize='';
}
}
}
}
webgen_setface();
}
}
function f_setBasic()
{
tts_curfontsize = '';
// var objSelectBox = document.getElementById("selectSite");
// objSelectBox.selectedIndex = 0;
webgen_setface();
}
function webgen_setface()
{
webgen_setface_run(document.body);
if(document.getElementById('select')!=null) {
document.getElementById('select').selectedIndex = parseInt(tts_fontcolorindex);
}
if(document.getElementById('select')!=null) {
document.getElementById('select').selectedIndex = parseInt(tts_bgcolorindex);
}
}
function webgen_setface_run(obj) {
if(obj==null) {
return;
}
if(obj.childNodes!=null) {
var i;
var s=false;
if(obj.style!=null) {
obj.style.backgroundColor=ttsenv_bgcolor[tts_bgcolorindex];
obj.style.color=ttsenv_fontcolor[tts_fontcolorindex];
}
for(i=0;i<obj.childNodes.length;i++) {
if(obj.childNodes[i].nodeName=="#text") {
if(s==false) {
if(obj.style!=null) {
if((document.body.style.zoom==null)||(ttsenv_mustadjustfont==true)) {
if(tts_curfontsize==null) {
obj.style.fontSize='';
} else if(tts_curfontsize=='') {
obj.style.fontSize='';
} else {
obj.style.fontSize=tts_curfontsize+'pt';
}
}
}
s=true;
}
} else {
webgen_setface_run(obj.childNodes[i]);
}
}
}
}
/* font 사이즈 */ | JavaScript |
//슬라이드메뉴
$(function(){
$('#question').click(function(){ //오버시 슬라이드될 버튼 지정
$('#answer').slideDown('fast'); //슬라이드될 메뉴지정
});
$('#answer').click(function(){ //슬라이드가 닫히는 영역을 지정
$('#question').slideUp('fast'); //슬라이드될 메뉴지정
});
});
| JavaScript |
$(document).ready(function(){
$('.navi_b').click(function(){
left_default();
$('.'+this.id.replace('left' , 'sub')).slideDown();
});
$("#Home").click(function(){
location.href = "/";
});
$("#LogOut").click(function(){
location.href = "/adminIndex/AD01/ad0102";
});
$("#AdminPwd").click(function(){
location.href = "/admin/AD02/ad0201";
});
});
function left_default(){
$('.sub_menu_01').slideUp();
$('.sub_menu_02').slideUp();
$('.sub_menu_03').slideUp();
$('.sub_menu_04').slideUp();
$('.sub_menu_05').slideUp();
$('.sub_menu_06').slideUp();
}
| JavaScript |
$(document).ready(function(){
var oEditors = [];
// 에디터 생성
nhn.husky.EZCreator.createInIFrame({
oAppRef: oEditors,
elPlaceHolder: "content",
sSkinURI: "/sEditor/SmartEditor2Skin.html",
fCreator: "createSEditor2",
});
function pasteHTMLDemo(){
sHTML = "<span style='color:#FF0000'>이미지 등도 이렇게 삽입하면 됩니다.</span>";
oEditors.getById["content"].exec("PASTE_HTML", [sHTML]);
}
function showHTML(){
alert(oEditors.getById["content"].getIR());
}
$("#btn_libReg").click(function(){
oEditors[0].exec("UPDATE_CONTENTS_FIELD", []);
if(validateCheck()){
if(confirm("등록하시겠습니까?")) {
$("#libFrm").submit();
}
}
});
$("#btn_qnaReg").click(function(){
oEditors[0].exec("UPDATE_CONTENTS_FIELD", []);
if(validateCheck()){
if(confirm("등록하시겠습니까?")) {
$("#qnaFrm").submit();
}
}
});
$("#btn_cyberReg").click(function(){
oEditors[0].exec("UPDATE_CONTENTS_FIELD", []);
if(validateCheck()){
if(confirm("등록하시겠습니까?")) {
$("#cyberFrm").submit();
}
}
});
$("#btn_libModi").click(function(){
oEditors[0].exec("UPDATE_CONTENTS_FIELD", []);
if(validateCheck()){
if(confirm("수정하시겠습니까?")) {
$("#libModiFrm").submit();
}
}
});
$("#btn_qnaModi").click(function(){
oEditors[0].exec("UPDATE_CONTENTS_FIELD", []);
if(validateCheck()){
if(confirm("수정하시겠습니까?")) {
$("#qnaModiFrm").submit();
}
}
});
function validateCheck(){
if($("#title").val() == ''){
alert('제목을 입력해주십시요');
$("#title").focus();
return false;
}
if($("#content").val() == ''){
alert('내용을입력해주십시요');
return false;
}
return true;
}
}); | JavaScript |
if(window.addEventListener){
//window.addEventListener("load", checkVersion, true); // FF
}else{
window.attachEvent("onload",checkVersion); // IE
}
function getInternetExplorerVersion() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function checkVersion() {
var ver = getInternetExplorerVersion();
var msg = "";
/*
if (ver > -1)
msg = "You are using Internet Explorer " + ver;
else
msg = "You are not using Internet Explorer";
*/
if( ver == 6 || ver == 7 ){
if ( iecheck_getCookie( "iecheck" ) != "done" )
{
window.open('/center/popup/20120209/pop_20120209.html', '', 'width=660, height=495,scrollbars=yes,top=50,left=50');
}
}else{
//window.open('/center/popup/20120209/pop_20120209.html', '', 'width=660, height=488,scrollbars=yes,top=50,left=50');
}
}
function iecheck_getCookie( name )
{
var nameOfCookie = name + "=";
var x = 0;
while ( x <= document.cookie.length )
{
var y = (x+nameOfCookie.length);
if ( document.cookie.substring( x, y ) == nameOfCookie ) {
if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
endOfCookie = document.cookie.length;
return unescape( document.cookie.substring( y, endOfCookie ) );
}
x = document.cookie.indexOf( " ", x ) + 1;
if ( x == 0 )
break;
}
return "";
} | JavaScript |
function removeCache()
{
document.DSWC_IEG.DeleteCache();
setTimeout("removeCache()", 20000);
}
function disableselect(e)
{
return false;
}
function reEnable()
{
return true;
}
if (navigator.appName != "Netscape")
{
document.onselectstart=new Function ("return false");
document.oncontextmenu=new Function ("return false");
document.ondragstart=new Function ("return false");
}
else
{
if (window.sidebar)
{
document.onmousedown=disableselect;
document.onclick=reEnable;
}
}
function StartGuard(right)
{
if (navigator.appName != "Netscape")
{
var nav;
nav = window.navigator.userAgent;
//alert(nav);
// NT 3,4 일경우 그냥 통과
if ((nav.indexOf("NT)") >= 0) || (nav.indexOf("NT 4") >= 0) || (nav.indexOf("NT 3") >= 0))
{
return;
}
if (typeof(document.DSWC_IEG.ErrMsg) != "undefined")
{
document.DSWC_IEG.LicenseString = "ZaoQdxa4tl79dGwTOu95OBQh4SV1x1D4pUjB6YFfRGU9Tf6rH/npZknKgFPOX0vYsBq9sh1wyaZprnZ6Q6FiPpLX+kAHczLmfzhxOcamDCtwLUaUrvRlQ881e8B4vmJ1P5o5oP6KCwfQ1Erv0T6njLmOlIHyz5jMHR6Y3E2UkAuAn6GSiCEKHKrCSGYveRq5VBdOmAgYAHcEOeJRZcPG/w==";
document.DSWC_IEG.Start(right);
document.DSWC_CP.ClearList();
document.DSWC_CP.AddList("","IrfanView","i_view32");
document.DSWC_CP.AddList("SnagIt","SnagIt5UI","");
document.DSWC_CP.AddList("Configure Screenshot Utility","TConfigForm","");
document.DSWC_CP.AddList("ScreenGet","#32770","");
document.DSWC_CP.AddList("Mr. Captor","MrCaptorClass","");
document.DSWC_CP.AddList("Capturex","TMainfrm","");
document.DSWC_CP.AddList("Capture Professional v5","CSWORX-CP5","");
document.DSWC_CP.AddList("ScreenSharePro","TScreenShareDlg","");
document.DSWC_CP.AddList("ScreenSharePro","TEditCenterDlg","");
document.DSWC_CP.AddList("Easy Screen Capture 1.22","TfrmMain","");
document.DSWC_CP.AddList("HardCopy Pro","#32770","");
document.DSWC_CP.AddList("CaptureEze Pro - What would you like to do?","CzeProFrameCls","");
document.DSWC_CP.AddList("20/20 v2.2","TMainForm","");
document.DSWC_CP.AddList("SD Capture","#32770","");
document.DSWC_CP.AddList("HotShot","TfrmHotShot","");
document.DSWC_CP.AddList("Grabbit 2","#32770","");
document.DSWC_CP.AddList("ClipMate [Short-Term]","TfrmCM","");
document.DSWC_CP.StartAction();
removeCache();
}
}
}
function ObjectWrite()
{
var nav;
nav = window.navigator.userAgent;
// NT 3,4 일경우 그냥 통과
if ((nav.indexOf("NT)") >= 0) || (nav.indexOf("NT 4") >= 0) || (nav.indexOf("NT 3") >= 0))
{
return;
}
document.write("<object id=DSWC_IEG codeBase='/jlandsoft/DSWC.cab#version=1,0,1,4'" +
" height=0 width=0 classid=CLSID:196300A5-09A2-4C9D-9B67-3A1F5168A025 name=DSWC_IEG>" +
" </object>" +
" <object id=DSWC_CP " +
" codeBase='../DSWC-5253.cab#version=1,0,1,4'" +
" height=0 width=0 classid=CLSID:25A4A1F7-309C-4C0E-9603-4C885EC05E84 name=DSWC_CP>" +
" </object>");
}
/*
var check_url = false;
var home_url="http://ekp.hdel.co.kr";
*/
//허가 referer
/*var allow_url = [
'http://ekp.hdel.co.kr',
'http://localhost:8080',
'http://localhost:8080/test.jsp',
'http://compliance.hdel.co.kr',
'http://compliance.hdel.co.kr/test.jsp',
'http://localhost:8080/main/login.hcom?id=6&dept=ECG&position=사원&name=이윤아&email=steve@ecglobal.co.kr',
];*/
/*var len = allow_url.length;
for(var i=0; i<len; i++) {
if(document.referrer.indexOf(allow_url[i])!=-1) {
//이 하위주소옆으로 다포함 indexOf("http://compliance.hdel.co.kr");
// indexOf("http://localhost:8080/")
check_url = true;
}
}
if(check_url===false) {
alert("비정상적인 접근으로 확인되어 초기화면으로 돌아갑니다.");
window.location=home_url;
}*/
| JavaScript |
$(document).ready(function(){
$("#resultScore").click(function(){
var q1 = parseInt($("input[name='q1']:checked").val());
var q2 = parseInt($("input[name='q2']:checked").val());
var q3 = parseInt($("input[name='q3']:checked").val());
var q4 = parseInt($("input[name='q4']:checked").val());
var q5 = parseInt($("input[name='q5']:checked").val());
var q6 = parseInt($("input[name='q6']:checked").val());
var q7 = parseInt($("input[name='q7']:checked").val());
var q8 = parseInt($("input[name='q8']:checked").val());
var q9 = parseInt($("input[name='q9']:checked").val());
var q10 = parseInt($("input[name='q10']:checked").val());
var sum;
sum = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10;
if(100>=sum && sum>=80){
//alert(sum+"점 : 와우~ 너무도 잘 알고 있는 스마트한 당신! 앞으로도 윤리경영실천에 더욱 앞장서 주세요.");
$("#dialogPop")
.css({
position:'absolute',
left: ($(window).width() - $("#dialogPop").outerWidth()) / 2,
top: ($(document).height() + $(document).scrollTop() - $("#dialogPop").outerHeight()) / 2,
display: ''
});
//$("#pop_txt").html("<span><font size=6 color='red'><Strong>" + sum + "</Strong></font></span> <img src='/images/ethic/popup_img.gif'/>");
//$("#pop_txt").html(sum + "<img src='/images/ethic/popup_img.gif'/>");
$("#dialogPop").html("<div id='popup'><div class='pop_box'><dl class='pop_txt'><dd class='pop_txt2'>" + sum + "</dd><dd class='pop_txt3'><img src='/images/ethic/popup_img.gif'/></dd></dl>" +
"<dl class='pop_img'><img src='/images/ethic/popup_best.gif'/></dd></dl></div></div>");
} else if(70>=sum && sum >=40) {
$("#dialogPop")
.css({
position:'absolute',
left: ($(window).width() - $("#dialogPop").outerWidth()) / 2,
top: ($(document).height() + $(document).scrollTop() - $("#dialogPop").outerHeight()) / 2,
display: ''
});
/*alert(sum+"점 : 나쁘지는 않지만 한 번 더 생각해보면 어떨까요? 그렇다면 당신의 윤리의식은 UP! UP! UP!");*/
$("#dialogPop").html("<div id='popup'><dlv class='pop_box'><dl class='middle_txt'><dd class='middle_txt2'>" + sum + "</dd><dd class='pop_txt3'><img src='/images/ethic/popup_img.gif'/></dd></dl>" +
"<dl class='middle_img'><dd class='middle_img2'><img src='/images/ethic/popup_middle.gif' width='252' height='98'/></dd></dl></div></div>");
} else if(30>=sum && sum >=0) {
$("#dialogPop")
.css({
position:'absolute',
left: ($(window).width() - $("#dialogPop").outerWidth()) / 2,
top: ($(document).height() + $(document).scrollTop() - $("#dialogPop").outerHeight()) / 2,
display: ''
});
/*alert(sum+"점 : 안돼요! 안돼! 윤리적 위기상태입니다 윤리경영실천! 생각보다 어렵지 않아요~ 시작이 반입니다. 작은 것부터 바꿔보세요");*/
$("#dialogPop").html("<div id='popup'><div class='pop_box'><dl class='down_txt'><dd class='down_txt2'>" + sum + "</dd><dd class='pop_txt3'><img src='/images/ethic/popup_img.gif'/></dd></dl>" +
"<dl class='down_img'><dd class ='down_img2'><img src='/images/ethic/popup_down.gif' width='252' height='98'/></dd></dl></div></div>");
} else {
alert("모든 질문에 답변해 주셔야 합니다.");
}
});
$("#dialogPop").click(function(){
$("#dialogPop").css('display', 'none');
});
});
| JavaScript |
$(document).ready(function(){
if($("#nameS").val() == null | $("#nameS").val()=="") {
alert("그룹웨어를 통해서 접근해 주십시오.");
location.href="http://ekp.hdel.co.kr";
} else {}
});
$().ready(function(){
$("#logout").click(function(){
alert("로그아웃되었습니다");
/*window.close();*/
window.opener = "nothing";
window.open('', '_parent', '');
window.close();
});
});
| JavaScript |
$(document).ready(function(){
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-34800159-1']);
_gaq.push(['_setDomainName', 'hdel.co.kr']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
});
| JavaScript |
$(document).ready(function(){
function movePage(page){
$("#currentPage").val(page);
//$("#searchForm").submit();
//alert($("#board_type").val());
location.href="/board/qnaList.ipsms?board_code="+$("#board_code").val()+"¤tPage="+$("#currentPage").val(page);
}
}); | JavaScript |
/*
*
//슬라이드메뉴
$(function(){
$('.lnb_box').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.top_menu').slideDown('fast'); //슬라이드될 메뉴지정
});
$('#header').siblings().mouseover(function(){ //슬라이드가 닫히는 영역을 지정
$('.top_menu').slideUp('fast'); //슬라이드될 메뉴지정
//왼쪽 어디로 가든 topmenu에서 떠나도 올라와
$('.top_menu').mouseleave(function(){
$(".top_menu").slideUp('fast');
});
});
});
*/
/*//show hide
$(function(){
$('.uj1').hide(); //윤리경영 숨기기
$('.uj2').hide(); //준법지원 숨기기
$('.uj3').hide(); //공정거래 숨기기
$('.uj4').hide(); //업무지원 숨기기
$('.uj5').hide(); //사이버제보 숨기기
//$('.lnb1').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.lnb1').click(function(){ //오버시 슬라이드될 버튼 지정
$('.uj1').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb1').mouseleave(function(){ //여기 떠나면
$(".uj1").slideUp('fast'); //숨기자
});
$('.lnb2').click(function(){ //오버시 슬라이드될 버튼 지정
$('.uj2').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb2').mouseleave(function(){ //여기 떠나면
$(".uj2").slideUp('fast'); //숨기자
});
$('.lnb3').click(function(){ //오버시 슬라이드될 버튼 지정
$('.uj3').slideDown('fast'); //슬라이드될 메뉴지정
$('.uj2').hide(); //준법지원 숨기기
$('.uj1').hide(); //공정거래 숨기기
$('.uj4').hide(); //업무지원 숨기기
$('.uj5').hide(); //사이버제보 숨기기
});
$('.lnb3').mouseleave(function(){ //여기 떠나면
$(".uj3").hide(); //숨기자
});
$('.lnb4').click(function(){ //오버시 슬라이드될 버튼 지정
$('.uj4').slideDown('fast'); //슬라이드될 메뉴지정
$('.uj1').hide(); //윤리경영 숨기기
$('.uj2').hide(); //준법지원 숨기기
$('.uj3').hide(); //공정거래 숨기기
$('.uj5').hide(); //사이버제보 숨기기
});
$('.lnb4').mouseleave(function(){ //여기 떠나면
$(".uj4").hide(); //숨기자
});
$('.lnb5').click(function(){ //오버시 슬라이드될 버튼 지정
$('.uj5').slideDown('fast'); //슬라이드될 메뉴지정
$('.uj1').hide(); //윤리경영 숨기기
$('.uj2').hide(); //준법지원 숨기기
$('.uj3').hide(); //공정거래 숨기기
$('.uj4').hide(); //업무지원 숨기기
});
$('.lnb5').mouseleave(function(){ //여기 떠나면
$(".uj5").hide(); //숨기자
});*/
/*
$(function(){
$('.uj1').hide(); //윤리경영 숨기기
$('.uj2').hide(); //준법지원 숨기기
$('.uj3').hide(); //공정거래 숨기기
$('.uj4').hide(); //업무지원 숨기기
$('.uj5').hide(); //사이버제보 숨기기
$('.lnb1').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.uj1').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb1').mouseleave(function(){ //여기 떠나면
$(".uj1").slideUp('fast'); //숨기자
});
$('.lnb2').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.uj2').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb2').mouseleave(function(){ //여기 떠나면
$(".uj2").slideUp('fast'); //숨기자
});
$('.lnb3').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.uj3').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb3').mouseleave(function(){ //여기 떠나면
$(".uj3").slideUp('fast'); //숨기자
});
$('.lnb4').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.uj4').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb4').mouseleave(function(){ //여기 떠나면
$(".uj4").slideUp('fast'); //숨기자
});
$('.lnb5').mouseover(function(){ //오버시 슬라이드될 버튼 지정
$('.uj5').slideDown('fast'); //슬라이드될 메뉴지정
});
$('.lnb5').mouseleave(function(){ //여기 떠나면
$(".uj5").slideUp('fast'); //숨기자
});
});
*/
//결국 고퀄리티는 개나줘버리게됫네
$(function(){
$('.uj1').hide(); //윤리경영 숨기기
$('.uj2').hide(); //준법지원 숨기기
$('.uj3').hide(); //공정거래 숨기기
$('.uj4').hide(); //업무지원 숨기기
$('.uj5').hide(); //사이버제보 숨기기
$(".lnb1").mouseenter(function() { //마우스 진입 감지 이벤트
$('.uj1').show(); //슬라이드 다운
})
.mouseleave(function() { //마우스 떠나면~
$('.uj1').hide(); //숨겟지
});
$(".lnb2").mouseenter(function() {
$('.uj2').show();
})
.mouseleave(function() {
$('.uj2').hide();
});
$(".lnb3").mouseenter(function() {
$('.uj3').show();
})
.mouseleave(function() {
$('.uj3').hide();
});
$(".lnb4").mouseenter(function() {
$('.uj4').show();
})
.mouseleave(function() {
$('.uj4').hide();
});
$(".lnb5").mouseenter(function() {
$('.uj5').show();
})
.mouseleave(function() {
$('.uj5').hide();
});
}); | JavaScript |
/*
* JQuery Rolling
* songsungkyun@naver.com
* 2008/03/16
*/
(function($) {
var rollingParam = {};
$.fn.rolling = function(rollingDirection, rollingItemWidth, rollingItemHeight, viewingItemCount) {
var rollingId = new Date().getTime();
var id = this.attr("id");
rollingParam[rollingId] = {
id: id,
rollingIsStarted: false,
rollingItemCount: 0,
rollingAnimationIndex: 0,
rollingItemWidth: 0,
rollingItemHeight: 0,
viewingItemCount: 0,
rollingTime: 0,
viewingTime: 0,
rollingAnimationFrame: 0,
rollingDirection: null,
rollingLeft: 0,
rollingTop: 0,
requestReverse: false,
newRollingAnimationFrame: 0
};
var param = rollingParam[rollingId];
param.rollingDirection = rollingDirection;
param.rollingItemWidth = rollingItemWidth;
param.rollingItemHeight = rollingItemHeight;
if (viewingItemCount == undefined) {
param.viewingItemCount = 1;
} else {
param.viewingItemCount = viewingItemCount;
}
if (param.rollingDirection == "left" ||
param.rollingDirection == "right") {
this.css("width", param.rollingItemWidth * param.viewingItemCount);
this.css("height", param.rollingItemHeight);
} else if (param.rollingDirection == "up" ||
param.rollingDirection == "down") {
this.css("width", param.rollingItemWidth);
this.css("height", param.rollingItemHeight * param.viewingItemCount);
}
this.css("position", "relative");
this.css("overflow", "hidden");
this.attr("rollingId", rollingId);
this.empty();
rollingContentDiv = $("<div/>").appendTo(this);
rollingContentDiv.attr("id", rollingId);
rollingContentDiv.css("position", "absolute");
rollingContentDiv.attr("align", "left");
rollingContentDiv.css("left", "0");
rollingContentDiv.css("top", "0");
return this;
};
$.fn.addRollingItem = function(html) {
var param = rollingParam[this.attr("rollingId")];
var rollingContentDiv = $("#" + this.attr("rollingId"));
param.rollingItemCount++;
var rollingItem = null;
if (param.rollingDirection == "up") {
rollingItem = $("<div class='item'/>").appendTo(rollingContentDiv);
} else if (param.rollingDirection == "right") {
rollingItem = $("<div class='item'/>").prependTo(rollingContentDiv);
rollingItem.css("float", "left");
rollingContentDiv.css("width", param.rollingItemCount * param.rollingItemWidth);
rollingContentDiv.css("left", -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemWidth);
param.rollingLeft = -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemWidth;
} else if (param.rollingDirection == "down") {
rollingItem = $("<div class='item'/>").prependTo(rollingContentDiv);
param.rollingTop = -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemHeight;
rollingContentDiv.css("top", -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemHeight);
} else if (param.rollingDirection == "left") {
rollingItem = $("<div class='item'/>").appendTo(rollingContentDiv);
rollingItem.css("float", "left");
rollingContentDiv.css("width", param.rollingItemCount * param.rollingItemWidth);
}
rollingItem.css("overflow", "hidden");
rollingItem.css("width", param.rollingItemWidth);
rollingItem.css("height", param.rollingItemHeight);
rollingItem.html(html);
return this;
};
rollingAnimation = function(id) {
var param = rollingParam[id];
var rollingContentDiv = $("#" + id);
if (rollingContentDiv.size() == 0) {
return;
}
var delayTime = param.rollingTime;
if (param.rollingIsStarted == false) {
setTimeout("rollingAnimation('" + id + "')", delayTime);
return;
}
if (param.rollingAnimationIndex == 0) {
if (param.newRollingAnimationFrame != param.rollingAnimationFrame) {
param.rollingAnimationFrame = param.newRollingAnimationFrame;
}
}
var isReverse = false;
if (param.requestReverse == true) {
isReverse = true;
param.requestReverse = false;
param.rollingAnimationIndex = param.rollingAnimationFrame - param.rollingAnimationIndex
if (param.rollingDirection == "left") {
param.rollingDirection = "right";
} else if (param.rollingDirection == "right") {
param.rollingDirection = "left";
} else if (param.rollingDirection == "down") {
param.rollingDirection = "up";
} else if (param.rollingDirection == "up") {
param.rollingDirection = "down";
}
$("#" + param.id).trigger("reverse");
} else {
if (param.rollingDirection == "up") {
param.rollingTop -= param.rollingItemHeight/param.rollingAnimationFrame;
if (-param.rollingTop > parseFloat(param.rollingItemHeight)* param.rollingItemCount) {
param.rollingTop = - parseFloat(param.rollingItemHeight)* param.rollingItemCount;
}
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "right") {
param.rollingLeft += param.rollingItemWidth/param.rollingAnimationFrame;
if (param.rollingLeft > parseFloat(param.rollingItemWidth)) {
param.rollingLeft = parseFloat(param.rollingItemWidth);
}
rollingContentDiv.css("left", param.rollingLeft);
} else if (param.rollingDirection == "down") {
param.rollingTop += param.rollingItemHeight/param.rollingAnimationFrame;
if (param.rollingTop > parseFloat(param.rollingItemHeight)) {
param.rollingTop = parseFloat(param.rollingItemHeight);
}
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "left") {
param.rollingLeft -= param.rollingItemWidth/param.rollingAnimationFrame;
if (-param.rollingLeft > parseFloat(param.rollingItemWidth) * param.rollingItemCount) {
param.rollingLeft = -parseFloat(param.rollingItemWidth) * param.rollingItemCount;
}
rollingContentDiv.css("left", param.rollingLeft);
}
param.rollingAnimationIndex++;
}
if (param.rollingAnimationIndex != 0 && param.rollingAnimationIndex%param.rollingAnimationFrame == 0) {
var currentRollingItemIndex = 0;
if (param.rollingDirection == "up" || param.rollingDirection == "left") {
currentRollingItemIndex = 0;
} else if (param.rollingDirection == "right" || param.rollingDirection == "down") {
currentRollingItemIndex = param.rollingItemCount - 1;
}
var currentRollingItem = $("div[class='item']:eq(" + currentRollingItemIndex + ")", rollingContentDiv);
var rollingItem = null;
if (param.rollingDirection == "up") {
rollingItem = currentRollingItem.clone(true).appendTo(rollingContentDiv);
param.rollingTop += parseFloat(param.rollingItemHeight);
param.rollingTop = param.rollingItemHeight * Math.round(param.rollingTop/param.rollingItemHeight);
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "right") {
rollingItem = currentRollingItem.clone(true).prependTo(rollingContentDiv);
param.rollingLeft -= parseFloat(param.rollingItemWidth);
param.rollingLeft = param.rollingItemWidth * Math.round(param.rollingLeft/param.rollingItemWidth);
$("#debug").html("rollingLeft:" + param.rollingLeft);
rollingItem.css("float", "left");
rollingContentDiv.css("left", param.rollingLeft);
} else if (param.rollingDirection == "down") {
rollingItem = currentRollingItem.clone(true).prependTo(rollingContentDiv);
param.rollingTop -= parseFloat(param.rollingItemHeight);
param.rollingTop = param.rollingItemHeight * Math.round(param.rollingTop/param.rollingItemHeight);
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "left") {
rollingItem = currentRollingItem.clone(true).appendTo(rollingContentDiv);
param.rollingLeft += parseFloat(param.rollingItemWidth);
param.rollingLeft = param.rollingItemWidth * Math.round(param.rollingLeft/param.rollingItemWidth);
$("#debug").html("rollingLeft:" + param.rollingLeft);
rollingItem.css("float", "left");
rollingContentDiv.css("left", param.rollingLeft);
}
currentRollingItem.remove();
if (!isReverse) {
delayTime = param.viewingTime;
} else {
delayTime = 0;
}
var previousRollingItem = $("div[class='item']:eq(" + currentRollingItemIndex + ")", rollingContentDiv);
$("#" + param.id).trigger("viewing", [previousRollingItem]);
param.rollingAnimationIndex = 0;
}
if (param.rollingAnimationIndex != 0) {
var currentRollingItem = $("div[class='item']:eq(0)", rollingContentDiv);
$("#" + param.id).trigger("rolling", [currentRollingItem]);
}
setTimeout("rollingAnimation('" + id + "')", delayTime);
}
$.fn.initRolling = function(rollingTime, viewingTime, rollingAnimationFrame) {
var param = rollingParam[this.attr("rollingId")];
var rollingContentDiv = $("#" + this.attr("rollingId"));
var currentRollingItemIndex = 0;
if (param.rollingDirection == "up" ||
param.rollingDirection == "left") {
currentRollingItemIndex = 0;
} else if (param.rollingDirection == "right" ||
param.rollingDirection == "down") {
currentRollingItemIndex = param.rollingItemCount - 1;
}
var currentRollingItem = $("div[class='item']:eq(" + currentRollingItemIndex + ")", rollingContentDiv);
this.trigger("viewing", [currentRollingItem]);
param.rollingTime = rollingTime
param.viewingTime = viewingTime;
param.rollingAnimationFrame = rollingAnimationFrame;
param.newRollingAnimationFrame = rollingAnimationFrame;
};
$.fn.startRolling = function(rollingTime, viewingTime, rollingAnimationFrame) {
this.initRolling(rollingTime, viewingTime, rollingAnimationFrame);
var param = rollingParam[this.attr("rollingId")];
if (param.rollingIsStarted == false) {
param.rollingIsStarted = true;
this.trigger("start");
setTimeout("rollingAnimation('" + this.attr("rollingId") + "')", param.viewingTime);
}
return this;
};
$.fn.readyRolling = function(rollingTime, viewingTime, rollingAnimationFrame) {
this.initRolling(rollingTime, viewingTime, rollingAnimationFrame);
var param = rollingParam[this.attr("rollingId")];
param.rollingIsStarted = false;
setTimeout("rollingAnimation('" + this.attr("rollingId") + "')", param.viewingTime);
return this;
};
$.fn.stopRolling = function() {
this.trigger("stop");
rollingParam[this.attr("rollingId")].rollingIsStarted = false;
return this;
};
$.fn.resumeRolling = function() {
if (rollingParam[this.attr('rollingId')].rollingIsStarted == false) {
rollingParam[this.attr('rollingId')].rollingIsStarted = true;
this.trigger("start");
}
return this;
};
$.fn.getRollingTime = function() {
return rollingParam[this.attr('rollingId')].rollingTime;
};
$.fn.getViewingTime = function() {
return rollingParam[this.attr('rollingId')].viewingTime;
};
$.fn.getRollingAnimationFrame = function() {
return rollingParam[this.attr('rollingId')].rollingAnimationFrame;
};
$.fn.getRollingDirection = function() {
return rollingParam[this.attr('rollingId')].rollingDirection;
};
$.fn.setRollingTime = function(rollingTime) {
rollingParam[this.attr('rollingId')].rollingTime = rollingTime;
return this;
};
$.fn.setViewingTime = function(viewingTime) {
rollingParam[this.attr('rollingId')].viewingTime = viewingTime;
return this;
};
$.fn.setRollingAnimationFrame = function(rollingAnimationFrame) {
var oldStep = rollingParam[this.attr('rollingId')].rollingAnimationFrame;
var oldIndex = rollingParam[this.attr('rollingId')].rollingAnimationIndex;
var multiplier = rollingAnimationFrame / oldStep;
rollingParam[this.attr('rollingId')].rollingAnimationFrame = rollingAnimationFrame;
rollingParam[this.attr('rollingId')].newRollingAnimationFrame = rollingAnimationFrame;
rollingParam[this.attr('rollingId')].rollingAnimationIndex = Math.round(multiplier * oldIndex);
return this;
};
$.fn.setRollingAnimationFrameNext = function(rollingAnimationFrame) {
rollingParam[this.attr('rollingId')].newRollingAnimationFrame = rollingAnimationFrame;
return this;
}
$.fn.getRollingItems = function() {
return $("div[class=item]", this);
};
$.fn.getViewingItemCount = function() {
return rollingParam[this.attr('rollingId')].viewingItemCount;
};
$.fn.bindViewingEvent = function(rollingEvent) {
return this.bind("viewing", rollingEvent);
};
$.fn.unbindViewingEvent = function() {
return this.unbind("viewing");
};
$.fn.bindRollingEvent = function(rollingEvent) {
return this.bind("rolling", rollingEvent);
};
$.fn.unbindRollingEvent = function() {
return this.unbind("rolling");
};
$.fn.bindStartEvent = function(rollingEvent) {
return this.bind("start", rollingEvent);
};
$.fn.unbindStartEvent = function() {
return this.unbind("start");
};
$.fn.bindStopEvent = function(rollingEvent) {
return this.bind("stop", rollingEvent);
};
$.fn.unbindStopEvent = function() {
return this.unbind("stop");
};
$.fn.bindReverseEvent = function(rollingEvent) {
return this.bind("reverse", rollingEvent);
};
$.fn.unbindReverseEvent = function() {
return this.unbind("reverse");
};
$.fn.reverseRolling = function() {
rollingParam[this.attr('rollingId')].requestReverse = true;
return this;
};
})(jQuery); | JavaScript |
if(window.addEventListener){
//window.addEventListener("load", checkVersion, true); // FF
}else{
window.attachEvent("onload",checkVersion); // IE
}
function getInternetExplorerVersion() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function checkVersion() {
var ver = getInternetExplorerVersion();
var msg = "";
/*
if (ver > -1)
msg = "You are using Internet Explorer " + ver;
else
msg = "You are not using Internet Explorer";
*/
if( ver == 6 || ver == 7 ){
if ( iecheck_getCookie( "iecheck" ) != "done" )
{
/*window.open('/popup/20120213/pop_20120213.html', '', 'width=459, height=357, rollbars=yes,top=50,left=20');*/
var result = confirm("준법지원 시스템 은 보안과 웹 표준 준수를 위해 IE 8 이상을 호환합니다 IE 6, 7 시스템을 이용중이신 사용자께서는 '확인' 을 클릭해서 IE 8로 업그레이드를 해주세요");
if (result) {
location.href="http://tools.naver.com/service/internet-explorer/index.nhn ";
}
else {
location.href="#";
}
}
}else{
//window.open('/center/popup/20120209/pop_20120209.html', '', 'width=660, height=488,scrollbars=yes,top=50,left=50');
}
}
function iecheck_getCookie( name )
{
var nameOfCookie = name + "=";
var x = 0;
while ( x <= document.cookie.length )
{
var y = (x+nameOfCookie.length);
if ( document.cookie.substring( x, y ) == nameOfCookie ) {
if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
endOfCookie = document.cookie.length;
return unescape( document.cookie.substring( y, endOfCookie ) );
}
x = document.cookie.indexOf( " ", x ) + 1;
if ( x == 0 )
break;
}
return "";
} | JavaScript |
/*
* Copyright (c) 2007 Josh Bush (digitalbush.com)
*
* 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.
*/
/*
* Version: Beta 1
* Release: 2007-06-01
*/
(function($) {
var map=new Array();
$.Watermark = {
ShowAll:function(){
for (var i=0;i<map.length;i++){
if(map[i].obj.val()==""){
map[i].obj.val(map[i].text);
map[i].obj.css("color",map[i].WatermarkColor);
}else{
map[i].obj.css("color",map[i].DefaultColor);
}
}
},
HideAll:function(){
for (var i=0;i<map.length;i++){
if(map[i].obj.val()==map[i].text)
map[i].obj.val("");
}
}
}
$.fn.Watermark = function(text,color) {
if(!color)
color="#aaa";
return this.each(
function(){
var input=$(this);
var defaultColor=input.css("color");
map[map.length]={text:text,obj:input,DefaultColor:defaultColor,WatermarkColor:color};
function clearMessage(){
if(input.val()==text)
input.val("");
input.css("color",defaultColor);
}
function insertMessage(){
if(input.val().length==0 || input.val()==text){
input.val(text);
input.css("color",color);
}else
input.css("color",defaultColor);
}
input.focus(clearMessage);
input.blur(insertMessage);
input.change(insertMessage);
insertMessage();
}
);
};
})(jQuery); | JavaScript |
// -----------------------------------------------------------------------
// Eros Fratini - eros@recoding.it
// jqprint 0.3
//
// - 19/06/2009 - some new implementations, added Opera support
// - 11/05/2009 - first sketch
//
// Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
// requires jQuery 1.3.x
//
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//------------------------------------------------------------------------
(function($) {
var opt;
$.fn.jqprint = function (options) {
opt = $.extend({}, $.fn.jqprint.defaults, options);
var $element = (this instanceof jQuery) ? this : $(this);
if (opt.operaSupport && $.browser.opera)
{
var tab = window.open("","jqPrint-preview");
tab.document.open();
var doc = tab.document;
}
else
{
var $iframe = $("<iframe />");
if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }
$iframe.appendTo("body");
var doc = $iframe[0].contentWindow.document;
}
if (opt.importCSS)
{
if ($("link[media=print]").length > 0)
{
$("link[media=print]").each( function() {
doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
});
}
else
{
$("link").each( function() {
doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
});
}
}
if (opt.printContainer) { doc.write($element.outer()); }
else { $element.each( function() { doc.write($(this).html()); }); }
doc.close();
(opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
}
$.fn.jqprint.defaults = {
debug: false,
importCSS: true,
printContainer: true,
operaSupport: true
};
// Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
jQuery.fn.outer = function() {
return $($('<div></div>').html(this.clone())).html();
}
})(jQuery); | JavaScript |
(function($){
$.fn.alphanumeric = function(p) {
p = $.extend({
ichars: "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: ""
}, p);
return this.each
(
function()
{
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for ( i=0;i<s.length;i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow,'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg,'');
$(this).keypress
(
function (e)
{
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey&&k=='v') e.preventDefault();
}
);
$(this).bind('contextmenu',function () {return false});
}
);
};
$.fn.numeric = function(p) {
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = $.extend({
nchars: az
}, p);
return this.each (function()
{
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each (function()
{
$(this).alphanumeric(p);
}
);
};
})(jQuery);
| JavaScript |
/*
* JQuery Rolling
* songsungkyun@naver.com
* 2008/03/16
*/
(function($) {
var rollingParam = {};
$.fn.rolling = function(rollingDirection, rollingItemWidth, rollingItemHeight, viewingItemCount) {
var rollingId = new Date().getTime();
var id = this.attr("id");
rollingParam[rollingId] = {
id: id,
rollingIsStarted: false,
rollingItemCount: 0,
rollingAnimationIndex: 0,
rollingItemWidth: 0,
rollingItemHeight: 0,
viewingItemCount: 0,
rollingTime: 0,
viewingTime: 0,
rollingAnimationFrame: 0,
rollingDirection: null,
rollingLeft: 0,
rollingTop: 0,
requestReverse: false,
newRollingAnimationFrame: 0
};
var param = rollingParam[rollingId];
param.rollingDirection = rollingDirection;
param.rollingItemWidth = rollingItemWidth;
param.rollingItemHeight = rollingItemHeight;
if (viewingItemCount == undefined) {
param.viewingItemCount = 1;
} else {
param.viewingItemCount = viewingItemCount;
}
if (param.rollingDirection == "left" ||
param.rollingDirection == "right") {
this.css("width", param.rollingItemWidth * param.viewingItemCount);
this.css("height", param.rollingItemHeight);
} else if (param.rollingDirection == "up" ||
param.rollingDirection == "down") {
this.css("width", param.rollingItemWidth);
this.css("height", param.rollingItemHeight * param.viewingItemCount);
}
this.css("position", "relative");
this.css("overflow", "hidden");
this.attr("rollingId", rollingId);
this.empty();
rollingContentDiv = $("<div/>").appendTo(this);
rollingContentDiv.attr("id", rollingId);
rollingContentDiv.css("position", "absolute");
rollingContentDiv.attr("align", "left");
rollingContentDiv.css("left", "0");
rollingContentDiv.css("top", "0");
return this;
};
$.fn.addRollingItem = function(html) {
var param = rollingParam[this.attr("rollingId")];
var rollingContentDiv = $("#" + this.attr("rollingId"));
param.rollingItemCount++;
var rollingItem = null;
if (param.rollingDirection == "up") {
rollingItem = $("<div class='item'/>").appendTo(rollingContentDiv);
} else if (param.rollingDirection == "right") {
rollingItem = $("<div class='item'/>").prependTo(rollingContentDiv);
rollingItem.css("float", "left");
rollingContentDiv.css("width", param.rollingItemCount * param.rollingItemWidth);
rollingContentDiv.css("left", -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemWidth);
param.rollingLeft = -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemWidth;
} else if (param.rollingDirection == "down") {
rollingItem = $("<div class='item'/>").prependTo(rollingContentDiv);
param.rollingTop = -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemHeight;
rollingContentDiv.css("top", -(param.rollingItemCount - param.viewingItemCount) * param.rollingItemHeight);
} else if (param.rollingDirection == "left") {
rollingItem = $("<div class='item'/>").appendTo(rollingContentDiv);
rollingItem.css("float", "left");
rollingContentDiv.css("width", param.rollingItemCount * param.rollingItemWidth);
}
rollingItem.css("overflow", "hidden");
rollingItem.css("width", param.rollingItemWidth);
rollingItem.css("height", param.rollingItemHeight);
rollingItem.html(html);
return this;
};
rollingAnimation = function(id) {
var param = rollingParam[id];
var rollingContentDiv = $("#" + id);
if (rollingContentDiv.size() == 0) {
return;
}
var delayTime = param.rollingTime;
if (param.rollingIsStarted == false) {
setTimeout("rollingAnimation('" + id + "')", delayTime);
return;
}
if (param.rollingAnimationIndex == 0) {
if (param.newRollingAnimationFrame != param.rollingAnimationFrame) {
param.rollingAnimationFrame = param.newRollingAnimationFrame;
}
}
var isReverse = false;
if (param.requestReverse == true) {
isReverse = true;
param.requestReverse = false;
param.rollingAnimationIndex = param.rollingAnimationFrame - param.rollingAnimationIndex
if (param.rollingDirection == "left") {
param.rollingDirection = "right";
} else if (param.rollingDirection == "right") {
param.rollingDirection = "left";
} else if (param.rollingDirection == "down") {
param.rollingDirection = "up";
} else if (param.rollingDirection == "up") {
param.rollingDirection = "down";
}
$("#" + param.id).trigger("reverse");
} else {
if (param.rollingDirection == "up") {
param.rollingTop -= param.rollingItemHeight/param.rollingAnimationFrame;
if (-param.rollingTop > parseFloat(param.rollingItemHeight)* param.rollingItemCount) {
param.rollingTop = - parseFloat(param.rollingItemHeight)* param.rollingItemCount;
}
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "right") {
param.rollingLeft += param.rollingItemWidth/param.rollingAnimationFrame;
if (param.rollingLeft > parseFloat(param.rollingItemWidth)) {
param.rollingLeft = parseFloat(param.rollingItemWidth);
}
rollingContentDiv.css("left", param.rollingLeft);
} else if (param.rollingDirection == "down") {
param.rollingTop += param.rollingItemHeight/param.rollingAnimationFrame;
if (param.rollingTop > parseFloat(param.rollingItemHeight)) {
param.rollingTop = parseFloat(param.rollingItemHeight);
}
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "left") {
param.rollingLeft -= param.rollingItemWidth/param.rollingAnimationFrame;
if (-param.rollingLeft > parseFloat(param.rollingItemWidth) * param.rollingItemCount) {
param.rollingLeft = -parseFloat(param.rollingItemWidth) * param.rollingItemCount;
}
rollingContentDiv.css("left", param.rollingLeft);
}
param.rollingAnimationIndex++;
}
if (param.rollingAnimationIndex != 0 && param.rollingAnimationIndex%param.rollingAnimationFrame == 0) {
var currentRollingItemIndex = 0;
if (param.rollingDirection == "up" || param.rollingDirection == "left") {
currentRollingItemIndex = 0;
} else if (param.rollingDirection == "right" || param.rollingDirection == "down") {
currentRollingItemIndex = param.rollingItemCount - 1;
}
var currentRollingItem = $("div[class='item']:eq(" + currentRollingItemIndex + ")", rollingContentDiv);
var rollingItem = null;
if (param.rollingDirection == "up") {
rollingItem = currentRollingItem.clone(true).appendTo(rollingContentDiv);
param.rollingTop += parseFloat(param.rollingItemHeight);
param.rollingTop = param.rollingItemHeight * Math.round(param.rollingTop/param.rollingItemHeight);
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "right") {
rollingItem = currentRollingItem.clone(true).prependTo(rollingContentDiv);
param.rollingLeft -= parseFloat(param.rollingItemWidth);
param.rollingLeft = param.rollingItemWidth * Math.round(param.rollingLeft/param.rollingItemWidth);
$("#debug").html("rollingLeft:" + param.rollingLeft);
rollingItem.css("float", "left");
rollingContentDiv.css("left", param.rollingLeft);
} else if (param.rollingDirection == "down") {
rollingItem = currentRollingItem.clone(true).prependTo(rollingContentDiv);
param.rollingTop -= parseFloat(param.rollingItemHeight);
param.rollingTop = param.rollingItemHeight * Math.round(param.rollingTop/param.rollingItemHeight);
rollingContentDiv.css("top", param.rollingTop);
} else if (param.rollingDirection == "left") {
rollingItem = currentRollingItem.clone(true).appendTo(rollingContentDiv);
param.rollingLeft += parseFloat(param.rollingItemWidth);
param.rollingLeft = param.rollingItemWidth * Math.round(param.rollingLeft/param.rollingItemWidth);
$("#debug").html("rollingLeft:" + param.rollingLeft);
rollingItem.css("float", "left");
rollingContentDiv.css("left", param.rollingLeft);
}
currentRollingItem.remove();
if (!isReverse) {
delayTime = param.viewingTime;
} else {
delayTime = 0;
}
var previousRollingItem = $("div[class='item']:eq(" + currentRollingItemIndex + ")", rollingContentDiv);
$("#" + param.id).trigger("viewing", [previousRollingItem]);
param.rollingAnimationIndex = 0;
}
if (param.rollingAnimationIndex != 0) {
var currentRollingItem = $("div[class='item']:eq(0)", rollingContentDiv);
$("#" + param.id).trigger("rolling", [currentRollingItem]);
}
setTimeout("rollingAnimation('" + id + "')", delayTime);
}
$.fn.initRolling = function(rollingTime, viewingTime, rollingAnimationFrame) {
var param = rollingParam[this.attr("rollingId")];
var rollingContentDiv = $("#" + this.attr("rollingId"));
var currentRollingItemIndex = 0;
if (param.rollingDirection == "up" ||
param.rollingDirection == "left") {
currentRollingItemIndex = 0;
} else if (param.rollingDirection == "right" ||
param.rollingDirection == "down") {
currentRollingItemIndex = param.rollingItemCount - 1;
}
var currentRollingItem = $("div[class='item']:eq(" + currentRollingItemIndex + ")", rollingContentDiv);
this.trigger("viewing", [currentRollingItem]);
param.rollingTime = rollingTime
param.viewingTime = viewingTime;
param.rollingAnimationFrame = rollingAnimationFrame;
param.newRollingAnimationFrame = rollingAnimationFrame;
};
$.fn.startRolling = function(rollingTime, viewingTime, rollingAnimationFrame) {
this.initRolling(rollingTime, viewingTime, rollingAnimationFrame);
var param = rollingParam[this.attr("rollingId")];
if (param.rollingIsStarted == false) {
param.rollingIsStarted = true;
this.trigger("start");
setTimeout("rollingAnimation('" + this.attr("rollingId") + "')", param.viewingTime);
}
return this;
};
$.fn.readyRolling = function(rollingTime, viewingTime, rollingAnimationFrame) {
this.initRolling(rollingTime, viewingTime, rollingAnimationFrame);
var param = rollingParam[this.attr("rollingId")];
param.rollingIsStarted = false;
setTimeout("rollingAnimation('" + this.attr("rollingId") + "')", param.viewingTime);
return this;
};
$.fn.stopRolling = function() {
this.trigger("stop");
rollingParam[this.attr("rollingId")].rollingIsStarted = false;
return this;
};
$.fn.resumeRolling = function() {
if (rollingParam[this.attr('rollingId')].rollingIsStarted == false) {
rollingParam[this.attr('rollingId')].rollingIsStarted = true;
this.trigger("start");
}
return this;
};
$.fn.getRollingTime = function() {
return rollingParam[this.attr('rollingId')].rollingTime;
};
$.fn.getViewingTime = function() {
return rollingParam[this.attr('rollingId')].viewingTime;
};
$.fn.getRollingAnimationFrame = function() {
return rollingParam[this.attr('rollingId')].rollingAnimationFrame;
};
$.fn.getRollingDirection = function() {
return rollingParam[this.attr('rollingId')].rollingDirection;
};
$.fn.setRollingTime = function(rollingTime) {
rollingParam[this.attr('rollingId')].rollingTime = rollingTime;
return this;
};
$.fn.setViewingTime = function(viewingTime) {
rollingParam[this.attr('rollingId')].viewingTime = viewingTime;
return this;
};
$.fn.setRollingAnimationFrame = function(rollingAnimationFrame) {
var oldStep = rollingParam[this.attr('rollingId')].rollingAnimationFrame;
var oldIndex = rollingParam[this.attr('rollingId')].rollingAnimationIndex;
var multiplier = rollingAnimationFrame / oldStep;
rollingParam[this.attr('rollingId')].rollingAnimationFrame = rollingAnimationFrame;
rollingParam[this.attr('rollingId')].newRollingAnimationFrame = rollingAnimationFrame;
rollingParam[this.attr('rollingId')].rollingAnimationIndex = Math.round(multiplier * oldIndex);
return this;
};
$.fn.setRollingAnimationFrameNext = function(rollingAnimationFrame) {
rollingParam[this.attr('rollingId')].newRollingAnimationFrame = rollingAnimationFrame;
return this;
}
$.fn.getRollingItems = function() {
return $("div[class=item]", this);
};
$.fn.getViewingItemCount = function() {
return rollingParam[this.attr('rollingId')].viewingItemCount;
};
$.fn.bindViewingEvent = function(rollingEvent) {
return this.bind("viewing", rollingEvent);
};
$.fn.unbindViewingEvent = function() {
return this.unbind("viewing");
};
$.fn.bindRollingEvent = function(rollingEvent) {
return this.bind("rolling", rollingEvent);
};
$.fn.unbindRollingEvent = function() {
return this.unbind("rolling");
};
$.fn.bindStartEvent = function(rollingEvent) {
return this.bind("start", rollingEvent);
};
$.fn.unbindStartEvent = function() {
return this.unbind("start");
};
$.fn.bindStopEvent = function(rollingEvent) {
return this.bind("stop", rollingEvent);
};
$.fn.unbindStopEvent = function() {
return this.unbind("stop");
};
$.fn.bindReverseEvent = function(rollingEvent) {
return this.bind("reverse", rollingEvent);
};
$.fn.unbindReverseEvent = function() {
return this.unbind("reverse");
};
$.fn.reverseRolling = function() {
rollingParam[this.attr('rollingId')].requestReverse = true;
return this;
};
})(jQuery); | JavaScript |
function createSEditor2(elIRField, htParams, elSeAppContainer){
if(!window.$Jindo){
parent.document.body.innerHTML="진도 프레임웍이 필요합니다.<br>\n<a href='http://dev.naver.com/projects/jindo/download'>http://dev.naver.com/projects/jindo/download</a>에서 Jindo 1.5.3 버전의 jindo.min.js를 다운로드 받아 /js 폴더에 복사 해 주세요.\n(아직 Jindo 2 는 지원하지 않습니다.)";
return;
}
var elAppContainer = (elSeAppContainer || jindo.$("smart_editor2"));
var elEditingArea = jindo.$$.getSingle("DIV.husky_seditor_editing_area_container", elAppContainer);
var oWYSIWYGIFrame = jindo.$$.getSingle("IFRAME.se2_input_wysiwyg", elEditingArea);
var oIRTextarea = elIRField?elIRField:jindo.$$.getSingle("TEXTAREA.blind", elEditingArea);
var oHTMLSrc = jindo.$$.getSingle("TEXTAREA.se2_input_htmlsrc", elEditingArea);
var oTextArea = jindo.$$.getSingle("TEXTAREA.se2_input_text", elEditingArea);
if(!htParams){
htParams = {};
htParams.fOnBeforeUnload = null;
}
htParams.elAppContainer = elAppContainer; // 에디터 UI 최상위 element 셋팅
htParams.oNavigator = jindo.$Agent().navigator(); // navigator 객체 셋팅
var oEditor = new nhn.husky.HuskyCore(htParams);
oEditor.registerPlugin(new nhn.husky.CorePlugin(htParams?htParams.fOnAppLoad:null));
oEditor.registerPlugin(new nhn.husky.StringConverterManager());
var htDimension = {
nMinHeight:205,
nMinWidth:parseInt(elIRField.style.minWidth, 10)||570,
nHeight:elIRField.style.height||elIRField.offsetHeight,
nWidth:elIRField.style.width||elIRField.offsetWidth
};
oEditor.registerPlugin(new nhn.husky.SE_EditingAreaManager("WYSIWYG", oIRTextarea, htDimension, htParams.fOnBeforeUnload, elAppContainer));
oEditor.registerPlugin(new nhn.husky.SE_EditingArea_WYSIWYG(oWYSIWYGIFrame)); // Tab Editor 모드
oEditor.registerPlugin(new nhn.husky.SE_EditingArea_HTMLSrc(oHTMLSrc)); // Tab HTML 모드
oEditor.registerPlugin(new nhn.husky.SE_EditingArea_TEXT(oTextArea)); // Tab Text 모드
oEditor.registerPlugin(new nhn.husky.SE2M_EditingModeChanger(elAppContainer)); // 모드간 변경(Editor, HTML, Text)
oEditor.registerPlugin(new nhn.husky.HuskyRangeManager(oWYSIWYGIFrame));
oEditor.registerPlugin(new nhn.husky.Utils());
oEditor.registerPlugin(new nhn.husky.SE2M_UtilPlugin());
oEditor.registerPlugin(new nhn.husky.SE_WYSIWYGStyler());
oEditor.registerPlugin(new nhn.husky.SE2M_Toolbar(elAppContainer));
oEditor.registerPlugin(new nhn.husky.Hotkey()); // 단축키
oEditor.registerPlugin(new nhn.husky.SE_EditingAreaVerticalResizer(elAppContainer)); // 편집영역 리사이즈
oEditor.registerPlugin(new nhn.husky.DialogLayerManager());
oEditor.registerPlugin(new nhn.husky.ActiveLayerManager());
oEditor.registerPlugin(new nhn.husky.SE_WYSIWYGStyleGetter()); // 커서 위치 스타일 정보 가져오기
oEditor.registerPlugin(new nhn.husky.SE2B_Customize_ToolBar(elAppContainer)); // 상단 툴바 (Basic)
oEditor.registerPlugin(new nhn.husky.SE_WYSIWYGEnterKey("P")); // 엔터 시 처리, 현재는 P로 처리
oEditor.registerPlugin(new nhn.husky.SE2M_ColorPalette(elAppContainer)); // 색상 팔레트
oEditor.registerPlugin(new nhn.husky.SE2M_FontColor(elAppContainer)); // 글자색
oEditor.registerPlugin(new nhn.husky.SE2M_BGColor(elAppContainer)); // 글자배경색
oEditor.registerPlugin(new nhn.husky.SE2M_FontNameWithLayerUI(elAppContainer)); // 글꼴종류
oEditor.registerPlugin(new nhn.husky.SE2M_FontSizeWithLayerUI(elAppContainer)); // 글꼴크기
oEditor.registerPlugin(new nhn.husky.SE2M_LineStyler());
oEditor.registerPlugin(new nhn.husky.SE2M_ExecCommand(oWYSIWYGIFrame));
oEditor.registerPlugin(new nhn.husky.SE2M_LineHeightWithLayerUI(elAppContainer)); // 줄간격
oEditor.registerPlugin(new nhn.husky.SE2M_Quote(elAppContainer)); // 인용구
oEditor.registerPlugin(new nhn.husky.SE2M_Hyperlink(elAppContainer)); // 링크
oEditor.registerPlugin(new nhn.husky.SE2M_SCharacter(elAppContainer)); // 특수문자
oEditor.registerPlugin(new nhn.husky.SE2M_FindReplacePlugin(elAppContainer)); // 찾기/바꾸기
oEditor.registerPlugin(new nhn.husky.SE2M_TableCreator(elAppContainer)); // 테이블 생성
oEditor.registerPlugin(new nhn.husky.SE2M_TableEditor(elAppContainer)); // 테이블 편집
oEditor.registerPlugin(new nhn.husky.SE2M_TableBlockStyler(elAppContainer)); // 테이블 스타일
oEditor.registerPlugin(new nhn.husky.SE2M_AttachQuickPhoto(elAppContainer)); // 사진
oEditor.registerPlugin(new nhn.husky.MessageManager(oMessageMap));
oEditor.registerPlugin(new nhn.husky.SE2M_QuickEditor_Common(elAppContainer)); // 퀵에디터 공통(표, 이미지)
if(jindo.$Agent().navigator().ie){
oEditor.registerPlugin(new nhn.husky.SE2M_ImgSizeRatioKeeper()); // 이미지 선택한 이후 마우스로 크기 조정하면 정비율로 변경
}
oEditor.registerPlugin(new nhn.husky.SE2B_CSSLoader()); // CSS lazy load
oEditor.registerPlugin(new nhn.husky.SE_OuterIFrameControl(elAppContainer, 100));
oEditor.registerPlugin(new nhn.husky.SE_ToolbarToggler(elAppContainer, htParams.bUseToolbar));
//파일 업로드 관련 : 20121110 , changwonkim
oEditor.registerPlugin(new nhn.husky.SE2M_AttachQuickPhoto(elAppContainer)); // 사진
return oEditor;
} | JavaScript |
if(typeof window.nhn=='undefined') window.nhn = {};
if (!nhn.husky) nhn.husky = {};
/**
* @fileOverview This file contains application creation helper function, which would load up an HTML(Skin) file and then execute a specified create function.
* @name HuskyEZCreator.js
*/
nhn.husky.EZCreator = new (function(){
this.nBlockerCount = 0;
this.createInIFrame = function(htOptions){
if(arguments.length == 1){
var oAppRef = htOptions.oAppRef;
var elPlaceHolder = htOptions.elPlaceHolder;
var sSkinURI = htOptions.sSkinURI;
var fCreator = htOptions.fCreator;
var fOnAppLoad = htOptions.fOnAppLoad;
var bUseBlocker = htOptions.bUseBlocker;
var htParams = htOptions.htParams || null;
}else{
// for backward compatibility only
var oAppRef = arguments[0];
var elPlaceHolder = arguments[1];
var sSkinURI = arguments[2];
var fCreator = arguments[3];
var fOnAppLoad = arguments[4];
var bUseBlocker = arguments[5];
var htParams = arguments[6];
}
if(bUseBlocker) nhn.husky.EZCreator.showBlocker();
var attachEvent = function(elNode, sEvent, fHandler){
if(elNode.addEventListener){
elNode.addEventListener(sEvent, fHandler, false);
}else{
elNode.attachEvent("on"+sEvent, fHandler);
}
}
if(!elPlaceHolder){
alert("Placeholder is required!");
return;
}
if(typeof(elPlaceHolder) != "object")
elPlaceHolder = document.getElementById(elPlaceHolder);
var elIFrame, nEditorWidth, nEditorHeight;
try{
elIFrame = document.createElement("<IFRAME frameborder=0 scrolling=no>");
}catch(e){
elIFrame = document.createElement("IFRAME");
elIFrame.setAttribute("frameborder", "0");
elIFrame.setAttribute("scrolling", "no");
}
elIFrame.style.width = "1px";
elIFrame.style.height = "1px";
elPlaceHolder.parentNode.insertBefore(elIFrame, elPlaceHolder.nextSibling);
attachEvent(elIFrame, "load", function(){
fCreator = elIFrame.contentWindow[fCreator] || elIFrame.contentWindow.createSEditor2;
// top.document.title = ((new Date())-window.STime);
// window.STime = new Date();
try{
nEditorWidth = elIFrame.contentWindow.document.body.scrollWidth || "500px";
nEditorHeight = elIFrame.contentWindow.document.body.scrollHeight + 12;
elIFrame.style.width = "100%";
elIFrame.style.height = nEditorHeight+ "px";
elIFrame.contentWindow.document.body.style.margin = "0";
}catch(e){
nhn.husky.EZCreator.hideBlocker(true);
elIFrame.style.border = "5px solid red";
elIFrame.style.width = "500px";
elIFrame.style.height = "500px";
alert("Failed to access "+sSkinURI);
return;
}
var oApp = fCreator(elPlaceHolder, htParams); // oEditor
oApp.elPlaceHolder = elPlaceHolder;
oAppRef[oAppRef.length] = oApp;
if(!oAppRef.getById) oAppRef.getById = {};
if(elPlaceHolder.id) oAppRef.getById[elPlaceHolder.id] = oApp;
oApp.run({fnOnAppReady:fOnAppLoad});
// top.document.title += ", "+((new Date())-window.STime);
nhn.husky.EZCreator.hideBlocker();
});
// window.STime = new Date();
elIFrame.src = sSkinURI;
};
this.showBlocker = function(){
if(this.nBlockerCount<1){
var elBlocker = document.createElement("DIV");
elBlocker.style.position = "absolute";
elBlocker.style.top = 0;
elBlocker.style.left = 0;
elBlocker.style.backgroundColor = "#FFFFFF";
elBlocker.style.width = "100%";
document.body.appendChild(elBlocker);
nhn.husky.EZCreator.elBlocker = elBlocker;
}
nhn.husky.EZCreator.elBlocker.style.height = Math.max(document.body.scrollHeight, document.body.clientHeight)+"px";
this.nBlockerCount++;
};
this.hideBlocker = function(bForce){
if(!bForce){
if(--this.nBlockerCount > 0) return;
}
this.nBlockerCount = 0;
if(nhn.husky.EZCreator.elBlocker) nhn.husky.EZCreator.elBlocker.style.display = "none";
}
})(); | JavaScript |
/*
* Smart Editor 2 Configuration
*/
if(typeof window.nhn=='undefined'){window.nhn = {};}
if (!nhn.husky){nhn.husky = {};}
nhn.husky.SE2M_Configuration = {};
nhn.husky.SE2M_Configuration.Editor = {
sJsBaseURL : './js_src',
sImageBaseURL : './img'
};
nhn.husky.SE2M_Configuration.LinkageDomain = {
sCommonAPI : 'http://api.se2.naver.com',
sCommonStatic : 'http://static.se2.naver.com',
sCommonImage : 'http://images.se2.naver.com'
};
nhn.husky.SE2M_Configuration.SE_EditingAreaManager = {
sBlankPageURL : "smart_editor2_inputarea.html",
sBlankPageURL_EmulateIE7 : "smart_editor2_inputarea_ie8.html",
aAddtionalEmulateIE7 : [9, 10] // IE8 default 사용, IE9 ~ 선택적 사용
};
nhn.husky.SE2M_Configuration.LazyLoad = {
sJsBaseURI : "js_lazyload"
};
nhn.husky.SE2M_Configuration.SE2B_CSSLoader = {
sCSSBaseURI : "./css"
};
nhn.husky.SE2M_Configuration.Quote = {
sImageBaseURL : 'http://static.se2.naver.com/static/img'
};
nhn.husky.SE2M_Configuration.CustomObject = {
sVersion : 1,
sClassName : '__se_object',
sValueName : 'jsonvalue',
sTagIdPrefix : 'se_object_',
sTailComment : '<!--__se_object_end -->',
sBlankTemplateURL : nhn.husky.SE2M_Configuration.LinkageDomain.sCommonStatic + '/static/db_attach/iframe_template_for_se1_obj.html',
sAttributeOfEmpty : 's_isempty="true"',
sAttributeOfOldDB : 's_olddb="true"',
sBlock : '<div class="_block" style="position:absolute;z-index:10000;background-color:#fff;"></div>',
sBlokTemplate : '<div[\\s\\S]*?class=[\'"]?_block[\'"]?[\\s\\S]*?</div>',
sHighlight : '<div class="_highlight" style="position:absolute;width:58px;height:16px;line-height:0;z-index:9999"><img src="' + nhn.husky.SE2M_Configuration.LinkageDomain.sCommonStatic + '/static/img/pencil2.png" alt="" width="58" height="16" style="vertical-align:top"></div>',
sHighlightTemplate : '<div[\\s\\S]*?class=[\'"]?_highlight[\'"]?[\\s\\S]*?</div>',
sHtmlTemplateStartTag : '<!-- se_object_template_start -->',
sHtmlTemplateEndTag : '<!-- se_object_template_end -->',
sHtmlFilterTag : '{=sType}_{=sSubType}_{=nSeq}',
sTplHtmlFilterTag : '<!--{=sType}_{=sSubType}_(\\d+)-->',
sImgComServerPath : nhn.husky.SE2M_Configuration.LinkageDomain.sCommonStatic + '/static/img/reviewitem',
nMaxWidth : 548
};
nhn.husky.SE2M_Configuration.SE2M_ReEditAction = {
bUsed : true,
nSecDisplayDulationReEditMsg : 3,
aReEditGuideMsg : [
'이미지 파일은 1회 클릭 시 크기 조절, 더블클릭 시 재편집이 가능합니다.',
'첨부한 파일을 더블클릭 시 재편집이 가능합니다.',
'첨부한 글양식 테이블을 드래그시 테이블 재편집이 가능합니다.',
'첨부한 표를 드래그 시 표 재편집이 가능합니다.'
]
};
nhn.husky.SE2M_Configuration.SE2M_ColorPalette = {
bUseRecentColor : false
};
nhn.husky.SE2M_Configuration.QuickEditor = {
common : {
bUseConfig : false
}
}; | JavaScript |
//변수 선언 및 초기화
var nImageInfoCnt = 0;
var htImageInfo = []; //image file정보 저장
var aResult = [];
var rFilter = /^(image\/bmp|image\/gif|image\/jpg|image\/jpeg|image\/png)$/i;
var rFilter2 = /^(bmp|gif|jpg|jpeg|png)$/i;
var nTotalSize = 0;
var nMaxImageSize = 10*1024*1024;
var nMaxTotalImageSize = 50*1024*1024;
var nMaxImageCount = 10;
var nImageFileCount = 0;
var bSupportDragAndDropAPI = false;
var oFileUploader;
var bAttachEvent = false;
//마크업에 따른 할당
var elContent= $("pop_content");
var elDropArea = jindo.$$.getSingle(".drag_area",elContent);
var elDropAreaUL = jindo.$$.getSingle(".lst_type",elContent);
var elCountTxtTxt = jindo.$$.getSingle("#imageCountTxt",elContent);
var elTotalSizeTxt = jindo.$$.getSingle("#totalSizeTxt",elContent);
var elTextGuide = $("guide_text");
var welUploadInputBox = $Element("uploadInputBox");
var oNavigator = jindo.$Agent().navigator();
//마크업-공통
var welBtnConfirm = $Element("btn_confirm"); //확인 버튼
var welBtnCancel= $Element("btn_cancel"); //취소 버튼
//진도로 랩핑된 element
var welTextGuide = $Element(elTextGuide);
var welDropArea = $Element(elDropArea);
var welDropAreaUL = $Element(elDropAreaUL);
var fnUploadImage = null;
//File API 지원 여부로 결정
function checkDragAndDropAPI(){
try{
if( !oNavigator.ie ){
if(!!oNavigator.safari && oNavigator.version <= 5){
bSupportDragAndDropAPI = false;
}else{
bSupportDragAndDropAPI = true;
}
} else {
bSupportDragAndDropAPI = false;
}
}catch(e){
bSupportDragAndDropAPI = false;
}
}
//--------------- html5 미지원 브라우저에서 (IE9 이하) ---------------
/**
* 이미지를 첨부 후 활성화된 버튼 상태
*/
function goStartMode(){
var sSrc = welBtnConfirm.attr("src")|| "";
if(sSrc.indexOf("btn_confirm2.png") < 0 ){
welBtnConfirm.attr("src","../../img/photoQuickPopup/btn_confirm2.png");
fnUploadImage.attach(welBtnConfirm.$value(), "click");
}
}
/**
* 이미지를 첨부 전 비활성화된 버튼 상태
* @return
*/
function goReadyMode(){
var sSrc = welBtnConfirm.attr("src")|| "";
if(sSrc.indexOf("btn_confirm2.png") >= 0 ){
fnUploadImage.detach(welBtnConfirm.$value(), "click");
welBtnConfirm.attr("src","../../img/photoQuickPopup/btn_confirm.png");
}
}
/**
* 일반 업로드
* @desc oFileUploader의 upload함수를 호출함.
*/
function generalUpload(){
oFileUploader.upload();
}
/**
* 이미지 첨부 전 안내 텍스트가 나오는 배경으로 '설정'하는 함수.
* @return
*/
function readyModeBG (){
var sClass = welTextGuide.className();
if(sClass.indexOf('nobg') >= 0){
welTextGuide.removeClass('nobg');
welTextGuide.className('bg');
}
}
/**
* 이미지 첨부 전 안내 텍스트가 나오는 배경을 '제거'하는 함수.
* @return
*/
function startModeBG (){
var sClass = welTextGuide.className();
if(sClass.indexOf('nobg') < 0){
welTextGuide.removeClass('bg');
welTextGuide.className('nobg');
}
}
//--------------------- html5 지원되는 브라우저에서 사용하는 함수 --------------------------
/**
* 팝업에 노출될 업로드 예정 사진의 수.
* @param {Object} nCount 현재 업로드 예정인 사진 장수
* @param {Object} nVariable 삭제되는 수
*/
function updateViewCount (nCount, nVariable){
var nCnt = nCount + nVariable;
elCountTxtTxt.innerHTML = nCnt +"장";
nImageFileCount = nCnt;
return nCnt;
}
/**
* 팝업에 노출될 업로드될 사진 총 용량
*/
function updateViewTotalSize(){
var nViewTotalSize = Number(parseInt((nTotalSize || 0), 10) / (1024*1024));
elTotalSizeTxt.innerHTML = nViewTotalSize.toFixed(2) +"MB";
}
/**
* 이미지 전체 용량 재계산.
* @param {Object} sParentId
*/
function refreshTotalImageSize(sParentId){
var nDelImgSize = htImageInfo[sParentId].size;
if(nTotalSize - nDelImgSize > -1 ){
nTotalSize = nTotalSize - nDelImgSize;
}
}
/**
* hash table에서 이미지 정보 초기화.
* @param {Object} sParentId
*/
function removeImageInfo (sParentId){
//삭제된 이미지의 공간을 초기화 한다.
htImageInfo[sParentId] = null;
}
/**
* byte로 받은 이미지 용량을 화면에 표시를 위해 포맷팅
* @param {Object} nByte
*/
function setUnitString (nByte) {
var nImageSize;
var sUnit;
if(nByte < 0 ){
nByte = 0;
}
if( nByte < 1024) {
nImageSize = Number(nByte);
sUnit = 'B';
return nImageSize + sUnit;
} else if( nByte > (1024*1024)) {
nImageSize = Number(parseInt((nByte || 0), 10) / (1024*1024));
sUnit = 'MB';
return nImageSize.toFixed(2) + sUnit;
} else {
nImageSize = Number(parseInt((nByte || 0), 10) / 1024);
sUnit = 'KB';
return nImageSize.toFixed(0) + sUnit;
}
}
/**
* 화면 목록에 적당하게 이름을 잘라서 표시.
* @param {Object} sName 파일명
* @param {Object} nMaxLng 최대 길이
*/
function cuttingNameByLength (sName, nMaxLng) {
var sTemp, nIndex;
if(sName.length > nMaxLng){
nIndex = sName.indexOf(".");
sTemp = sName.substring(0,nMaxLng) + "..." + sName.substring(nIndex,sName.length) ;
} else {
sTemp = sName;
}
return sTemp;
}
/**
* Total Image Size를 체크해서 추가로 이미지를 넣을지 말지를 결정함.
* @param {Object} nByte
*/
function checkTotalImageSize(nByte){
if( nTotalSize + nByte < nMaxTotalImageSize){
nTotalSize = nTotalSize + nByte;
return false;
} else {
return true;
}
}
// 이벤트 핸들러 할당
function dragEnter(ev) {
ev.stopPropagation();
ev.preventDefault();
}
function dragExit(ev) {
ev.stopPropagation();
ev.preventDefault();
}
function dragOver(ev) {
ev.stopPropagation();
ev.preventDefault();
}
/**
* 드랍 영역에 사진을 떨구는 순간 발생하는 이벤트
* @param {Object} ev
*/
function drop(ev) {
ev.stopPropagation();
ev.preventDefault();
if (nImageFileCount >= 10){
alert("최대 10장까지만 등록할 수 있습니다.");
return;
}
if(typeof ev.dataTransfer.files == 'undefined'){
alert("HTML5 지원이 정상적으로 이루어지지 않는 브라우저입니다.");
}else{
//변수 선언
var wel,
files,
nCount,
sListTag = '';
//초기화
files = ev.dataTransfer.files;
nCount = files.length;
if (!!files && nCount === 0){
//파일이 아닌, 웹페이지에서 이미지를 드래서 놓는 경우.
alert("정상적인 첨부방식이 아닙니다.");
return ;
}
for (var i = 0, j = nImageFileCount ; i < nCount ; i++){
if (!rFilter.test(files[i].type)) {
alert("이미지파일 (jpg,gif,png,bmp)만 업로드 가능합니다.");
} else if(files[i].size > nMaxImageSize){
alert("이미지 용량이 10MB를 초과하여 등록할 수 없습니다.");
} else {
//제한된 수만 업로드 가능.
if ( j < nMaxImageCount ){
sListTag += addImage(files[i]);
//다음 사진을위한 셋팅
j = j+1;
nImageInfoCnt = nImageInfoCnt+1;
} else {
alert("최대 10장까지만 등록할 수 있습니다.");
break;
}
}
}
if(j > 0){
//배경 이미지 변경
startModeBG();
if ( sListTag.length > 1){
welDropAreaUL.prependHTML(sListTag);
}
//이미지 총사이즈 view update
updateViewTotalSize();
//이미치 총 수 view update
nImageFileCount = j;
updateViewCount(nImageFileCount, 0);
// 저장 버튼 활성화
goStartMode();
}else{
readyModeBG();
}
}
}
/**
* 이미지를 추가하기 위해서 file을 저장하고, 목록에 보여주기 위해서 string을 만드는 함수.
* @param ofile 한개의 이미지 파일
* @return
*/
function addImage(ofile){
//파일 사이즈
var ofile = ofile,
sFileSize = 0,
sFileName = "",
sLiTag = "",
bExceedLimitTotalSize = false,
aFileList = [];
sFileSize = setUnitString(ofile.size);
sFileName = cuttingNameByLength(ofile.name, 15);
bExceedLimitTotalSize = checkTotalImageSize(ofile.size);
if( !!bExceedLimitTotalSize ){
alert("전체 이미지 용량이 50MB를 초과하여 등록할 수 없습니다. \n\n (파일명 : "+sFileName+", 사이즈 : "+sFileSize+")");
} else {
//이미지 정보 저장
htImageInfo['img'+nImageInfoCnt] = ofile;
//List 마크업 생성하기
aFileList.push(' <li id="img'+nImageInfoCnt+'" class="imgLi"><span>'+ sFileName +'</span>');
aFileList.push(' <em>'+ sFileSize +'</em>');
aFileList.push(' <a onclick="delImage(\'img'+nImageInfoCnt+'\')"><img class="del_button" src="../../img/photoQuickPopup/btn_del.png" width="14" height="13" alt="첨부 사진 삭제"></a>');
aFileList.push(' </li> ');
sLiTag = aFileList.join(" ");
aFileList = [];
}
return sLiTag;
}
/**
* HTML5 DragAndDrop으로 사진을 추가하고, 확인버튼을 누른 경우에 동작한다.
* @return
*/
function html5Upload() {
var tempFile,
sUploadURL;
sUploadURL= 'http://test.naver.com/popup/quick_photo/FileUploader_html5.php'; //upload URL
//파일을 하나씩 보내고, 결과를 받음.
for(var j=0, k=0; j < nImageInfoCnt; j++) {
tempFile = htImageInfo['img'+j];
try{
if(!!tempFile){
//Ajax통신하는 부분. 파일과 업로더할 url을 전달한다.
callAjaxForHTML5(tempFile,sUploadURL);
k += 1;
}
}catch(e){}
tempFile = null;
}
}
function callAjaxForHTML5 (tempFile, sUploadURL){
var oAjax = jindo.$Ajax(sUploadURL, {
type: 'xhr',
method : "post",
onload : function(res){ // 요청이 완료되면 실행될 콜백 함수
if (res.readyState() == 4) {
//성공 시에 responseText를 가지고 array로 만드는 부분.
makeArrayFromString(res._response.responseText);
}
},
timeout : 3,
onerror : jindo.$Fn(onAjaxError, this).bind()
});
oAjax.header("contentType","multipart/form-data");
oAjax.header("file-name",encodeURIComponent(tempFile.name));
oAjax.header("file-size",tempFile.size);
oAjax.header("file-Type",tempFile.type);
oAjax.request(tempFile);
}
function makeArrayFromString(sResString){
var aTemp = [],
aSubTemp = [],
htTemp = {}
aResultleng = 0;
try{
if(!sResString || sResString.indexOf("sFileURL") < 0){
return ;
}
aTemp = sResString.split("&");
for (var i = 0; i < aTemp.length ; i++){
if( !!aTemp[i] && aTemp[i] != "" && aTemp[i].indexOf("=") > 0){
aSubTemp = aTemp[i].split("=");
htTemp[aSubTemp[0]] = aSubTemp[1];
}
}
}catch(e){}
aResultleng = aResult.length;
aResult[aResultleng] = htTemp;
if(aResult.length == nImageFileCount){
setPhotoToEditor(aResult);
aResult = null;
window.close();
}
}
/**
* 사진 삭제 시에 호출되는 함수
* @param {Object} sParentId
*/
function delImage (sParentId){
var elLi = jindo.$$.getSingle("#"+sParentId);
refreshTotalImageSize(sParentId);
updateViewTotalSize();
updateViewCount(nImageFileCount,-1);
//사진 file array에서 정보 삭제.
removeImageInfo(sParentId);
//해당 li삭제
$Element(elLi).leave();
//마지막 이미지인경우.
if(nImageFileCount === 0){
readyModeBG();
//사진 추가 버튼 비활성화
goReadyMode();
}
// drop 영역 이벤트 다시 활성화.
if(!bAttachEvent){
addEvent();
}
}
/**
* 이벤트 할당
*/
function addEvent() {
bAttachEvent = true;
elDropArea.addEventListener("dragenter", dragEnter, false);
elDropArea.addEventListener("dragexit", dragExit, false);
elDropArea.addEventListener("dragover", dragOver, false);
elDropArea.addEventListener("drop", drop, false);
}
function removeEvent(){
bAttachEvent = false;
elDropArea.removeEventListener("dragenter", dragEnter, false);
elDropArea.removeEventListener("dragexit", dragExit, false);
elDropArea.removeEventListener("dragover", dragOver, false);
elDropArea.removeEventListener("drop", drop, false);
}
/**
* Ajax 통신 시 error가 발생할 때 처리하는 함수입니다.
* @return
*/
function onAjaxError (){
alert("[가이드]사진 업로더할 서버URL셋팅이 필요합니다.-onAjaxError"); //설치 가이드 안내 문구임. 실 서비스에서는 삭제.
}
/**
* 이미지 업로드 시작
* 확인 버튼 클릭하면 호출되는 msg
*/
function uploadImage (e){
if(!bSupportDragAndDropAPI){
generalUpload();
}else{
html5Upload();
}
}
/**
* jindo에 파일 업로드 사용.(iframe에 Form을 Submit하여 리프레시없이 파일을 업로드하는 컴포넌트)
*/
function callFileUploader (){
oFileUploader = new jindo.FileUploader(jindo.$("uploadInputBox"),{
sUrl : 'http://test.naver.com/Official-trunk/workspace/popup/quick_photo/FileUploader.php', //샘플 URL입니다.
sCallback : location.href.replace(/\/[^\/]*$/, '') + '/callback.html', //업로드 이후에 iframe이 redirect될 콜백페이지의 주소
sFiletype : "*.jpg;*.png;*.bmp;*.gif", //허용할 파일의 형식. ex) "*", "*.*", "*.jpg", 구분자(;)
sMsgNotAllowedExt : 'JPG, GIF, PNG, BMP 확장자만 가능합니다', //허용할 파일의 형식이 아닌경우에 띄워주는 경고창의 문구
bAutoUpload : false, //파일이 선택됨과 동시에 자동으로 업로드를 수행할지 여부 (upload 메소드 수행)
bAutoReset : true // 업로드한 직후에 파일폼을 리셋 시킬지 여부 (reset 메소드 수행)
}).attach({
select : function(oCustomEvent) {
//파일 선택이 완료되었을 때 발생
// oCustomEvent (이벤트 객체) = {
// sValue (String) 선택된 File Input의 값
// bAllowed (Boolean) 선택된 파일의 형식이 허용되는 형식인지 여부
// sMsgNotAllowedExt (String) 허용되지 않는 파일 형식인 경우 띄워줄 경고메세지
// }
// 선택된 파일의 형식이 허용되는 경우만 처리
if(oCustomEvent.bAllowed === true){
goStartMode();
}else{
goReadyMode();
oFileUploader.reset();
}
// bAllowed 값이 false인 경우 경고문구와 함께 alert 수행
// oCustomEvent.stop(); 수행시 bAllowed 가 false이더라도 alert이 수행되지 않음
},
success : function(oCustomEvent) {
// alert("success");
// 업로드가 성공적으로 완료되었을 때 발생
// oCustomEvent(이벤트 객체) = {
// htResult (Object) 서버에서 전달해주는 결과 객체 (서버 설정에 따라 유동적으로 선택가능)
// }
var aResult = [];
aResult[0] = oCustomEvent.htResult;
setPhotoToEditor(aResult);
//버튼 비활성화
goReadyMode();
oFileUploader.reset();
//window.close();
},
error : function(oCustomEvent) {
//업로드가 실패했을 때 발생
//oCustomEvent(이벤트 객체) = {
// htResult : { (Object) 서버에서 전달해주는 결과 객체. 에러발생시 errstr 프로퍼티를 반드시 포함하도록 서버 응답을 설정하여야한다.
// errstr : (String) 에러메시지
// }
//}
//var wel = jindo.$Element("info");
//wel.html(oCustomEvent.htResult.errstr);
alert(oCustomEvent.htResult.errstr);
}
});
}
/**
* 페이지 닫기 버튼 클릭
*/
function closeWindow(){
if(bSupportDragAndDropAPI){
removeEvent();
}
// window.close();
}
window.onload = function(){
checkDragAndDropAPI();
if(bSupportDragAndDropAPI){
$Element("pop_container2").hide();
$Element("pop_container").show();
welTextGuide.removeClass("nobg");
welTextGuide.className("bg");
addEvent();
} else {
$Element("pop_container").hide();
$Element("pop_container2").show();
callFileUploader();
}
fnUploadImage = $Fn(uploadImage,this);
$Fn(closeWindow,this).attach(welBtnCancel.$value(), "click");
};
/**
* 서버로부터 받은 데이타를 에디터에 전달하고 창을 닫음.
* @parameter aFileInfo [{},{},...]
* @ex aFileInfo = [
* {
sFileName : "nmms_215646753.gif",
sFileURL :"http://static.naver.net/www/u/2010/0611/nmms_215646753.gif",
bNewLine : true
},
{
sFileName : "btn_sch_over.gif",
sFileURL :"http://static1.naver.net/w9/btn_sch_over.gif",
bNewLine : true
}
* ]
*/
function setPhotoToEditor(oFileInfo){
if (!!opener && !!opener.nhn && !!opener.nhn.husky && !!opener.nhn.husky.PopUpManager) {
//스마트 에디터 플러그인을 통해서 넣는 방법 (oFileInfo는 Array)
opener.nhn.husky.PopUpManager.setCallback(window, 'SET_PHOTO', [oFileInfo]);
//본문에 바로 tag를 넣는 방법 (oFileInfo는 String으로 <img src=....> )
//opener.nhn.husky.PopUpManager.setCallback(window, 'PASTE_HTML', [oFileInfo]);
}
}
// 2012.05 현재] jindo.$Ajax.prototype.request에서 file과 form을 지원하지 안함.
jindo.$Ajax.prototype.request = function(oData) {
this._status++;
var t = this;
var req = this._request;
var opt = this._options;
var data, v,a = [], data = "";
var _timer = null;
var url = this._url;
this._is_abort = false;
if( opt.postBody && opt.type.toUpperCase()=="XHR" && opt.method.toUpperCase()!="GET"){
if(typeof oData == 'string'){
data = oData;
}else{
data = jindo.$Json(oData).toString();
}
}else if (typeof oData == "undefined" || !oData) {
data = null;
} else {
data = oData;
}
req.open(opt.method.toUpperCase(), url, opt.async);
if (opt.sendheader) {
if(!this._headers["Content-Type"]){
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
}
req.setRequestHeader("charset", "utf-8");
for (var x in this._headers) {
if(this._headers.hasOwnProperty(x)){
if (typeof this._headers[x] == "function")
continue;
req.setRequestHeader(x, String(this._headers[x]));
}
}
}
var navi = navigator.userAgent;
if(req.addEventListener&&!(navi.indexOf("Opera") > -1)&&!(navi.indexOf("MSIE") > -1)){
/*
* opera 10.60에서 XMLHttpRequest에 addEventListener기 추가되었지만 정상적으로 동작하지 않아 opera는 무조건 dom1방식으로 지원함.
* IE9에서도 opera와 같은 문제가 있음.
*/
if(this._loadFunc){ req.removeEventListener("load", this._loadFunc, false); }
this._loadFunc = function(rq){
clearTimeout(_timer);
_timer = undefined;
t._onload(rq);
}
req.addEventListener("load", this._loadFunc, false);
}else{
if (typeof req.onload != "undefined") {
req.onload = function(rq){
if(req.readyState == 4 && !t._is_abort){
clearTimeout(_timer);
_timer = undefined;
t._onload(rq);
}
};
} else {
/*
* IE6에서는 onreadystatechange가 동기적으로 실행되어 timeout이벤트가 발생안됨.
* 그래서 interval로 체크하여 timeout이벤트가 정상적으로 발생되도록 수정. 비동기 방식일때만
*/
if(window.navigator.userAgent.match(/(?:MSIE) ([0-9.]+)/)[1]==6&&opt.async){
var onreadystatechange = function(rq){
if(req.readyState == 4 && !t._is_abort){
if(_timer){
clearTimeout(_timer);
_timer = undefined;
}
t._onload(rq);
clearInterval(t._interval);
t._interval = undefined;
}
};
this._interval = setInterval(onreadystatechange,300);
}else{
req.onreadystatechange = function(rq){
if(req.readyState == 4){
clearTimeout(_timer);
_timer = undefined;
t._onload(rq);
}
};
}
}
}
req.send(data);
return this;
}; | JavaScript |
/**
* Jindo Component
* @version 1.0.3
* NHN_Library:Jindo_Component-1.0.3;JavaScript Components for Jindo;
* @include Component, UIComponent, FileUploader
*/
jindo.Component = jindo.$Class({
_htEventHandler: null,
_htOption: null,
$init: function () {
var aInstance = this.constructor.getInstance();
aInstance.push(this);
this._htEventHandler = {};
this._htOption = {};
this._htOption._htSetter = {};
},
option: function (sName, vValue) {
switch (typeof sName) {
case "undefined":
return this._htOption;
case "string":
if (typeof vValue != "undefined") {
if (sName == "htCustomEventHandler") {
if (typeof this._htOption[sName] == "undefined") {
this.attach(vValue);
} else {
return this;
}
}
this._htOption[sName] = vValue;
if (typeof this._htOption._htSetter[sName] == "function") {
this._htOption._htSetter[sName](vValue);
}
} else {
return this._htOption[sName];
}
break;
case "object":
for (var sKey in sName) {
if (sKey == "htCustomEventHandler") {
if (typeof this._htOption[sKey] == "undefined") {
this.attach(sName[sKey]);
} else {
continue;
}
}
this._htOption[sKey] = sName[sKey];
if (typeof this._htOption._htSetter[sKey] == "function") {
this._htOption._htSetter[sKey](sName[sKey]);
}
}
break;
}
return this;
},
optionSetter: function (sName, fSetter) {
switch (typeof sName) {
case "undefined":
return this._htOption._htSetter;
case "string":
if (typeof fSetter != "undefined") {
this._htOption._htSetter[sName] = jindo.$Fn(fSetter, this).bind();
} else {
return this._htOption._htSetter[sName];
}
break;
case "object":
for (var sKey in sName) {
this._htOption._htSetter[sKey] = jindo.$Fn(sName[sKey], this).bind();
}
break;
}
return this;
},
fireEvent: function (sEvent, oEvent) {
oEvent = oEvent || {};
var fInlineHandler = this['on' + sEvent],
aHandlerList = this._htEventHandler[sEvent] || [],
bHasInlineHandler = typeof fInlineHandler == "function",
bHasHandlerList = aHandlerList.length > 0;
if (!bHasInlineHandler && !bHasHandlerList) {
return true;
}
aHandlerList = aHandlerList.concat();
oEvent.sType = sEvent;
if (typeof oEvent._aExtend == 'undefined') {
oEvent._aExtend = [];
oEvent.stop = function () {
if (oEvent._aExtend.length > 0) {
oEvent._aExtend[oEvent._aExtend.length - 1].bCanceled = true;
}
};
}
oEvent._aExtend.push({
sType: sEvent,
bCanceled: false
});
var aArg = [oEvent],
i, nLen;
for (i = 2, nLen = arguments.length; i < nLen; i++) {
aArg.push(arguments[i]);
}
if (bHasInlineHandler) {
fInlineHandler.apply(this, aArg);
}
if (bHasHandlerList) {
var fHandler;
for (i = 0, fHandler;
(fHandler = aHandlerList[i]); i++) {
fHandler.apply(this, aArg);
}
}
return !oEvent._aExtend.pop().bCanceled;
},
attach: function (sEvent, fHandlerToAttach) {
if (arguments.length == 1) {
jindo.$H(arguments[0]).forEach(jindo.$Fn(function (fHandler, sEvent) {
this.attach(sEvent, fHandler);
}, this).bind());
return this;
}
var aHandler = this._htEventHandler[sEvent];
if (typeof aHandler == 'undefined') {
aHandler = this._htEventHandler[sEvent] = [];
}
aHandler.push(fHandlerToAttach);
return this;
},
detach: function (sEvent, fHandlerToDetach) {
if (arguments.length == 1) {
jindo.$H(arguments[0]).forEach(jindo.$Fn(function (fHandler, sEvent) {
this.detach(sEvent, fHandler);
}, this).bind());
return this;
}
var aHandler = this._htEventHandler[sEvent];
if (aHandler) {
for (var i = 0, fHandler;
(fHandler = aHandler[i]); i++) {
if (fHandler === fHandlerToDetach) {
aHandler = aHandler.splice(i, 1);
break;
}
}
}
return this;
},
detachAll: function (sEvent) {
var aHandler = this._htEventHandler;
if (arguments.length) {
if (typeof aHandler[sEvent] == 'undefined') {
return this;
}
delete aHandler[sEvent];
return this;
}
for (var o in aHandler) {
delete aHandler[o];
}
return this;
}
});
jindo.Component.factory = function (aObject, htOption) {
var aReturn = [],
oInstance;
if (typeof htOption == "undefined") {
htOption = {};
}
for (var i = 0, el;
(el = aObject[i]); i++) {
oInstance = new this(el, htOption);
aReturn[aReturn.length] = oInstance;
}
return aReturn;
};
jindo.Component.getInstance = function () {
if (typeof this._aInstance == "undefined") {
this._aInstance = [];
}
return this._aInstance;
};
jindo.UIComponent = jindo.$Class({
$init: function () {
this._bIsActivating = false;
},
isActivating: function () {
return this._bIsActivating;
},
activate: function () {
if (this.isActivating()) {
return this;
}
this._bIsActivating = true;
if (arguments.length > 0) {
this._onActivate.apply(this, arguments);
} else {
this._onActivate();
}
return this;
},
deactivate: function () {
if (!this.isActivating()) {
return this;
}
this._bIsActivating = false;
if (arguments.length > 0) {
this._onDeactivate.apply(this, arguments);
} else {
this._onDeactivate();
}
return this;
}
}).extend(jindo.Component);
jindo.FileUploader = jindo.$Class({
_bIsActivating: false,
_aHiddenInput: [],
$init: function (elFileSelect, htOption) {
var htDefaultOption = {
sUrl: '',
sCallback: '',
htData: {},
sFiletype: '*',
sMsgNotAllowedExt: "업로드가 허용되지 않는 파일형식입니다",
bAutoUpload: false,
bAutoReset: true,
bActivateOnload: true
};
this.option(htDefaultOption);
this.option(htOption || {});
this._el = jindo.$(elFileSelect);
this._wel = jindo.$Element(this._el);
this._elForm = this._el.form;
this._aHiddenInput = [];
this.constructor._oCallback = {};
this._wfChange = jindo.$Fn(this._onFileSelectChange, this);
if (this.option("bActivateOnload")) {
this.activate();
}
},
_appendIframe: function () {
var sIframeName = 'tmpFrame_' + this._makeUniqueId();
this._welIframe = jindo.$Element(jindo.$('<iframe name="' + sIframeName + '" src="' + this.option("sCallback") + '?blank">')).css({
width: '10px',
border: '2px',
height: '10px',
left: '10px',
top: '10px'
});
document.body.appendChild(this._welIframe.$value());
},
_removeIframe: function () {
this._welIframe.leave();
},
getBaseElement: function () {
return this.getFileSelect();
},
getFileSelect: function () {
return this._el;
},
getFormElement: function () {
return this._elForm;
},
upload: function () {
this._appendIframe();
var elForm = this.getFormElement(),
welForm = jindo.$Element(elForm),
sIframeName = this._welIframe.attr("name"),
sFunctionName = sIframeName + '_func',
sAction = this.option("sUrl");
welForm.attr({
target: sIframeName,
action: sAction
});
this._aHiddenInput.push(this._createElement('input', {
'type': 'hidden',
'name': 'callback',
'value': this.option("sCallback")
}));
this._aHiddenInput.push(this._createElement('input', {
'type': 'hidden',
'name': 'callback_func',
'value': sFunctionName
}));
for (var k in this.option("htData")) {
this._aHiddenInput.push(this._createElement('input', {
'type': 'hidden',
'name': k,
'value': this.option("htData")[k]
}));
}
for (var i = 0; i < this._aHiddenInput.length; i++) {
elForm.appendChild(this._aHiddenInput[i]);
}
this.constructor._oCallback[sFunctionName + '_success'] = jindo.$Fn(function (oParameter) {
this.fireEvent("success", {
htResult: oParameter
});
delete this.constructor._oCallback[oParameter.callback_func + '_success'];
delete this.constructor._oCallback[oParameter.callback_func + '_error'];
for (var i = 0; i < this._aHiddenInput.length; i++) {
jindo.$Element(this._aHiddenInput[i]).leave();
}
this._aHiddenInput.length = 0;
this._removeIframe();
}, this).bind();
this.constructor._oCallback[sFunctionName + '_error'] = jindo.$Fn(function (oParameter) {
this.fireEvent("error", {
htResult: oParameter
});
delete this.constructor._oCallback[oParameter.callback_func + '_success'];
delete this.constructor._oCallback[oParameter.callback_func + '_error'];
for (var i = 0; i < this._aHiddenInput.length; i++) {
jindo.$Element(this._aHiddenInput[i]).leave();
}
this._aHiddenInput.length = 0;
this._removeIframe();
}, this).bind();
elForm.submit();
if (this.option("bAutoReset")) {
this.reset();
}
},
reset: function () {
var elWrapForm = jindo.$("<form>");
this._wel.wrap(elWrapForm);
elWrapForm.reset();
jindo.$Element(elWrapForm).replace(this._el);
var elForm = this.getFormElement(),
welForm = jindo.$Element(elForm);
welForm.attr({
target: this._sPrevTarget,
action: this._sAction
});
return this;
},
_onActivate: function () {
var elForm = this.getFormElement(),
welForm = jindo.$Element(elForm);
this._sPrevTarget = welForm.attr("target");
this._sAction = welForm.attr("action");
this._el.value = "";
this._wfChange.attach(this._el, "change");
},
_onDeactivate: function () {
this._wfChange.detach(this._el, "change");
},
_makeUniqueId: function () {
return new Date().getMilliseconds() + Math.floor(Math.random() * 100000);
},
_createElement: function (name, attributes) {
var el = jindo.$("<" + name + ">");
var wel = jindo.$Element(el);
for (var k in attributes) {
wel.attr(k, attributes[k]);
}
return el;
},
_checkExtension: function (sFile) {
var aType = this.option("sFiletype").split(';');
for (var i = 0, sType; i < aType.length; i++) {
sType = (aType[i] == "*.*") ? "*" : aType[i];
sType = sType.replace(/^\s+|\s+$/, '');
sType = sType.replace(/\./g, '\\.');
sType = sType.replace(/\*/g, '[^\\\/]+');
if ((new RegExp(sType + '$', 'gi')).test(sFile)) {
return true;
}
}
return false;
},
_onFileSelectChange: function (we) {
var sValue = we.element.value,
bAllowed = this._checkExtension(sValue),
htParam = {
sValue: sValue,
bAllowed: bAllowed,
sMsgNotAllowedExt: this.option("sMsgNotAllowedExt")
};
if (sValue.length && this.fireEvent("select", htParam)) {
if (bAllowed) {
if (this.option("bAutoUpload")) {
this.upload();
}
} else {
alert(htParam.sMsgNotAllowedExt);
}
}
}
}).extend(jindo.UIComponent); | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.