code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.htmlParser.basicWriter = CKEDITOR.tools.createClass(
{
$ : function()
{
this._ =
{
output : []
};
},
proto :
{
/**
* Writes the tag opening part for a opener tag.
* @param {String} tagName The element name for this tag.
* @param {Object} attributes The attributes defined for this tag. The
* attributes could be used to inspect the tag.
* @example
* // Writes "<p".
* writer.openTag( 'p', { class : 'MyClass', id : 'MyId' } );
*/
openTag : function( tagName, attributes )
{
this._.output.push( '<', tagName );
},
/**
* Writes the tag closing part for a opener tag.
* @param {String} tagName The element name for this tag.
* @param {Boolean} isSelfClose Indicates that this is a self-closing tag,
* like "br" or "img".
* @example
* // Writes ">".
* writer.openTagClose( 'p', false );
* @example
* // Writes " />".
* writer.openTagClose( 'br', true );
*/
openTagClose : function( tagName, isSelfClose )
{
if ( isSelfClose )
this._.output.push( ' />' );
else
this._.output.push( '>' );
},
/**
* Writes an attribute. This function should be called after opening the
* tag with {@link #openTagClose}.
* @param {String} attName The attribute name.
* @param {String} attValue The attribute value.
* @example
* // Writes ' class="MyClass"'.
* writer.attribute( 'class', 'MyClass' );
*/
attribute : function( attName, attValue )
{
// Browsers don't always escape special character in attribute values. (#4683, #4719).
if ( typeof attValue == 'string' )
attValue = CKEDITOR.tools.htmlEncodeAttr( attValue );
this._.output.push( ' ', attName, '="', attValue, '"' );
},
/**
* Writes a closer tag.
* @param {String} tagName The element name for this tag.
* @example
* // Writes "</p>".
* writer.closeTag( 'p' );
*/
closeTag : function( tagName )
{
this._.output.push( '</', tagName, '>' );
},
/**
* Writes text.
* @param {String} text The text value
* @example
* // Writes "Hello Word".
* writer.text( 'Hello Word' );
*/
text : function( text )
{
this._.output.push( text );
},
/**
* Writes a comment.
* @param {String} comment The comment text.
* @example
* // Writes "<!-- My comment -->".
* writer.comment( ' My comment ' );
*/
comment : function( comment )
{
this._.output.push( '<!--', comment, '-->' );
},
/**
* Writes any kind of data to the ouput.
* @example
* writer.write( 'This is an <b>example</b>.' );
*/
write : function( data )
{
this._.output.push( data );
},
/**
* Empties the current output buffer.
* @example
* writer.reset();
*/
reset : function()
{
this._.output = [];
this._.indent = false;
},
/**
* Empties the current output buffer.
* @param {Boolean} reset Indicates that the {@link reset} function is to
* be automatically called after retrieving the HTML.
* @returns {String} The HTML written to the writer so far.
* @example
* var html = writer.getHtml();
*/
getHtml : function( reset )
{
var html = this._.output.join( '' );
if ( reset )
this.reset();
return html;
}
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* A lightweight representation of an HTML DOM structure.
* @constructor
* @example
*/
CKEDITOR.htmlParser.fragment = function()
{
/**
* The nodes contained in the root of this fragment.
* @type Array
* @example
* var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<b>Sample</b> Text' );
* alert( fragment.children.length ); "2"
*/
this.children = [];
/**
* Get the fragment parent. Should always be null.
* @type Object
* @default null
* @example
*/
this.parent = null;
/** @private */
this._ =
{
isBlockLike : true,
hasInlineStarted : false
};
};
(function()
{
// Block-level elements whose internal structure should be respected during
// parser fixing.
var nonBreakingBlocks = CKEDITOR.tools.extend( { table:1,ul:1,ol:1,dl:1 }, CKEDITOR.dtd.table, CKEDITOR.dtd.ul, CKEDITOR.dtd.ol, CKEDITOR.dtd.dl );
// IE < 8 don't output the close tag on definition list items. (#6975)
var optionalCloseTags = CKEDITOR.env.ie && CKEDITOR.env.version < 8 ? { dd : 1, dt :1 } : {};
var listBlocks = { ol:1, ul:1 };
// Dtd of the fragment element, basically it accept anything except for intermediate structure, e.g. orphan <li>.
var rootDtd = CKEDITOR.tools.extend( {}, { html: 1 }, CKEDITOR.dtd.html, CKEDITOR.dtd.body, CKEDITOR.dtd.head, { style:1,script:1 } );
function isRemoveEmpty( node )
{
// Empty link is to be removed when empty but not anchor. (#7894)
return node.name == 'a' && node.attributes.href
|| CKEDITOR.dtd.$removeEmpty[ node.name ];
}
/**
* Creates a {@link CKEDITOR.htmlParser.fragment} from an HTML string.
* @param {String} fragmentHtml The HTML to be parsed, filling the fragment.
* @param {Number} [fixForBody=false] Wrap body with specified element if needed.
* @param {CKEDITOR.htmlParser.element} contextNode Parse the html as the content of this element.
* @returns CKEDITOR.htmlParser.fragment The fragment created.
* @example
* var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<b>Sample</b> Text' );
* alert( fragment.children[0].name ); "b"
* alert( fragment.children[1].value ); " Text"
*/
CKEDITOR.htmlParser.fragment.fromHtml = function( fragmentHtml, fixForBody, contextNode )
{
var parser = new CKEDITOR.htmlParser(),
fragment = contextNode || new CKEDITOR.htmlParser.fragment(),
pendingInline = [],
pendingBRs = [],
currentNode = fragment,
// Indicate we're inside a <textarea> element, spaces should be touched differently.
inTextarea = false,
// Indicate we're inside a <pre> element, spaces should be touched differently.
inPre = false;
function checkPending( newTagName )
{
var pendingBRsSent;
if ( pendingInline.length > 0 )
{
for ( var i = 0 ; i < pendingInline.length ; i++ )
{
var pendingElement = pendingInline[ i ],
pendingName = pendingElement.name,
pendingDtd = CKEDITOR.dtd[ pendingName ],
currentDtd = currentNode.name && CKEDITOR.dtd[ currentNode.name ];
if ( ( !currentDtd || currentDtd[ pendingName ] ) && ( !newTagName || !pendingDtd || pendingDtd[ newTagName ] || !CKEDITOR.dtd[ newTagName ] ) )
{
if ( !pendingBRsSent )
{
sendPendingBRs();
pendingBRsSent = 1;
}
// Get a clone for the pending element.
pendingElement = pendingElement.clone();
// Add it to the current node and make it the current,
// so the new element will be added inside of it.
pendingElement.parent = currentNode;
currentNode = pendingElement;
// Remove the pending element (back the index by one
// to properly process the next entry).
pendingInline.splice( i, 1 );
i--;
}
else
{
// Some element of the same type cannot be nested, flat them,
// e.g. <a href="#">foo<a href="#">bar</a></a>. (#7894)
if ( pendingName == currentNode.name )
addElement( currentNode, currentNode.parent, 1 ), i--;
}
}
}
}
function sendPendingBRs()
{
while ( pendingBRs.length )
addElement( pendingBRs.shift(), currentNode );
}
/*
* Beside of simply append specified element to target, this function also takes
* care of other dirty lifts like forcing block in body, trimming spaces at
* the block boundaries etc.
*
* @param {Element} element The element to be added as the last child of {@link target}.
* @param {Element} target The parent element to relieve the new node.
* @param {Boolean} [moveCurrent=false] Don't change the "currentNode" global unless
* there's a return point node specified on the element, otherwise move current onto {@link target} node.
*/
function addElement( element, target, moveCurrent )
{
// Ignore any element that has already been added.
if ( element.previous !== undefined )
return;
target = target || currentNode || fragment;
// Current element might be mangled by fix body below,
// save it for restore later.
var savedCurrent = currentNode;
// If the target is the fragment and this inline element can't go inside
// body (if fixForBody).
if ( fixForBody && ( !target.type || target.name == 'body' ) )
{
var elementName, realElementName;
if ( element.attributes
&& ( realElementName =
element.attributes[ 'data-cke-real-element-type' ] ) )
elementName = realElementName;
else
elementName = element.name;
if ( elementName && !( elementName in CKEDITOR.dtd.$body || elementName == 'body' || element.isOrphan ) )
{
// Create a <p> in the fragment.
currentNode = target;
parser.onTagOpen( fixForBody, {} );
// The new target now is the <p>.
element.returnPoint = target = currentNode;
}
}
// Rtrim empty spaces on block end boundary. (#3585)
if ( element._.isBlockLike
&& element.name != 'pre' && element.name != 'textarea' )
{
var length = element.children.length,
lastChild = element.children[ length - 1 ],
text;
if ( lastChild && lastChild.type == CKEDITOR.NODE_TEXT )
{
if ( !( text = CKEDITOR.tools.rtrim( lastChild.value ) ) )
element.children.length = length -1;
else
lastChild.value = text;
}
}
target.add( element );
if ( element.name == 'pre' )
inPre = false;
if ( element.name == 'textarea' )
inTextarea = false;
if ( element.returnPoint )
{
currentNode = element.returnPoint;
delete element.returnPoint;
}
else
currentNode = moveCurrent ? target : savedCurrent;
}
parser.onTagOpen = function( tagName, attributes, selfClosing, optionalClose )
{
var element = new CKEDITOR.htmlParser.element( tagName, attributes );
// "isEmpty" will be always "false" for unknown elements, so we
// must force it if the parser has identified it as a selfClosing tag.
if ( element.isUnknown && selfClosing )
element.isEmpty = true;
// Check for optional closed elements, including browser quirks and manually opened blocks.
element.isOptionalClose = tagName in optionalCloseTags || optionalClose;
// This is a tag to be removed if empty, so do not add it immediately.
if ( isRemoveEmpty( element ) )
{
pendingInline.push( element );
return;
}
else if ( tagName == 'pre' )
inPre = true;
else if ( tagName == 'br' && inPre )
{
currentNode.add( new CKEDITOR.htmlParser.text( '\n' ) );
return;
}
else if ( tagName == 'textarea' )
inTextarea = true;
if ( tagName == 'br' )
{
pendingBRs.push( element );
return;
}
while( 1 )
{
var currentName = currentNode.name;
var currentDtd = currentName ? ( CKEDITOR.dtd[ currentName ]
|| ( currentNode._.isBlockLike ? CKEDITOR.dtd.div : CKEDITOR.dtd.span ) )
: rootDtd;
// If the element cannot be child of the current element.
if ( !element.isUnknown && !currentNode.isUnknown && !currentDtd[ tagName ] )
{
// Current node doesn't have a close tag, time for a close
// as this element isn't fit in. (#7497)
if ( currentNode.isOptionalClose )
parser.onTagClose( currentName );
// Fixing malformed nested lists by moving it into a previous list item. (#3828)
else if ( tagName in listBlocks
&& currentName in listBlocks )
{
var children = currentNode.children,
lastChild = children[ children.length - 1 ];
// Establish the list item if it's not existed.
if ( !( lastChild && lastChild.name == 'li' ) )
addElement( ( lastChild = new CKEDITOR.htmlParser.element( 'li' ) ), currentNode );
!element.returnPoint && ( element.returnPoint = currentNode );
currentNode = lastChild;
}
// Establish new list root for orphan list items.
else if ( tagName in CKEDITOR.dtd.$listItem && currentName != tagName )
parser.onTagOpen( tagName == 'li' ? 'ul' : 'dl', {}, 0, 1 );
// We're inside a structural block like table and list, AND the incoming element
// is not of the same type (e.g. <td>td1<td>td2</td>), we simply add this new one before it,
// and most importantly, return back to here once this element is added,
// e.g. <table><tr><td>td1</td><p>p1</p><td>td2</td></tr></table>
else if ( currentName in nonBreakingBlocks && currentName != tagName )
{
!element.returnPoint && ( element.returnPoint = currentNode );
currentNode = currentNode.parent;
}
else
{
// The current element is an inline element, which
// need to be continued even after the close, so put
// it in the pending list.
if ( currentName in CKEDITOR.dtd.$inline )
pendingInline.unshift( currentNode );
// The most common case where we just need to close the
// current one and append the new one to the parent.
if ( currentNode.parent )
addElement( currentNode, currentNode.parent, 1 );
// We've tried our best to fix the embarrassment here, while
// this element still doesn't find it's parent, mark it as
// orphan and show our tolerance to it.
else
{
element.isOrphan = 1;
break;
}
}
}
else
break;
}
checkPending( tagName );
sendPendingBRs();
element.parent = currentNode;
if ( element.isEmpty )
addElement( element );
else
currentNode = element;
};
parser.onTagClose = function( tagName )
{
// Check if there is any pending tag to be closed.
for ( var i = pendingInline.length - 1 ; i >= 0 ; i-- )
{
// If found, just remove it from the list.
if ( tagName == pendingInline[ i ].name )
{
pendingInline.splice( i, 1 );
return;
}
}
var pendingAdd = [],
newPendingInline = [],
candidate = currentNode;
while ( candidate != fragment && candidate.name != tagName )
{
// If this is an inline element, add it to the pending list, if we're
// really closing one of the parents element later, they will continue
// after it.
if ( !candidate._.isBlockLike )
newPendingInline.unshift( candidate );
// This node should be added to it's parent at this point. But,
// it should happen only if the closing tag is really closing
// one of the nodes. So, for now, we just cache it.
pendingAdd.push( candidate );
// Make sure return point is properly restored.
candidate = candidate.returnPoint || candidate.parent;
}
if ( candidate != fragment )
{
// Add all elements that have been found in the above loop.
for ( i = 0 ; i < pendingAdd.length ; i++ )
{
var node = pendingAdd[ i ];
addElement( node, node.parent );
}
currentNode = candidate;
if ( candidate._.isBlockLike )
sendPendingBRs();
addElement( candidate, candidate.parent );
// The parent should start receiving new nodes now, except if
// addElement changed the currentNode.
if ( candidate == currentNode )
currentNode = currentNode.parent;
pendingInline = pendingInline.concat( newPendingInline );
}
if ( tagName == 'body' )
fixForBody = false;
};
parser.onText = function( text )
{
// Trim empty spaces at beginning of text contents except <pre> and <textarea>.
if ( ( !currentNode._.hasInlineStarted || pendingBRs.length ) && !inPre && !inTextarea )
{
text = CKEDITOR.tools.ltrim( text );
if ( text.length === 0 )
return;
}
var currentName = currentNode.name,
currentDtd = currentName ? ( CKEDITOR.dtd[ currentName ]
|| ( currentNode._.isBlockLike ?
CKEDITOR.dtd.div : CKEDITOR.dtd.span ) ) : rootDtd;
// Fix orphan text in list/table. (#8540) (#8870)
if ( !inTextarea &&
!currentDtd [ '#' ] &&
currentName in nonBreakingBlocks )
{
parser.onTagOpen( currentName in listBlocks ? 'li' :
currentName == 'dl' ? 'dd' :
currentName == 'table' ? 'tr' :
currentName == 'tr' ? 'td' : '' );
parser.onText( text );
return;
}
sendPendingBRs();
checkPending();
if ( fixForBody
&& ( !currentNode.type || currentNode.name == 'body' )
&& CKEDITOR.tools.trim( text ) )
{
this.onTagOpen( fixForBody, {}, 0, 1 );
}
// Shrinking consequential spaces into one single for all elements
// text contents.
if ( !inPre && !inTextarea )
text = text.replace( /[\t\r\n ]{2,}|[\t\r\n]/g, ' ' );
currentNode.add( new CKEDITOR.htmlParser.text( text ) );
};
parser.onCDATA = function( cdata )
{
currentNode.add( new CKEDITOR.htmlParser.cdata( cdata ) );
};
parser.onComment = function( comment )
{
sendPendingBRs();
checkPending();
currentNode.add( new CKEDITOR.htmlParser.comment( comment ) );
};
// Parse it.
parser.parse( fragmentHtml );
// Send all pending BRs except one, which we consider a unwanted bogus. (#5293)
sendPendingBRs( !CKEDITOR.env.ie && 1 );
// Close all pending nodes, make sure return point is properly restored.
while ( currentNode != fragment )
addElement( currentNode, currentNode.parent, 1 );
return fragment;
};
CKEDITOR.htmlParser.fragment.prototype =
{
/**
* Adds a node to this fragment.
* @param {Object} node The node to be added. It can be any of of the
* following types: {@link CKEDITOR.htmlParser.element},
* {@link CKEDITOR.htmlParser.text} and
* {@link CKEDITOR.htmlParser.comment}.
* @param {Number} [index] From where the insertion happens.
* @example
*/
add : function( node, index )
{
isNaN( index ) && ( index = this.children.length );
var previous = index > 0 ? this.children[ index - 1 ] : null;
if ( previous )
{
// If the block to be appended is following text, trim spaces at
// the right of it.
if ( node._.isBlockLike && previous.type == CKEDITOR.NODE_TEXT )
{
previous.value = CKEDITOR.tools.rtrim( previous.value );
// If we have completely cleared the previous node.
if ( previous.value.length === 0 )
{
// Remove it from the list and add the node again.
this.children.pop();
this.add( node );
return;
}
}
previous.next = node;
}
node.previous = previous;
node.parent = this;
this.children.splice( index, 0, node );
this._.hasInlineStarted = node.type == CKEDITOR.NODE_TEXT || ( node.type == CKEDITOR.NODE_ELEMENT && !node._.isBlockLike );
},
/**
* Writes the fragment HTML to a CKEDITOR.htmlWriter.
* @param {CKEDITOR.htmlWriter} writer The writer to which write the HTML.
* @example
* var writer = new CKEDITOR.htmlWriter();
* var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<P><B>Example' );
* fragment.writeHtml( writer )
* alert( writer.getHtml() ); "<p><b>Example</b></p>"
*/
writeHtml : function( writer, filter )
{
var isChildrenFiltered;
this.filterChildren = function()
{
var writer = new CKEDITOR.htmlParser.basicWriter();
this.writeChildrenHtml.call( this, writer, filter, true );
var html = writer.getHtml();
this.children = new CKEDITOR.htmlParser.fragment.fromHtml( html ).children;
isChildrenFiltered = 1;
};
// Filtering the root fragment before anything else.
!this.name && filter && filter.onFragment( this );
this.writeChildrenHtml( writer, isChildrenFiltered ? null : filter );
},
writeChildrenHtml : function( writer, filter )
{
for ( var i = 0 ; i < this.children.length ; i++ )
this.children[i].writeHtml( writer, filter );
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* A lightweight representation of an HTML element.
* @param {String} name The element name.
* @param {Object} attributes And object holding all attributes defined for
* this element.
* @constructor
* @example
*/
CKEDITOR.htmlParser.element = function( name, attributes )
{
/**
* The element name.
* @type String
* @example
*/
this.name = name;
/**
* Holds the attributes defined for this element.
* @type Object
* @example
*/
this.attributes = attributes || {};
/**
* The nodes that are direct children of this element.
* @type Array
* @example
*/
this.children = [];
// Reveal the real semantic of our internal custom tag name (#6639),
// when resolving whether it's block like.
var realName = name || '',
prefixed = realName.match( /^cke:(.*)/ );
prefixed && ( realName = prefixed[ 1 ] );
var isBlockLike = !!( CKEDITOR.dtd.$nonBodyContent[ realName ]
|| CKEDITOR.dtd.$block[ realName ]
|| CKEDITOR.dtd.$listItem[ realName ]
|| CKEDITOR.dtd.$tableContent[ realName ]
|| CKEDITOR.dtd.$nonEditable[ realName ]
|| realName == 'br' );
this.isEmpty = !!CKEDITOR.dtd.$empty[ name ];
this.isUnknown = !CKEDITOR.dtd[ name ];
/** @private */
this._ =
{
isBlockLike : isBlockLike,
hasInlineStarted : this.isEmpty || !isBlockLike
};
};
/**
* Object presentation of CSS style declaration text.
* @param {CKEDITOR.htmlParser.element|String} elementOrStyleText A html parser element or the inline style text.
*/
CKEDITOR.htmlParser.cssStyle = function()
{
var styleText,
arg = arguments[ 0 ],
rules = {};
styleText = arg instanceof CKEDITOR.htmlParser.element ? arg.attributes.style : arg;
// html-encoded quote might be introduced by 'font-family'
// from MS-Word which confused the following regexp. e.g.
//'font-family: "Lucida, Console"'
( styleText || '' )
.replace( /"/g, '"' )
.replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g,
function( match, name, value )
{
name == 'font-family' && ( value = value.replace( /["']/g, '' ) );
rules[ name.toLowerCase() ] = value;
});
return {
rules : rules,
/**
* Apply the styles onto the specified element or object.
* @param {CKEDITOR.htmlParser.element|CKEDITOR.dom.element|Object} obj
*/
populate : function( obj )
{
var style = this.toString();
if ( style )
{
obj instanceof CKEDITOR.dom.element ?
obj.setAttribute( 'style', style ) :
obj instanceof CKEDITOR.htmlParser.element ?
obj.attributes.style = style :
obj.style = style;
}
},
toString : function()
{
var output = [];
for ( var i in rules )
rules[ i ] && output.push( i, ':', rules[ i ], ';' );
return output.join( '' );
}
};
};
(function()
{
// Used to sort attribute entries in an array, where the first element of
// each object is the attribute name.
var sortAttribs = function( a, b )
{
a = a[0];
b = b[0];
return a < b ? -1 : a > b ? 1 : 0;
};
CKEDITOR.htmlParser.element.prototype =
{
/**
* The node type. This is a constant value set to {@link CKEDITOR.NODE_ELEMENT}.
* @type Number
* @example
*/
type : CKEDITOR.NODE_ELEMENT,
/**
* Adds a node to the element children list.
* @param {Object} node The node to be added. It can be any of of the
* following types: {@link CKEDITOR.htmlParser.element},
* {@link CKEDITOR.htmlParser.text} and
* {@link CKEDITOR.htmlParser.comment}.
* @function
* @example
*/
add : CKEDITOR.htmlParser.fragment.prototype.add,
/**
* Clone this element.
* @returns {CKEDITOR.htmlParser.element} The element clone.
* @example
*/
clone : function()
{
return new CKEDITOR.htmlParser.element( this.name, this.attributes );
},
/**
* Writes the element HTML to a CKEDITOR.htmlWriter.
* @param {CKEDITOR.htmlWriter} writer The writer to which write the HTML.
* @example
*/
writeHtml : function( writer, filter )
{
var attributes = this.attributes;
// Ignore cke: prefixes when writing HTML.
var element = this,
writeName = element.name,
a, newAttrName, value;
var isChildrenFiltered;
/**
* Providing an option for bottom-up filtering order ( element
* children to be pre-filtered before the element itself ).
*/
element.filterChildren = function()
{
if ( !isChildrenFiltered )
{
var writer = new CKEDITOR.htmlParser.basicWriter();
CKEDITOR.htmlParser.fragment.prototype.writeChildrenHtml.call( element, writer, filter );
element.children = new CKEDITOR.htmlParser.fragment.fromHtml( writer.getHtml(), 0, element.clone() ).children;
isChildrenFiltered = 1;
}
};
if ( filter )
{
while ( true )
{
if ( !( writeName = filter.onElementName( writeName ) ) )
return;
element.name = writeName;
if ( !( element = filter.onElement( element ) ) )
return;
element.parent = this.parent;
if ( element.name == writeName )
break;
// If the element has been replaced with something of a
// different type, then make the replacement write itself.
if ( element.type != CKEDITOR.NODE_ELEMENT )
{
element.writeHtml( writer, filter );
return;
}
writeName = element.name;
// This indicate that the element has been dropped by
// filter but not the children.
if ( !writeName )
{
// Fix broken parent refs.
for ( var c = 0, length = this.children.length ; c < length ; c++ )
this.children[ c ].parent = element.parent;
this.writeChildrenHtml.call( element, writer, isChildrenFiltered ? null : filter );
return;
}
}
// The element may have been changed, so update the local
// references.
attributes = element.attributes;
}
// Open element tag.
writer.openTag( writeName, attributes );
// Copy all attributes to an array.
var attribsArray = [];
// Iterate over the attributes twice since filters may alter
// other attributes.
for ( var i = 0 ; i < 2; i++ )
{
for ( a in attributes )
{
newAttrName = a;
value = attributes[ a ];
if ( i == 1 )
attribsArray.push( [ a, value ] );
else if ( filter )
{
while ( true )
{
if ( !( newAttrName = filter.onAttributeName( a ) ) )
{
delete attributes[ a ];
break;
}
else if ( newAttrName != a )
{
delete attributes[ a ];
a = newAttrName;
continue;
}
else
break;
}
if ( newAttrName )
{
if ( ( value = filter.onAttribute( element, newAttrName, value ) ) === false )
delete attributes[ newAttrName ];
else
attributes [ newAttrName ] = value;
}
}
}
}
// Sort the attributes by name.
if ( writer.sortAttributes )
attribsArray.sort( sortAttribs );
// Send the attributes.
var len = attribsArray.length;
for ( i = 0 ; i < len ; i++ )
{
var attrib = attribsArray[ i ];
writer.attribute( attrib[0], attrib[1] );
}
// Close the tag.
writer.openTagClose( writeName, element.isEmpty );
if ( !element.isEmpty )
{
this.writeChildrenHtml.call( element, writer, isChildrenFiltered ? null : filter );
// Close the element.
writer.closeTag( writeName );
}
},
writeChildrenHtml : function( writer, filter )
{
// Send children.
CKEDITOR.htmlParser.fragment.prototype.writeChildrenHtml.apply( this, arguments );
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the "virtual" {@link CKEDITOR.commandDefinition} class,
* which contains the defintion of a command. This file is for
* documentation purposes only.
*/
/**
* (Virtual Class) Do not call this constructor. This class is not really part
* of the API.
* @name CKEDITOR.commandDefinition
* @class Virtual class that illustrates the features of command objects to be
* passed to the {@link CKEDITOR.editor.prototype.addCommand} function.
* @example
*/
/**
* The function to be fired when the commend is executed.
* @name CKEDITOR.commandDefinition.prototype.exec
* @function
* @param {CKEDITOR.editor} editor The editor within which run the command.
* @param {Object} [data] Additional data to be used to execute the command.
* @returns {Boolean} Whether the command has been successfully executed.
* Defaults to "true", if nothing is returned.
* @example
* editorInstance.addCommand( 'sample',
* {
* exec : function( editor )
* {
* alert( 'Executing a command for the editor name "' + editor.name + '"!' );
* }
* });
*/
/**
* Whether the command need to be hooked into the redo/undo system.
* @name CKEDITOR.commandDefinition.prototype.canUndo
* @type {Boolean}
* @default true
* @field
* @example
* editorInstance.addCommand( 'alertName',
* {
* exec : function( editor )
* {
* alert( editor.name );
* },
* canUndo : false // No support for undo/redo
* });
*/
/**
* Whether the command is asynchronous, which means that the
* {@link CKEDITOR.editor#event:afterCommandExec} event will be fired by the
* command itself manually, and that the return value of this command is not to
* be returned by the {@link CKEDITOR.command#exec} function.
* @name CKEDITOR.commandDefinition.prototype.async
* @default false
* @type {Boolean}
* @example
* editorInstance.addCommand( 'loadOptions',
* {
* exec : function( editor )
* {
* // Asynchronous operation below.
* CKEDITOR.ajax.loadXml( 'data.xml', function()
* {
* editor.fire( 'afterCommandExec' );
* ));
* },
* async : true // The command need some time to complete after exec function returns.
* });
*/
/**
* Whether the command should give focus to the editor before execution.
* @name CKEDITOR.commandDefinition.prototype.editorFocus
* @type {Boolean}
* @default true
* @see CKEDITOR.command#editorFocus
* @example
* editorInstance.addCommand( 'maximize',
* {
* exec : function( editor )
* {
* // ...
* },
* editorFocus : false // The command doesn't require focusing the editing document.
* });
*/
/**
* Whether the command state should be set to {@link CKEDITOR.TRISTATE_DISABLED} on startup.
* @name CKEDITOR.commandDefinition.prototype.startDisabled
* @type {Boolean}
* @default false
* @example
* editorInstance.addCommand( 'unlink',
* {
* exec : function( editor )
* {
* // ...
* },
* startDisabled : true // Command is unavailable until selection is inside a link.
* });
*/
/**
* The editor modes within which the command can be executed. The execution
* will have no action if the current mode is not listed in this property.
* @name CKEDITOR.commandDefinition.prototype.modes
* @type Object
* @default { wysiwyg : 1 }
* @see CKEDITOR.command#modes
* @example
* editorInstance.addCommand( 'link',
* {
* exec : function( editor )
* {
* // ...
* },
* modes : { wysiwyg : 1 } // Command is available in wysiwyg mode only.
* });
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* Creates a {@link CKEDITOR.htmlParser} class instance.
* @class Provides an "event like" system to parse strings of HTML data.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagOpen = function( tagName, attributes, selfClosing )
* {
* alert( tagName );
* };
* parser.parse( '<p>Some <b>text</b>.</p>' );
*/
CKEDITOR.htmlParser = function()
{
this._ =
{
htmlPartsRegex : new RegExp( '<(?:(?:\\/([^>]+)>)|(?:!--([\\S|\\s]*?)-->)|(?:([^\\s>]+)\\s*((?:(?:"[^"]*")|(?:\'[^\']*\')|[^"\'>])*)\\/?>))', 'g' )
};
};
(function()
{
var attribsRegex = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g,
emptyAttribs = {checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1};
CKEDITOR.htmlParser.prototype =
{
/**
* Function to be fired when a tag opener is found. This function
* should be overriden when using this class.
* @param {String} tagName The tag name. The name is guarantted to be
* lowercased.
* @param {Object} attributes An object containing all tag attributes. Each
* property in this object represent and attribute name and its
* value is the attribute value.
* @param {Boolean} selfClosing true if the tag closes itself, false if the
* tag doesn't.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagOpen = function( tagName, attributes, selfClosing )
* {
* alert( tagName ); // e.g. "b"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onTagOpen : function() {},
/**
* Function to be fired when a tag closer is found. This function
* should be overriden when using this class.
* @param {String} tagName The tag name. The name is guarantted to be
* lowercased.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagClose = function( tagName )
* {
* alert( tagName ); // e.g. "b"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onTagClose : function() {},
/**
* Function to be fired when text is found. This function
* should be overriden when using this class.
* @param {String} text The text found.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onText = function( text )
* {
* alert( text ); // e.g. "Hello"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onText : function() {},
/**
* Function to be fired when CDATA section is found. This function
* should be overriden when using this class.
* @param {String} cdata The CDATA been found.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onCDATA = function( cdata )
* {
* alert( cdata ); // e.g. "var hello;"
* });
* parser.parse( "<script>var hello;</script>" );
*/
onCDATA : function() {},
/**
* Function to be fired when a commend is found. This function
* should be overriden when using this class.
* @param {String} comment The comment text.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onComment = function( comment )
* {
* alert( comment ); // e.g. " Example "
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onComment : function() {},
/**
* Parses text, looking for HTML tokens, like tag openers or closers,
* or comments. This function fires the onTagOpen, onTagClose, onText
* and onComment function during its execution.
* @param {String} html The HTML to be parsed.
* @example
* var parser = new CKEDITOR.htmlParser();
* // The onTagOpen, onTagClose, onText and onComment should be overriden
* // at this point.
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
parse : function( html )
{
var parts,
tagName,
nextIndex = 0,
cdata; // The collected data inside a CDATA section.
while ( ( parts = this._.htmlPartsRegex.exec( html ) ) )
{
var tagIndex = parts.index;
if ( tagIndex > nextIndex )
{
var text = html.substring( nextIndex, tagIndex );
if ( cdata )
cdata.push( text );
else
this.onText( text );
}
nextIndex = this._.htmlPartsRegex.lastIndex;
/*
"parts" is an array with the following items:
0 : The entire match for opening/closing tags and comments.
1 : Group filled with the tag name for closing tags.
2 : Group filled with the comment text.
3 : Group filled with the tag name for opening tags.
4 : Group filled with the attributes part of opening tags.
*/
// Closing tag
if ( ( tagName = parts[ 1 ] ) )
{
tagName = tagName.toLowerCase();
if ( cdata && CKEDITOR.dtd.$cdata[ tagName ] )
{
// Send the CDATA data.
this.onCDATA( cdata.join('') );
cdata = null;
}
if ( !cdata )
{
this.onTagClose( tagName );
continue;
}
}
// If CDATA is enabled, just save the raw match.
if ( cdata )
{
cdata.push( parts[ 0 ] );
continue;
}
// Opening tag
if ( ( tagName = parts[ 3 ] ) )
{
tagName = tagName.toLowerCase();
// There are some tag names that can break things, so let's
// simply ignore them when parsing. (#5224)
if ( /="/.test( tagName ) )
continue;
var attribs = {},
attribMatch,
attribsPart = parts[ 4 ],
selfClosing = !!( attribsPart && attribsPart.charAt( attribsPart.length - 1 ) == '/' );
if ( attribsPart )
{
while ( ( attribMatch = attribsRegex.exec( attribsPart ) ) )
{
var attName = attribMatch[1].toLowerCase(),
attValue = attribMatch[2] || attribMatch[3] || attribMatch[4] || '';
if ( !attValue && emptyAttribs[ attName ] )
attribs[ attName ] = attName;
else
attribs[ attName ] = attValue;
}
}
this.onTagOpen( tagName, attribs, selfClosing );
// Open CDATA mode when finding the appropriate tags.
if ( !cdata && CKEDITOR.dtd.$cdata[ tagName ] )
cdata = [];
continue;
}
// Comment
if ( ( tagName = parts[ 2 ] ) )
this.onComment( tagName );
}
if ( html.length > nextIndex )
this.onText( html.substring( nextIndex, html.length ) );
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.ajax} object, which holds ajax methods for
* data loading.
*/
/**
* Ajax methods for data loading.
* @namespace
* @example
*/
CKEDITOR.ajax = (function()
{
var createXMLHttpRequest = function()
{
// In IE, using the native XMLHttpRequest for local files may throw
// "Access is Denied" errors.
if ( !CKEDITOR.env.ie || location.protocol != 'file:' )
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject( 'Msxml2.XMLHTTP' ); } catch (e) {}
try { return new ActiveXObject( 'Microsoft.XMLHTTP' ); } catch (e) {}
return null;
};
var checkStatus = function( xhr )
{
// HTTP Status Codes:
// 2xx : Success
// 304 : Not Modified
// 0 : Returned when running locally (file://)
// 1223 : IE may change 204 to 1223 (see http://dev.jquery.com/ticket/1450)
return ( xhr.readyState == 4 &&
( ( xhr.status >= 200 && xhr.status < 300 ) ||
xhr.status == 304 ||
xhr.status === 0 ||
xhr.status == 1223 ) );
};
var getResponseText = function( xhr )
{
if ( checkStatus( xhr ) )
return xhr.responseText;
return null;
};
var getResponseXml = function( xhr )
{
if ( checkStatus( xhr ) )
{
var xml = xhr.responseXML;
return new CKEDITOR.xml( xml && xml.firstChild ? xml : xhr.responseText );
}
return null;
};
var load = function( url, callback, getResponseFn )
{
var async = !!callback;
var xhr = createXMLHttpRequest();
if ( !xhr )
return null;
xhr.open( 'GET', url, async );
if ( async )
{
// TODO: perform leak checks on this closure.
/** @ignore */
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
callback( getResponseFn( xhr ) );
xhr = null;
}
};
}
xhr.send(null);
return async ? '' : getResponseFn( xhr );
};
return /** @lends CKEDITOR.ajax */ {
/**
* Loads data from an URL as plain text.
* @param {String} url The URL from which load data.
* @param {Function} [callback] A callback function to be called on
* data load. If not provided, the data will be loaded
* asynchronously, passing the data value the function on load.
* @returns {String} The loaded data. For asynchronous requests, an
* empty string. For invalid requests, null.
* @example
* // Load data synchronously.
* var data = CKEDITOR.ajax.load( 'somedata.txt' );
* alert( data );
* @example
* // Load data asynchronously.
* var data = CKEDITOR.ajax.load( 'somedata.txt', function( data )
* {
* alert( data );
* } );
*/
load : function( url, callback )
{
return load( url, callback, getResponseText );
},
/**
* Loads data from an URL as XML.
* @param {String} url The URL from which load data.
* @param {Function} [callback] A callback function to be called on
* data load. If not provided, the data will be loaded
* asynchronously, passing the data value the function on load.
* @returns {CKEDITOR.xml} An XML object holding the loaded data. For asynchronous requests, an
* empty string. For invalid requests, null.
* @example
* // Load XML synchronously.
* var xml = CKEDITOR.ajax.loadXml( 'somedata.xml' );
* alert( xml.getInnerXml( '//' ) );
* @example
* // Load XML asynchronously.
* var data = CKEDITOR.ajax.loadXml( 'somedata.xml', function( xml )
* {
* alert( xml.getInnerXml( '//' ) );
* } );
*/
loadXml : function( url, callback )
{
return load( url, callback, getResponseXml );
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var loadedLangs = {};
/**
* @namespace Holds language related functions.
*/
CKEDITOR.lang =
{
/**
* The list of languages available in the editor core.
* @type Object
* @example
* alert( CKEDITOR.lang.en ); // "true"
*/
languages :
{
'af' : 1,
'ar' : 1,
'bg' : 1,
'bn' : 1,
'bs' : 1,
'ca' : 1,
'cs' : 1,
'cy' : 1,
'da' : 1,
'de' : 1,
'el' : 1,
'en-au' : 1,
'en-ca' : 1,
'en-gb' : 1,
'en' : 1,
'eo' : 1,
'es' : 1,
'et' : 1,
'eu' : 1,
'fa' : 1,
'fi' : 1,
'fo' : 1,
'fr-ca' : 1,
'fr' : 1,
'gl' : 1,
'gu' : 1,
'he' : 1,
'hi' : 1,
'hr' : 1,
'hu' : 1,
'is' : 1,
'it' : 1,
'ja' : 1,
'ka' : 1,
'km' : 1,
'ko' : 1,
'ku' : 1,
'lt' : 1,
'lv' : 1,
'mn' : 1,
'ms' : 1,
'nb' : 1,
'nl' : 1,
'no' : 1,
'pl' : 1,
'pt-br' : 1,
'pt' : 1,
'ro' : 1,
'ru' : 1,
'sk' : 1,
'sl' : 1,
'sr-latn' : 1,
'sr' : 1,
'sv' : 1,
'th' : 1,
'tr' : 1,
'ug' : 1,
'uk' : 1,
'vi' : 1,
'zh-cn' : 1,
'zh' : 1
},
/**
* Loads a specific language file, or auto detect it. A callback is
* then called when the file gets loaded.
* @param {String} languageCode The code of the language file to be
* loaded. If null or empty, autodetection will be performed. The
* same happens if the language is not supported.
* @param {String} defaultLanguage The language to be used if
* languageCode is not supported or if the autodetection fails.
* @param {Function} callback A function to be called once the
* language file is loaded. Two parameters are passed to this
* function: the language code and the loaded language entries.
* @example
*/
load : function( languageCode, defaultLanguage, callback )
{
// If no languageCode - fallback to browser or default.
// If languageCode - fallback to no-localized version or default.
if ( !languageCode || !CKEDITOR.lang.languages[ languageCode ] )
languageCode = this.detect( defaultLanguage, languageCode );
if ( !this[ languageCode ] )
{
CKEDITOR.scriptLoader.load( CKEDITOR.getUrl(
'_source/' + // @Packager.RemoveLine
'lang/' + languageCode + '.js' ),
function()
{
callback( languageCode, this[ languageCode ] );
}
, this );
}
else
callback( languageCode, this[ languageCode ] );
},
/**
* Returns the language that best fit the user language. For example,
* suppose that the user language is "pt-br". If this language is
* supported by the editor, it is returned. Otherwise, if only "pt" is
* supported, it is returned instead. If none of the previous are
* supported, a default language is then returned.
* @param {String} defaultLanguage The default language to be returned
* if the user language is not supported.
* @param {String} [probeLanguage] A language code to try to use,
* instead of the browser based autodetection.
* @returns {String} The detected language code.
* @example
* alert( CKEDITOR.lang.detect( 'en' ) ); // e.g., in a German browser: "de"
*/
detect : function( defaultLanguage, probeLanguage )
{
var languages = this.languages;
probeLanguage = probeLanguage || navigator.userLanguage || navigator.language || defaultLanguage;
var parts = probeLanguage
.toLowerCase()
.match( /([a-z]+)(?:-([a-z]+))?/ ),
lang = parts[1],
locale = parts[2];
if ( languages[ lang + '-' + locale ] )
lang = lang + '-' + locale;
else if ( !languages[ lang ] )
lang = null;
CKEDITOR.lang.detect = lang ?
function() { return lang; } :
function( defaultLanguage ) { return defaultLanguage; };
return lang || defaultLanguage;
}
};
})();
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview API initialization code.
*/
(function()
{
// Disable HC detaction in WebKit. (#5429)
if ( CKEDITOR.env.webkit )
{
CKEDITOR.env.hc = false;
return;
}
// Check whether high contrast is active by creating a colored border.
var hcDetect = CKEDITOR.dom.element.createFromHtml(
'<div style="width:0px;height:0px;position:absolute;left:-10000px;' +
'border: 1px solid;border-color: red blue;"></div>', CKEDITOR.document );
hcDetect.appendTo( CKEDITOR.document.getHead() );
// Update CKEDITOR.env.
// Catch exception needed sometimes for FF. (#4230)
try
{
CKEDITOR.env.hc = hcDetect.getComputedStyle( 'border-top-color' ) == hcDetect.getComputedStyle( 'border-right-color' );
}
catch (e)
{
CKEDITOR.env.hc = false;
}
if ( CKEDITOR.env.hc )
CKEDITOR.env.cssClass += ' cke_hc';
hcDetect.remove();
})();
// Load core plugins.
CKEDITOR.plugins.load( CKEDITOR.config.corePlugins.split( ',' ), function()
{
CKEDITOR.status = 'loaded';
CKEDITOR.fire( 'loaded' );
// Process all instances created by the "basic" implementation.
var pending = CKEDITOR._.pending;
if ( pending )
{
delete CKEDITOR._.pending;
for ( var i = 0 ; i < pending.length ; i++ )
CKEDITOR.add( pending[ i ] );
}
});
// Needed for IE6 to not request image (HTTP 200 or 304) for every CSS background. (#6187)
if ( CKEDITOR.env.ie )
{
// Remove IE mouse flickering on IE6 because of background images.
try
{
document.execCommand( 'BackgroundImageCache', false, true );
}
catch (e)
{
// We have been reported about loading problems caused by the above
// line. For safety, let's just ignore errors.
}
}
/**
* Indicates that CKEditor is running on a High Contrast environment.
* @name CKEDITOR.env.hc
* @example
* if ( CKEDITOR.env.hc )
* alert( 'You're running on High Contrast mode. The editor interface will get adapted to provide you a better experience.' );
*/
/**
* Fired when a CKEDITOR core object is fully loaded and ready for interaction.
* @name CKEDITOR#loaded
* @event
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.comment} class, which represents
* a DOM comment node.
*/
/**
* Represents a DOM comment node.
* @constructor
* @augments CKEDITOR.dom.node
* @param {Object|String} comment A native DOM comment node or a string containing
* the text to use to create a new comment node.
* @param {CKEDITOR.dom.document} [ownerDocument] The document that will contain
* the node in case of new node creation. Defaults to the current document.
* @example
* var nativeNode = document.createComment( 'Example' );
* var comment = CKEDITOR.dom.comment( nativeNode );
* @example
* var comment = CKEDITOR.dom.comment( 'Example' );
*/
CKEDITOR.dom.comment = function( comment, ownerDocument )
{
if ( typeof comment == 'string' )
comment = ( ownerDocument ? ownerDocument.$ : document ).createComment( comment );
CKEDITOR.dom.domObject.call( this, comment );
};
CKEDITOR.dom.comment.prototype = new CKEDITOR.dom.node();
CKEDITOR.tools.extend( CKEDITOR.dom.comment.prototype,
/** @lends CKEDITOR.dom.comment.prototype */
{
type : CKEDITOR.NODE_COMMENT,
getOuterHtml : function()
{
return '<!--' + this.$.nodeValue + '-->';
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.editor} class, which is the base
* for other classes representing DOM objects.
*/
/**
* Represents a DOM object. This class is not intended to be used directly. It
* serves as the base class for other classes representing specific DOM
* objects.
* @constructor
* @param {Object} nativeDomObject A native DOM object.
* @augments CKEDITOR.event
* @example
*/
CKEDITOR.dom.domObject = function( nativeDomObject )
{
if ( nativeDomObject )
{
/**
* The native DOM object represented by this class instance.
* @type Object
* @example
* var element = new CKEDITOR.dom.element( 'span' );
* alert( element.$.nodeType ); // "1"
*/
this.$ = nativeDomObject;
}
};
CKEDITOR.dom.domObject.prototype = (function()
{
// Do not define other local variables here. We want to keep the native
// listener closures as clean as possible.
var getNativeListener = function( domObject, eventName )
{
return function( domEvent )
{
// In FF, when reloading the page with the editor focused, it may
// throw an error because the CKEDITOR global is not anymore
// available. So, we check it here first. (#2923)
if ( typeof CKEDITOR != 'undefined' )
domObject.fire( eventName, new CKEDITOR.dom.event( domEvent ) );
};
};
return /** @lends CKEDITOR.dom.domObject.prototype */ {
getPrivate : function()
{
var priv;
// Get the main private function from the custom data. Create it if not
// defined.
if ( !( priv = this.getCustomData( '_' ) ) )
this.setCustomData( '_', ( priv = {} ) );
return priv;
},
/** @ignore */
on : function( eventName )
{
// We customize the "on" function here. The basic idea is that we'll have
// only one listener for a native event, which will then call all listeners
// set to the event.
// Get the listeners holder object.
var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
if ( !nativeListeners )
{
nativeListeners = {};
this.setCustomData( '_cke_nativeListeners', nativeListeners );
}
// Check if we have a listener for that event.
if ( !nativeListeners[ eventName ] )
{
var listener = nativeListeners[ eventName ] = getNativeListener( this, eventName );
if ( this.$.addEventListener )
this.$.addEventListener( eventName, listener, !!CKEDITOR.event.useCapture );
else if ( this.$.attachEvent )
this.$.attachEvent( 'on' + eventName, listener );
}
// Call the original implementation.
return CKEDITOR.event.prototype.on.apply( this, arguments );
},
/** @ignore */
removeListener : function( eventName )
{
// Call the original implementation.
CKEDITOR.event.prototype.removeListener.apply( this, arguments );
// If we don't have listeners for this event, clean the DOM up.
if ( !this.hasListeners( eventName ) )
{
var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
var listener = nativeListeners && nativeListeners[ eventName ];
if ( listener )
{
if ( this.$.removeEventListener )
this.$.removeEventListener( eventName, listener, false );
else if ( this.$.detachEvent )
this.$.detachEvent( 'on' + eventName, listener );
delete nativeListeners[ eventName ];
}
}
},
/**
* Removes any listener set on this object.
* To avoid memory leaks we must assure that there are no
* references left after the object is no longer needed.
*/
removeAllListeners : function()
{
var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
for ( var eventName in nativeListeners )
{
var listener = nativeListeners[ eventName ];
if ( this.$.detachEvent )
this.$.detachEvent( 'on' + eventName, listener );
else if ( this.$.removeEventListener )
this.$.removeEventListener( eventName, listener, false );
delete nativeListeners[ eventName ];
}
}
};
})();
(function( domObjectProto )
{
var customData = {};
CKEDITOR.on( 'reset', function()
{
customData = {};
});
/**
* Determines whether the specified object is equal to the current object.
* @name CKEDITOR.dom.domObject.prototype.equals
* @function
* @param {Object} object The object to compare with the current object.
* @returns {Boolean} "true" if the object is equal.
* @example
* var doc = new CKEDITOR.dom.document( document );
* alert( doc.equals( CKEDITOR.document ) ); // "true"
* alert( doc == CKEDITOR.document ); // "false"
*/
domObjectProto.equals = function( object )
{
return ( object && object.$ === this.$ );
};
/**
* Sets a data slot value for this object. These values are shared by all
* instances pointing to that same DOM object.
* <strong>Note:</strong> The created data slot is only guarantied to be available on this unique dom node,
* thus any wish to continue access it from other element clones (either created by clone node or from innerHtml)
* will fail, for such usage, please use {@link CKEDITOR.dom.element::setAttribute} instead.
* @name CKEDITOR.dom.domObject.prototype.setCustomData
* @function
* @param {String} key A key used to identify the data slot.
* @param {Object} value The value to set to the data slot.
* @returns {CKEDITOR.dom.domObject} This DOM object instance.
* @see CKEDITOR.dom.domObject.prototype.getCustomData
* @example
* var element = new CKEDITOR.dom.element( 'span' );
* element.setCustomData( 'hasCustomData', true );
*/
domObjectProto.setCustomData = function( key, value )
{
var expandoNumber = this.getUniqueId(),
dataSlot = customData[ expandoNumber ] || ( customData[ expandoNumber ] = {} );
dataSlot[ key ] = value;
return this;
};
/**
* Gets the value set to a data slot in this object.
* @name CKEDITOR.dom.domObject.prototype.getCustomData
* @function
* @param {String} key The key used to identify the data slot.
* @returns {Object} This value set to the data slot.
* @see CKEDITOR.dom.domObject.prototype.setCustomData
* @example
* var element = new CKEDITOR.dom.element( 'span' );
* alert( element.getCustomData( 'hasCustomData' ) ); // e.g. 'true'
*/
domObjectProto.getCustomData = function( key )
{
var expandoNumber = this.$[ 'data-cke-expando' ],
dataSlot = expandoNumber && customData[ expandoNumber ];
return dataSlot && dataSlot[ key ];
};
/**
* @name CKEDITOR.dom.domObject.prototype.removeCustomData
*/
domObjectProto.removeCustomData = function( key )
{
var expandoNumber = this.$[ 'data-cke-expando' ],
dataSlot = expandoNumber && customData[ expandoNumber ],
retval = dataSlot && dataSlot[ key ];
if ( typeof retval != 'undefined' )
delete dataSlot[ key ];
return retval || null;
};
/**
* Removes any data stored on this object.
* To avoid memory leaks we must assure that there are no
* references left after the object is no longer needed.
* @name CKEDITOR.dom.domObject.prototype.clearCustomData
* @function
*/
domObjectProto.clearCustomData = function()
{
// Clear all event listeners
this.removeAllListeners();
var expandoNumber = this.$[ 'data-cke-expando' ];
expandoNumber && delete customData[ expandoNumber ];
};
/**
* Gets an ID that can be used to identiquely identify this DOM object in
* the running session.
* @name CKEDITOR.dom.domObject.prototype.getUniqueId
* @function
* @returns {Number} A unique ID.
*/
domObjectProto.getUniqueId = function()
{
return this.$[ 'data-cke-expando' ] || ( this.$[ 'data-cke-expando' ] = CKEDITOR.tools.getNextNumber() );
};
// Implement CKEDITOR.event.
CKEDITOR.event.implementOn( domObjectProto );
})( CKEDITOR.dom.domObject.prototype );
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.node} class which is the base
* class for classes that represent DOM nodes.
*/
/**
* Base class for classes representing DOM nodes. This constructor may return
* an instance of a class that inherits from this class, like
* {@link CKEDITOR.dom.element} or {@link CKEDITOR.dom.text}.
* @augments CKEDITOR.dom.domObject
* @param {Object} domNode A native DOM node.
* @constructor
* @see CKEDITOR.dom.element
* @see CKEDITOR.dom.text
* @example
*/
CKEDITOR.dom.node = function( domNode )
{
if ( domNode )
{
var type = domNode.nodeType == CKEDITOR.NODE_DOCUMENT ? 'document'
: domNode.nodeType == CKEDITOR.NODE_ELEMENT ? 'element'
: domNode.nodeType == CKEDITOR.NODE_TEXT ? 'text'
: domNode.nodeType == CKEDITOR.NODE_COMMENT ? 'comment'
: 'domObject'; // Call the base constructor otherwise.
return new CKEDITOR.dom[ type ]( domNode );
}
return this;
};
CKEDITOR.dom.node.prototype = new CKEDITOR.dom.domObject();
/**
* Element node type.
* @constant
* @example
*/
CKEDITOR.NODE_ELEMENT = 1;
/**
* Document node type.
* @constant
* @example
*/
CKEDITOR.NODE_DOCUMENT = 9;
/**
* Text node type.
* @constant
* @example
*/
CKEDITOR.NODE_TEXT = 3;
/**
* Comment node type.
* @constant
* @example
*/
CKEDITOR.NODE_COMMENT = 8;
CKEDITOR.NODE_DOCUMENT_FRAGMENT = 11;
CKEDITOR.POSITION_IDENTICAL = 0;
CKEDITOR.POSITION_DISCONNECTED = 1;
CKEDITOR.POSITION_FOLLOWING = 2;
CKEDITOR.POSITION_PRECEDING = 4;
CKEDITOR.POSITION_IS_CONTAINED = 8;
CKEDITOR.POSITION_CONTAINS = 16;
CKEDITOR.tools.extend( CKEDITOR.dom.node.prototype,
/** @lends CKEDITOR.dom.node.prototype */
{
/**
* Makes this node a child of another element.
* @param {CKEDITOR.dom.element} element The target element to which
* this node will be appended.
* @returns {CKEDITOR.dom.element} The target element.
* @example
* var p = new CKEDITOR.dom.element( 'p' );
* var strong = new CKEDITOR.dom.element( 'strong' );
* strong.appendTo( p );
*
* // result: "<p><strong></strong></p>"
*/
appendTo : function( element, toStart )
{
element.append( this, toStart );
return element;
},
clone : function( includeChildren, cloneId )
{
var $clone = this.$.cloneNode( includeChildren );
var removeIds = function( node )
{
if ( node.nodeType != CKEDITOR.NODE_ELEMENT )
return;
if ( !cloneId )
node.removeAttribute( 'id', false );
node[ 'data-cke-expando' ] = undefined;
if ( includeChildren )
{
var childs = node.childNodes;
for ( var i=0; i < childs.length; i++ )
removeIds( childs[ i ] );
}
};
// The "id" attribute should never be cloned to avoid duplication.
removeIds( $clone );
return new CKEDITOR.dom.node( $clone );
},
hasPrevious : function()
{
return !!this.$.previousSibling;
},
hasNext : function()
{
return !!this.$.nextSibling;
},
/**
* Inserts this element after a node.
* @param {CKEDITOR.dom.node} node The node that will precede this element.
* @returns {CKEDITOR.dom.node} The node preceding this one after
* insertion.
* @example
* var em = new CKEDITOR.dom.element( 'em' );
* var strong = new CKEDITOR.dom.element( 'strong' );
* strong.insertAfter( em );
*
* // result: "<em></em><strong></strong>"
*/
insertAfter : function( node )
{
node.$.parentNode.insertBefore( this.$, node.$.nextSibling );
return node;
},
/**
* Inserts this element before a node.
* @param {CKEDITOR.dom.node} node The node that will succeed this element.
* @returns {CKEDITOR.dom.node} The node being inserted.
* @example
* var em = new CKEDITOR.dom.element( 'em' );
* var strong = new CKEDITOR.dom.element( 'strong' );
* strong.insertBefore( em );
*
* // result: "<strong></strong><em></em>"
*/
insertBefore : function( node )
{
node.$.parentNode.insertBefore( this.$, node.$ );
return node;
},
insertBeforeMe : function( node )
{
this.$.parentNode.insertBefore( node.$, this.$ );
return node;
},
/**
* Retrieves a uniquely identifiable tree address for this node.
* The tree address returned is an array of integers, with each integer
* indicating a child index of a DOM node, starting from
* <code>document.documentElement</code>.
*
* For example, assuming <code><body></code> is the second child
* of <code><html></code> (<code><head></code> being the first),
* and we would like to address the third child under the
* fourth child of <code><body></code>, the tree address returned would be:
* [1, 3, 2]
*
* The tree address cannot be used for finding back the DOM tree node once
* the DOM tree structure has been modified.
*/
getAddress : function( normalized )
{
var address = [];
var $documentElement = this.getDocument().$.documentElement;
var node = this.$;
while ( node && node != $documentElement )
{
var parentNode = node.parentNode;
if ( parentNode )
{
// Get the node index. For performance, call getIndex
// directly, instead of creating a new node object.
address.unshift( this.getIndex.call( { $ : node }, normalized ) );
}
node = parentNode;
}
return address;
},
/**
* Gets the document containing this element.
* @returns {CKEDITOR.dom.document} The document.
* @example
* var element = CKEDITOR.document.getById( 'example' );
* alert( <strong>element.getDocument().equals( CKEDITOR.document )</strong> ); // "true"
*/
getDocument : function()
{
return new CKEDITOR.dom.document( this.$.ownerDocument || this.$.parentNode.ownerDocument );
},
getIndex : function( normalized )
{
// Attention: getAddress depends on this.$
var current = this.$,
index = 0;
while ( ( current = current.previousSibling ) )
{
// When normalizing, do not count it if this is an
// empty text node or if it's a text node following another one.
if ( normalized && current.nodeType == 3 &&
( !current.nodeValue.length ||
( current.previousSibling && current.previousSibling.nodeType == 3 ) ) )
{
continue;
}
index++;
}
return index;
},
getNextSourceNode : function( startFromSibling, nodeType, guard )
{
// If "guard" is a node, transform it in a function.
if ( guard && !guard.call )
{
var guardNode = guard;
guard = function( node )
{
return !node.equals( guardNode );
};
}
var node = ( !startFromSibling && this.getFirst && this.getFirst() ),
parent;
// Guarding when we're skipping the current element( no children or 'startFromSibling' ).
// send the 'moving out' signal even we don't actually dive into.
if ( !node )
{
if ( this.type == CKEDITOR.NODE_ELEMENT && guard && guard( this, true ) === false )
return null;
node = this.getNext();
}
while ( !node && ( parent = ( parent || this ).getParent() ) )
{
// The guard check sends the "true" paramenter to indicate that
// we are moving "out" of the element.
if ( guard && guard( parent, true ) === false )
return null;
node = parent.getNext();
}
if ( !node )
return null;
if ( guard && guard( node ) === false )
return null;
if ( nodeType && nodeType != node.type )
return node.getNextSourceNode( false, nodeType, guard );
return node;
},
getPreviousSourceNode : function( startFromSibling, nodeType, guard )
{
if ( guard && !guard.call )
{
var guardNode = guard;
guard = function( node )
{
return !node.equals( guardNode );
};
}
var node = ( !startFromSibling && this.getLast && this.getLast() ),
parent;
// Guarding when we're skipping the current element( no children or 'startFromSibling' ).
// send the 'moving out' signal even we don't actually dive into.
if ( !node )
{
if ( this.type == CKEDITOR.NODE_ELEMENT && guard && guard( this, true ) === false )
return null;
node = this.getPrevious();
}
while ( !node && ( parent = ( parent || this ).getParent() ) )
{
// The guard check sends the "true" paramenter to indicate that
// we are moving "out" of the element.
if ( guard && guard( parent, true ) === false )
return null;
node = parent.getPrevious();
}
if ( !node )
return null;
if ( guard && guard( node ) === false )
return null;
if ( nodeType && node.type != nodeType )
return node.getPreviousSourceNode( false, nodeType, guard );
return node;
},
getPrevious : function( evaluator )
{
var previous = this.$, retval;
do
{
previous = previous.previousSibling;
// Avoid returning the doc type node.
// http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-412266927
retval = previous && previous.nodeType != 10 && new CKEDITOR.dom.node( previous );
}
while ( retval && evaluator && !evaluator( retval ) )
return retval;
},
/**
* Gets the node that follows this element in its parent's child list.
* @param {Function} evaluator Filtering the result node.
* @returns {CKEDITOR.dom.node} The next node or null if not available.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div><b>Example</b> <i>next</i></div>' );
* var first = <strong>element.getFirst().getNext()</strong>;
* alert( first.getName() ); // "i"
*/
getNext : function( evaluator )
{
var next = this.$, retval;
do
{
next = next.nextSibling;
retval = next && new CKEDITOR.dom.node( next );
}
while ( retval && evaluator && !evaluator( retval ) )
return retval;
},
/**
* Gets the parent element for this node.
* @returns {CKEDITOR.dom.element} The parent element.
* @example
* var node = editor.document.getBody().getFirst();
* var parent = node.<strong>getParent()</strong>;
* alert( node.getName() ); // "body"
*/
getParent : function()
{
var parent = this.$.parentNode;
return ( parent && parent.nodeType == 1 ) ? new CKEDITOR.dom.node( parent ) : null;
},
getParents : function( closerFirst )
{
var node = this;
var parents = [];
do
{
parents[ closerFirst ? 'push' : 'unshift' ]( node );
}
while ( ( node = node.getParent() ) )
return parents;
},
getCommonAncestor : function( node )
{
if ( node.equals( this ) )
return this;
if ( node.contains && node.contains( this ) )
return node;
var start = this.contains ? this : this.getParent();
do
{
if ( start.contains( node ) )
return start;
}
while ( ( start = start.getParent() ) );
return null;
},
getPosition : function( otherNode )
{
var $ = this.$;
var $other = otherNode.$;
if ( $.compareDocumentPosition )
return $.compareDocumentPosition( $other );
// IE and Safari have no support for compareDocumentPosition.
if ( $ == $other )
return CKEDITOR.POSITION_IDENTICAL;
// Only element nodes support contains and sourceIndex.
if ( this.type == CKEDITOR.NODE_ELEMENT && otherNode.type == CKEDITOR.NODE_ELEMENT )
{
if ( $.contains )
{
if ( $.contains( $other ) )
return CKEDITOR.POSITION_CONTAINS + CKEDITOR.POSITION_PRECEDING;
if ( $other.contains( $ ) )
return CKEDITOR.POSITION_IS_CONTAINED + CKEDITOR.POSITION_FOLLOWING;
}
if ( 'sourceIndex' in $ )
{
return ( $.sourceIndex < 0 || $other.sourceIndex < 0 ) ? CKEDITOR.POSITION_DISCONNECTED :
( $.sourceIndex < $other.sourceIndex ) ? CKEDITOR.POSITION_PRECEDING :
CKEDITOR.POSITION_FOLLOWING;
}
}
// For nodes that don't support compareDocumentPosition, contains
// or sourceIndex, their "address" is compared.
var addressOfThis = this.getAddress(),
addressOfOther = otherNode.getAddress(),
minLevel = Math.min( addressOfThis.length, addressOfOther.length );
// Determinate preceed/follow relationship.
for ( var i = 0 ; i <= minLevel - 1 ; i++ )
{
if ( addressOfThis[ i ] != addressOfOther[ i ] )
{
if ( i < minLevel )
{
return addressOfThis[ i ] < addressOfOther[ i ] ?
CKEDITOR.POSITION_PRECEDING : CKEDITOR.POSITION_FOLLOWING;
}
break;
}
}
// Determinate contains/contained relationship.
return ( addressOfThis.length < addressOfOther.length ) ?
CKEDITOR.POSITION_CONTAINS + CKEDITOR.POSITION_PRECEDING :
CKEDITOR.POSITION_IS_CONTAINED + CKEDITOR.POSITION_FOLLOWING;
},
/**
* Gets the closest ancestor node of this node, specified by its name.
* @param {String} reference The name of the ancestor node to search or
* an object with the node names to search for.
* @param {Boolean} [includeSelf] Whether to include the current
* node in the search.
* @returns {CKEDITOR.dom.node} The located ancestor node or null if not found.
* @since 3.6.1
* @example
* // Suppose we have the following HTML structure:
* // <div id="outer"><div id="inner"><p><b>Some text</b></p></div></div>
* // If node == <b>
* ascendant = node.getAscendant( 'div' ); // ascendant == <div id="inner">
* ascendant = node.getAscendant( 'b' ); // ascendant == null
* ascendant = node.getAscendant( 'b', true ); // ascendant == <b>
* ascendant = node.getAscendant( { div: 1, p: 1} ); // Searches for the first 'div' or 'p': ascendant == <div id="inner">
*/
getAscendant : function( reference, includeSelf )
{
var $ = this.$,
name;
if ( !includeSelf )
$ = $.parentNode;
while ( $ )
{
if ( $.nodeName && ( name = $.nodeName.toLowerCase(), ( typeof reference == 'string' ? name == reference : name in reference ) ) )
return new CKEDITOR.dom.node( $ );
$ = $.parentNode;
}
return null;
},
hasAscendant : function( name, includeSelf )
{
var $ = this.$;
if ( !includeSelf )
$ = $.parentNode;
while ( $ )
{
if ( $.nodeName && $.nodeName.toLowerCase() == name )
return true;
$ = $.parentNode;
}
return false;
},
move : function( target, toStart )
{
target.append( this.remove(), toStart );
},
/**
* Removes this node from the document DOM.
* @param {Boolean} [preserveChildren] Indicates that the children
* elements must remain in the document, removing only the outer
* tags.
* @example
* var element = CKEDITOR.dom.element.getById( 'MyElement' );
* <strong>element.remove()</strong>;
*/
remove : function( preserveChildren )
{
var $ = this.$;
var parent = $.parentNode;
if ( parent )
{
if ( preserveChildren )
{
// Move all children before the node.
for ( var child ; ( child = $.firstChild ) ; )
{
parent.insertBefore( $.removeChild( child ), $ );
}
}
parent.removeChild( $ );
}
return this;
},
replace : function( nodeToReplace )
{
this.insertBefore( nodeToReplace );
nodeToReplace.remove();
},
trim : function()
{
this.ltrim();
this.rtrim();
},
ltrim : function()
{
var child;
while ( this.getFirst && ( child = this.getFirst() ) )
{
if ( child.type == CKEDITOR.NODE_TEXT )
{
var trimmed = CKEDITOR.tools.ltrim( child.getText() ),
originalLength = child.getLength();
if ( !trimmed )
{
child.remove();
continue;
}
else if ( trimmed.length < originalLength )
{
child.split( originalLength - trimmed.length );
// IE BUG: child.remove() may raise JavaScript errors here. (#81)
this.$.removeChild( this.$.firstChild );
}
}
break;
}
},
rtrim : function()
{
var child;
while ( this.getLast && ( child = this.getLast() ) )
{
if ( child.type == CKEDITOR.NODE_TEXT )
{
var trimmed = CKEDITOR.tools.rtrim( child.getText() ),
originalLength = child.getLength();
if ( !trimmed )
{
child.remove();
continue;
}
else if ( trimmed.length < originalLength )
{
child.split( trimmed.length );
// IE BUG: child.getNext().remove() may raise JavaScript errors here.
// (#81)
this.$.lastChild.parentNode.removeChild( this.$.lastChild );
}
}
break;
}
if ( !CKEDITOR.env.ie && !CKEDITOR.env.opera )
{
child = this.$.lastChild;
if ( child && child.type == 1 && child.nodeName.toLowerCase() == 'br' )
{
// Use "eChildNode.parentNode" instead of "node" to avoid IE bug (#324).
child.parentNode.removeChild( child ) ;
}
}
},
/**
* Checks if this node is read-only (should not be changed).
* @returns {Boolean}
* @since 3.5
* @example
* // For the following HTML:
* // <div contenteditable="false">Some <b>text</b></div>
*
* // If "ele" is the above <div>
* ele.isReadOnly(); // true
*/
isReadOnly : function()
{
var element = this;
if ( this.type != CKEDITOR.NODE_ELEMENT )
element = this.getParent();
if ( element && typeof element.$.isContentEditable != 'undefined' )
return ! ( element.$.isContentEditable || element.data( 'cke-editable' ) );
else
{
// Degrade for old browsers which don't support "isContentEditable", e.g. FF3
var current = element;
while( current )
{
if ( current.is( 'body' ) || !!current.data( 'cke-editable' ) )
break;
if ( current.getAttribute( 'contentEditable' ) == 'false' )
return true;
else if ( current.getAttribute( 'contentEditable' ) == 'true' )
break;
current = current.getParent();
}
return false;
}
}
}
);
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @class DocumentFragment is a "lightweight" or "minimal" Document object. It is
* commonly used to extract a portion of a document's tree or to create a new
* fragment of a document. Various operations may take DocumentFragment objects
* as arguments and results in all the child nodes of the DocumentFragment being
* moved to the child list of this node.
* @param {Object} ownerDocument
*/
CKEDITOR.dom.documentFragment = function( ownerDocument )
{
ownerDocument = ownerDocument || CKEDITOR.document;
this.$ = ownerDocument.$.createDocumentFragment();
};
CKEDITOR.tools.extend( CKEDITOR.dom.documentFragment.prototype,
CKEDITOR.dom.element.prototype,
{
type : CKEDITOR.NODE_DOCUMENT_FRAGMENT,
insertAfterNode : function( node )
{
node = node.$;
node.parentNode.insertBefore( this.$, node.nextSibling );
}
},
true,
{
'append' : 1,
'appendBogus' : 1,
'getFirst' : 1,
'getLast' : 1,
'appendTo' : 1,
'moveChildren' : 1,
'insertBefore' : 1,
'insertAfterNode' : 1,
'replace' : 1,
'trim' : 1,
'type' : 1,
'ltrim' : 1,
'rtrim' : 1,
'getDocument' : 1,
'getChildCount' : 1,
'getChild' : 1,
'getChildren' : 1
} );
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.text} class, which represents
* a DOM text node.
*/
/**
* Represents a DOM text node.
* @constructor
* @augments CKEDITOR.dom.node
* @param {Object|String} text A native DOM text node or a string containing
* the text to use to create a new text node.
* @param {CKEDITOR.dom.document} [ownerDocument] The document that will contain
* the node in case of new node creation. Defaults to the current document.
* @example
* var nativeNode = document.createTextNode( 'Example' );
* var text = CKEDITOR.dom.text( nativeNode );
* @example
* var text = CKEDITOR.dom.text( 'Example' );
*/
CKEDITOR.dom.text = function( text, ownerDocument )
{
if ( typeof text == 'string' )
text = ( ownerDocument ? ownerDocument.$ : document ).createTextNode( text );
// Theoretically, we should call the base constructor here
// (not CKEDITOR.dom.node though). But, IE doesn't support expando
// properties on text node, so the features provided by domObject will not
// work for text nodes (which is not a big issue for us).
//
// CKEDITOR.dom.domObject.call( this, element );
/**
* The native DOM text node represented by this class instance.
* @type Object
* @example
* var element = new CKEDITOR.dom.text( 'Example' );
* alert( element.$.nodeType ); // "3"
*/
this.$ = text;
};
CKEDITOR.dom.text.prototype = new CKEDITOR.dom.node();
CKEDITOR.tools.extend( CKEDITOR.dom.text.prototype,
/** @lends CKEDITOR.dom.text.prototype */
{
/**
* The node type. This is a constant value set to
* {@link CKEDITOR.NODE_TEXT}.
* @type Number
* @example
*/
type : CKEDITOR.NODE_TEXT,
getLength : function()
{
return this.$.nodeValue.length;
},
getText : function()
{
return this.$.nodeValue;
},
setText : function( text )
{
this.$.nodeValue = text;
},
/**
* Breaks this text node into two nodes at the specified offset,
* keeping both in the tree as siblings. This node then only contains
* all the content up to the offset point. A new text node, which is
* inserted as the next sibling of this node, contains all the content
* at and after the offset point. When the offset is equal to the
* length of this node, the new node has no data.
* @param {Number} The position at which to split, starting from zero.
* @returns {CKEDITOR.dom.text} The new text node.
*/
split : function( offset )
{
// If the offset is after the last char, IE creates the text node
// on split, but don't include it into the DOM. So, we have to do
// that manually here.
if ( CKEDITOR.env.ie && offset == this.getLength() )
{
var next = this.getDocument().createText( '' );
next.insertAfter( this );
return next;
}
var doc = this.getDocument();
var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc );
// IE BUG: IE8 does not update the childNodes array in DOM after splitText(),
// we need to make some DOM changes to make it update. (#3436)
if ( CKEDITOR.env.ie8 )
{
var workaround = new CKEDITOR.dom.text( '', doc );
workaround.insertAfter( retval );
workaround.remove();
}
return retval;
},
/**
* Extracts characters from indexA up to but not including indexB.
* @param {Number} indexA An integer between 0 and one less than the
* length of the text.
* @param {Number} [indexB] An integer between 0 and the length of the
* string. If omitted, extracts characters to the end of the text.
*/
substring : function( indexA, indexB )
{
// We need the following check due to a Firefox bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=458886
if ( typeof indexB != 'number' )
return this.$.nodeValue.substr( indexA );
else
return this.$.nodeValue.substring( indexA, indexB );
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* Creates a CKEDITOR.dom.range instance that can be used inside a specific
* DOM Document.
* @class Represents a delimited piece of content in a DOM Document.
* It is contiguous in the sense that it can be characterized as selecting all
* of the content between a pair of boundary-points.<br>
* <br>
* This class shares much of the W3C
* <a href="http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html">Document Object Model Range</a>
* ideas and features, adding several range manipulation tools to it, but it's
* not intended to be compatible with it.
* @param {CKEDITOR.dom.document} document The document into which the range
* features will be available.
* @example
* // Create a range for the entire contents of the editor document body.
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* // Delete the contents.
* range.deleteContents();
*/
CKEDITOR.dom.range = function( document )
{
/**
* Node within which the range begins.
* @type {CKEDITOR.NODE_ELEMENT|CKEDITOR.NODE_TEXT}
* @example
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.startContainer.getName() ); // "body"
*/
this.startContainer = null;
/**
* Offset within the starting node of the range.
* @type {Number}
* @example
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.startOffset ); // "0"
*/
this.startOffset = null;
/**
* Node within which the range ends.
* @type {CKEDITOR.NODE_ELEMENT|CKEDITOR.NODE_TEXT}
* @example
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.endContainer.getName() ); // "body"
*/
this.endContainer = null;
/**
* Offset within the ending node of the range.
* @type {Number}
* @example
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.endOffset ); // == editor.document.getBody().getChildCount()
*/
this.endOffset = null;
/**
* Indicates that this is a collapsed range. A collapsed range has it's
* start and end boudaries at the very same point so nothing is contained
* in it.
* @example
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.collapsed ); // "false"
* range.collapse();
* alert( range.collapsed ); // "true"
*/
this.collapsed = true;
/**
* The document within which the range can be used.
* @type {CKEDITOR.dom.document}
* @example
* // Selects the body contents of the range document.
* range.selectNodeContents( range.document.getBody() );
*/
this.document = document;
};
(function()
{
// Updates the "collapsed" property for the given range object.
var updateCollapsed = function( range )
{
range.collapsed = (
range.startContainer &&
range.endContainer &&
range.startContainer.equals( range.endContainer ) &&
range.startOffset == range.endOffset );
};
// This is a shared function used to delete, extract and clone the range
// contents.
// V2
var execContentsAction = function( range, action, docFrag, mergeThen )
{
range.optimizeBookmark();
var startNode = range.startContainer;
var endNode = range.endContainer;
var startOffset = range.startOffset;
var endOffset = range.endOffset;
var removeStartNode;
var removeEndNode;
// 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.type == CKEDITOR.NODE_TEXT )
endNode = endNode.split( endOffset );
else
{
// If the end container has children and the offset is pointing
// to a child, then we should start from it.
if ( endNode.getChildCount() > 0 )
{
// If the offset points after the last node.
if ( endOffset >= endNode.getChildCount() )
{
// Let's create a temporary node and mark it for removal.
endNode = endNode.append( range.document.createText( '' ) );
removeEndNode = true;
}
else
endNode = endNode.getChild( endOffset );
}
}
// For text containers, we must simply split the node. The removal will
// be handled by the rest of the code .
if ( startNode.type == CKEDITOR.NODE_TEXT )
{
startNode.split( 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.equals( endNode ) )
endNode = startNode.getNext();
}
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 )
{
// Let's create a temporary node and mark it for removal.
startNode = startNode.getFirst().insertBeforeMe( range.document.createText( '' ) );
removeStartNode = true;
}
else if ( startOffset >= startNode.getChildCount() )
{
// Let's create a temporary node and mark it for removal.
startNode = startNode.append( range.document.createText( '' ) );
removeStartNode = true;
}
else
startNode = startNode.getChild( startOffset ).getPrevious();
}
// Get the parent nodes tree for the start and end boundaries.
var startParents = startNode.getParents();
var endParents = endNode.getParents();
// 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.equals( topEnd ) )
break;
}
var clone = docFrag, levelStartNode, levelClone, currentNode, currentSibling;
// 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.equals( startNode ) ) // action = 0 = Delete
levelClone = clone.append( levelStartNode.clone() );
currentNode = levelStartNode.getNext();
while ( currentNode )
{
// Stop processing when the current node matches a node in the
// endParents tree or if it is the endNode.
if ( currentNode.equals( endParents[ j ] ) || currentNode.equals( endNode ) )
break;
// Cache the next sibling.
currentSibling = currentNode.getNext();
// If cloning, just clone it.
if ( action == 2 ) // 2 = Clone
clone.append( currentNode.clone( true ) );
else
{
// Both Delete and Extract will remove the node.
currentNode.remove();
// When Extracting, move the removed node to the docFrag.
if ( action == 1 ) // 1 = Extract
clone.append( currentNode );
}
currentNode = currentSibling;
}
if ( clone )
clone = levelClone;
}
clone = docFrag;
// 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.equals( endNode ) ) // action = 0 = Delete
levelClone = clone.append( levelStartNode.clone() );
// The processing of siblings may have already been done by the parent.
if ( !startParents[ k ] || levelStartNode.$.parentNode != startParents[ k ].$.parentNode )
{
currentNode = levelStartNode.getPrevious();
while ( currentNode )
{
// Stop processing when the current node matches a node in the
// startParents tree or if it is the startNode.
if ( currentNode.equals( startParents[ k ] ) || currentNode.equals( startNode ) )
break;
// Cache the next sibling.
currentSibling = currentNode.getPrevious();
// 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.remove();
// 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 = range.startContainer;
if ( startTextNode.type == CKEDITOR.NODE_TEXT )
{
startTextNode.$.data += startTextNode.$.nextSibling.data;
startTextNode.$.parentNode.removeChild( startTextNode.$.nextSibling );
}
var endTextNode = range.endContainer;
if ( endTextNode.type == CKEDITOR.NODE_TEXT && 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 = topEnd.getIndex();
// If the start node is to be removed, we must correct the
// index to reflect the removal.
if ( removeStartNode && topEnd.$.parentNode == startNode.$.parentNode )
endIndex--;
// Merge splitted parents.
if ( mergeThen && topStart.type == CKEDITOR.NODE_ELEMENT )
{
var span = CKEDITOR.dom.element.createFromHtml( '<span ' +
'data-cke-bookmark="1" style="display:none"> </span>', range.document );
span.insertAfter( topStart );
topStart.mergeSiblings( false );
range.moveToBookmark( { startNode : span } );
}
else
range.setStart( topEnd.getParent(), endIndex );
}
// Collapse it to the start.
range.collapse( true );
}
// Cleanup any marked node.
if ( removeStartNode )
startNode.remove();
if ( removeEndNode && endNode.$.parentNode )
endNode.remove();
};
var inlineChildReqElements = { abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 };
// Creates the appropriate node evaluator for the dom walker used inside
// check(Start|End)OfBlock.
function getCheckStartEndBlockEvalFunction()
{
var skipBogus = false,
whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmarkEvaluator = CKEDITOR.dom.walker.bookmark( true ),
isBogus = CKEDITOR.dom.walker.bogus();
return function( node )
{
// First skip empty nodes.
if ( bookmarkEvaluator( node ) || whitespaces( node ) )
return true;
// Skip the bogus node at the end of block.
if ( isBogus( node ) &&
!skipBogus )
{
skipBogus = true;
return true;
}
// If there's any visible text, then we're not at the start.
if ( node.type == CKEDITOR.NODE_TEXT &&
( node.hasAscendant( 'pre' ) ||
CKEDITOR.tools.trim( node.getText() ).length ) )
return false;
// If there are non-empty inline elements (e.g. <img />), then we're not
// at the start.
if ( node.type == CKEDITOR.NODE_ELEMENT && !inlineChildReqElements[ node.getName() ] )
return false;
return true;
};
}
var isBogus = CKEDITOR.dom.walker.bogus();
// Evaluator for CKEDITOR.dom.element::checkBoundaryOfElement, reject any
// text node and non-empty elements unless it's being bookmark text.
function elementBoundaryEval( checkStart )
{
var whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmark = CKEDITOR.dom.walker.bookmark( 1 );
return function( node )
{
// First skip empty nodes.
if ( bookmark( node ) || whitespaces( node ) )
return true;
// Tolerant bogus br when checking at the end of block.
// Reject any text node unless it's being bookmark
// OR it's spaces.
// Reject any element unless it's being invisible empty. (#3883)
return !checkStart && isBogus( node ) ||
node.type == CKEDITOR.NODE_ELEMENT &&
node.getName() in CKEDITOR.dtd.$removeEmpty;
};
}
var whitespaceEval = new CKEDITOR.dom.walker.whitespaces(),
bookmarkEval = new CKEDITOR.dom.walker.bookmark(),
nbspRegExp = /^[\t\r\n ]*(?: |\xa0)$/;
function nonWhitespaceOrBookmarkEval( node )
{
// Whitespaces and bookmark nodes are to be ignored.
return !whitespaceEval( node ) && !bookmarkEval( node );
}
CKEDITOR.dom.range.prototype =
{
clone : function()
{
var clone = new CKEDITOR.dom.range( this.document );
clone.startContainer = this.startContainer;
clone.startOffset = this.startOffset;
clone.endContainer = this.endContainer;
clone.endOffset = this.endOffset;
clone.collapsed = this.collapsed;
return clone;
},
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;
},
/**
* The content nodes of the range are cloned and added to a document fragment, which is returned.
* <strong> Note: </strong> Text selection may lost after invoking this method. (caused by text node splitting).
*/
cloneContents : function()
{
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
if ( !this.collapsed )
execContentsAction( this, 2, docFrag );
return docFrag;
},
/**
* Deletes the content nodes of the range permanently from the DOM tree.
* @param {Boolean} [mergeThen] Merge any splitted elements result in DOM true due to partial selection.
*/
deleteContents : function( mergeThen )
{
if ( this.collapsed )
return;
execContentsAction( this, 0, null, mergeThen );
},
/**
* The content nodes of the range are cloned and added to a document fragment,
* meanwhile they're removed permanently from the DOM tree.
* @param {Boolean} [mergeThen] Merge any splitted elements result in DOM true due to partial selection.
*/
extractContents : function( mergeThen )
{
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
if ( !this.collapsed )
execContentsAction( this, 1, docFrag, mergeThen );
return docFrag;
},
/**
* Creates a bookmark object, which can be later used to restore the
* range by using the moveToBookmark function.
* 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.
* @param {Boolean} [serializable] Indicates that the bookmark nodes
* must contain ids, which can be used to restore the range even
* when these nodes suffer mutations (like a clonation or innerHTML
* change).
* @returns {Object} And object representing a bookmark.
*/
createBookmark : function( serializable )
{
var startNode, endNode;
var baseId;
var clone;
var collapsed = this.collapsed;
startNode = this.document.createElement( 'span' );
startNode.data( 'cke-bookmark', 1 );
startNode.setStyle( 'display', 'none' );
// For IE, it must have something inside, otherwise it may be
// removed during DOM operations.
startNode.setHtml( ' ' );
if ( serializable )
{
baseId = 'cke_bm_' + CKEDITOR.tools.getNextNumber();
startNode.setAttribute( 'id', baseId + ( collapsed ? 'C' : 'S' ) );
}
// If collapsed, the endNode will not be created.
if ( !collapsed )
{
endNode = startNode.clone();
endNode.setHtml( ' ' );
if ( serializable )
endNode.setAttribute( 'id', baseId + 'E' );
clone = this.clone();
clone.collapse();
clone.insertNode( endNode );
}
clone = this.clone();
clone.collapse( true );
clone.insertNode( startNode );
// Update the range position.
if ( endNode )
{
this.setStartAfter( startNode );
this.setEndBefore( endNode );
}
else
this.moveToPosition( startNode, CKEDITOR.POSITION_AFTER_END );
return {
startNode : serializable ? baseId + ( collapsed ? 'C' : 'S' ) : startNode,
endNode : serializable ? baseId + 'E' : endNode,
serializable : serializable,
collapsed : collapsed
};
},
/**
* Creates a "non intrusive" and "mutation sensible" bookmark. This
* kind of bookmark should be used only when the DOM is supposed to
* remain stable after its creation.
* @param {Boolean} [normalized] Indicates that the bookmark must
* normalized. When normalized, the successive text nodes are
* considered a single node. To sucessful load a normalized
* bookmark, the DOM tree must be also normalized before calling
* moveToBookmark.
* @returns {Object} An object representing the bookmark.
*/
createBookmark2 : function( normalized )
{
var startContainer = this.startContainer,
endContainer = this.endContainer;
var startOffset = this.startOffset,
endOffset = this.endOffset;
var collapsed = this.collapsed;
var child, previous;
// 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 ( !startContainer || !endContainer )
return { start : 0, end : 0 };
if ( normalized )
{
// Find out if the start is pointing to a text node that will
// be normalized.
if ( startContainer.type == CKEDITOR.NODE_ELEMENT )
{
child = startContainer.getChild( startOffset );
// In this case, move the start information to that text
// node.
if ( child && child.type == CKEDITOR.NODE_TEXT
&& startOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT )
{
startContainer = child;
startOffset = 0;
}
// Get the normalized offset.
if ( child && child.type == CKEDITOR.NODE_ELEMENT )
startOffset = child.getIndex( 1 );
}
// Normalize the start.
while ( startContainer.type == CKEDITOR.NODE_TEXT
&& ( previous = startContainer.getPrevious() )
&& previous.type == CKEDITOR.NODE_TEXT )
{
startContainer = previous;
startOffset += previous.getLength();
}
// Process the end only if not normalized.
if ( !collapsed )
{
// Find out if the start is pointing to a text node that
// will be normalized.
if ( endContainer.type == CKEDITOR.NODE_ELEMENT )
{
child = endContainer.getChild( endOffset );
// In this case, move the start information to that
// text node.
if ( child && child.type == CKEDITOR.NODE_TEXT
&& endOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT )
{
endContainer = child;
endOffset = 0;
}
// Get the normalized offset.
if ( child && child.type == CKEDITOR.NODE_ELEMENT )
endOffset = child.getIndex( 1 );
}
// Normalize the end.
while ( endContainer.type == CKEDITOR.NODE_TEXT
&& ( previous = endContainer.getPrevious() )
&& previous.type == CKEDITOR.NODE_TEXT )
{
endContainer = previous;
endOffset += previous.getLength();
}
}
}
return {
start : startContainer.getAddress( normalized ),
end : collapsed ? null : endContainer.getAddress( normalized ),
startOffset : startOffset,
endOffset : endOffset,
normalized : normalized,
collapsed : collapsed,
is2 : true // It's a createBookmark2 bookmark.
};
},
moveToBookmark : function( bookmark )
{
if ( bookmark.is2 ) // Created with createBookmark2().
{
// Get the start information.
var startContainer = this.document.getByAddress( bookmark.start, bookmark.normalized ),
startOffset = bookmark.startOffset;
// Get the end information.
var endContainer = bookmark.end && this.document.getByAddress( bookmark.end, bookmark.normalized ),
endOffset = bookmark.endOffset;
// Set the start boundary.
this.setStart( startContainer, startOffset );
// Set the end boundary. If not available, collapse it.
if ( endContainer )
this.setEnd( endContainer, endOffset );
else
this.collapse( true );
}
else // Created with createBookmark().
{
var serializable = bookmark.serializable,
startNode = serializable ? this.document.getById( bookmark.startNode ) : bookmark.startNode,
endNode = serializable ? this.document.getById( bookmark.endNode ) : bookmark.endNode;
// Set the range start at the bookmark start node position.
this.setStartBefore( startNode );
// Remove it, because it may interfere in the setEndBefore call.
startNode.remove();
// Set the range end at the bookmark end node position, or simply
// collapse it if it is not available.
if ( endNode )
{
this.setEndBefore( endNode );
endNode.remove();
}
else
this.collapse( true );
}
},
getBoundaryNodes : function()
{
var startNode = this.startContainer,
endNode = this.endContainer,
startOffset = this.startOffset,
endOffset = this.endOffset,
childCount;
if ( startNode.type == CKEDITOR.NODE_ELEMENT )
{
childCount = startNode.getChildCount();
if ( childCount > startOffset )
startNode = startNode.getChild( startOffset );
else if ( childCount < 1 )
startNode = startNode.getPreviousSourceNode();
else // startOffset > childCount but childCount is not 0
{
// Try to take the node just after the current position.
startNode = startNode.$;
while ( startNode.lastChild )
startNode = startNode.lastChild;
startNode = new CKEDITOR.dom.node( startNode );
// Normally we should take the next node in DFS order. But it
// is also possible that we've already reached the end of
// document.
startNode = startNode.getNextSourceNode() || startNode;
}
}
if ( endNode.type == CKEDITOR.NODE_ELEMENT )
{
childCount = endNode.getChildCount();
if ( childCount > endOffset )
endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true );
else if ( childCount < 1 )
endNode = endNode.getPreviousSourceNode();
else // endOffset > childCount but childCount is not 0
{
// Try to take the node just before the current position.
endNode = endNode.$;
while ( endNode.lastChild )
endNode = endNode.lastChild;
endNode = new CKEDITOR.dom.node( endNode );
}
}
// Sometimes the endNode will come right before startNode for collapsed
// ranges. Fix it. (#3780)
if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING )
startNode = endNode;
return { startNode : startNode, endNode : endNode };
},
/**
* Find the node which fully contains the range.
* @param includeSelf
* @param {Boolean} ignoreTextNode Whether ignore CKEDITOR.NODE_TEXT type.
*/
getCommonAncestor : function( includeSelf , ignoreTextNode )
{
var start = this.startContainer,
end = this.endContainer,
ancestor;
if ( start.equals( end ) )
{
if ( includeSelf
&& start.type == CKEDITOR.NODE_ELEMENT
&& this.startOffset == this.endOffset - 1 )
ancestor = start.getChild( this.startOffset );
else
ancestor = start;
}
else
ancestor = start.getCommonAncestor( end );
return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor;
},
/**
* Transforms the startContainer and endContainer properties from text
* nodes to element nodes, whenever possible. This is actually possible
* if either of the boundary containers point to a text node, and its
* offset is set to zero, or after the last char in the node.
*/
optimize : function()
{
var container = this.startContainer;
var offset = this.startOffset;
if ( container.type != CKEDITOR.NODE_ELEMENT )
{
if ( !offset )
this.setStartBefore( container );
else if ( offset >= container.getLength() )
this.setStartAfter( container );
}
container = this.endContainer;
offset = this.endOffset;
if ( container.type != CKEDITOR.NODE_ELEMENT )
{
if ( !offset )
this.setEndBefore( container );
else if ( offset >= container.getLength() )
this.setEndAfter( container );
}
},
/**
* Move the range out of bookmark nodes if they'd been the container.
*/
optimizeBookmark: function()
{
var startNode = this.startContainer,
endNode = this.endContainer;
if ( startNode.is && startNode.is( 'span' )
&& startNode.data( 'cke-bookmark' ) )
this.setStartAt( startNode, CKEDITOR.POSITION_BEFORE_START );
if ( endNode && endNode.is && endNode.is( 'span' )
&& endNode.data( 'cke-bookmark' ) )
this.setEndAt( endNode, CKEDITOR.POSITION_AFTER_END );
},
trim : function( ignoreStart, ignoreEnd )
{
var startContainer = this.startContainer,
startOffset = this.startOffset,
collapsed = this.collapsed;
if ( ( !ignoreStart || collapsed )
&& startContainer && startContainer.type == CKEDITOR.NODE_TEXT )
{
// If the offset is zero, we just insert the new node before
// the start.
if ( !startOffset )
{
startOffset = startContainer.getIndex();
startContainer = startContainer.getParent();
}
// If the offset is at the end, we'll insert it after the text
// node.
else if ( startOffset >= startContainer.getLength() )
{
startOffset = startContainer.getIndex() + 1;
startContainer = startContainer.getParent();
}
// In other case, we split the text node and insert the new
// node at the split point.
else
{
var nextText = startContainer.split( startOffset );
startOffset = startContainer.getIndex() + 1;
startContainer = startContainer.getParent();
// Check all necessity of updating the end boundary.
if ( this.startContainer.equals( this.endContainer ) )
this.setEnd( nextText, this.endOffset - this.startOffset );
else if ( startContainer.equals( this.endContainer ) )
this.endOffset += 1;
}
this.setStart( startContainer, startOffset );
if ( collapsed )
{
this.collapse( true );
return;
}
}
var endContainer = this.endContainer;
var endOffset = this.endOffset;
if ( !( ignoreEnd || collapsed )
&& endContainer && endContainer.type == CKEDITOR.NODE_TEXT )
{
// If the offset is zero, we just insert the new node before
// the start.
if ( !endOffset )
{
endOffset = endContainer.getIndex();
endContainer = endContainer.getParent();
}
// If the offset is at the end, we'll insert it after the text
// node.
else if ( endOffset >= endContainer.getLength() )
{
endOffset = endContainer.getIndex() + 1;
endContainer = endContainer.getParent();
}
// In other case, we split the text node and insert the new
// node at the split point.
else
{
endContainer.split( endOffset );
endOffset = endContainer.getIndex() + 1;
endContainer = endContainer.getParent();
}
this.setEnd( endContainer, endOffset );
}
},
/**
* Expands the range so that partial units are completely contained.
* @param unit {Number} The unit type to expand with.
* @param {Boolean} [excludeBrs=false] Whether include line-breaks when expanding.
*/
enlarge : function( unit, excludeBrs )
{
switch ( unit )
{
case CKEDITOR.ENLARGE_ELEMENT :
if ( this.collapsed )
return;
// Get the common ancestor.
var commonAncestor = this.getCommonAncestor();
var body = this.document.getBody();
// For each boundary
// a. Depending on its position, find out the first node to be checked (a sibling) or, if not available, to be enlarge.
// b. Go ahead checking siblings and enlarging the boundary as much as possible until the common ancestor is not reached. After reaching the common ancestor, just save the enlargeable node to be used later.
var startTop, endTop;
var enlargeable, sibling, commonReached;
// Indicates that the node can be added only if whitespace
// is available before it.
var needsWhiteSpace = false;
var isWhiteSpace;
var siblingText;
// Process the start boundary.
var container = this.startContainer;
var offset = this.startOffset;
if ( container.type == CKEDITOR.NODE_TEXT )
{
if ( offset )
{
// Check if there is any non-space text before the
// offset. Otherwise, container is null.
container = !CKEDITOR.tools.trim( container.substring( 0, offset ) ).length && container;
// If we found only whitespace in the node, it
// means that we'll need more whitespace to be able
// to expand. For example, <i> can be expanded in
// "A <i> [B]</i>", but not in "A<i> [B]</i>".
needsWhiteSpace = !!container;
}
if ( container )
{
if ( !( sibling = container.getPrevious() ) )
enlargeable = container.getParent();
}
}
else
{
// If we have offset, get the node preceeding it as the
// first sibling to be checked.
if ( offset )
sibling = container.getChild( offset - 1 ) || container.getLast();
// If there is no sibling, mark the container to be
// enlarged.
if ( !sibling )
enlargeable = container;
}
while ( enlargeable || sibling )
{
if ( enlargeable && !sibling )
{
// If we reached the common ancestor, mark the flag
// for it.
if ( !commonReached && enlargeable.equals( commonAncestor ) )
commonReached = true;
if ( !body.contains( enlargeable ) )
break;
// If we don't need space or this element breaks
// the line, then enlarge it.
if ( !needsWhiteSpace || enlargeable.getComputedStyle( 'display' ) != 'inline' )
{
needsWhiteSpace = false;
// If the common ancestor has been reached,
// we'll not enlarge it immediately, but just
// mark it to be enlarged later if the end
// boundary also enlarges it.
if ( commonReached )
startTop = enlargeable;
else
this.setStartBefore( enlargeable );
}
sibling = enlargeable.getPrevious();
}
// Check all sibling nodes preceeding the enlargeable
// node. The node wil lbe enlarged only if none of them
// blocks it.
while ( sibling )
{
// This flag indicates that this node has
// whitespaces at the end.
isWhiteSpace = false;
if ( sibling.type == CKEDITOR.NODE_COMMENT )
{
sibling = sibling.getPrevious();
continue;
}
else if ( sibling.type == CKEDITOR.NODE_TEXT )
{
siblingText = sibling.getText();
if ( /[^\s\ufeff]/.test( siblingText ) )
sibling = null;
isWhiteSpace = /[\s\ufeff]$/.test( siblingText );
}
else
{
// If this is a visible element.
// We need to check for the bookmark attribute because IE insists on
// rendering the display:none nodes we use for bookmarks. (#3363)
// Line-breaks (br) are rendered with zero width, which we don't want to include. (#7041)
if ( ( sibling.$.offsetWidth > 0 || excludeBrs && sibling.is( 'br' ) ) && !sibling.data( 'cke-bookmark' ) )
{
// We'll accept it only if we need
// whitespace, and this is an inline
// element with whitespace only.
if ( needsWhiteSpace && CKEDITOR.dtd.$removeEmpty[ sibling.getName() ] )
{
// It must contains spaces and inline elements only.
siblingText = sibling.getText();
if ( (/[^\s\ufeff]/).test( siblingText ) ) // Spaces + Zero Width No-Break Space (U+FEFF)
sibling = null;
else
{
var allChildren = sibling.$.getElementsByTagName( '*' );
for ( var i = 0, child ; child = allChildren[ i++ ] ; )
{
if ( !CKEDITOR.dtd.$removeEmpty[ child.nodeName.toLowerCase() ] )
{
sibling = null;
break;
}
}
}
if ( sibling )
isWhiteSpace = !!siblingText.length;
}
else
sibling = null;
}
}
// A node with whitespaces has been found.
if ( isWhiteSpace )
{
// Enlarge the last enlargeable node, if we
// were waiting for spaces.
if ( needsWhiteSpace )
{
if ( commonReached )
startTop = enlargeable;
else if ( enlargeable )
this.setStartBefore( enlargeable );
}
else
needsWhiteSpace = true;
}
if ( sibling )
{
var next = sibling.getPrevious();
if ( !enlargeable && !next )
{
// Set the sibling as enlargeable, so it's
// parent will be get later outside this while.
enlargeable = sibling;
sibling = null;
break;
}
sibling = next;
}
else
{
// If sibling has been set to null, then we
// need to stop enlarging.
enlargeable = null;
}
}
if ( enlargeable )
enlargeable = enlargeable.getParent();
}
// Process the end boundary. This is basically the same
// code used for the start boundary, with small changes to
// make it work in the oposite side (to the right). This
// makes it difficult to reuse the code here. So, fixes to
// the above code are likely to be replicated here.
container = this.endContainer;
offset = this.endOffset;
// Reset the common variables.
enlargeable = sibling = null;
commonReached = needsWhiteSpace = false;
if ( container.type == CKEDITOR.NODE_TEXT )
{
// Check if there is any non-space text after the
// offset. Otherwise, container is null.
container = !CKEDITOR.tools.trim( container.substring( offset ) ).length && container;
// If we found only whitespace in the node, it
// means that we'll need more whitespace to be able
// to expand. For example, <i> can be expanded in
// "A <i> [B]</i>", but not in "A<i> [B]</i>".
needsWhiteSpace = !( container && container.getLength() );
if ( container )
{
if ( !( sibling = container.getNext() ) )
enlargeable = container.getParent();
}
}
else
{
// Get the node right after the boudary to be checked
// first.
sibling = container.getChild( offset );
if ( !sibling )
enlargeable = container;
}
while ( enlargeable || sibling )
{
if ( enlargeable && !sibling )
{
if ( !commonReached && enlargeable.equals( commonAncestor ) )
commonReached = true;
if ( !body.contains( enlargeable ) )
break;
if ( !needsWhiteSpace || enlargeable.getComputedStyle( 'display' ) != 'inline' )
{
needsWhiteSpace = false;
if ( commonReached )
endTop = enlargeable;
else if ( enlargeable )
this.setEndAfter( enlargeable );
}
sibling = enlargeable.getNext();
}
while ( sibling )
{
isWhiteSpace = false;
if ( sibling.type == CKEDITOR.NODE_TEXT )
{
siblingText = sibling.getText();
if ( /[^\s\ufeff]/.test( siblingText ) )
sibling = null;
isWhiteSpace = /^[\s\ufeff]/.test( siblingText );
}
else if ( sibling.type == CKEDITOR.NODE_ELEMENT )
{
// If this is a visible element.
// We need to check for the bookmark attribute because IE insists on
// rendering the display:none nodes we use for bookmarks. (#3363)
// Line-breaks (br) are rendered with zero width, which we don't want to include. (#7041)
if ( ( sibling.$.offsetWidth > 0 || excludeBrs && sibling.is( 'br' ) ) && !sibling.data( 'cke-bookmark' ) )
{
// We'll accept it only if we need
// whitespace, and this is an inline
// element with whitespace only.
if ( needsWhiteSpace && CKEDITOR.dtd.$removeEmpty[ sibling.getName() ] )
{
// It must contains spaces and inline elements only.
siblingText = sibling.getText();
if ( (/[^\s\ufeff]/).test( siblingText ) )
sibling = null;
else
{
allChildren = sibling.$.getElementsByTagName( '*' );
for ( i = 0 ; child = allChildren[ i++ ] ; )
{
if ( !CKEDITOR.dtd.$removeEmpty[ child.nodeName.toLowerCase() ] )
{
sibling = null;
break;
}
}
}
if ( sibling )
isWhiteSpace = !!siblingText.length;
}
else
sibling = null;
}
}
else
isWhiteSpace = 1;
if ( isWhiteSpace )
{
if ( needsWhiteSpace )
{
if ( commonReached )
endTop = enlargeable;
else
this.setEndAfter( enlargeable );
}
}
if ( sibling )
{
next = sibling.getNext();
if ( !enlargeable && !next )
{
enlargeable = sibling;
sibling = null;
break;
}
sibling = next;
}
else
{
// If sibling has been set to null, then we
// need to stop enlarging.
enlargeable = null;
}
}
if ( enlargeable )
enlargeable = enlargeable.getParent();
}
// If the common ancestor can be enlarged by both boundaries, then include it also.
if ( startTop && endTop )
{
commonAncestor = startTop.contains( endTop ) ? endTop : startTop;
this.setStartBefore( commonAncestor );
this.setEndAfter( commonAncestor );
}
break;
case CKEDITOR.ENLARGE_BLOCK_CONTENTS:
case CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS:
// Enlarging the start boundary.
var walkerRange = new CKEDITOR.dom.range( this.document );
body = this.document.getBody();
walkerRange.setStartAt( body, CKEDITOR.POSITION_AFTER_START );
walkerRange.setEnd( this.startContainer, this.startOffset );
var walker = new CKEDITOR.dom.walker( walkerRange ),
blockBoundary, // The node on which the enlarging should stop.
tailBr, // In case BR as block boundary.
notBlockBoundary = CKEDITOR.dom.walker.blockBoundary(
( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS ) ? { br : 1 } : null ),
// Record the encountered 'blockBoundary' for later use.
boundaryGuard = function( node )
{
var retval = notBlockBoundary( node );
if ( !retval )
blockBoundary = node;
return retval;
},
// Record the encounted 'tailBr' for later use.
tailBrGuard = function( node )
{
var retval = boundaryGuard( node );
if ( !retval && node.is && node.is( 'br' ) )
tailBr = node;
return retval;
};
walker.guard = boundaryGuard;
enlargeable = walker.lastBackward();
// It's the body which stop the enlarging if no block boundary found.
blockBoundary = blockBoundary || body;
// Start the range either after the end of found block (<p>...</p>[text)
// or at the start of block (<p>[text...), by comparing the document position
// with 'enlargeable' node.
this.setStartAt(
blockBoundary,
!blockBoundary.is( 'br' ) &&
( !enlargeable && this.checkStartOfBlock()
|| enlargeable && blockBoundary.contains( enlargeable ) ) ?
CKEDITOR.POSITION_AFTER_START :
CKEDITOR.POSITION_AFTER_END );
// Avoid enlarging the range further when end boundary spans right after the BR. (#7490)
if ( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS )
{
var theRange = this.clone();
walker = new CKEDITOR.dom.walker( theRange );
var whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmark = CKEDITOR.dom.walker.bookmark();
walker.evaluator = function( node ) { return !whitespaces( node ) && !bookmark( node ); };
var previous = walker.previous();
if ( previous && previous.type == CKEDITOR.NODE_ELEMENT && previous.is( 'br' ) )
return;
}
// Enlarging the end boundary.
walkerRange = this.clone();
walkerRange.collapse();
walkerRange.setEndAt( body, CKEDITOR.POSITION_BEFORE_END );
walker = new CKEDITOR.dom.walker( walkerRange );
// tailBrGuard only used for on range end.
walker.guard = ( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS ) ?
tailBrGuard : boundaryGuard;
blockBoundary = null;
// End the range right before the block boundary node.
enlargeable = walker.lastForward();
// It's the body which stop the enlarging if no block boundary found.
blockBoundary = blockBoundary || body;
// Close the range either before the found block start (text]<p>...</p>) or at the block end (...text]</p>)
// by comparing the document position with 'enlargeable' node.
this.setEndAt(
blockBoundary,
( !enlargeable && this.checkEndOfBlock()
|| enlargeable && blockBoundary.contains( enlargeable ) ) ?
CKEDITOR.POSITION_BEFORE_END :
CKEDITOR.POSITION_BEFORE_START );
// We must include the <br> at the end of range if there's
// one and we're expanding list item contents
if ( tailBr )
this.setEndAfter( tailBr );
}
},
/**
* Descrease the range to make sure that boundaries
* always anchor beside text nodes or innermost element.
* @param {Number} mode ( CKEDITOR.SHRINK_ELEMENT | CKEDITOR.SHRINK_TEXT ) The shrinking mode.
* <dl>
* <dt>CKEDITOR.SHRINK_ELEMENT</dt>
* <dd>Shrink the range boundaries to the edge of the innermost element.</dd>
* <dt>CKEDITOR.SHRINK_TEXT</dt>
* <dd>Shrink the range boudaries to anchor by the side of enclosed text node, range remains if there's no text nodes on boundaries at all.</dd>
* </dl>
* @param {Boolean} selectContents Whether result range anchors at the inner OR outer boundary of the node.
*/
shrink : function( mode, selectContents )
{
// Unable to shrink a collapsed range.
if ( !this.collapsed )
{
mode = mode || CKEDITOR.SHRINK_TEXT;
var walkerRange = this.clone();
var startContainer = this.startContainer,
endContainer = this.endContainer,
startOffset = this.startOffset,
endOffset = this.endOffset,
collapsed = this.collapsed;
// Whether the start/end boundary is moveable.
var moveStart = 1,
moveEnd = 1;
if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT )
{
if ( !startOffset )
walkerRange.setStartBefore( startContainer );
else if ( startOffset >= startContainer.getLength( ) )
walkerRange.setStartAfter( startContainer );
else
{
// Enlarge the range properly to avoid walker making
// DOM changes caused by triming the text nodes later.
walkerRange.setStartBefore( startContainer );
moveStart = 0;
}
}
if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT )
{
if ( !endOffset )
walkerRange.setEndBefore( endContainer );
else if ( endOffset >= endContainer.getLength( ) )
walkerRange.setEndAfter( endContainer );
else
{
walkerRange.setEndAfter( endContainer );
moveEnd = 0;
}
}
var walker = new CKEDITOR.dom.walker( walkerRange ),
isBookmark = CKEDITOR.dom.walker.bookmark();
walker.evaluator = function( node )
{
return node.type == ( mode == CKEDITOR.SHRINK_ELEMENT ?
CKEDITOR.NODE_ELEMENT : CKEDITOR.NODE_TEXT );
};
var currentElement;
walker.guard = function( node, movingOut )
{
if ( isBookmark( node ) )
return true;
// Stop when we're shrink in element mode while encountering a text node.
if ( mode == CKEDITOR.SHRINK_ELEMENT && node.type == CKEDITOR.NODE_TEXT )
return false;
// Stop when we've already walked "through" an element.
if ( movingOut && node.equals( currentElement ) )
return false;
if ( !movingOut && node.type == CKEDITOR.NODE_ELEMENT )
currentElement = node;
return true;
};
if ( moveStart )
{
var textStart = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastForward' : 'next']();
textStart && this.setStartAt( textStart, selectContents ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_START );
}
if ( moveEnd )
{
walker.reset();
var textEnd = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastBackward' : 'previous']();
textEnd && this.setEndAt( textEnd, selectContents ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_AFTER_END );
}
return !!( moveStart || moveEnd );
}
},
/**
* Inserts a node at the start of the range. The range will be expanded
* the contain the node.
*/
insertNode : function( node )
{
this.optimizeBookmark();
this.trim( false, true );
var startContainer = this.startContainer;
var startOffset = this.startOffset;
var nextNode = startContainer.getChild( startOffset );
if ( nextNode )
node.insertBefore( nextNode );
else
startContainer.append( node );
// Check if we need to update the end boundary.
if ( node.getParent().equals( this.endContainer ) )
this.endOffset++;
// Expand the range to embrace the new node.
this.setStartBefore( node );
},
moveToPosition : function( node, position )
{
this.setStartAt( node, position );
this.collapse( true );
},
selectNodeContents : function( node )
{
this.setStart( node, 0 );
this.setEnd( node, node.type == CKEDITOR.NODE_TEXT ? node.getLength() : node.getChildCount() );
},
/**
* Sets the start position of a Range.
* @param {CKEDITOR.dom.node} startNode The node to start the range.
* @param {Number} startOffset An integer greater than or equal to zero
* representing the offset for the start of the range from the start
* of startNode.
*/
setStart : function( startNode, startOffset )
{
// 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.
// Fixing invalid range start inside dtd empty elements.
if( startNode.type == CKEDITOR.NODE_ELEMENT
&& CKEDITOR.dtd.$empty[ startNode.getName() ] )
startOffset = startNode.getIndex(), startNode = startNode.getParent();
this.startContainer = startNode;
this.startOffset = startOffset;
if ( !this.endContainer )
{
this.endContainer = startNode;
this.endOffset = startOffset;
}
updateCollapsed( this );
},
/**
* Sets the end position of a Range.
* @param {CKEDITOR.dom.node} endNode The node to end the range.
* @param {Number} endOffset An integer greater than or equal to zero
* representing the offset for the end of the range from the start
* of endNode.
*/
setEnd : function( endNode, endOffset )
{
// 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.
// Fixing invalid range end inside dtd empty elements.
if( endNode.type == CKEDITOR.NODE_ELEMENT
&& CKEDITOR.dtd.$empty[ endNode.getName() ] )
endOffset = endNode.getIndex() + 1, endNode = endNode.getParent();
this.endContainer = endNode;
this.endOffset = endOffset;
if ( !this.startContainer )
{
this.startContainer = endNode;
this.startOffset = endOffset;
}
updateCollapsed( this );
},
setStartAfter : function( node )
{
this.setStart( node.getParent(), node.getIndex() + 1 );
},
setStartBefore : function( node )
{
this.setStart( node.getParent(), node.getIndex() );
},
setEndAfter : function( node )
{
this.setEnd( node.getParent(), node.getIndex() + 1 );
},
setEndBefore : function( node )
{
this.setEnd( node.getParent(), node.getIndex() );
},
setStartAt : function( node, position )
{
switch( position )
{
case CKEDITOR.POSITION_AFTER_START :
this.setStart( node, 0 );
break;
case CKEDITOR.POSITION_BEFORE_END :
if ( node.type == CKEDITOR.NODE_TEXT )
this.setStart( node, node.getLength() );
else
this.setStart( node, node.getChildCount() );
break;
case CKEDITOR.POSITION_BEFORE_START :
this.setStartBefore( node );
break;
case CKEDITOR.POSITION_AFTER_END :
this.setStartAfter( node );
}
updateCollapsed( this );
},
setEndAt : function( node, position )
{
switch( position )
{
case CKEDITOR.POSITION_AFTER_START :
this.setEnd( node, 0 );
break;
case CKEDITOR.POSITION_BEFORE_END :
if ( node.type == CKEDITOR.NODE_TEXT )
this.setEnd( node, node.getLength() );
else
this.setEnd( node, node.getChildCount() );
break;
case CKEDITOR.POSITION_BEFORE_START :
this.setEndBefore( node );
break;
case CKEDITOR.POSITION_AFTER_END :
this.setEndAfter( node );
}
updateCollapsed( this );
},
fixBlock : function( isStart, blockTag )
{
var bookmark = this.createBookmark(),
fixedBlock = this.document.createElement( blockTag );
this.collapse( isStart );
this.enlarge( CKEDITOR.ENLARGE_BLOCK_CONTENTS );
this.extractContents().appendTo( fixedBlock );
fixedBlock.trim();
if ( !CKEDITOR.env.ie )
fixedBlock.appendBogus();
this.insertNode( fixedBlock );
this.moveToBookmark( bookmark );
return fixedBlock;
},
splitBlock : function( blockTag )
{
var startPath = new CKEDITOR.dom.elementPath( this.startContainer ),
endPath = new CKEDITOR.dom.elementPath( this.endContainer );
var startBlockLimit = startPath.blockLimit,
endBlockLimit = endPath.blockLimit;
var startBlock = startPath.block,
endBlock = endPath.block;
var elementPath = null;
// Do nothing if the boundaries are in different block limits.
if ( !startBlockLimit.equals( endBlockLimit ) )
return null;
// Get or fix current blocks.
if ( blockTag != 'br' )
{
if ( !startBlock )
{
startBlock = this.fixBlock( true, blockTag );
endBlock = new CKEDITOR.dom.elementPath( this.endContainer ).block;
}
if ( !endBlock )
endBlock = this.fixBlock( false, blockTag );
}
// Get the range position.
var isStartOfBlock = startBlock && this.checkStartOfBlock(),
isEndOfBlock = endBlock && this.checkEndOfBlock();
// Delete the current contents.
// TODO: Why is 2.x doing CheckIsEmpty()?
this.deleteContents();
if ( startBlock && startBlock.equals( endBlock ) )
{
if ( isEndOfBlock )
{
elementPath = new CKEDITOR.dom.elementPath( this.startContainer );
this.moveToPosition( endBlock, CKEDITOR.POSITION_AFTER_END );
endBlock = null;
}
else if ( isStartOfBlock )
{
elementPath = new CKEDITOR.dom.elementPath( this.startContainer );
this.moveToPosition( startBlock, CKEDITOR.POSITION_BEFORE_START );
startBlock = null;
}
else
{
endBlock = this.splitElement( startBlock );
// 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 ( !CKEDITOR.env.ie && !startBlock.is( 'ul', 'ol') )
startBlock.appendBogus() ;
}
}
return {
previousBlock : startBlock,
nextBlock : endBlock,
wasStartOfBlock : isStartOfBlock,
wasEndOfBlock : isEndOfBlock,
elementPath : elementPath
};
},
/**
* Branch the specified element from the collapsed range position and
* place the caret between the two result branches.
* Note: The range must be collapsed and been enclosed by this element.
* @param {CKEDITOR.dom.element} element
* @return {CKEDITOR.dom.element} Root element of the new branch after the split.
*/
splitElement : function( toSplit )
{
if ( !this.collapsed )
return null;
// Extract the contents of the block from the selection point to the end
// of its contents.
this.setEndAt( toSplit, CKEDITOR.POSITION_BEFORE_END );
var documentFragment = this.extractContents();
// Duplicate the element after it.
var clone = toSplit.clone( false );
// Place the extracted contents into the duplicated element.
documentFragment.appendTo( clone );
clone.insertAfter( toSplit );
this.moveToPosition( toSplit, CKEDITOR.POSITION_AFTER_END );
return clone;
},
/**
* Check whether a range boundary is at the inner boundary of a given
* element.
* @param {CKEDITOR.dom.element} element The target element to check.
* @param {Number} checkType The boundary to check for both the range
* and the element. It can be CKEDITOR.START or CKEDITOR.END.
* @returns {Boolean} "true" if the range boundary is at the inner
* boundary of the element.
*/
checkBoundaryOfElement : function( element, checkType )
{
var checkStart = ( checkType == CKEDITOR.START );
// Create a copy of this range, so we can manipulate it for our checks.
var walkerRange = this.clone();
// Collapse the range at the proper size.
walkerRange.collapse( checkStart );
// Expand the range to element boundary.
walkerRange[ checkStart ? 'setStartAt' : 'setEndAt' ]
( element, checkStart ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_END );
// Create the walker, which will check if we have anything useful
// in the range.
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = elementBoundaryEval( checkStart );
return walker[ checkStart ? 'checkBackward' : 'checkForward' ]();
},
// Calls to this function may produce changes to the DOM. The range may
// be updated to reflect such changes.
checkStartOfBlock : function()
{
var startContainer = this.startContainer,
startOffset = this.startOffset;
// [IE] Special handling for range start in text with a leading NBSP,
// we it to be isolated, for bogus check.
if ( CKEDITOR.env.ie && startOffset && startContainer.type == CKEDITOR.NODE_TEXT )
{
var textBefore = CKEDITOR.tools.ltrim( startContainer.substring( 0, startOffset ) );
if ( nbspRegExp.test( textBefore ) )
this.trim( 0, 1 );
}
// We need to grab the block element holding the start boundary, so
// let's use an element path for it.
var path = new CKEDITOR.dom.elementPath( this.startContainer );
// Creates a range starting at the block start until the range start.
var walkerRange = this.clone();
walkerRange.collapse( true );
walkerRange.setStartAt( path.block || path.blockLimit, CKEDITOR.POSITION_AFTER_START );
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = getCheckStartEndBlockEvalFunction();
return walker.checkBackward();
},
checkEndOfBlock : function()
{
var endContainer = this.endContainer,
endOffset = this.endOffset;
// [IE] Special handling for range end in text with a following NBSP,
// we it to be isolated, for bogus check.
if ( CKEDITOR.env.ie && endContainer.type == CKEDITOR.NODE_TEXT )
{
var textAfter = CKEDITOR.tools.rtrim( endContainer.substring( endOffset ) );
if ( nbspRegExp.test( textAfter ) )
this.trim( 1, 0 );
}
// We need to grab the block element holding the start boundary, so
// let's use an element path for it.
var path = new CKEDITOR.dom.elementPath( this.endContainer );
// Creates a range starting at the block start until the range start.
var walkerRange = this.clone();
walkerRange.collapse( false );
walkerRange.setEndAt( path.block || path.blockLimit, CKEDITOR.POSITION_BEFORE_END );
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = getCheckStartEndBlockEvalFunction();
return walker.checkForward();
},
/**
* Traverse with {@link CKEDITOR.dom.walker} to retrieve the previous element before the range start.
* @param {Function} evaluator Function used as the walker's evaluator.
* @param {Function} [guard] Function used as the walker's guard.
* @param {CKEDITOR.dom.element} [boundary] A range ancestor element in which the traversal is limited,
* default to the root editable if not defined.
*
* @return {CKEDITOR.dom.element|null} The returned node from the traversal.
*/
getPreviousNode : function( evaluator, guard, boundary ) {
var walkerRange = this.clone();
walkerRange.collapse( 1 );
walkerRange.setStartAt( boundary || this.document.getBody(), CKEDITOR.POSITION_AFTER_START );
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = evaluator;
walker.guard = guard;
return walker.previous();
},
/**
* Traverse with {@link CKEDITOR.dom.walker} to retrieve the next element before the range start.
* @param {Function} evaluator Function used as the walker's evaluator.
* @param {Function} [guard] Function used as the walker's guard.
* @param {CKEDITOR.dom.element} [boundary] A range ancestor element in which the traversal is limited,
* default to the root editable if not defined.
*
* @return {CKEDITOR.dom.element|null} The returned node from the traversal.
*/
getNextNode: function( evaluator, guard, boundary )
{
var walkerRange = this.clone();
walkerRange.collapse();
walkerRange.setEndAt( boundary || this.document.getBody(), CKEDITOR.POSITION_BEFORE_END );
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = evaluator;
walker.guard = guard;
return walker.next();
},
checkReadOnly : ( function()
{
function checkNodesEditable( node, anotherEnd )
{
while( node )
{
if ( node.type == CKEDITOR.NODE_ELEMENT )
{
if ( node.getAttribute( 'contentEditable' ) == 'false'
&& !node.data( 'cke-editable' ) )
{
return 0;
}
// Range enclosed entirely in an editable element.
else if ( node.is( 'html' )
|| node.getAttribute( 'contentEditable' ) == 'true'
&& ( node.contains( anotherEnd ) || node.equals( anotherEnd ) ) )
{
break;
}
}
node = node.getParent();
}
return 1;
}
return function()
{
var startNode = this.startContainer,
endNode = this.endContainer;
// Check if elements path at both boundaries are editable.
return !( checkNodesEditable( startNode, endNode ) && checkNodesEditable( endNode, startNode ) );
};
})(),
/**
* Moves the range boundaries to the first/end editing point inside an
* element. For example, in an element tree like
* "<p><b><i></i></b> Text</p>", the start editing point is
* "<p><b><i>^</i></b> Text</p>" (inside <i>).
* @param {CKEDITOR.dom.element} el The element into which look for the
* editing spot.
* @param {Boolean} isMoveToEnd Whether move to the end editable position.
*/
moveToElementEditablePosition : function( el, isMoveToEnd )
{
function nextDFS( node, childOnly )
{
var next;
if ( node.type == CKEDITOR.NODE_ELEMENT && node.isEditable( false ) )
next = node[ isMoveToEnd ? 'getLast' : 'getFirst' ]( nonWhitespaceOrBookmarkEval );
if ( !childOnly && !next )
next = node[ isMoveToEnd ? 'getPrevious' : 'getNext' ]( nonWhitespaceOrBookmarkEval );
return next;
}
// Handle non-editable element e.g. HR.
if ( el.type == CKEDITOR.NODE_ELEMENT && !el.isEditable( false ) )
{
this.moveToPosition( el, isMoveToEnd ?
CKEDITOR.POSITION_AFTER_END :
CKEDITOR.POSITION_BEFORE_START );
return true;
}
var found = 0;
while ( el )
{
// Stop immediately if we've found a text node.
if ( el.type == CKEDITOR.NODE_TEXT )
{
// Put cursor before block filler.
if ( isMoveToEnd && this.checkEndOfBlock() && nbspRegExp.test( el.getText() ) )
this.moveToPosition( el, CKEDITOR.POSITION_BEFORE_START );
else
this.moveToPosition( el, isMoveToEnd ?
CKEDITOR.POSITION_AFTER_END :
CKEDITOR.POSITION_BEFORE_START );
found = 1;
break;
}
// If an editable element is found, move inside it, but not stop the searching.
if ( el.type == CKEDITOR.NODE_ELEMENT )
{
if ( el.isEditable() )
{
this.moveToPosition( el, isMoveToEnd ?
CKEDITOR.POSITION_BEFORE_END :
CKEDITOR.POSITION_AFTER_START );
found = 1;
}
// Put cursor before padding block br.
else if ( isMoveToEnd && el.is( 'br' ) && this.checkEndOfBlock() )
this.moveToPosition( el, CKEDITOR.POSITION_BEFORE_START );
}
el = nextDFS( el, found );
}
return !!found;
},
/**
*@see {CKEDITOR.dom.range.moveToElementEditablePosition}
*/
moveToElementEditStart : function( target )
{
return this.moveToElementEditablePosition( target );
},
/**
*@see {CKEDITOR.dom.range.moveToElementEditablePosition}
*/
moveToElementEditEnd : function( target )
{
return this.moveToElementEditablePosition( target, true );
},
/**
* Get the single node enclosed within the range if there's one.
*/
getEnclosedNode : function()
{
var walkerRange = this.clone();
// Optimize and analyze the range to avoid DOM destructive nature of walker. (#5780)
walkerRange.optimize();
if ( walkerRange.startContainer.type != CKEDITOR.NODE_ELEMENT
|| walkerRange.endContainer.type != CKEDITOR.NODE_ELEMENT )
return null;
var walker = new CKEDITOR.dom.walker( walkerRange ),
isNotBookmarks = CKEDITOR.dom.walker.bookmark( true ),
isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),
evaluator = function( node )
{
return isNotWhitespaces( node ) && isNotBookmarks( node );
};
walkerRange.evaluator = evaluator;
var node = walker.next();
walker.reset();
return node && node.equals( walker.previous() ) ? node : null;
},
getTouchedStartNode : function()
{
var container = this.startContainer ;
if ( this.collapsed || container.type != CKEDITOR.NODE_ELEMENT )
return container ;
return container.getChild( this.startOffset ) || container ;
},
getTouchedEndNode : function()
{
var container = this.endContainer ;
if ( this.collapsed || container.type != CKEDITOR.NODE_ELEMENT )
return container ;
return container.getChild( this.endOffset - 1 ) || container ;
}
};
})();
CKEDITOR.POSITION_AFTER_START = 1; // <element>^contents</element> "^text"
CKEDITOR.POSITION_BEFORE_END = 2; // <element>contents^</element> "text^"
CKEDITOR.POSITION_BEFORE_START = 3; // ^<element>contents</element> ^"text"
CKEDITOR.POSITION_AFTER_END = 4; // <element>contents</element>^ "text"
CKEDITOR.ENLARGE_ELEMENT = 1;
CKEDITOR.ENLARGE_BLOCK_CONTENTS = 2;
CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS = 3;
// Check boundary types.
// @see CKEDITOR.dom.range.prototype.checkBoundaryOfElement
CKEDITOR.START = 1;
CKEDITOR.END = 2;
CKEDITOR.STARTEND = 3;
// Shrink range types.
// @see CKEDITOR.dom.range.prototype.shrink
CKEDITOR.SHRINK_ELEMENT = 1;
CKEDITOR.SHRINK_TEXT = 2;
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.document} class, which
* represents a DOM document.
*/
/**
* Represents a DOM window.
* @constructor
* @augments CKEDITOR.dom.domObject
* @param {Object} domWindow A native DOM window.
* @example
* var document = new CKEDITOR.dom.window( window );
*/
CKEDITOR.dom.window = function( domWindow )
{
CKEDITOR.dom.domObject.call( this, domWindow );
};
CKEDITOR.dom.window.prototype = new CKEDITOR.dom.domObject();
CKEDITOR.tools.extend( CKEDITOR.dom.window.prototype,
/** @lends CKEDITOR.dom.window.prototype */
{
/**
* Moves the selection focus to this window.
* @function
* @example
* var win = new CKEDITOR.dom.window( window );
* <b>win.focus()</b>;
*/
focus : function()
{
// Webkit is sometimes failed to focus iframe, blur it first(#3835).
if ( CKEDITOR.env.webkit && this.$.parent )
this.$.parent.focus();
this.$.focus();
},
/**
* Gets the width and height of this window's viewable area.
* @function
* @returns {Object} An object with the "width" and "height"
* properties containing the size.
* @example
* var win = new CKEDITOR.dom.window( window );
* var size = <b>win.getViewPaneSize()</b>;
* alert( size.width );
* alert( size.height );
*/
getViewPaneSize : function()
{
var doc = this.$.document,
stdMode = doc.compatMode == 'CSS1Compat';
return {
width : ( stdMode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
height : ( stdMode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
};
},
/**
* Gets the current position of the window's scroll.
* @function
* @returns {Object} An object with the "x" and "y" properties
* containing the scroll position.
* @example
* var win = new CKEDITOR.dom.window( window );
* var pos = <b>win.getScrollPosition()</b>;
* alert( pos.x );
* alert( pos.y );
*/
getScrollPosition : function()
{
var $ = this.$;
if ( 'pageXOffset' in $ )
{
return {
x : $.pageXOffset || 0,
y : $.pageYOffset || 0
};
}
else
{
var doc = $.document;
return {
x : doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
y : doc.documentElement.scrollTop || doc.body.scrollTop || 0
};
}
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @class
*/
CKEDITOR.dom.nodeList = function( nativeList )
{
this.$ = nativeList;
};
CKEDITOR.dom.nodeList.prototype =
{
count : function()
{
return this.$.length;
},
getItem : function( index )
{
var $node = this.$[ index ];
return $node ? new CKEDITOR.dom.node( $node ) : null;
}
};
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.document} class, which
* represents a DOM document.
*/
/**
* Represents a DOM document.
* @constructor
* @augments CKEDITOR.dom.domObject
* @param {Object} domDocument A native DOM document.
* @example
* var document = new CKEDITOR.dom.document( document );
*/
CKEDITOR.dom.document = function( domDocument )
{
CKEDITOR.dom.domObject.call( this, domDocument );
};
// PACKAGER_RENAME( CKEDITOR.dom.document )
CKEDITOR.dom.document.prototype = new CKEDITOR.dom.domObject();
CKEDITOR.tools.extend( CKEDITOR.dom.document.prototype,
/** @lends CKEDITOR.dom.document.prototype */
{
/**
* Appends a CSS file to the document.
* @param {String} cssFileUrl The CSS file URL.
* @example
* <b>CKEDITOR.document.appendStyleSheet( '/mystyles.css' )</b>;
*/
appendStyleSheet : function( cssFileUrl )
{
if ( this.$.createStyleSheet )
this.$.createStyleSheet( cssFileUrl );
else
{
var link = new CKEDITOR.dom.element( 'link' );
link.setAttributes(
{
rel :'stylesheet',
type : 'text/css',
href : cssFileUrl
});
this.getHead().append( link );
}
},
appendStyleText : function( cssStyleText )
{
if ( this.$.createStyleSheet )
{
var styleSheet = this.$.createStyleSheet( "" );
styleSheet.cssText = cssStyleText ;
}
else
{
var style = new CKEDITOR.dom.element( 'style', this );
style.append( new CKEDITOR.dom.text( cssStyleText, this ) );
this.getHead().append( style );
}
},
createElement : function( name, attribsAndStyles )
{
var element = new CKEDITOR.dom.element( name, this );
if ( attribsAndStyles )
{
if ( attribsAndStyles.attributes )
element.setAttributes( attribsAndStyles.attributes );
if ( attribsAndStyles.styles )
element.setStyles( attribsAndStyles.styles );
}
return element;
},
createText : function( text )
{
return new CKEDITOR.dom.text( text, this );
},
focus : function()
{
this.getWindow().focus();
},
/**
* Gets and element based on its id.
* @param {String} elementId The element id.
* @returns {CKEDITOR.dom.element} The element instance, or null if not found.
* @example
* var element = <b>CKEDITOR.document.getById( 'myElement' )</b>;
* alert( element.getId() ); // "myElement"
*/
getById : function( elementId )
{
var $ = this.$.getElementById( elementId );
return $ ? new CKEDITOR.dom.element( $ ) : null;
},
getByAddress : function( address, normalized )
{
var $ = this.$.documentElement;
for ( var i = 0 ; $ && i < address.length ; i++ )
{
var target = address[ i ];
if ( !normalized )
{
$ = $.childNodes[ target ];
continue;
}
var currentIndex = -1;
for (var j = 0 ; j < $.childNodes.length ; j++ )
{
var candidate = $.childNodes[ j ];
if ( normalized === true &&
candidate.nodeType == 3 &&
candidate.previousSibling &&
candidate.previousSibling.nodeType == 3 )
{
continue;
}
currentIndex++;
if ( currentIndex == target )
{
$ = candidate;
break;
}
}
}
return $ ? new CKEDITOR.dom.node( $ ) : null;
},
getElementsByTag : function( tagName, namespace )
{
if ( !( CKEDITOR.env.ie && ! ( document.documentMode > 8 ) ) && namespace )
tagName = namespace + ':' + tagName;
return new CKEDITOR.dom.nodeList( this.$.getElementsByTagName( tagName ) );
},
/**
* Gets the <head> element for this document.
* @returns {CKEDITOR.dom.element} The <head> element.
* @example
* var element = <b>CKEDITOR.document.getHead()</b>;
* alert( element.getName() ); // "head"
*/
getHead : function()
{
var head = this.$.getElementsByTagName( 'head' )[0];
if ( !head )
head = this.getDocumentElement().append( new CKEDITOR.dom.element( 'head' ), true );
else
head = new CKEDITOR.dom.element( head );
return (
this.getHead = function()
{
return head;
})();
},
/**
* Gets the <body> element for this document.
* @returns {CKEDITOR.dom.element} The <body> element.
* @example
* var element = <b>CKEDITOR.document.getBody()</b>;
* alert( element.getName() ); // "body"
*/
getBody : function()
{
var body = new CKEDITOR.dom.element( this.$.body );
return (
this.getBody = function()
{
return body;
})();
},
/**
* Gets the DOM document element for this document.
* @returns {CKEDITOR.dom.element} The DOM document element.
*/
getDocumentElement : function()
{
var documentElement = new CKEDITOR.dom.element( this.$.documentElement );
return (
this.getDocumentElement = function()
{
return documentElement;
})();
},
/**
* Gets the window object that holds this document.
* @returns {CKEDITOR.dom.window} The window object.
*/
getWindow : function()
{
var win = new CKEDITOR.dom.window( this.$.parentWindow || this.$.defaultView );
return (
this.getWindow = function()
{
return win;
})();
},
/**
* Defines the document contents through document.write. Note that the
* previous document contents will be lost (cleaned).
* @since 3.5
* @param {String} html The HTML defining the document contents.
* @example
* document.write(
* '<html>' +
* '<head><title>Sample Doc</title></head>' +
* '<body>Document contents created by code</body>' +
* '</html>' );
*/
write : function( html )
{
// Don't leave any history log in IE. (#5657)
this.$.open( 'text/html', 'replace' );
// Support for custom document.domain in IE.
CKEDITOR.env.isCustomDomain() && ( this.$.domain = document.domain );
this.$.write( html );
this.$.close();
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
// This function is to be called under a "walker" instance scope.
function iterate( rtl, breakOnFalse )
{
var range = this.range;
// Return null if we have reached the end.
if ( this._.end )
return null;
// This is the first call. Initialize it.
if ( !this._.start )
{
this._.start = 1;
// A collapsed range must return null at first call.
if ( range.collapsed )
{
this.end();
return null;
}
// Move outside of text node edges.
range.optimize();
}
var node,
startCt = range.startContainer,
endCt = range.endContainer,
startOffset = range.startOffset,
endOffset = range.endOffset,
guard,
userGuard = this.guard,
type = this.type,
getSourceNodeFn = ( rtl ? 'getPreviousSourceNode' : 'getNextSourceNode' );
// Create the LTR guard function, if necessary.
if ( !rtl && !this._.guardLTR )
{
// The node that stops walker from moving up.
var limitLTR = endCt.type == CKEDITOR.NODE_ELEMENT ?
endCt :
endCt.getParent();
// The node that stops the walker from going to next.
var blockerLTR = endCt.type == CKEDITOR.NODE_ELEMENT ?
endCt.getChild( endOffset ) :
endCt.getNext();
this._.guardLTR = function( node, movingOut )
{
return ( ( !movingOut || !limitLTR.equals( node ) )
&& ( !blockerLTR || !node.equals( blockerLTR ) )
&& ( node.type != CKEDITOR.NODE_ELEMENT || !movingOut || node.getName() != 'body' ) );
};
}
// Create the RTL guard function, if necessary.
if ( rtl && !this._.guardRTL )
{
// The node that stops walker from moving up.
var limitRTL = startCt.type == CKEDITOR.NODE_ELEMENT ?
startCt :
startCt.getParent();
// The node that stops the walker from going to next.
var blockerRTL = startCt.type == CKEDITOR.NODE_ELEMENT ?
startOffset ?
startCt.getChild( startOffset - 1 ) : null :
startCt.getPrevious();
this._.guardRTL = function( node, movingOut )
{
return ( ( !movingOut || !limitRTL.equals( node ) )
&& ( !blockerRTL || !node.equals( blockerRTL ) )
&& ( node.type != CKEDITOR.NODE_ELEMENT || !movingOut || node.getName() != 'body' ) );
};
}
// Define which guard function to use.
var stopGuard = rtl ? this._.guardRTL : this._.guardLTR;
// Make the user defined guard function participate in the process,
// otherwise simply use the boundary guard.
if ( userGuard )
{
guard = function( node, movingOut )
{
if ( stopGuard( node, movingOut ) === false )
return false;
return userGuard( node, movingOut );
};
}
else
guard = stopGuard;
if ( this.current )
node = this.current[ getSourceNodeFn ]( false, type, guard );
else
{
// Get the first node to be returned.
if ( rtl )
{
node = endCt;
if ( node.type == CKEDITOR.NODE_ELEMENT )
{
if ( endOffset > 0 )
node = node.getChild( endOffset - 1 );
else
node = ( guard ( node, true ) === false ) ?
null : node.getPreviousSourceNode( true, type, guard );
}
}
else
{
node = startCt;
if ( node.type == CKEDITOR.NODE_ELEMENT )
{
if ( ! ( node = node.getChild( startOffset ) ) )
node = ( guard ( startCt, true ) === false ) ?
null : startCt.getNextSourceNode( true, type, guard ) ;
}
}
if ( node && guard( node ) === false )
node = null;
}
while ( node && !this._.end )
{
this.current = node;
if ( !this.evaluator || this.evaluator( node ) !== false )
{
if ( !breakOnFalse )
return node;
}
else if ( breakOnFalse && this.evaluator )
return false;
node = node[ getSourceNodeFn ]( false, type, guard );
}
this.end();
return this.current = null;
}
function iterateToLast( rtl )
{
var node, last = null;
while ( ( node = iterate.call( this, rtl ) ) )
last = node;
return last;
}
CKEDITOR.dom.walker = CKEDITOR.tools.createClass(
{
/**
* Utility class to "walk" the DOM inside a range boundaries. If
* necessary, partially included nodes (text nodes) are broken to
* reflect the boundaries limits, so DOM and range changes may happen.
* Outside changes to the range may break the walker.
*
* The walker may return nodes that are not totaly included into the
* range boundaires. Let's take the following range representation,
* where the square brackets indicate the boundaries:
*
* [<p>Some <b>sample] text</b>
*
* While walking forward into the above range, the following nodes are
* returned: <p>, "Some ", <b> and "sample". Going
* backwards instead we have: "sample" and "Some ". So note that the
* walker always returns nodes when "entering" them, but not when
* "leaving" them. The guard function is instead called both when
* entering and leaving nodes.
*
* @constructor
* @param {CKEDITOR.dom.range} range The range within which walk.
*/
$ : function( range )
{
this.range = range;
/**
* A function executed for every matched node, to check whether
* it's to be considered into the walk or not. If not provided, all
* matched nodes are considered good.
* If the function returns "false" the node is ignored.
* @name CKEDITOR.dom.walker.prototype.evaluator
* @property
* @type Function
*/
// this.evaluator = null;
/**
* A function executed for every node the walk pass by to check
* whether the walk is to be finished. It's called when both
* entering and exiting nodes, as well as for the matched nodes.
* If this function returns "false", the walking ends and no more
* nodes are evaluated.
* @name CKEDITOR.dom.walker.prototype.guard
* @property
* @type Function
*/
// this.guard = null;
/** @private */
this._ = {};
},
// statics :
// {
// /* Creates a CKEDITOR.dom.walker instance to walk inside DOM boundaries set by nodes.
// * @param {CKEDITOR.dom.node} startNode The node from wich the walk
// * will start.
// * @param {CKEDITOR.dom.node} [endNode] The last node to be considered
// * in the walk. No more nodes are retrieved after touching or
// * passing it. If not provided, the walker stops at the
// * <body> closing boundary.
// * @returns {CKEDITOR.dom.walker} A DOM walker for the nodes between the
// * provided nodes.
// */
// createOnNodes : function( startNode, endNode, startInclusive, endInclusive )
// {
// var range = new CKEDITOR.dom.range();
// if ( startNode )
// range.setStartAt( startNode, startInclusive ? CKEDITOR.POSITION_BEFORE_START : CKEDITOR.POSITION_AFTER_END ) ;
// else
// range.setStartAt( startNode.getDocument().getBody(), CKEDITOR.POSITION_AFTER_START ) ;
//
// if ( endNode )
// range.setEndAt( endNode, endInclusive ? CKEDITOR.POSITION_AFTER_END : CKEDITOR.POSITION_BEFORE_START ) ;
// else
// range.setEndAt( startNode.getDocument().getBody(), CKEDITOR.POSITION_BEFORE_END ) ;
//
// return new CKEDITOR.dom.walker( range );
// }
// },
//
proto :
{
/**
* Stop walking. No more nodes are retrieved if this function gets
* called.
*/
end : function()
{
this._.end = 1;
},
/**
* Retrieves the next node (at right).
* @returns {CKEDITOR.dom.node} The next node or null if no more
* nodes are available.
*/
next : function()
{
return iterate.call( this );
},
/**
* Retrieves the previous node (at left).
* @returns {CKEDITOR.dom.node} The previous node or null if no more
* nodes are available.
*/
previous : function()
{
return iterate.call( this, 1 );
},
/**
* Check all nodes at right, executing the evaluation fuction.
* @returns {Boolean} "false" if the evaluator function returned
* "false" for any of the matched nodes. Otherwise "true".
*/
checkForward : function()
{
return iterate.call( this, 0, 1 ) !== false;
},
/**
* Check all nodes at left, executing the evaluation fuction.
* @returns {Boolean} "false" if the evaluator function returned
* "false" for any of the matched nodes. Otherwise "true".
*/
checkBackward : function()
{
return iterate.call( this, 1, 1 ) !== false;
},
/**
* Executes a full walk forward (to the right), until no more nodes
* are available, returning the last valid node.
* @returns {CKEDITOR.dom.node} The last node at the right or null
* if no valid nodes are available.
*/
lastForward : function()
{
return iterateToLast.call( this );
},
/**
* Executes a full walk backwards (to the left), until no more nodes
* are available, returning the last valid node.
* @returns {CKEDITOR.dom.node} The last node at the left or null
* if no valid nodes are available.
*/
lastBackward : function()
{
return iterateToLast.call( this, 1 );
},
reset : function()
{
delete this.current;
this._ = {};
}
}
});
/*
* Anything whose display computed style is block, list-item, table,
* table-row-group, table-header-group, table-footer-group, table-row,
* table-column-group, table-column, table-cell, table-caption, or whose node
* name is hr, br (when enterMode is br only) is a block boundary.
*/
var blockBoundaryDisplayMatch =
{
block : 1,
'list-item' : 1,
table : 1,
'table-row-group' : 1,
'table-header-group' : 1,
'table-footer-group' : 1,
'table-row' : 1,
'table-column-group' : 1,
'table-column' : 1,
'table-cell' : 1,
'table-caption' : 1
};
CKEDITOR.dom.element.prototype.isBlockBoundary = function( customNodeNames )
{
var nodeNameMatches = customNodeNames ?
CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$block, customNodeNames || {} ) :
CKEDITOR.dtd.$block;
// Don't consider floated formatting as block boundary, fall back to dtd check in that case. (#6297)
return this.getComputedStyle( 'float' ) == 'none' && blockBoundaryDisplayMatch[ this.getComputedStyle( 'display' ) ]
|| nodeNameMatches[ this.getName() ];
};
CKEDITOR.dom.walker.blockBoundary = function( customNodeNames )
{
return function( node , type )
{
return ! ( node.type == CKEDITOR.NODE_ELEMENT
&& node.isBlockBoundary( customNodeNames ) );
};
};
CKEDITOR.dom.walker.listItemBoundary = function()
{
return this.blockBoundary( { br : 1 } );
};
/**
* Whether the to-be-evaluated node is a bookmark node OR bookmark node
* inner contents.
* @param {Boolean} contentOnly Whether only test againt the text content of
* bookmark node instead of the element itself(default).
* @param {Boolean} isReject Whether should return 'false' for the bookmark
* node instead of 'true'(default).
*/
CKEDITOR.dom.walker.bookmark = function( contentOnly, isReject )
{
function isBookmarkNode( node )
{
return ( node && node.getName
&& node.getName() == 'span'
&& node.data( 'cke-bookmark' ) );
}
return function( node )
{
var isBookmark, parent;
// Is bookmark inner text node?
isBookmark = ( node && !node.getName && ( parent = node.getParent() )
&& isBookmarkNode( parent ) );
// Is bookmark node?
isBookmark = contentOnly ? isBookmark : isBookmark || isBookmarkNode( node );
return !! ( isReject ^ isBookmark );
};
};
/**
* Whether the node is a text node containing only whitespaces characters.
* @param isReject
*/
CKEDITOR.dom.walker.whitespaces = function( isReject )
{
return function( node )
{
var isWhitespace;
if ( node && node.type == CKEDITOR.NODE_TEXT )
{
// whitespace, as well as the text cursor filler node we used in Webkit. (#9384)
isWhitespace = !CKEDITOR.tools.trim( node.getText() ) ||
CKEDITOR.env.webkit && node.getText() == '\u200b';
}
return !! ( isReject ^ isWhitespace );
};
};
/**
* Whether the node is invisible in wysiwyg mode.
* @param isReject
*/
CKEDITOR.dom.walker.invisible = function( isReject )
{
var whitespace = CKEDITOR.dom.walker.whitespaces();
return function( node )
{
var invisible;
if ( whitespace( node ) )
invisible = 1;
else
{
// Visibility should be checked on element.
if ( node.type == CKEDITOR.NODE_TEXT )
node = node.getParent();
// Nodes that take no spaces in wysiwyg:
// 1. White-spaces but not including NBSP;
// 2. Empty inline elements, e.g. <b></b> we're checking here
// 'offsetHeight' instead of 'offsetWidth' for properly excluding
// all sorts of empty paragraph, e.g. <br />.
invisible = !node.$.offsetHeight;
}
return !! ( isReject ^ invisible );
};
};
CKEDITOR.dom.walker.nodeType = function( type, isReject )
{
return function( node )
{
return !! ( isReject ^ ( node.type == type ) );
};
};
CKEDITOR.dom.walker.bogus = function( isReject )
{
function nonEmpty( node )
{
return !isWhitespaces( node ) && !isBookmark( node );
}
return function( node )
{
var isBogus = !CKEDITOR.env.ie ? node.is && node.is( 'br' ) :
node.getText && tailNbspRegex.test( node.getText() );
if ( isBogus )
{
var parent = node.getParent(), next = node.getNext( nonEmpty );
isBogus = parent.isBlockBoundary() &&
( !next ||
next.type == CKEDITOR.NODE_ELEMENT &&
next.isBlockBoundary() );
}
return !! ( isReject ^ isBogus );
};
};
var tailNbspRegex = /^[\t\r\n ]*(?: |\xa0)$/,
isWhitespaces = CKEDITOR.dom.walker.whitespaces(),
isBookmark = CKEDITOR.dom.walker.bookmark(),
toSkip = function( node )
{
return isBookmark( node )
|| isWhitespaces( node )
|| node.type == CKEDITOR.NODE_ELEMENT
&& node.getName() in CKEDITOR.dtd.$inline
&& !( node.getName() in CKEDITOR.dtd.$empty );
};
// Check if there's a filler node at the end of an element, and return it.
CKEDITOR.dom.element.prototype.getBogus = function()
{
// Bogus are not always at the end, e.g. <p><a>text<br /></a></p> (#7070).
var tail = this;
do { tail = tail.getPreviousSourceNode(); }
while ( toSkip( tail ) )
if ( tail && ( !CKEDITOR.env.ie ? tail.is && tail.is( 'br' )
: tail.getText && tailNbspRegex.test( tail.getText() ) ) )
{
return tail;
}
return false;
};
})();
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.element} class, which
* represents a DOM element.
*/
/**
* Represents a DOM element.
* @constructor
* @augments CKEDITOR.dom.node
* @param {Object|String} element A native DOM element or the element name for
* new elements.
* @param {CKEDITOR.dom.document} [ownerDocument] The document that will contain
* the element in case of element creation.
* @example
* // Create a new <span> element.
* var element = new CKEDITOR.dom.element( 'span' );
* @example
* // Create an element based on a native DOM element.
* var element = new CKEDITOR.dom.element( document.getElementById( 'myId' ) );
*/
CKEDITOR.dom.element = function( element, ownerDocument )
{
if ( typeof element == 'string' )
element = ( ownerDocument ? ownerDocument.$ : document ).createElement( element );
// Call the base constructor (we must not call CKEDITOR.dom.node).
CKEDITOR.dom.domObject.call( this, element );
};
// PACKAGER_RENAME( CKEDITOR.dom.element )
/**
* The the {@link CKEDITOR.dom.element} representing and element. If the
* element is a native DOM element, it will be transformed into a valid
* CKEDITOR.dom.element object.
* @returns {CKEDITOR.dom.element} The transformed element.
* @example
* var element = new CKEDITOR.dom.element( 'span' );
* alert( element == <b>CKEDITOR.dom.element.get( element )</b> ); "true"
* @example
* var element = document.getElementById( 'myElement' );
* alert( <b>CKEDITOR.dom.element.get( element )</b>.getName() ); e.g. "p"
*/
CKEDITOR.dom.element.get = function( element )
{
return element && ( element.$ ? element : new CKEDITOR.dom.element( element ) );
};
CKEDITOR.dom.element.prototype = new CKEDITOR.dom.node();
/**
* Creates an instance of the {@link CKEDITOR.dom.element} class based on the
* HTML representation of an element.
* @param {String} html The element HTML. It should define only one element in
* the "root" level. The "root" element can have child nodes, but not
* siblings.
* @returns {CKEDITOR.dom.element} The element instance.
* @example
* var element = <b>CKEDITOR.dom.element.createFromHtml( '<strong class="anyclass">My element</strong>' )</b>;
* alert( element.getName() ); // "strong"
*/
CKEDITOR.dom.element.createFromHtml = function( html, ownerDocument )
{
var temp = new CKEDITOR.dom.element( 'div', ownerDocument );
temp.setHtml( html );
// When returning the node, remove it from its parent to detach it.
return temp.getFirst().remove();
};
CKEDITOR.dom.element.setMarker = function( database, element, name, value )
{
var id = element.getCustomData( 'list_marker_id' ) ||
( element.setCustomData( 'list_marker_id', CKEDITOR.tools.getNextNumber() ).getCustomData( 'list_marker_id' ) ),
markerNames = element.getCustomData( 'list_marker_names' ) ||
( element.setCustomData( 'list_marker_names', {} ).getCustomData( 'list_marker_names' ) );
database[id] = element;
markerNames[name] = 1;
return element.setCustomData( name, value );
};
CKEDITOR.dom.element.clearAllMarkers = function( database )
{
for ( var i in database )
CKEDITOR.dom.element.clearMarkers( database, database[i], 1 );
};
CKEDITOR.dom.element.clearMarkers = function( database, element, removeFromDatabase )
{
var names = element.getCustomData( 'list_marker_names' ),
id = element.getCustomData( 'list_marker_id' );
for ( var i in names )
element.removeCustomData( i );
element.removeCustomData( 'list_marker_names' );
if ( removeFromDatabase )
{
element.removeCustomData( 'list_marker_id' );
delete database[id];
}
};
( function()
{
CKEDITOR.tools.extend( CKEDITOR.dom.element.prototype,
/** @lends CKEDITOR.dom.element.prototype */
{
/**
* The node type. This is a constant value set to
* {@link CKEDITOR.NODE_ELEMENT}.
* @type Number
* @example
*/
type : CKEDITOR.NODE_ELEMENT,
/**
* Adds a CSS class to the element. It appends the class to the
* already existing names.
* @param {String} className The name of the class to be added.
* @example
* var element = new CKEDITOR.dom.element( 'div' );
* element.addClass( 'classA' ); // <div class="classA">
* element.addClass( 'classB' ); // <div class="classA classB">
* element.addClass( 'classA' ); // <div class="classA classB">
*/
addClass : function( className )
{
var c = this.$.className;
if ( c )
{
var regex = new RegExp( '(?:^|\\s)' + className + '(?:\\s|$)', '' );
if ( !regex.test( c ) )
c += ' ' + className;
}
this.$.className = c || className;
},
/**
* Removes a CSS class name from the elements classes. Other classes
* remain untouched.
* @param {String} className The name of the class to remove.
* @example
* var element = new CKEDITOR.dom.element( 'div' );
* element.addClass( 'classA' ); // <div class="classA">
* element.addClass( 'classB' ); // <div class="classA classB">
* element.removeClass( 'classA' ); // <div class="classB">
* element.removeClass( 'classB' ); // <div>
*/
removeClass : function( className )
{
var c = this.getAttribute( 'class' );
if ( c )
{
var regex = new RegExp( '(?:^|\\s+)' + className + '(?=\\s|$)', 'i' );
if ( regex.test( c ) )
{
c = c.replace( regex, '' ).replace( /^\s+/, '' );
if ( c )
this.setAttribute( 'class', c );
else
this.removeAttribute( 'class' );
}
}
},
hasClass : function( className )
{
var regex = new RegExp( '(?:^|\\s+)' + className + '(?=\\s|$)', '' );
return regex.test( this.getAttribute('class') );
},
/**
* Append a node as a child of this element.
* @param {CKEDITOR.dom.node|String} node The node or element name to be
* appended.
* @param {Boolean} [toStart] Indicates that the element is to be
* appended at the start.
* @returns {CKEDITOR.dom.node} The appended node.
* @example
* var p = new CKEDITOR.dom.element( 'p' );
*
* var strong = new CKEDITOR.dom.element( 'strong' );
* <b>p.append( strong );</b>
*
* var em = <b>p.append( 'em' );</b>
*
* // result: "<p><strong></strong><em></em></p>"
*/
append : function( node, toStart )
{
if ( typeof node == 'string' )
node = this.getDocument().createElement( node );
if ( toStart )
this.$.insertBefore( node.$, this.$.firstChild );
else
this.$.appendChild( node.$ );
return node;
},
appendHtml : function( html )
{
if ( !this.$.childNodes.length )
this.setHtml( html );
else
{
var temp = new CKEDITOR.dom.element( 'div', this.getDocument() );
temp.setHtml( html );
temp.moveChildren( this );
}
},
/**
* Append text to this element.
* @param {String} text The text to be appended.
* @returns {CKEDITOR.dom.node} The appended node.
* @example
* var p = new CKEDITOR.dom.element( 'p' );
* p.appendText( 'This is' );
* p.appendText( ' some text' );
*
* // result: "<p>This is some text</p>"
*/
appendText : function( text )
{
if ( this.$.text != undefined )
this.$.text += text;
else
this.append( new CKEDITOR.dom.text( text ) );
},
appendBogus : function()
{
var lastChild = this.getLast() ;
// Ignore empty/spaces text.
while ( lastChild && lastChild.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.rtrim( lastChild.getText() ) )
lastChild = lastChild.getPrevious();
if ( !lastChild || !lastChild.is || !lastChild.is( 'br' ) )
{
var bogus = CKEDITOR.env.opera ?
this.getDocument().createText('') :
this.getDocument().createElement( 'br' );
CKEDITOR.env.gecko && bogus.setAttribute( 'type', '_moz' );
this.append( bogus );
}
},
/**
* Breaks one of the ancestor element in the element position, moving
* this element between the broken parts.
* @param {CKEDITOR.dom.element} parent The anscestor element to get broken.
* @example
* // Before breaking:
* // <b>This <i>is some<span /> sample</i> test text</b>
* // If "element" is <span /> and "parent" is <i>:
* // <b>This <i>is some</i><span /><i> sample</i> test text</b>
* element.breakParent( parent );
* @example
* // Before breaking:
* // <b>This <i>is some<span /> sample</i> test text</b>
* // If "element" is <span /> and "parent" is <b>:
* // <b>This <i>is some</i></b><span /><b><i> sample</i> test text</b>
* element.breakParent( parent );
*/
breakParent : function( parent )
{
var range = new CKEDITOR.dom.range( this.getDocument() );
// We'll be extracting part of this element, so let's use our
// range to get the correct piece.
range.setStartAfter( this );
range.setEndAfter( parent );
// Extract it.
var docFrag = range.extractContents();
// Move the element outside the broken element.
range.insertNode( this.remove() );
// Re-insert the extracted piece after the element.
docFrag.insertAfterNode( this );
},
contains :
CKEDITOR.env.ie || CKEDITOR.env.webkit ?
function( node )
{
var $ = this.$;
return node.type != CKEDITOR.NODE_ELEMENT ?
$.contains( node.getParent().$ ) :
$ != node.$ && $.contains( node.$ );
}
:
function( node )
{
return !!( this.$.compareDocumentPosition( node.$ ) & 16 );
},
/**
* Moves the selection focus to this element.
* @function
* @param {Boolean} defer Whether to asynchronously defer the
* execution by 100 ms.
* @example
* var element = CKEDITOR.document.getById( 'myTextarea' );
* <b>element.focus()</b>;
*/
focus : ( function()
{
function exec()
{
// IE throws error if the element is not visible.
try
{
this.$.focus();
}
catch (e)
{}
}
return function( defer )
{
if ( defer )
CKEDITOR.tools.setTimeout( exec, 100, this );
else
exec.call( this );
};
})(),
/**
* Gets the inner HTML of this element.
* @returns {String} The inner HTML of this element.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div><b>Example</b></div>' );
* alert( <b>p.getHtml()</b> ); // "<b>Example</b>"
*/
getHtml : function()
{
var retval = this.$.innerHTML;
// Strip <?xml:namespace> tags in IE. (#3341).
return CKEDITOR.env.ie ? retval.replace( /<\?[^>]*>/g, '' ) : retval;
},
getOuterHtml : function()
{
if ( this.$.outerHTML )
{
// IE includes the <?xml:namespace> tag in the outerHTML of
// namespaced element. So, we must strip it here. (#3341)
return this.$.outerHTML.replace( /<\?[^>]*>/, '' );
}
var tmpDiv = this.$.ownerDocument.createElement( 'div' );
tmpDiv.appendChild( this.$.cloneNode( true ) );
return tmpDiv.innerHTML;
},
/**
* Sets the inner HTML of this element.
* @param {String} html The HTML to be set for this element.
* @returns {String} The inserted HTML.
* @example
* var p = new CKEDITOR.dom.element( 'p' );
* <b>p.setHtml( '<b>Inner</b> HTML' );</b>
*
* // result: "<p><b>Inner</b> HTML</p>"
*/
setHtml : function( html )
{
return ( this.$.innerHTML = html );
},
/**
* Sets the element contents as plain text.
* @param {String} text The text to be set.
* @returns {String} The inserted text.
* @example
* var element = new CKEDITOR.dom.element( 'div' );
* element.setText( 'A > B & C < D' );
* alert( element.innerHTML ); // "A &gt; B &amp; C &lt; D"
*/
setText : function( text )
{
CKEDITOR.dom.element.prototype.setText = ( this.$.innerText != undefined ) ?
function ( text )
{
return this.$.innerText = text;
} :
function ( text )
{
return this.$.textContent = text;
};
return this.setText( text );
},
/**
* Gets the value of an element attribute.
* @function
* @param {String} name The attribute name.
* @returns {String} The attribute value or null if not defined.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<input type="text" />' );
* alert( <b>element.getAttribute( 'type' )</b> ); // "text"
*/
getAttribute : (function()
{
var standard = function( name )
{
return this.$.getAttribute( name, 2 );
};
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )
{
return function( name )
{
switch ( name )
{
case 'class':
name = 'className';
break;
case 'http-equiv':
name = 'httpEquiv';
break;
case 'name':
return this.$.name;
case 'tabindex':
var tabIndex = standard.call( this, name );
// IE returns tabIndex=0 by default for all
// elements. For those elements,
// getAtrribute( 'tabindex', 2 ) returns 32768
// instead. So, we must make this check to give a
// uniform result among all browsers.
if ( tabIndex !== 0 && this.$.tabIndex === 0 )
tabIndex = null;
return tabIndex;
break;
case 'checked':
{
var attr = this.$.attributes.getNamedItem( name ),
attrValue = attr.specified ? attr.nodeValue // For value given by parser.
: this.$.checked; // For value created via DOM interface.
return attrValue ? 'checked' : null;
}
case 'hspace':
case 'value':
return this.$[ name ];
case 'style':
// IE does not return inline styles via getAttribute(). See #2947.
return this.$.style.cssText;
case 'contenteditable':
case 'contentEditable':
return this.$.attributes.getNamedItem( 'contentEditable' ).specified ?
this.$.getAttribute( 'contentEditable' ) : null;
}
return standard.call( this, name );
};
}
else
return standard;
})(),
getChildren : function()
{
return new CKEDITOR.dom.nodeList( this.$.childNodes );
},
/**
* Gets the current computed value of one of the element CSS style
* properties.
* @function
* @param {String} propertyName The style property name.
* @returns {String} The property value.
* @example
* var element = new CKEDITOR.dom.element( 'span' );
* alert( <b>element.getComputedStyle( 'display' )</b> ); // "inline"
*/
getComputedStyle :
CKEDITOR.env.ie ?
function( propertyName )
{
return this.$.currentStyle[ CKEDITOR.tools.cssStyleToDomStyle( propertyName ) ];
}
:
function( propertyName )
{
var style = this.getWindow().$.getComputedStyle( this.$, null );
// Firefox may return null if we call the above on a hidden iframe. (#9117)
return style ? style.getPropertyValue( propertyName ) : '';
},
/**
* Gets the DTD entries for this element.
* @returns {Object} An object containing the list of elements accepted
* by this element.
*/
getDtd : function()
{
var dtd = CKEDITOR.dtd[ this.getName() ];
this.getDtd = function()
{
return dtd;
};
return dtd;
},
getElementsByTag : CKEDITOR.dom.document.prototype.getElementsByTag,
/**
* Gets the computed tabindex for this element.
* @function
* @returns {Number} The tabindex value.
* @example
* var element = CKEDITOR.document.getById( 'myDiv' );
* alert( <b>element.getTabIndex()</b> ); // e.g. "-1"
*/
getTabIndex :
CKEDITOR.env.ie ?
function()
{
var tabIndex = this.$.tabIndex;
// IE returns tabIndex=0 by default for all elements. In
// those cases we must check that the element really has
// the tabindex attribute set to zero, or it is one of
// those element that should have zero by default.
if ( tabIndex === 0 && !CKEDITOR.dtd.$tabIndex[ this.getName() ] && parseInt( this.getAttribute( 'tabindex' ), 10 ) !== 0 )
tabIndex = -1;
return tabIndex;
}
: CKEDITOR.env.webkit ?
function()
{
var tabIndex = this.$.tabIndex;
// Safari returns "undefined" for elements that should not
// have tabindex (like a div). So, we must try to get it
// from the attribute.
// https://bugs.webkit.org/show_bug.cgi?id=20596
if ( tabIndex == undefined )
{
tabIndex = parseInt( this.getAttribute( 'tabindex' ), 10 );
// If the element don't have the tabindex attribute,
// then we should return -1.
if ( isNaN( tabIndex ) )
tabIndex = -1;
}
return tabIndex;
}
:
function()
{
return this.$.tabIndex;
},
/**
* Gets the text value of this element.
*
* Only in IE (which uses innerText), <br> will cause linebreaks,
* and sucessive whitespaces (including line breaks) will be reduced to
* a single space. This behavior is ok for us, for now. It may change
* in the future.
* @returns {String} The text value.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div>Sample <i>text</i>.</div>' );
* alert( <b>element.getText()</b> ); // "Sample text."
*/
getText : function()
{
return this.$.textContent || this.$.innerText || '';
},
/**
* Gets the window object that contains this element.
* @returns {CKEDITOR.dom.window} The window object.
* @example
*/
getWindow : function()
{
return this.getDocument().getWindow();
},
/**
* Gets the value of the "id" attribute of this element.
* @returns {String} The element id, or null if not available.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<p id="myId"></p>' );
* alert( <b>element.getId()</b> ); // "myId"
*/
getId : function()
{
return this.$.id || null;
},
/**
* Gets the value of the "name" attribute of this element.
* @returns {String} The element name, or null if not available.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<input name="myName"></input>' );
* alert( <b>element.getNameAtt()</b> ); // "myName"
*/
getNameAtt : function()
{
return this.$.name || null;
},
/**
* Gets the element name (tag name). The returned name is guaranteed to
* be always full lowercased.
* @returns {String} The element name.
* @example
* var element = new CKEDITOR.dom.element( 'span' );
* alert( <b>element.getName()</b> ); // "span"
*/
getName : function()
{
// Cache the lowercased name inside a closure.
var nodeName = this.$.nodeName.toLowerCase();
if ( CKEDITOR.env.ie && ! ( document.documentMode > 8 ) )
{
var scopeName = this.$.scopeName;
if ( scopeName != 'HTML' )
nodeName = scopeName.toLowerCase() + ':' + nodeName;
}
return (
this.getName = function()
{
return nodeName;
})();
},
/**
* Gets the value set to this element. This value is usually available
* for form field elements.
* @returns {String} The element value.
*/
getValue : function()
{
return this.$.value;
},
/**
* Gets the first child node of this element.
* @param {Function} evaluator Filtering the result node.
* @returns {CKEDITOR.dom.node} The first child node or null if not
* available.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div><b>Example</b></div>' );
* var first = <b>element.getFirst()</b>;
* alert( first.getName() ); // "b"
*/
getFirst : function( evaluator )
{
var first = this.$.firstChild,
retval = first && new CKEDITOR.dom.node( first );
if ( retval && evaluator && !evaluator( retval ) )
retval = retval.getNext( evaluator );
return retval;
},
/**
* @param {Function} evaluator Filtering the result node.
*/
getLast : function( evaluator )
{
var last = this.$.lastChild,
retval = last && new CKEDITOR.dom.node( last );
if ( retval && evaluator && !evaluator( retval ) )
retval = retval.getPrevious( evaluator );
return retval;
},
getStyle : function( name )
{
return this.$.style[ CKEDITOR.tools.cssStyleToDomStyle( name ) ];
},
/**
* Checks if the element name matches one or more names.
* @param {String} name[,name[,...]] One or more names to be checked.
* @returns {Boolean} true if the element name matches any of the names.
* @example
* var element = new CKEDITOR.element( 'span' );
* alert( <b>element.is( 'span' )</b> ); "true"
* alert( <b>element.is( 'p', 'span' )</b> ); "true"
* alert( <b>element.is( 'p' )</b> ); "false"
* alert( <b>element.is( 'p', 'div' )</b> ); "false"
*/
is : function()
{
var name = this.getName();
for ( var i = 0 ; i < arguments.length ; i++ )
{
if ( arguments[ i ] == name )
return true;
}
return false;
},
/**
* Decide whether one element is able to receive cursor.
* @param {Boolean} [textCursor=true] Only consider element that could receive text child.
*/
isEditable : function( textCursor )
{
var name = this.getName();
if ( this.isReadOnly()
|| this.getComputedStyle( 'display' ) == 'none'
|| this.getComputedStyle( 'visibility' ) == 'hidden'
|| this.is( 'a' ) && this.data( 'cke-saved-name' ) && !this.getChildCount()
|| CKEDITOR.dtd.$nonEditable[ name ]
|| CKEDITOR.dtd.$empty[ name ] )
{
return false;
}
if ( textCursor !== false )
{
// Get the element DTD (defaults to span for unknown elements).
var dtd = CKEDITOR.dtd[ name ] || CKEDITOR.dtd.span;
// In the DTD # == text node.
return ( dtd && dtd[ '#'] );
}
return true;
},
isIdentical : function( otherElement )
{
if ( this.getName() != otherElement.getName() )
return false;
var thisAttribs = this.$.attributes,
otherAttribs = otherElement.$.attributes;
var thisLength = thisAttribs.length,
otherLength = otherAttribs.length;
for ( var i = 0 ; i < thisLength ; i++ )
{
var attribute = thisAttribs[ i ];
if ( attribute.nodeName == '_moz_dirty' )
continue;
if ( ( !CKEDITOR.env.ie || ( attribute.specified && attribute.nodeName != 'data-cke-expando' ) ) && attribute.nodeValue != otherElement.getAttribute( attribute.nodeName ) )
return false;
}
// For IE, we have to for both elements, because it's difficult to
// know how the atttibutes collection is organized in its DOM.
if ( CKEDITOR.env.ie )
{
for ( i = 0 ; i < otherLength ; i++ )
{
attribute = otherAttribs[ i ];
if ( attribute.specified && attribute.nodeName != 'data-cke-expando'
&& attribute.nodeValue != this.getAttribute( attribute.nodeName ) )
return false;
}
}
return true;
},
/**
* Checks if this element is visible. May not work if the element is
* child of an element with visibility set to "hidden", but works well
* on the great majority of cases.
* @return {Boolean} True if the element is visible.
*/
isVisible : function()
{
var isVisible = ( this.$.offsetHeight || this.$.offsetWidth ) && this.getComputedStyle( 'visibility' ) != 'hidden',
elementWindow,
elementWindowFrame;
// Webkit and Opera report non-zero offsetHeight despite that
// element is inside an invisible iframe. (#4542)
if ( isVisible && ( CKEDITOR.env.webkit || CKEDITOR.env.opera ) )
{
elementWindow = this.getWindow();
if ( !elementWindow.equals( CKEDITOR.document.getWindow() )
&& ( elementWindowFrame = elementWindow.$.frameElement ) )
{
isVisible = new CKEDITOR.dom.element( elementWindowFrame ).isVisible();
}
}
return !!isVisible;
},
/**
* Whether it's an empty inline elements which has no visual impact when removed.
*/
isEmptyInlineRemoveable : function()
{
if ( !CKEDITOR.dtd.$removeEmpty[ this.getName() ] )
return false;
var children = this.getChildren();
for ( var i = 0, count = children.count(); i < count; i++ )
{
var child = children.getItem( i );
if ( child.type == CKEDITOR.NODE_ELEMENT && child.data( 'cke-bookmark' ) )
continue;
if ( child.type == CKEDITOR.NODE_ELEMENT && !child.isEmptyInlineRemoveable()
|| child.type == CKEDITOR.NODE_TEXT && CKEDITOR.tools.trim( child.getText() ) )
{
return false;
}
}
return true;
},
/**
* Checks if the element has any defined attributes.
* @function
* @returns {Boolean} True if the element has attributes.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div title="Test">Example</div>' );
* alert( <b>element.hasAttributes()</b> ); // "true"
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div>Example</div>' );
* alert( <b>element.hasAttributes()</b> ); // "false"
*/
hasAttributes :
CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) ?
function()
{
var attributes = this.$.attributes;
for ( var i = 0 ; i < attributes.length ; i++ )
{
var attribute = attributes[i];
switch ( attribute.nodeName )
{
case 'class' :
// IE has a strange bug. If calling removeAttribute('className'),
// the attributes collection will still contain the "class"
// attribute, which will be marked as "specified", even if the
// outerHTML of the element is not displaying the class attribute.
// Note : I was not able to reproduce it outside the editor,
// but I've faced it while working on the TC of #1391.
if ( this.getAttribute( 'class' ) )
return true;
// Attributes to be ignored.
case 'data-cke-expando' :
continue;
/*jsl:fallthru*/
default :
if ( attribute.specified )
return true;
}
}
return false;
}
:
function()
{
var attrs = this.$.attributes,
attrsNum = attrs.length;
// The _moz_dirty attribute might get into the element after pasting (#5455)
var execludeAttrs = { 'data-cke-expando' : 1, _moz_dirty : 1 };
return attrsNum > 0 &&
( attrsNum > 2 ||
!execludeAttrs[ attrs[0].nodeName ] ||
( attrsNum == 2 && !execludeAttrs[ attrs[1].nodeName ] ) );
},
/**
* Checks if the specified attribute is defined for this element.
* @returns {Boolean} True if the specified attribute is defined.
* @param {String} name The attribute name.
* @example
*/
hasAttribute : (function()
{
function standard( name )
{
var $attr = this.$.attributes.getNamedItem( name );
return !!( $attr && $attr.specified );
}
return ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 ) ?
function( name )
{
// On IE < 8 the name attribute cannot be retrieved
// right after the element creation and setting the
// name with setAttribute.
if ( name == 'name' )
return !!this.$.name;
return standard.call( this, name );
}
:
standard;
})(),
/**
* Hides this element (display:none).
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.hide()</b>;
*/
hide : function()
{
this.setStyle( 'display', 'none' );
},
moveChildren : function( target, toStart )
{
var $ = this.$;
target = target.$;
if ( $ == target )
return;
var child;
if ( toStart )
{
while ( ( child = $.lastChild ) )
target.insertBefore( $.removeChild( child ), target.firstChild );
}
else
{
while ( ( child = $.firstChild ) )
target.appendChild( $.removeChild( child ) );
}
},
/**
* Merges sibling elements that are identical to this one.<br>
* <br>
* Identical child elements are also merged. For example:<br>
* <b><i></i></b><b><i></i></b> => <b><i></i></b>
* @function
* @param {Boolean} [inlineOnly] Allow only inline elements to be merged. Defaults to "true".
*/
mergeSiblings : ( function()
{
function mergeElements( element, sibling, isNext )
{
if ( sibling && sibling.type == CKEDITOR.NODE_ELEMENT )
{
// Jumping over bookmark nodes and empty inline elements, e.g. <b><i></i></b>,
// queuing them to be moved later. (#5567)
var pendingNodes = [];
while ( sibling.data( 'cke-bookmark' )
|| sibling.isEmptyInlineRemoveable() )
{
pendingNodes.push( sibling );
sibling = isNext ? sibling.getNext() : sibling.getPrevious();
if ( !sibling || sibling.type != CKEDITOR.NODE_ELEMENT )
return;
}
if ( element.isIdentical( sibling ) )
{
// Save the last child to be checked too, to merge things like
// <b><i></i></b><b><i></i></b> => <b><i></i></b>
var innerSibling = isNext ? element.getLast() : element.getFirst();
// Move pending nodes first into the target element.
while( pendingNodes.length )
pendingNodes.shift().move( element, !isNext );
sibling.moveChildren( element, !isNext );
sibling.remove();
// Now check the last inner child (see two comments above).
if ( innerSibling && innerSibling.type == CKEDITOR.NODE_ELEMENT )
innerSibling.mergeSiblings();
}
}
}
return function( inlineOnly )
{
if ( ! ( inlineOnly === false
|| CKEDITOR.dtd.$removeEmpty[ this.getName() ]
|| this.is( 'a' ) ) ) // Merge empty links and anchors also. (#5567)
{
return;
}
mergeElements( this, this.getNext(), true );
mergeElements( this, this.getPrevious() );
};
} )(),
/**
* Shows this element (display it).
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.show()</b>;
*/
show : function()
{
this.setStyles(
{
display : '',
visibility : ''
});
},
/**
* Sets the value of an element attribute.
* @param {String} name The name of the attribute.
* @param {String} value The value to be set to the attribute.
* @function
* @returns {CKEDITOR.dom.element} This element instance.
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.setAttribute( 'class', 'myClass' )</b>;
* <b>element.setAttribute( 'title', 'This is an example' )</b>;
*/
setAttribute : (function()
{
var standard = function( name, value )
{
this.$.setAttribute( name, value );
return this;
};
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )
{
return function( name, value )
{
if ( name == 'class' )
this.$.className = value;
else if ( name == 'style' )
this.$.style.cssText = value;
else if ( name == 'tabindex' ) // Case sensitive.
this.$.tabIndex = value;
else if ( name == 'checked' )
this.$.checked = value;
else if ( name == 'contenteditable' )
standard.call( this, 'contentEditable', value );
else
standard.apply( this, arguments );
return this;
};
}
else if ( CKEDITOR.env.ie8Compat && CKEDITOR.env.secure )
{
return function( name, value )
{
// IE8 throws error when setting src attribute to non-ssl value. (#7847)
if ( name == 'src' && value.match( /^http:\/\// ) )
try { standard.apply( this, arguments ); } catch( e ){}
else
standard.apply( this, arguments );
return this;
};
}
else
return standard;
})(),
/**
* Sets the value of several element attributes.
* @param {Object} attributesPairs An object containing the names and
* values of the attributes.
* @returns {CKEDITOR.dom.element} This element instance.
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.setAttributes({
* 'class' : 'myClass',
* 'title' : 'This is an example' })</b>;
*/
setAttributes : function( attributesPairs )
{
for ( var name in attributesPairs )
this.setAttribute( name, attributesPairs[ name ] );
return this;
},
/**
* Sets the element value. This function is usually used with form
* field element.
* @param {String} value The element value.
* @returns {CKEDITOR.dom.element} This element instance.
*/
setValue : function( value )
{
this.$.value = value;
return this;
},
/**
* Removes an attribute from the element.
* @param {String} name The attribute name.
* @function
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div class="classA"></div>' );
* element.removeAttribute( 'class' );
*/
removeAttribute : (function()
{
var standard = function( name )
{
this.$.removeAttribute( name );
};
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )
{
return function( name )
{
if ( name == 'class' )
name = 'className';
else if ( name == 'tabindex' )
name = 'tabIndex';
else if ( name == 'contenteditable' )
name = 'contentEditable';
standard.call( this, name );
};
}
else
return standard;
})(),
removeAttributes : function ( attributes )
{
if ( CKEDITOR.tools.isArray( attributes ) )
{
for ( var i = 0 ; i < attributes.length ; i++ )
this.removeAttribute( attributes[ i ] );
}
else
{
for ( var attr in attributes )
attributes.hasOwnProperty( attr ) && this.removeAttribute( attr );
}
},
/**
* Removes a style from the element.
* @param {String} name The style name.
* @function
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<div style="display:none"></div>' );
* element.removeStyle( 'display' );
*/
removeStyle : function( name )
{
// Removes the specified property from the current style object.
var $ = this.$.style;
// "removeProperty" need to be specific on the following styles.
if ( !$.removeProperty && ( name == 'border' || name == 'margin' || name == 'padding' ) )
{
var names = expandedRules( name );
for ( var i = 0 ; i < names.length ; i++ )
this.removeStyle( names[ i ] );
return;
}
$.removeProperty ? $.removeProperty( name ) : $.removeAttribute( CKEDITOR.tools.cssStyleToDomStyle( name ) );
if ( !this.$.style.cssText )
this.removeAttribute( 'style' );
},
/**
* Sets the value of an element style.
* @param {String} name The name of the style. The CSS naming notation
* must be used (e.g. "background-color").
* @param {String} value The value to be set to the style.
* @returns {CKEDITOR.dom.element} This element instance.
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.setStyle( 'background-color', '#ff0000' )</b>;
* <b>element.setStyle( 'margin-top', '10px' )</b>;
* <b>element.setStyle( 'float', 'right' )</b>;
*/
setStyle : function( name, value )
{
this.$.style[ CKEDITOR.tools.cssStyleToDomStyle( name ) ] = value;
return this;
},
/**
* Sets the value of several element styles.
* @param {Object} stylesPairs An object containing the names and
* values of the styles.
* @returns {CKEDITOR.dom.element} This element instance.
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.setStyles({
* 'position' : 'absolute',
* 'float' : 'right' })</b>;
*/
setStyles : function( stylesPairs )
{
for ( var name in stylesPairs )
this.setStyle( name, stylesPairs[ name ] );
return this;
},
/**
* Sets the opacity of an element.
* @param {Number} opacity A number within the range [0.0, 1.0].
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* <b>element.setOpacity( 0.75 )</b>;
*/
setOpacity : function( opacity )
{
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 )
{
opacity = Math.round( opacity * 100 );
this.setStyle( 'filter', opacity >= 100 ? '' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')' );
}
else
this.setStyle( 'opacity', opacity );
},
/**
* Makes the element and its children unselectable.
* @function
* @example
* var element = CKEDITOR.dom.element.getById( 'myElement' );
* element.unselectable();
*/
unselectable :
CKEDITOR.env.gecko ?
function()
{
this.$.style.MozUserSelect = 'none';
this.on( 'dragstart', function( evt ) { evt.data.preventDefault(); } );
}
: CKEDITOR.env.webkit ?
function()
{
this.$.style.KhtmlUserSelect = 'none';
this.on( 'dragstart', function( evt ) { evt.data.preventDefault(); } );
}
:
function()
{
if ( CKEDITOR.env.ie || CKEDITOR.env.opera )
{
var element = this.$,
elements = element.getElementsByTagName("*"),
e,
i = 0;
element.unselectable = 'on';
while ( ( e = elements[ i++ ] ) )
{
switch ( e.tagName.toLowerCase() )
{
case 'iframe' :
case 'textarea' :
case 'input' :
case 'select' :
/* Ignore the above tags */
break;
default :
e.unselectable = 'on';
}
}
}
},
getPositionedAncestor : function()
{
var current = this;
while ( current.getName() != 'html' )
{
if ( current.getComputedStyle( 'position' ) != 'static' )
return current;
current = current.getParent();
}
return null;
},
getDocumentPosition : function( refDocument )
{
var x = 0, y = 0,
doc = this.getDocument(),
body = doc.getBody(),
quirks = doc.$.compatMode == 'BackCompat';
if ( document.documentElement[ "getBoundingClientRect" ] )
{
var box = this.$.getBoundingClientRect(),
$doc = doc.$,
$docElem = $doc.documentElement;
var clientTop = $docElem.clientTop || body.$.clientTop || 0,
clientLeft = $docElem.clientLeft || body.$.clientLeft || 0,
needAdjustScrollAndBorders = true;
/*
* #3804: getBoundingClientRect() works differently on IE and non-IE
* browsers, regarding scroll positions.
*
* On IE, the top position of the <html> element is always 0, no matter
* how much you scrolled down.
*
* On other browsers, the top position of the <html> element is negative
* scrollTop.
*/
if ( CKEDITOR.env.ie )
{
var inDocElem = doc.getDocumentElement().contains( this ),
inBody = doc.getBody().contains( this );
needAdjustScrollAndBorders = ( quirks && inBody ) || ( !quirks && inDocElem );
}
if ( needAdjustScrollAndBorders )
{
x = box.left + ( !quirks && $docElem.scrollLeft || body.$.scrollLeft );
x -= clientLeft;
y = box.top + ( !quirks && $docElem.scrollTop || body.$.scrollTop );
y -= clientTop;
}
}
else
{
var current = this, previous = null, offsetParent;
while ( current && !( current.getName() == 'body' || current.getName() == 'html' ) )
{
x += current.$.offsetLeft - current.$.scrollLeft;
y += current.$.offsetTop - current.$.scrollTop;
// Opera includes clientTop|Left into offsetTop|Left.
if ( !current.equals( this ) )
{
x += ( current.$.clientLeft || 0 );
y += ( current.$.clientTop || 0 );
}
var scrollElement = previous;
while ( scrollElement && !scrollElement.equals( current ) )
{
x -= scrollElement.$.scrollLeft;
y -= scrollElement.$.scrollTop;
scrollElement = scrollElement.getParent();
}
previous = current;
current = ( offsetParent = current.$.offsetParent ) ?
new CKEDITOR.dom.element( offsetParent ) : null;
}
}
if ( refDocument )
{
var currentWindow = this.getWindow(),
refWindow = refDocument.getWindow();
if ( !currentWindow.equals( refWindow ) && currentWindow.$.frameElement )
{
var iframePosition = ( new CKEDITOR.dom.element( currentWindow.$.frameElement ) ).getDocumentPosition( refDocument );
x += iframePosition.x;
y += iframePosition.y;
}
}
if ( !document.documentElement[ "getBoundingClientRect" ] )
{
// In Firefox, we'll endup one pixel before the element positions,
// so we must add it here.
if ( CKEDITOR.env.gecko && !quirks )
{
x += this.$.clientLeft ? 1 : 0;
y += this.$.clientTop ? 1 : 0;
}
}
return { x : x, y : y };
},
/**
* Make any page element visible inside the browser viewport.
* @param {Boolean} [alignToTop]
*/
scrollIntoView : function( alignToTop )
{
var parent = this.getParent();
if ( !parent ) return;
// Scroll the element into parent container from the inner out.
do
{
// Check ancestors that overflows.
var overflowed =
parent.$.clientWidth && parent.$.clientWidth < parent.$.scrollWidth
|| parent.$.clientHeight && parent.$.clientHeight < parent.$.scrollHeight;
if ( overflowed )
this.scrollIntoParent( parent, alignToTop, 1 );
// Walk across the frame.
if ( parent.is( 'html' ) )
{
var win = parent.getWindow();
// Avoid security error.
try
{
var iframe = win.$.frameElement;
iframe && ( parent = new CKEDITOR.dom.element( iframe ) );
}
catch(er){}
}
}
while ( ( parent = parent.getParent() ) );
},
/**
* Make any page element visible inside one of the ancestors by scrolling the parent.
* @param {CKEDITOR.dom.element|CKEDITOR.dom.window} parent The container to scroll into.
* @param {Boolean} [alignToTop] Align the element's top side with the container's
* when <code>true</code> is specified; align the bottom with viewport bottom when
* <code>false</code> is specified. Otherwise scroll on either side with the minimum
* amount to show the element.
* @param {Boolean} [hscroll] Whether horizontal overflow should be considered.
*/
scrollIntoParent : function( parent, alignToTop, hscroll )
{
!parent && ( parent = this.getWindow() );
var doc = parent.getDocument();
var isQuirks = doc.$.compatMode == 'BackCompat';
// On window <html> is scrolled while quirks scrolls <body>.
if ( parent instanceof CKEDITOR.dom.window )
parent = isQuirks ? doc.getBody() : doc.getDocumentElement();
// Scroll the parent by the specified amount.
function scrollBy( x, y )
{
// Webkit doesn't support "scrollTop/scrollLeft"
// on documentElement/body element.
if ( /body|html/.test( parent.getName() ) )
parent.getWindow().$.scrollBy( x, y );
else
{
parent.$[ 'scrollLeft' ] += x;
parent.$[ 'scrollTop' ] += y;
}
}
// Figure out the element position relative to the specified window.
function screenPos( element, refWin )
{
var pos = { x: 0, y: 0 };
if ( !( element.is( isQuirks ? 'body' : 'html' ) ) )
{
var box = element.$.getBoundingClientRect();
pos.x = box.left, pos.y = box.top;
}
var win = element.getWindow();
if ( !win.equals( refWin ) )
{
var outerPos = screenPos( CKEDITOR.dom.element.get( win.$.frameElement ), refWin );
pos.x += outerPos.x, pos.y += outerPos.y;
}
return pos;
}
// calculated margin size.
function margin( element, side )
{
return parseInt( element.getComputedStyle( 'margin-' + side ) || 0, 10 ) || 0;
}
var win = parent.getWindow();
var thisPos = screenPos( this, win ),
parentPos = screenPos( parent, win ),
eh = this.$.offsetHeight,
ew = this.$.offsetWidth,
ch = parent.$.clientHeight,
cw = parent.$.clientWidth,
lt,
br;
// Left-top margins.
lt =
{
x : thisPos.x - margin( this, 'left' ) - parentPos.x || 0,
y : thisPos.y - margin( this, 'top' ) - parentPos.y|| 0
};
// Bottom-right margins.
br =
{
x : thisPos.x + ew + margin( this, 'right' ) - ( ( parentPos.x ) + cw ) || 0,
y : thisPos.y + eh + margin( this, 'bottom' ) - ( ( parentPos.y ) + ch ) || 0
};
// 1. Do the specified alignment as much as possible;
// 2. Otherwise be smart to scroll only the minimum amount;
// 3. Never cut at the top;
// 4. DO NOT scroll when already visible.
if ( lt.y < 0 || br.y > 0 )
{
scrollBy( 0,
alignToTop === true ? lt.y :
alignToTop === false ? br.y :
lt.y < 0 ? lt.y : br.y );
}
if ( hscroll && ( lt.x < 0 || br.x > 0 ) )
scrollBy( lt.x < 0 ? lt.x : br.x, 0 );
},
setState : function( state )
{
switch ( state )
{
case CKEDITOR.TRISTATE_ON :
this.addClass( 'cke_on' );
this.removeClass( 'cke_off' );
this.removeClass( 'cke_disabled' );
break;
case CKEDITOR.TRISTATE_DISABLED :
this.addClass( 'cke_disabled' );
this.removeClass( 'cke_off' );
this.removeClass( 'cke_on' );
break;
default :
this.addClass( 'cke_off' );
this.removeClass( 'cke_on' );
this.removeClass( 'cke_disabled' );
break;
}
},
/**
* Returns the inner document of this IFRAME element.
* @returns {CKEDITOR.dom.document} The inner document.
*/
getFrameDocument : function()
{
var $ = this.$;
try
{
// In IE, with custom document.domain, it may happen that
// the iframe is not yet available, resulting in "Access
// Denied" for the following property access.
$.contentWindow.document;
}
catch ( e )
{
// Trick to solve this issue, forcing the iframe to get ready
// by simply setting its "src" property.
$.src = $.src;
// In IE6 though, the above is not enough, so we must pause the
// execution for a while, giving it time to think.
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 )
{
window.showModalDialog(
'javascript:document.write("' +
'<script>' +
'window.setTimeout(' +
'function(){window.close();}' +
',50);' +
'</script>")' );
}
}
return $ && new CKEDITOR.dom.document( $.contentWindow.document );
},
/**
* Copy all the attributes from one node to the other, kinda like a clone
* skipAttributes is an object with the attributes that must NOT be copied.
* @param {CKEDITOR.dom.element} dest The destination element.
* @param {Object} skipAttributes A dictionary of attributes to skip.
* @example
*/
copyAttributes : function( dest, skipAttributes )
{
var attributes = this.$.attributes;
skipAttributes = skipAttributes || {};
for ( var n = 0 ; n < attributes.length ; n++ )
{
var attribute = attributes[n];
// Lowercase attribute name hard rule is broken for
// some attribute on IE, e.g. CHECKED.
var attrName = attribute.nodeName.toLowerCase(),
attrValue;
// We can set the type only once, so do it with the proper value, not copying it.
if ( attrName in skipAttributes )
continue;
if ( attrName == 'checked' && ( attrValue = this.getAttribute( attrName ) ) )
dest.setAttribute( attrName, attrValue );
// IE BUG: value attribute is never specified even if it exists.
else if ( attribute.specified ||
( CKEDITOR.env.ie && attribute.nodeValue && attrName == 'value' ) )
{
attrValue = this.getAttribute( attrName );
if ( attrValue === null )
attrValue = attribute.nodeValue;
dest.setAttribute( attrName, attrValue );
}
}
// The style:
if ( this.$.style.cssText !== '' )
dest.$.style.cssText = this.$.style.cssText;
},
/**
* Changes the tag name of the current element.
* @param {String} newTag The new tag for the element.
*/
renameNode : function( newTag )
{
// If it's already correct exit here.
if ( this.getName() == newTag )
return;
var doc = this.getDocument();
// Create the new node.
var newNode = new CKEDITOR.dom.element( newTag, doc );
// Copy all attributes.
this.copyAttributes( newNode );
// Move children to the new node.
this.moveChildren( newNode );
// Replace the node.
this.getParent() && this.$.parentNode.replaceChild( newNode.$, this.$ );
newNode.$[ 'data-cke-expando' ] = this.$[ 'data-cke-expando' ];
this.$ = newNode.$;
},
/**
* Gets a DOM tree descendant under the current node.
* @param {Array|Number} indices The child index or array of child indices under the node.
* @returns {CKEDITOR.dom.node} The specified DOM child under the current node. Null if child does not exist.
* @example
* var strong = p.getChild(0);
*/
getChild : function( indices )
{
var rawNode = this.$;
if ( !indices.slice )
rawNode = rawNode.childNodes[ indices ];
else
{
while ( indices.length > 0 && rawNode )
rawNode = rawNode.childNodes[ indices.shift() ];
}
return rawNode ? new CKEDITOR.dom.node( rawNode ) : null;
},
getChildCount : function()
{
return this.$.childNodes.length;
},
disableContextMenu : function()
{
this.on( 'contextmenu', function( event )
{
// Cancel the browser context menu.
if ( !event.data.getTarget().hasClass( 'cke_enable_context_menu' ) )
event.data.preventDefault();
} );
},
/**
* Gets element's direction. Supports both CSS 'direction' prop and 'dir' attr.
*/
getDirection : function( useComputed )
{
return useComputed ?
this.getComputedStyle( 'direction' )
// Webkit: offline element returns empty direction (#8053).
|| this.getDirection()
|| this.getDocument().$.dir
|| this.getDocument().getBody().getDirection( 1 )
: this.getStyle( 'direction' ) || this.getAttribute( 'dir' );
},
/**
* Gets, sets and removes custom data to be stored as HTML5 data-* attributes.
* @param {String} name The name of the attribute, excluding the 'data-' part.
* @param {String} [value] The value to set. If set to false, the attribute will be removed.
* @example
* element.data( 'extra-info', 'test' ); // appended the attribute data-extra-info="test" to the element
* alert( element.data( 'extra-info' ) ); // "test"
* element.data( 'extra-info', false ); // remove the data-extra-info attribute from the element
*/
data : function ( name, value )
{
name = 'data-' + name;
if ( value === undefined )
return this.getAttribute( name );
else if ( value === false )
this.removeAttribute( name );
else
this.setAttribute( name, value );
return null;
}
});
var sides = {
width : [ "border-left-width", "border-right-width","padding-left", "padding-right" ],
height : [ "border-top-width", "border-bottom-width", "padding-top", "padding-bottom" ]
};
// Generate list of specific style rules, applicable to margin/padding/border.
function expandedRules( style )
{
var sides = [ 'top', 'left', 'right', 'bottom' ], components;
if ( style == 'border' )
components = [ 'color', 'style', 'width' ];
var styles = [];
for ( var i = 0 ; i < sides.length ; i++ )
{
if ( components )
{
for ( var j = 0 ; j < components.length ; j++ )
styles.push( [ style, sides[ i ], components[j] ].join( '-' ) );
}
else
styles.push( [ style, sides[ i ] ].join( '-' ) );
}
return styles;
}
function marginAndPaddingSize( type )
{
var adjustment = 0;
for ( var i = 0, len = sides[ type ].length; i < len; i++ )
adjustment += parseInt( this.getComputedStyle( sides [ type ][ i ] ) || 0, 10 ) || 0;
return adjustment;
}
/**
* Sets the element size considering the box model.
* @name CKEDITOR.dom.element.prototype.setSize
* @function
* @param {String} type The dimension to set. It accepts "width" and "height".
* @param {Number} size The length unit in px.
* @param {Boolean} isBorderBox Apply the size based on the border box model.
*/
CKEDITOR.dom.element.prototype.setSize = function( type, size, isBorderBox )
{
if ( typeof size == 'number' )
{
if ( isBorderBox && !( CKEDITOR.env.ie && CKEDITOR.env.quirks ) )
size -= marginAndPaddingSize.call( this, type );
this.setStyle( type, size + 'px' );
}
};
/**
* Gets the element size, possibly considering the box model.
* @name CKEDITOR.dom.element.prototype.getSize
* @function
* @param {String} type The dimension to get. It accepts "width" and "height".
* @param {Boolean} isBorderBox Get the size based on the border box model.
*/
CKEDITOR.dom.element.prototype.getSize = function( type, isBorderBox )
{
var size = Math.max( this.$[ 'offset' + CKEDITOR.tools.capitalize( type ) ],
this.$[ 'client' + CKEDITOR.tools.capitalize( type ) ] ) || 0;
if ( isBorderBox )
size -= marginAndPaddingSize.call( this, type );
return size;
};
})();
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
/**
* Represents a list os CKEDITOR.dom.range objects, which can be easily
* iterated sequentially.
* @constructor
* @param {CKEDITOR.dom.range|Array} [ranges] The ranges contained on this list.
* Note that, if an array of ranges is specified, the range sequence
* should match its DOM order. This class will not help to sort them.
*/
CKEDITOR.dom.rangeList = function( ranges )
{
if ( ranges instanceof CKEDITOR.dom.rangeList )
return ranges;
if ( !ranges )
ranges = [];
else if ( ranges instanceof CKEDITOR.dom.range )
ranges = [ ranges ];
return CKEDITOR.tools.extend( ranges, mixins );
};
var mixins =
/** @lends CKEDITOR.dom.rangeList.prototype */
{
/**
* Creates an instance of the rangeList iterator, it should be used
* only when the ranges processing could be DOM intrusive, which
* means it may pollute and break other ranges in this list.
* Otherwise, it's enough to just iterate over this array in a for loop.
* @returns {CKEDITOR.dom.rangeListIterator}
*/
createIterator : function()
{
var rangeList = this,
bookmark = CKEDITOR.dom.walker.bookmark(),
guard = function( node ) { return ! ( node.is && node.is( 'tr' ) ); },
bookmarks = [],
current;
/**
* @lends CKEDITOR.dom.rangeListIterator.prototype
*/
return {
/**
* Retrieves the next range in the list.
* @param {Boolean} mergeConsequent Whether join two adjacent ranges into single, e.g. consequent table cells.
*/
getNextRange : function( mergeConsequent )
{
current = current == undefined ? 0 : current + 1;
var range = rangeList[ current ];
// Multiple ranges might be mangled by each other.
if ( range && rangeList.length > 1 )
{
// Bookmarking all other ranges on the first iteration,
// the range correctness after it doesn't matter since we'll
// restore them before the next iteration.
if ( !current )
{
// Make sure bookmark correctness by reverse processing.
for ( var i = rangeList.length - 1; i >= 0; i-- )
bookmarks.unshift( rangeList[ i ].createBookmark( true ) );
}
if ( mergeConsequent )
{
// Figure out how many ranges should be merged.
var mergeCount = 0;
while ( rangeList[ current + mergeCount + 1 ] )
{
var doc = range.document,
found = 0,
left = doc.getById( bookmarks[ mergeCount ].endNode ),
right = doc.getById( bookmarks[ mergeCount + 1 ].startNode ),
next;
// Check subsequent range.
while ( 1 )
{
next = left.getNextSourceNode( false );
if ( !right.equals( next ) )
{
// This could be yet another bookmark or
// walking across block boundaries.
if ( bookmark( next ) || ( next.type == CKEDITOR.NODE_ELEMENT && next.isBlockBoundary() ) )
{
left = next;
continue;
}
}
else
found = 1;
break;
}
if ( !found )
break;
mergeCount++;
}
}
range.moveToBookmark( bookmarks.shift() );
// Merge ranges finally after moving to bookmarks.
while( mergeCount-- )
{
next = rangeList[ ++current ];
next.moveToBookmark( bookmarks.shift() );
range.setEnd( next.endContainer, next.endOffset );
}
}
return range;
}
};
},
createBookmarks : function( serializable )
{
var retval = [], bookmark;
for ( var i = 0; i < this.length ; i++ )
{
retval.push( bookmark = this[ i ].createBookmark( serializable, true) );
// Updating the container & offset values for ranges
// that have been touched.
for ( var j = i + 1; j < this.length; j++ )
{
this[ j ] = updateDirtyRange( bookmark, this[ j ] );
this[ j ] = updateDirtyRange( bookmark, this[ j ], true );
}
}
return retval;
},
createBookmarks2 : function( normalized )
{
var bookmarks = [];
for ( var i = 0 ; i < this.length ; i++ )
bookmarks.push( this[ i ].createBookmark2( normalized ) );
return bookmarks;
},
/**
* Move each range in the list to the position specified by a list of bookmarks.
* @param {Array} bookmarks The list of bookmarks, each one matching a range in the list.
*/
moveToBookmarks : function( bookmarks )
{
for ( var i = 0 ; i < this.length ; i++ )
this[ i ].moveToBookmark( bookmarks[ i ] );
}
};
// Update the specified range which has been mangled by previous insertion of
// range bookmark nodes.(#3256)
function updateDirtyRange( bookmark, dirtyRange, checkEnd )
{
var serializable = bookmark.serializable,
container = dirtyRange[ checkEnd ? 'endContainer' : 'startContainer' ],
offset = checkEnd ? 'endOffset' : 'startOffset';
var bookmarkStart = serializable ?
dirtyRange.document.getById( bookmark.startNode )
: bookmark.startNode;
var bookmarkEnd = serializable ?
dirtyRange.document.getById( bookmark.endNode )
: bookmark.endNode;
if ( container.equals( bookmarkStart.getPrevious() ) )
{
dirtyRange.startOffset = dirtyRange.startOffset
- container.getLength()
- bookmarkEnd.getPrevious().getLength();
container = bookmarkEnd.getNext();
}
else if ( container.equals( bookmarkEnd.getPrevious() ) )
{
dirtyRange.startOffset = dirtyRange.startOffset - container.getLength();
container = bookmarkEnd.getNext();
}
container.equals( bookmarkStart.getParent() ) && dirtyRange[ offset ]++;
container.equals( bookmarkEnd.getParent() ) && dirtyRange[ offset ]++;
// Update and return this range.
dirtyRange[ checkEnd ? 'endContainer' : 'startContainer' ] = container;
return dirtyRange;
}
})();
/**
* (Virtual Class) Do not call this constructor. This class is not really part
* of the API. It just describes the return type of {@link CKEDITOR.dom.rangeList#createIterator}.
* @name CKEDITOR.dom.rangeListIterator
* @constructor
* @example
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
// Elements that may be considered the "Block boundary" in an element path.
var pathBlockElements = { address:1,blockquote:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,li:1,dt:1,dd:1, legend:1,caption:1 };
// Elements that may be considered the "Block limit" in an element path.
var pathBlockLimitElements = { body:1,div:1,table:1,tbody:1,tr:1,td:1,th:1,form:1,fieldset:1 };
// Check if an element contains any block element.
var checkHasBlock = function( element )
{
var childNodes = element.getChildren();
for ( var i = 0, count = childNodes.count() ; i < count ; i++ )
{
var child = childNodes.getItem( i );
if ( child.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$block[ child.getName() ] )
return true;
}
return false;
};
/**
* @class
*/
CKEDITOR.dom.elementPath = function( lastNode )
{
var block = null;
var blockLimit = null;
var elements = [];
var e = lastNode;
while ( e )
{
if ( e.type == CKEDITOR.NODE_ELEMENT )
{
if ( !this.lastElement )
this.lastElement = e;
var elementName = e.getName();
if ( !blockLimit )
{
if ( !block && pathBlockElements[ elementName ] )
block = e;
if ( pathBlockLimitElements[ elementName ] )
{
// DIV is considered the Block, if no block is available (#525)
// and if it doesn't contain other blocks.
if ( !block && elementName == 'div' && !checkHasBlock( e ) )
block = e;
else
blockLimit = e;
}
}
elements.push( e );
if ( elementName == 'body' )
break;
}
e = e.getParent();
}
this.block = block;
this.blockLimit = blockLimit;
this.elements = elements;
};
})();
CKEDITOR.dom.elementPath.prototype =
{
/**
* Compares this element path with another one.
* @param {CKEDITOR.dom.elementPath} otherPath The elementPath object to be
* compared with this one.
* @returns {Boolean} "true" if the paths are equal, containing the same
* number of elements and the same elements in the same order.
*/
compare : function( otherPath )
{
var thisElements = this.elements;
var otherElements = otherPath && otherPath.elements;
if ( !otherElements || thisElements.length != otherElements.length )
return false;
for ( var i = 0 ; i < thisElements.length ; i++ )
{
if ( !thisElements[ i ].equals( otherElements[ i ] ) )
return false;
}
return true;
},
contains : function( tagNames )
{
var elements = this.elements;
for ( var i = 0 ; i < elements.length ; i++ )
{
if ( elements[ i ].getName() in tagNames )
return elements[ i ];
}
return null;
}
};
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.event} class, which
* represents the a native DOM event object.
*/
/**
* Represents a native DOM event object.
* @constructor
* @param {Object} domEvent A native DOM event object.
* @example
*/
CKEDITOR.dom.event = function( domEvent )
{
/**
* The native DOM event object represented by this class instance.
* @type Object
* @example
*/
this.$ = domEvent;
};
CKEDITOR.dom.event.prototype =
{
/**
* Gets the key code associated to the event.
* @returns {Number} The key code.
* @example
* alert( event.getKey() ); "65" is "a" has been pressed
*/
getKey : function()
{
return this.$.keyCode || this.$.which;
},
/**
* Gets a number represeting the combination of the keys pressed during the
* event. It is the sum with the current key code and the {@link CKEDITOR.CTRL},
* {@link CKEDITOR.SHIFT} and {@link CKEDITOR.ALT} constants.
* @returns {Number} The number representing the keys combination.
* @example
* alert( event.getKeystroke() == 65 ); // "a" key
* alert( event.getKeystroke() == CKEDITOR.CTRL + 65 ); // CTRL + "a" key
* alert( event.getKeystroke() == CKEDITOR.CTRL + CKEDITOR.SHIFT + 65 ); // CTRL + SHIFT + "a" key
*/
getKeystroke : function()
{
var keystroke = this.getKey();
if ( this.$.ctrlKey || this.$.metaKey )
keystroke += CKEDITOR.CTRL;
if ( this.$.shiftKey )
keystroke += CKEDITOR.SHIFT;
if ( this.$.altKey )
keystroke += CKEDITOR.ALT;
return keystroke;
},
/**
* Prevents the original behavior of the event to happen. It can optionally
* stop propagating the event in the event chain.
* @param {Boolean} [stopPropagation] Stop propagating this event in the
* event chain.
* @example
* var element = CKEDITOR.document.getById( 'myElement' );
* element.on( 'click', function( ev )
* {
* // The DOM event object is passed by the "data" property.
* var domEvent = ev.data;
* // Prevent the click to chave any effect in the element.
* domEvent.preventDefault();
* });
*/
preventDefault : function( stopPropagation )
{
var $ = this.$;
if ( $.preventDefault )
$.preventDefault();
else
$.returnValue = false;
if ( stopPropagation )
this.stopPropagation();
},
stopPropagation : function()
{
var $ = this.$;
if ( $.stopPropagation )
$.stopPropagation();
else
$.cancelBubble = true;
},
/**
* Returns the DOM node where the event was targeted to.
* @returns {CKEDITOR.dom.node} The target DOM node.
* @example
* var element = CKEDITOR.document.getById( 'myElement' );
* element.on( 'click', function( ev )
* {
* // The DOM event object is passed by the "data" property.
* var domEvent = ev.data;
* // Add a CSS class to the event target.
* domEvent.getTarget().addClass( 'clicked' );
* });
*/
getTarget : function()
{
var rawNode = this.$.target || this.$.srcElement;
return rawNode ? new CKEDITOR.dom.node( rawNode ) : null;
},
/**
* Retrieves the coordinates of the mouse pointer relative to the top-left
* corner of the document, in mouse related event.
* @returns {Object} The object contains the position.
* @example
* element.on( 'mousemouse', function( ev )
* {
* var pageOffset = ev.data.getPageOffset();
* alert( pageOffset.x ); // page offset X
* alert( pageOffset.y ); // page offset Y
* });
*/
getPageOffset : function()
{
var doc = this.getTarget().getDocument().$;
var pageX = this.$.pageX || this.$.clientX + ( doc.documentElement.scrollLeft || doc.body.scrollLeft );
var pageY = this.$.pageY || this.$.clientY + ( doc.documentElement.scrollTop || doc.body.scrollTop );
return { x : pageX, y : pageY };
}
};
// For the followind constants, we need to go over the Unicode boundaries
// (0x10FFFF) to avoid collision.
/**
* CTRL key (0x110000).
* @constant
* @example
*/
CKEDITOR.CTRL = 0x110000;
/**
* SHIFT key (0x220000).
* @constant
* @example
*/
CKEDITOR.SHIFT = 0x220000;
/**
* ALT key (0x440000).
* @constant
* @example
*/
CKEDITOR.ALT = 0x440000;
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.resourceManager} class, which is
* the base for resource managers, like plugins and themes.
*/
/**
* Base class for resource managers, like plugins and themes. This class is not
* intended to be used out of the CKEditor core code.
* @param {String} basePath The path for the resources folder.
* @param {String} fileName The name used for resource files.
* @namespace
* @example
*/
CKEDITOR.resourceManager = function( basePath, fileName )
{
/**
* The base directory containing all resources.
* @name CKEDITOR.resourceManager.prototype.basePath
* @type String
* @example
*/
this.basePath = basePath;
/**
* The name used for resource files.
* @name CKEDITOR.resourceManager.prototype.fileName
* @type String
* @example
*/
this.fileName = fileName;
/**
* Contains references to all resources that have already been registered
* with {@link #add}.
* @name CKEDITOR.resourceManager.prototype.registered
* @type Object
* @example
*/
this.registered = {};
/**
* Contains references to all resources that have already been loaded
* with {@link #load}.
* @name CKEDITOR.resourceManager.prototype.loaded
* @type Object
* @example
*/
this.loaded = {};
/**
* Contains references to all resources that have already been registered
* with {@link #addExternal}.
* @name CKEDITOR.resourceManager.prototype.externals
* @type Object
* @example
*/
this.externals = {};
/**
* @private
*/
this._ =
{
// List of callbacks waiting for plugins to be loaded.
waitingList : {}
};
};
CKEDITOR.resourceManager.prototype =
{
/**
* Registers a resource.
* @param {String} name The resource name.
* @param {Object} [definition] The resource definition.
* @example
* CKEDITOR.plugins.add( 'sample', { ... plugin definition ... } );
* @see CKEDITOR.pluginDefinition
*/
add : function( name, definition )
{
if ( this.registered[ name ] )
throw '[CKEDITOR.resourceManager.add] The resource name "' + name + '" is already registered.';
CKEDITOR.fire( name + CKEDITOR.tools.capitalize( this.fileName ) + 'Ready',
this.registered[ name ] = definition || {} );
},
/**
* Gets the definition of a specific resource.
* @param {String} name The resource name.
* @type Object
* @example
* var definition = <b>CKEDITOR.plugins.get( 'sample' )</b>;
*/
get : function( name )
{
return this.registered[ name ] || null;
},
/**
* Get the folder path for a specific loaded resource.
* @param {String} name The resource name.
* @type String
* @example
* alert( <b>CKEDITOR.plugins.getPath( 'sample' )</b> ); // "<editor path>/plugins/sample/"
*/
getPath : function( name )
{
var external = this.externals[ name ];
return CKEDITOR.getUrl( ( external && external.dir ) || this.basePath + name + '/' );
},
/**
* Get the file path for a specific loaded resource.
* @param {String} name The resource name.
* @type String
* @example
* alert( <b>CKEDITOR.plugins.getFilePath( 'sample' )</b> ); // "<editor path>/plugins/sample/plugin.js"
*/
getFilePath : function( name )
{
var external = this.externals[ name ];
return CKEDITOR.getUrl(
this.getPath( name ) +
( ( external && ( typeof external.file == 'string' ) ) ? external.file : this.fileName + '.js' ) );
},
/**
* Registers one or more resources to be loaded from an external path
* instead of the core base path.
* @param {String} names The resource names, separated by commas.
* @param {String} path The path of the folder containing the resource.
* @param {String} [fileName] The resource file name. If not provided, the
* default name is used; If provided with a empty string, will implicitly indicates that {@param path}
* is already the full path.
* @example
* // Loads a plugin from '/myplugin/samples/plugin.js'.
* CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/' );
* @example
* // Loads a plugin from '/myplugin/samples/my_plugin.js'.
* CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/', 'my_plugin.js' );
* @example
* // Loads a plugin from '/myplugin/samples/my_plugin.js'.
* CKEDITOR.plugins.addExternal( 'sample', '/myplugins/sample/my_plugin.js', '' );
*/
addExternal : function( names, path, fileName )
{
names = names.split( ',' );
for ( var i = 0 ; i < names.length ; i++ )
{
var name = names[ i ];
this.externals[ name ] =
{
dir : path,
file : fileName
};
}
},
/**
* Loads one or more resources.
* @param {String|Array} name The name of the resource to load. It may be a
* string with a single resource name, or an array with several names.
* @param {Function} callback A function to be called when all resources
* are loaded. The callback will receive an array containing all
* loaded names.
* @param {Object} [scope] The scope object to be used for the callback
* call.
* @example
* <b>CKEDITOR.plugins.load</b>( 'myplugin', function( plugins )
* {
* alert( plugins['myplugin'] ); // "object"
* });
*/
load : function( names, callback, scope )
{
// Ensure that we have an array of names.
if ( !CKEDITOR.tools.isArray( names ) )
names = names ? [ names ] : [];
var loaded = this.loaded,
registered = this.registered,
urls = [],
urlsNames = {},
resources = {};
// Loop through all names.
for ( var i = 0 ; i < names.length ; i++ )
{
var name = names[ i ];
if ( !name )
continue;
// If not available yet.
if ( !loaded[ name ] && !registered[ name ] )
{
var url = this.getFilePath( name );
urls.push( url );
if ( !( url in urlsNames ) )
urlsNames[ url ] = [];
urlsNames[ url ].push( name );
}
else
resources[ name ] = this.get( name );
}
CKEDITOR.scriptLoader.load( urls, function( completed, failed )
{
if ( failed.length )
{
throw '[CKEDITOR.resourceManager.load] Resource name "' + urlsNames[ failed[ 0 ] ].join( ',' )
+ '" was not found at "' + failed[ 0 ] + '".';
}
for ( var i = 0 ; i < completed.length ; i++ )
{
var nameList = urlsNames[ completed[ i ] ];
for ( var j = 0 ; j < nameList.length ; j++ )
{
var name = nameList[ j ];
resources[ name ] = this.get( name );
loaded[ name ] = 1;
}
}
callback.call( scope, resources );
}
, this);
}
};
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.editor} class, which represents an
* editor instance.
*/
(function()
{
// The counter for automatic instance names.
var nameCounter = 0;
var getNewName = function()
{
var name = 'editor' + ( ++nameCounter );
return ( CKEDITOR.instances && CKEDITOR.instances[ name ] ) ? getNewName() : name;
};
// ##### START: Config Privates
// These function loads custom configuration files and cache the
// CKEDITOR.editorConfig functions defined on them, so there is no need to
// download them more than once for several instances.
var loadConfigLoaded = {};
var loadConfig = function( editor )
{
var customConfig = editor.config.customConfig;
// Check if there is a custom config to load.
if ( !customConfig )
return false;
customConfig = CKEDITOR.getUrl( customConfig );
var loadedConfig = loadConfigLoaded[ customConfig ] || ( loadConfigLoaded[ customConfig ] = {} );
// If the custom config has already been downloaded, reuse it.
if ( loadedConfig.fn )
{
// Call the cached CKEDITOR.editorConfig defined in the custom
// config file for the editor instance depending on it.
loadedConfig.fn.call( editor, editor.config );
// If there is no other customConfig in the chain, fire the
// "configLoaded" event.
if ( CKEDITOR.getUrl( editor.config.customConfig ) == customConfig || !loadConfig( editor ) )
editor.fireOnce( 'customConfigLoaded' );
}
else
{
// Load the custom configuration file.
CKEDITOR.scriptLoader.load( customConfig, function()
{
// If the CKEDITOR.editorConfig function has been properly
// defined in the custom configuration file, cache it.
if ( CKEDITOR.editorConfig )
loadedConfig.fn = CKEDITOR.editorConfig;
else
loadedConfig.fn = function(){};
// Call the load config again. This time the custom
// config is already cached and so it will get loaded.
loadConfig( editor );
});
}
return true;
};
var initConfig = function( editor, instanceConfig )
{
// Setup the lister for the "customConfigLoaded" event.
editor.on( 'customConfigLoaded', function()
{
if ( instanceConfig )
{
// Register the events that may have been set at the instance
// configuration object.
if ( instanceConfig.on )
{
for ( var eventName in instanceConfig.on )
{
editor.on( eventName, instanceConfig.on[ eventName ] );
}
}
// Overwrite the settings from the in-page config.
CKEDITOR.tools.extend( editor.config, instanceConfig, true );
delete editor.config.on;
}
onConfigLoaded( editor );
});
// The instance config may override the customConfig setting to avoid
// loading the default ~/config.js file.
if ( instanceConfig && instanceConfig.customConfig != undefined )
editor.config.customConfig = instanceConfig.customConfig;
// Load configs from the custom configuration files.
if ( !loadConfig( editor ) )
editor.fireOnce( 'customConfigLoaded' );
};
// ##### END: Config Privates
var onConfigLoaded = function( editor )
{
// Set config related properties.
var skin = editor.config.skin.split( ',' ),
skinName = skin[ 0 ],
skinPath = CKEDITOR.getUrl( skin[ 1 ] || (
'_source/' + // @Packager.RemoveLine
'skins/' + skinName + '/' ) );
/**
* The name of the skin used by this editor instance. The skin name can
* be set through the <code>{@link CKEDITOR.config.skin}</code> setting.
* @name CKEDITOR.editor.prototype.skinName
* @type String
* @example
* alert( editor.skinName ); // E.g. "kama"
*/
editor.skinName = skinName;
/**
* The full URL of the skin directory.
* @name CKEDITOR.editor.prototype.skinPath
* @type String
* @example
* alert( editor.skinPath ); // E.g. "http://example.com/ckeditor/skins/kama/"
*/
editor.skinPath = skinPath;
/**
* The CSS class name used for skin identification purposes.
* @name CKEDITOR.editor.prototype.skinClass
* @type String
* @example
* alert( editor.skinClass ); // E.g. "cke_skin_kama"
*/
editor.skinClass = 'cke_skin_' + skinName;
/**
* The <a href="http://en.wikipedia.org/wiki/Tabbing_navigation">tabbing
* navigation</a> order that has been calculated for this editor
* instance. This can be set by the <code>{@link CKEDITOR.config.tabIndex}</code>
* setting or taken from the <code>tabindex</code> attribute of the
* <code>{@link #element}</code> associated with the editor.
* @name CKEDITOR.editor.prototype.tabIndex
* @type Number
* @default 0 (zero)
* @example
* alert( editor.tabIndex ); // E.g. "0"
*/
editor.tabIndex = editor.config.tabIndex || editor.element.getAttribute( 'tabindex' ) || 0;
/**
* Indicates the read-only state of this editor. This is a read-only property.
* @name CKEDITOR.editor.prototype.readOnly
* @type Boolean
* @since 3.6
* @see CKEDITOR.editor#setReadOnly
*/
editor.readOnly = !!( editor.config.readOnly || editor.element.getAttribute( 'disabled' ) );
// Fire the "configLoaded" event.
editor.fireOnce( 'configLoaded' );
// Load language file.
loadSkin( editor );
};
var loadLang = function( editor )
{
CKEDITOR.lang.load( editor.config.language, editor.config.defaultLanguage, function( languageCode, lang )
{
/**
* The code for the language resources that have been loaded
* for the user interface elements of this editor instance.
* @name CKEDITOR.editor.prototype.langCode
* @type String
* @example
* alert( editor.langCode ); // E.g. "en"
*/
editor.langCode = languageCode;
/**
* An object that contains all language strings used by the editor
* interface.
* @name CKEDITOR.editor.prototype.lang
* @type CKEDITOR.lang
* @example
* alert( editor.lang.bold ); // E.g. "Negrito" (if the language is set to Portuguese)
*/
// As we'll be adding plugin specific entries that could come
// from different language code files, we need a copy of lang,
// not a direct reference to it.
editor.lang = CKEDITOR.tools.prototypedCopy( lang );
// We're not able to support RTL in Firefox 2 at this time.
if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 && editor.lang.dir == 'rtl' )
editor.lang.dir = 'ltr';
editor.fire( 'langLoaded' );
var config = editor.config;
config.contentsLangDirection == 'ui' && ( config.contentsLangDirection = editor.lang.dir );
loadPlugins( editor );
});
};
var loadPlugins = function( editor )
{
var config = editor.config,
plugins = config.plugins,
extraPlugins = config.extraPlugins,
removePlugins = config.removePlugins;
if ( extraPlugins )
{
// Remove them first to avoid duplications.
var removeRegex = new RegExp( '(?:^|,)(?:' + extraPlugins.replace( /\s*,\s*/g, '|' ) + ')(?=,|$)' , 'g' );
plugins = plugins.replace( removeRegex, '' );
plugins += ',' + extraPlugins;
}
if ( removePlugins )
{
removeRegex = new RegExp( '(?:^|,)(?:' + removePlugins.replace( /\s*,\s*/g, '|' ) + ')(?=,|$)' , 'g' );
plugins = plugins.replace( removeRegex, '' );
}
// Load the Adobe AIR plugin conditionally.
CKEDITOR.env.air && ( plugins += ',adobeair' );
// Load all plugins defined in the "plugins" setting.
CKEDITOR.plugins.load( plugins.split( ',' ), function( plugins )
{
// The list of plugins.
var pluginsArray = [];
// The language code to get loaded for each plugin. Null
// entries will be appended for plugins with no language files.
var languageCodes = [];
// The list of URLs to language files.
var languageFiles = [];
/**
* An object that contains references to all plugins used by this
* editor instance.
* @name CKEDITOR.editor.prototype.plugins
* @type Object
* @example
* alert( editor.plugins.dialog.path ); // E.g. "http://example.com/ckeditor/plugins/dialog/"
*/
editor.plugins = plugins;
// Loop through all plugins, to build the list of language
// files to get loaded.
for ( var pluginName in plugins )
{
var plugin = plugins[ pluginName ],
pluginLangs = plugin.lang,
pluginPath = CKEDITOR.plugins.getPath( pluginName ),
lang = null;
// Set the plugin path in the plugin.
plugin.path = pluginPath;
// If the plugin has "lang".
if ( pluginLangs )
{
// Resolve the plugin language. If the current language
// is not available, get the first one (default one).
lang = ( CKEDITOR.tools.indexOf( pluginLangs, editor.langCode ) >= 0 ? editor.langCode : pluginLangs[ 0 ] );
if ( !plugin.langEntries || !plugin.langEntries[ lang ] )
{
// Put the language file URL into the list of files to
// get downloaded.
languageFiles.push( CKEDITOR.getUrl( pluginPath + 'lang/' + lang + '.js' ) );
}
else
{
CKEDITOR.tools.extend( editor.lang, plugin.langEntries[ lang ] );
lang = null;
}
}
// Save the language code, so we know later which
// language has been resolved to this plugin.
languageCodes.push( lang );
pluginsArray.push( plugin );
}
// Load all plugin specific language files in a row.
CKEDITOR.scriptLoader.load( languageFiles, function()
{
// Initialize all plugins that have the "beforeInit" and "init" methods defined.
var methods = [ 'beforeInit', 'init', 'afterInit' ];
for ( var m = 0 ; m < methods.length ; m++ )
{
for ( var i = 0 ; i < pluginsArray.length ; i++ )
{
var plugin = pluginsArray[ i ];
// Uses the first loop to update the language entries also.
if ( m === 0 && languageCodes[ i ] && plugin.lang )
CKEDITOR.tools.extend( editor.lang, plugin.langEntries[ languageCodes[ i ] ] );
// Call the plugin method (beforeInit and init).
if ( plugin[ methods[ m ] ] )
plugin[ methods[ m ] ]( editor );
}
}
// Load the editor skin.
editor.fire( 'pluginsLoaded' );
loadTheme( editor );
});
});
};
var loadSkin = function( editor )
{
CKEDITOR.skins.load( editor, 'editor', function()
{
loadLang( editor );
});
};
var loadTheme = function( editor )
{
var theme = editor.config.theme;
CKEDITOR.themes.load( theme, function()
{
/**
* The theme used by this editor instance.
* @name CKEDITOR.editor.prototype.theme
* @type CKEDITOR.theme
* @example
* alert( editor.theme ); // E.g. "http://example.com/ckeditor/themes/default/"
*/
var editorTheme = editor.theme = CKEDITOR.themes.get( theme );
editorTheme.path = CKEDITOR.themes.getPath( theme );
editorTheme.build( editor );
if ( editor.config.autoUpdateElement )
attachToForm( editor );
});
};
var attachToForm = function( editor )
{
var element = editor.element;
// If are replacing a textarea, we must
if ( editor.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE && element.is( 'textarea' ) )
{
var form = element.$.form && new CKEDITOR.dom.element( element.$.form );
if ( form )
{
function onSubmit()
{
editor.updateElement();
}
form.on( 'submit',onSubmit );
// Setup the submit function because it doesn't fire the
// "submit" event.
if ( !form.$.submit.nodeName && !form.$.submit.length )
{
form.$.submit = CKEDITOR.tools.override( form.$.submit, function( originalSubmit )
{
return function()
{
editor.updateElement();
// For IE, the DOM submit function is not a
// function, so we need thid check.
if ( originalSubmit.apply )
originalSubmit.apply( this, arguments );
else
originalSubmit();
};
});
}
// Remove 'submit' events registered on form element before destroying.(#3988)
editor.on( 'destroy', function()
{
form.removeListener( 'submit', onSubmit );
} );
}
}
};
function updateCommands()
{
var command,
commands = this._.commands,
mode = this.mode;
if ( !mode )
return;
for ( var name in commands )
{
command = commands[ name ];
command[ command.startDisabled ? 'disable' :
this.readOnly && !command.readOnly ? 'disable' : command.modes[ mode ] ? 'enable' : 'disable' ]();
}
}
/**
* Initializes the editor instance. This function is called by the editor
* contructor (<code>editor_basic.js</code>).
* @private
*/
CKEDITOR.editor.prototype._init = function()
{
// Get the properties that have been saved in the editor_base
// implementation.
var element = CKEDITOR.dom.element.get( this._.element ),
instanceConfig = this._.instanceConfig;
delete this._.element;
delete this._.instanceConfig;
this._.commands = {};
this._.styles = [];
/**
* The DOM element that was replaced by this editor instance. This
* element stores the editor data on load and post.
* @name CKEDITOR.editor.prototype.element
* @type CKEDITOR.dom.element
* @example
* var editor = CKEDITOR.instances.editor1;
* alert( <strong>editor.element</strong>.getName() ); // E.g. "textarea"
*/
this.element = element;
/**
* The editor instance name. It may be the replaced element ID, name, or
* a default name using the progressive counter (<code>editor1</code>,
* <code>editor2</code>, ...).
* @name CKEDITOR.editor.prototype.name
* @type String
* @example
* var editor = CKEDITOR.instances.editor1;
* alert( <strong>editor.name</strong> ); // "editor1"
*/
this.name = ( element && ( this.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
&& ( element.getId() || element.getNameAtt() ) )
|| getNewName();
if ( this.name in CKEDITOR.instances )
throw '[CKEDITOR.editor] The instance "' + this.name + '" already exists.';
/**
* A unique random string assigned to each editor instance on the page.
* @name CKEDITOR.editor.prototype.id
* @type String
*/
this.id = CKEDITOR.tools.getNextId();
/**
* The configurations for this editor instance. It inherits all
* settings defined in <code>(@link CKEDITOR.config}</code>, combined with settings
* loaded from custom configuration files and those defined inline in
* the page when creating the editor.
* @name CKEDITOR.editor.prototype.config
* @type Object
* @example
* var editor = CKEDITOR.instances.editor1;
* alert( <strong>editor.config.theme</strong> ); // E.g. "default"
*/
this.config = CKEDITOR.tools.prototypedCopy( CKEDITOR.config );
/**
* The namespace containing UI features related to this editor instance.
* @name CKEDITOR.editor.prototype.ui
* @type CKEDITOR.ui
* @example
*/
this.ui = new CKEDITOR.ui( this );
/**
* Controls the focus state of this editor instance. This property
* is rarely used for normal API operations. It is mainly
* intended for developers adding UI elements to the editor interface.
* @name CKEDITOR.editor.prototype.focusManager
* @type CKEDITOR.focusManager
* @example
*/
this.focusManager = new CKEDITOR.focusManager( this );
CKEDITOR.fire( 'instanceCreated', null, this );
this.on( 'mode', updateCommands, null, null, 1 );
this.on( 'readOnly', updateCommands, null, null, 1 );
initConfig( this, instanceConfig );
};
})();
CKEDITOR.tools.extend( CKEDITOR.editor.prototype,
/** @lends CKEDITOR.editor.prototype */
{
/**
* Adds a command definition to the editor instance. Commands added with
* this function can be executed later with the <code>{@link #execCommand}</code> method.
* @param {String} commandName The indentifier name of the command.
* @param {CKEDITOR.commandDefinition} commandDefinition The command definition.
* @example
* editorInstance.addCommand( 'sample',
* {
* exec : function( editor )
* {
* alert( 'Executing a command for the editor name "' + editor.name + '"!' );
* }
* });
*/
addCommand : function( commandName, commandDefinition )
{
return this._.commands[ commandName ] = new CKEDITOR.command( this, commandDefinition );
},
/**
* Adds a piece of CSS code to the editor which will be applied to the WYSIWYG editing document.
* This CSS would not be added to the output, and is there mainly for editor-specific editing requirements.
* Note: This function should be called before the editor is loaded to take effect.
* @param css {String} CSS text.
* @example
* editorInstance.addCss( 'body { background-color: grey; }' );
*/
addCss : function( css )
{
this._.styles.push( css );
},
/**
* Destroys the editor instance, releasing all resources used by it.
* If the editor replaced an element, the element will be recovered.
* @param {Boolean} [noUpdate] If the instance is replacing a DOM
* element, this parameter indicates whether or not to update the
* element with the instance contents.
* @example
* alert( CKEDITOR.instances.editor1 ); // E.g "object"
* <strong>CKEDITOR.instances.editor1.destroy()</strong>;
* alert( CKEDITOR.instances.editor1 ); // "undefined"
*/
destroy : function( noUpdate )
{
if ( !noUpdate )
this.updateElement();
this.fire( 'destroy' );
this.theme && this.theme.destroy( this );
CKEDITOR.remove( this );
CKEDITOR.fire( 'instanceDestroyed', null, this );
},
/**
* Executes a command associated with the editor.
* @param {String} commandName The indentifier name of the command.
* @param {Object} [data] Data to be passed to the command.
* @returns {Boolean} <code>true</code> if the command was executed
* successfully, otherwise <code>false</code>.
* @see CKEDITOR.editor.addCommand
* @example
* editorInstance.execCommand( 'bold' );
*/
execCommand : function( commandName, data )
{
var command = this.getCommand( commandName );
var eventData =
{
name: commandName,
commandData: data,
command: command
};
if ( command && command.state != CKEDITOR.TRISTATE_DISABLED )
{
if ( this.fire( 'beforeCommandExec', eventData ) !== true )
{
eventData.returnValue = command.exec( eventData.commandData );
// Fire the 'afterCommandExec' immediately if command is synchronous.
if ( !command.async && this.fire( 'afterCommandExec', eventData ) !== true )
return eventData.returnValue;
}
}
// throw 'Unknown command name "' + commandName + '"';
return false;
},
/**
* Gets one of the registered commands. Note that after registering a
* command definition with <code>{@link #addCommand}</code>, it is
* transformed internally into an instance of
* <code>{@link CKEDITOR.command}</code>, which will then be returned
* by this function.
* @param {String} commandName The name of the command to be returned.
* This is the same name that is used to register the command with
* <code>addCommand</code>.
* @returns {CKEDITOR.command} The command object identified by the
* provided name.
*/
getCommand : function( commandName )
{
return this._.commands[ commandName ];
},
/**
* Gets the editor data. The data will be in raw format. It is the same
* data that is posted by the editor.
* @type String
* @returns (String) The editor data.
* @example
* if ( CKEDITOR.instances.editor1.<strong>getData()</strong> == '' )
* alert( 'There is no data available' );
*/
getData : function()
{
this.fire( 'beforeGetData' );
var eventData = this._.data;
if ( typeof eventData != 'string' )
{
var element = this.element;
if ( element && this.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
eventData = element.is( 'textarea' ) ? element.getValue() : element.getHtml();
else
eventData = '';
}
eventData = { dataValue : eventData };
// Fire "getData" so data manipulation may happen.
this.fire( 'getData', eventData );
return eventData.dataValue;
},
/**
* Gets the "raw data" currently available in the editor. This is a
* fast method which returns the data as is, without processing, so it is
* not recommended to use it on resulting pages. Instead it can be used
* combined with the <code>{@link #loadSnapshot}</code> method in order
* to be able to automatically save the editor data from time to time
* while the user is using the editor, to avoid data loss, without risking
* performance issues.
* @see CKEDITOR.editor.getData
* @example
* alert( editor.getSnapshot() );
*/
getSnapshot : function()
{
var data = this.fire( 'getSnapshot' );
if ( typeof data != 'string' )
{
var element = this.element;
if ( element && this.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
data = element.is( 'textarea' ) ? element.getValue() : element.getHtml();
}
return data;
},
/**
* Loads "raw data" into the editor. The data is loaded with processing
* straight to the editing area. It should not be used as a way to load
* any kind of data, but instead in combination with
* <code>{@link #getSnapshot}</code> produced data.
* @see CKEDITOR.editor.setData
* @example
* var data = editor.getSnapshot();
* editor.<strong>loadSnapshot( data )</strong>;
*/
loadSnapshot : function( snapshot )
{
this.fire( 'loadSnapshot', snapshot );
},
/**
* Sets the editor data. The data must be provided in the raw format (HTML).<br />
* <br />
* Note that this method is asynchronous. The <code>callback</code> parameter must
* be used if interaction with the editor is needed after setting the data.
* @param {String} data HTML code to replace the curent content in the
* editor.
* @param {Function} callback Function to be called after the <code>setData</code>
* is completed.
*@param {Boolean} internal Whether to suppress any event firing when copying data
* internally inside the editor.
* @example
* CKEDITOR.instances.editor1.<strong>setData</strong>( '<p>This is the editor data.</p>' );
* @example
* CKEDITOR.instances.editor1.<strong>setData</strong>( '<p>Some other editor data.</p>', function()
* {
* this.checkDirty(); // true
* });
*/
setData : function( data , callback, internal )
{
if( callback )
{
this.on( 'dataReady', function( evt )
{
evt.removeListener();
callback.call( evt.editor );
} );
}
// Fire "setData" so data manipulation may happen.
var eventData = { dataValue : data };
!internal && this.fire( 'setData', eventData );
this._.data = eventData.dataValue;
!internal && this.fire( 'afterSetData', eventData );
},
/**
* Puts or restores the editor into read-only state. When in read-only,
* the user is not able to change the editor contents, but can still use
* some editor features. This function sets the <code>{@link CKEDITOR.config.readOnly}</code>
* property of the editor, firing the <code>{@link CKEDITOR.editor#readOnly}</code> event.<br><br>
* <strong>Note:</strong> the current editing area will be reloaded.
* @param {Boolean} [isReadOnly] Indicates that the editor must go
* read-only (<code>true</code>, default) or be restored and made editable
* (<code>false</code>).
* @since 3.6
*/
setReadOnly : function( isReadOnly )
{
isReadOnly = ( isReadOnly == undefined ) || isReadOnly;
if ( this.readOnly != isReadOnly )
{
this.readOnly = isReadOnly;
// Fire the readOnly event so the editor features can update
// their state accordingly.
this.fire( 'readOnly' );
}
},
/**
* Inserts HTML code into the currently selected position in the editor in WYSIWYG mode.
* @param {String} data HTML code to be inserted into the editor.
* @example
* CKEDITOR.instances.editor1.<strong>insertHtml( '<p>This is a new paragraph.</p>' )</strong>;
*/
insertHtml : function( data )
{
this.fire( 'insertHtml', data );
},
/**
* Insert text content into the currently selected position in the
* editor in WYSIWYG mode. The styles of the selected element will be applied to the inserted text.
* Spaces around the text will be leaving untouched.
* <strong>Note:</strong> two subsequent line-breaks will introduce one paragraph. This depends on <code>{@link CKEDITOR.config.enterMode}</code>;
* A single line-break will be instead translated into one <br />.
* @since 3.5
* @param {String} text Text to be inserted into the editor.
* @example
* CKEDITOR.instances.editor1.<strong>insertText( ' line1 \n\n line2' )</strong>;
*/
insertText : function( text )
{
this.fire( 'insertText', text );
},
/**
* Inserts an element into the currently selected position in the
* editor in WYSIWYG mode.
* @param {CKEDITOR.dom.element} element The element to be inserted
* into the editor.
* @example
* var element = CKEDITOR.dom.element.createFromHtml( '<img src="hello.png" border="0" title="Hello" />' );
* CKEDITOR.instances.editor1.<strong>insertElement( element )</strong>;
*/
insertElement : function( element )
{
this.fire( 'insertElement', element );
},
/**
* Checks whether the current editor contents contain changes when
* compared to the contents loaded into the editor at startup, or to
* the contents available in the editor when <code>{@link #resetDirty}</code>
* was called.
* @returns {Boolean} "true" is the contents contain changes.
* @example
* function beforeUnload( e )
* {
* if ( CKEDITOR.instances.editor1.<strong>checkDirty()</strong> )
* return e.returnValue = "You will lose the changes made in the editor.";
* }
*
* if ( window.addEventListener )
* window.addEventListener( 'beforeunload', beforeUnload, false );
* else
* window.attachEvent( 'onbeforeunload', beforeUnload );
*/
checkDirty : function()
{
return ( this.mayBeDirty && this._.previousValue !== this.getSnapshot() );
},
/**
* Resets the "dirty state" of the editor so subsequent calls to
* <code>{@link #checkDirty}</code> will return <code>false</code> if the user will not
* have made further changes to the contents.
* @example
* alert( editor.checkDirty() ); // E.g. "true"
* editor.<strong>resetDirty()</strong>;
* alert( editor.checkDirty() ); // "false"
*/
resetDirty : function()
{
if ( this.mayBeDirty )
this._.previousValue = this.getSnapshot();
},
/**
* Updates the <code><textarea></code> element that was replaced by the editor with
* the current data available in the editor.
* @see CKEDITOR.editor.element
* @example
* CKEDITOR.instances.editor1.updateElement();
* alert( document.getElementById( 'editor1' ).value ); // The current editor data.
*/
updateElement : function()
{
var element = this.element;
if ( element && this.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
{
var data = this.getData();
if ( this.config.htmlEncodeOutput )
data = CKEDITOR.tools.htmlEncode( data );
if ( element.is( 'textarea' ) )
element.setValue( data );
else
element.setHtml( data );
}
}
});
CKEDITOR.on( 'loaded', function()
{
// Run the full initialization for pending editors.
var pending = CKEDITOR.editor._pending;
if ( pending )
{
delete CKEDITOR.editor._pending;
for ( var i = 0 ; i < pending.length ; i++ )
pending[ i ]._init();
}
});
/**
* Whether to escape HTML when the editor updates the original input element.
* @name CKEDITOR.config.htmlEncodeOutput
* @since 3.1
* @type Boolean
* @default false
* @example
* config.htmlEncodeOutput = true;
*/
/**
* If <code>true</code>, makes the editor start in read-only state. Otherwise, it will check
* if the linked <code><textarea></code> element has the <code>disabled</code> attribute.
* @name CKEDITOR.config.readOnly
* @see CKEDITOR.editor#setReadOnly
* @type Boolean
* @default false
* @since 3.6
* @example
* config.readOnly = true;
*/
/**
* Fired when a CKEDITOR instance is created, but still before initializing it.
* To interact with a fully initialized instance, use the
* <code>{@link CKEDITOR#instanceReady}</code> event instead.
* @name CKEDITOR#instanceCreated
* @event
* @param {CKEDITOR.editor} editor The editor instance that has been created.
*/
/**
* Fired when a CKEDITOR instance is destroyed.
* @name CKEDITOR#instanceDestroyed
* @event
* @param {CKEDITOR.editor} editor The editor instance that has been destroyed.
*/
/**
* Fired when the language is loaded into the editor instance.
* @name CKEDITOR.editor#langLoaded
* @event
* @since 3.6.1
* @param {CKEDITOR.editor} editor This editor instance.
*/
/**
* Fired when all plugins are loaded and initialized into the editor instance.
* @name CKEDITOR.editor#pluginsLoaded
* @event
* @param {CKEDITOR.editor} editor This editor instance.
*/
/**
* Fired before the command execution when <code>{@link #execCommand}</code> is called.
* @name CKEDITOR.editor#beforeCommandExec
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} data.name The command name.
* @param {Object} data.commandData The data to be sent to the command. This
* can be manipulated by the event listener.
* @param {CKEDITOR.command} data.command The command itself.
*/
/**
* Fired after the command execution when <code>{@link #execCommand}</code> is called.
* @name CKEDITOR.editor#afterCommandExec
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} data.name The command name.
* @param {Object} data.commandData The data sent to the command.
* @param {CKEDITOR.command} data.command The command itself.
* @param {Object} data.returnValue The value returned by the command execution.
*/
/**
* Fired when the custom configuration file is loaded, before the final
* configurations initialization.<br />
* <br />
* Custom configuration files can be loaded thorugh the
* <code>{@link CKEDITOR.config.customConfig}</code> setting. Several files can be loaded
* by changing this setting.
* @name CKEDITOR.editor#customConfigLoaded
* @event
* @param {CKEDITOR.editor} editor This editor instance.
*/
/**
* Fired once the editor configuration is ready (loaded and processed).
* @name CKEDITOR.editor#configLoaded
* @event
* @param {CKEDITOR.editor} editor This editor instance.
*/
/**
* Fired when this editor instance is destroyed. The editor at this
* point is not usable and this event should be used to perform the clean-up
* in any plugin.
* @name CKEDITOR.editor#destroy
* @event
*/
/**
* Internal event to get the current data.
* @name CKEDITOR.editor#beforeGetData
* @event
*/
/**
* Internal event to perform the <code>#getSnapshot</code> call.
* @name CKEDITOR.editor#getSnapshot
* @event
*/
/**
* Internal event to perform the <code>#loadSnapshot</code> call.
* @name CKEDITOR.editor#loadSnapshot
* @event
*/
/**
* Event fired before the <code>#getData</code> call returns allowing additional manipulation.
* @name CKEDITOR.editor#getData
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} data.dataValue The data that will be returned.
*/
/**
* Event fired before the <code>#setData</code> call is executed allowing additional manipulation.
* @name CKEDITOR.editor#setData
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} data.dataValue The data that will be used.
*/
/**
* Event fired at the end of the <code>#setData</code> call execution. Usually it is better to use the
* <code>{@link CKEDITOR.editor.prototype.dataReady}</code> event.
* @name CKEDITOR.editor#afterSetData
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} data.dataValue The data that has been set.
*/
/**
* Internal event to perform the <code>#insertHtml</code> call
* @name CKEDITOR.editor#insertHtml
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} data The HTML to insert.
*/
/**
* Internal event to perform the <code>#insertText</code> call
* @name CKEDITOR.editor#insertText
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {String} text The text to insert.
*/
/**
* Internal event to perform the <code>#insertElement</code> call
* @name CKEDITOR.editor#insertElement
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {Object} element The element to insert.
*/
/**
* Event fired after the <code>{@link CKEDITOR.editor#readOnly}</code> property changes.
* @name CKEDITOR.editor#readOnly
* @event
* @since 3.6
* @param {CKEDITOR.editor} editor This editor instance.
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.event} class, which serves as the
* base for classes and objects that require event handling features.
*/
if ( !CKEDITOR.event )
{
/**
* Creates an event class instance. This constructor is rearely used, being
* the {@link #.implementOn} function used in class prototypes directly
* instead.
* @class This is a base class for classes and objects that require event
* handling features.<br />
* <br />
* Do not confuse this class with {@link CKEDITOR.dom.event} which is
* instead used for DOM events. The CKEDITOR.event class implements the
* internal event system used by the CKEditor to fire API related events.
* @example
*/
CKEDITOR.event = function()
{};
/**
* Implements the {@link CKEDITOR.event} features in an object.
* @param {Object} targetObject The object into which implement the features.
* @example
* var myObject = { message : 'Example' };
* <b>CKEDITOR.event.implementOn( myObject }</b>;
* myObject.on( 'testEvent', function()
* {
* alert( this.message ); // "Example"
* });
* myObject.fire( 'testEvent' );
*/
CKEDITOR.event.implementOn = function( targetObject )
{
var eventProto = CKEDITOR.event.prototype;
for ( var prop in eventProto )
{
if ( targetObject[ prop ] == undefined )
targetObject[ prop ] = eventProto[ prop ];
}
};
CKEDITOR.event.prototype = (function()
{
// Returns the private events object for a given object.
var getPrivate = function( obj )
{
var _ = ( obj.getPrivate && obj.getPrivate() ) || obj._ || ( obj._ = {} );
return _.events || ( _.events = {} );
};
var eventEntry = function( eventName )
{
this.name = eventName;
this.listeners = [];
};
eventEntry.prototype =
{
// Get the listener index for a specified function.
// Returns -1 if not found.
getListenerIndex : function( listenerFunction )
{
for ( var i = 0, listeners = this.listeners ; i < listeners.length ; i++ )
{
if ( listeners[i].fn == listenerFunction )
return i;
}
return -1;
}
};
return /** @lends CKEDITOR.event.prototype */ {
/**
* Registers a listener to a specific event in the current object.
* @param {String} eventName The event name to which listen.
* @param {Function} listenerFunction The function listening to the
* event. A single {@link CKEDITOR.eventInfo} object instanced
* is passed to this function containing all the event data.
* @param {Object} [scopeObj] The object used to scope the listener
* call (the this object. If omitted, the current object is used.
* @param {Object} [listenerData] Data to be sent as the
* {@link CKEDITOR.eventInfo#listenerData} when calling the
* listener.
* @param {Number} [priority] The listener priority. Lower priority
* listeners are called first. Listeners with the same priority
* value are called in registration order. Defaults to 10.
* @example
* someObject.on( 'someEvent', function()
* {
* alert( this == someObject ); // "true"
* });
* @example
* someObject.on( 'someEvent', function()
* {
* alert( this == anotherObject ); // "true"
* }
* , anotherObject );
* @example
* someObject.on( 'someEvent', function( event )
* {
* alert( event.listenerData ); // "Example"
* }
* , null, 'Example' );
* @example
* someObject.on( 'someEvent', function() { ... } ); // 2nd called
* someObject.on( 'someEvent', function() { ... }, null, null, 100 ); // 3rd called
* someObject.on( 'someEvent', function() { ... }, null, null, 1 ); // 1st called
*/
on : function( eventName, listenerFunction, scopeObj, listenerData, priority )
{
// Get the event entry (create it if needed).
var events = getPrivate( this ),
event = events[ eventName ] || ( events[ eventName ] = new eventEntry( eventName ) );
if ( event.getListenerIndex( listenerFunction ) < 0 )
{
// Get the listeners.
var listeners = event.listeners;
// Fill the scope.
if ( !scopeObj )
scopeObj = this;
// Default the priority, if needed.
if ( isNaN( priority ) )
priority = 10;
var me = this;
// Create the function to be fired for this listener.
var listenerFirer = function( editor, publisherData, stopFn, cancelFn )
{
var ev =
{
name : eventName,
sender : this,
editor : editor,
data : publisherData,
listenerData : listenerData,
stop : stopFn,
cancel : cancelFn,
removeListener : function()
{
me.removeListener( eventName, listenerFunction );
}
};
listenerFunction.call( scopeObj, ev );
return ev.data;
};
listenerFirer.fn = listenerFunction;
listenerFirer.priority = priority;
// Search for the right position for this new listener, based on its
// priority.
for ( var i = listeners.length - 1 ; i >= 0 ; i-- )
{
// Find the item which should be before the new one.
if ( listeners[ i ].priority <= priority )
{
// Insert the listener in the array.
listeners.splice( i + 1, 0, listenerFirer );
return;
}
}
// If no position has been found (or zero length), put it in
// the front of list.
listeners.unshift( listenerFirer );
}
},
/**
* Fires an specific event in the object. All registered listeners are
* called at this point.
* @function
* @param {String} eventName The event name to fire.
* @param {Object} [data] Data to be sent as the
* {@link CKEDITOR.eventInfo#data} when calling the
* listeners.
* @param {CKEDITOR.editor} [editor] The editor instance to send as the
* {@link CKEDITOR.eventInfo#editor} when calling the
* listener.
* @returns {Boolean|Object} A booloan indicating that the event is to be
* canceled, or data returned by one of the listeners.
* @example
* someObject.on( 'someEvent', function() { ... } );
* someObject.on( 'someEvent', function() { ... } );
* <b>someObject.fire( 'someEvent' )</b>; // both listeners are called
* @example
* someObject.on( 'someEvent', function( event )
* {
* alert( event.data ); // "Example"
* });
* <b>someObject.fire( 'someEvent', 'Example' )</b>;
*/
fire : (function()
{
// Create the function that marks the event as stopped.
var stopped = false;
var stopEvent = function()
{
stopped = true;
};
// Create the function that marks the event as canceled.
var canceled = false;
var cancelEvent = function()
{
canceled = true;
};
return function( eventName, data, editor )
{
// Get the event entry.
var event = getPrivate( this )[ eventName ];
// Save the previous stopped and cancelled states. We may
// be nesting fire() calls.
var previousStopped = stopped,
previousCancelled = canceled;
// Reset the stopped and canceled flags.
stopped = canceled = false;
if ( event )
{
var listeners = event.listeners;
if ( listeners.length )
{
// As some listeners may remove themselves from the
// event, the original array length is dinamic. So,
// let's make a copy of all listeners, so we are
// sure we'll call all of them.
listeners = listeners.slice( 0 );
// Loop through all listeners.
for ( var i = 0 ; i < listeners.length ; i++ )
{
// Call the listener, passing the event data.
var retData = listeners[i].call( this, editor, data, stopEvent, cancelEvent );
if ( typeof retData != 'undefined' )
data = retData;
// No further calls is stopped or canceled.
if ( stopped || canceled )
break;
}
}
}
var ret = canceled || ( typeof data == 'undefined' ? false : data );
// Restore the previous stopped and canceled states.
stopped = previousStopped;
canceled = previousCancelled;
return ret;
};
})(),
/**
* Fires an specific event in the object, releasing all listeners
* registered to that event. The same listeners are not called again on
* successive calls of it or of {@link #fire}.
* @param {String} eventName The event name to fire.
* @param {Object} [data] Data to be sent as the
* {@link CKEDITOR.eventInfo#data} when calling the
* listeners.
* @param {CKEDITOR.editor} [editor] The editor instance to send as the
* {@link CKEDITOR.eventInfo#editor} when calling the
* listener.
* @returns {Boolean|Object} A booloan indicating that the event is to be
* canceled, or data returned by one of the listeners.
* @example
* someObject.on( 'someEvent', function() { ... } );
* someObject.fire( 'someEvent' ); // above listener called
* <b>someObject.fireOnce( 'someEvent' )</b>; // above listener called
* someObject.fire( 'someEvent' ); // no listeners called
*/
fireOnce : function( eventName, data, editor )
{
var ret = this.fire( eventName, data, editor );
delete getPrivate( this )[ eventName ];
return ret;
},
/**
* Unregisters a listener function from being called at the specified
* event. No errors are thrown if the listener has not been
* registered previously.
* @param {String} eventName The event name.
* @param {Function} listenerFunction The listener function to unregister.
* @example
* var myListener = function() { ... };
* someObject.on( 'someEvent', myListener );
* someObject.fire( 'someEvent' ); // myListener called
* <b>someObject.removeListener( 'someEvent', myListener )</b>;
* someObject.fire( 'someEvent' ); // myListener not called
*/
removeListener : function( eventName, listenerFunction )
{
// Get the event entry.
var event = getPrivate( this )[ eventName ];
if ( event )
{
var index = event.getListenerIndex( listenerFunction );
if ( index >= 0 )
event.listeners.splice( index, 1 );
}
},
/**
* Checks if there is any listener registered to a given event.
* @param {String} eventName The event name.
* @example
* var myListener = function() { ... };
* someObject.on( 'someEvent', myListener );
* alert( someObject.<b>hasListeners( 'someEvent' )</b> ); // "true"
* alert( someObject.<b>hasListeners( 'noEvent' )</b> ); // "false"
*/
hasListeners : function( eventName )
{
var event = getPrivate( this )[ eventName ];
return ( event && event.listeners.length > 0 ) ;
}
};
})();
}
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the "virtual" {@link CKEDITOR.dataProcessor} class, which
* defines the basic structure of data processor objects to be
* set to {@link CKEDITOR.editor.dataProcessor}.
*/
/**
* If defined, points to the data processor which is responsible to translate
* and transform the editor data on input and output.
* Generaly it will point to an instance of {@link CKEDITOR.htmlDataProcessor},
* which handles HTML data. The editor may also handle other data formats by
* using different data processors provided by specific plugins.
* @name CKEDITOR.editor.prototype.dataProcessor
* @type CKEDITOR.dataProcessor
*/
/**
* This class is here for documentation purposes only and is not really part of
* the API. It serves as the base ("interface") for data processors
* implementation.
* @name CKEDITOR.dataProcessor
* @class Represents a data processor, which is responsible to translate and
* transform the editor data on input and output.
* @example
*/
/**
* Transforms input data into HTML to be loaded in the editor.
* While the editor is able to handle non HTML data (like BBCode), at runtime
* it can handle HTML data only. The role of the data processor is transforming
* the input data into HTML through this function.
* @name CKEDITOR.dataProcessor.prototype.toHtml
* @function
* @param {String} data The input data to be transformed.
* @param {String} [fixForBody] The tag name to be used if the data must be
* fixed because it is supposed to be loaded direcly into the <body>
* tag. This is generally not used by non-HTML data processors.
* @example
* // Tranforming BBCode data, having a custom BBCode data processor.
* var data = 'This is [b]an example[/b].';
* var html = editor.dataProcessor.toHtml( data ); // '<p>This is <b>an example</b>.</p>'
*/
/**
* Transforms HTML into data to be outputted by the editor, in the format
* expected by the data processor.
* While the editor is able to handle non HTML data (like BBCode), at runtime
* it can handle HTML data only. The role of the data processor is transforming
* the HTML data containined by the editor into a specific data format through
* this function.
* @name CKEDITOR.dataProcessor.prototype.toDataFormat
* @function
* @param {String} html The HTML to be transformed.
* @param {String} fixForBody The tag name to be used if the output data is
* coming from <body> and may be eventually fixed for it. This is
* generally not used by non-HTML data processors.
* // Tranforming into BBCode data, having a custom BBCode data processor.
* var html = '<p>This is <b>an example</b>.</p>';
* var data = editor.dataProcessor.toDataFormat( html ); // 'This is [b]an example[/b].'
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @name CKEDITOR.theme
* @class
*/
CKEDITOR.themes.add( 'default', (function()
{
var hiddenSkins = {};
function checkSharedSpace( editor, spaceName )
{
var container,
element;
// Try to retrieve the target element from the sharedSpaces settings.
element = editor.config.sharedSpaces;
element = element && element[ spaceName ];
element = element && CKEDITOR.document.getById( element );
// If the element is available, we'll then create the container for
// the space.
if ( element )
{
// Creates an HTML structure that reproduces the editor class hierarchy.
var html =
'<span class="cke_shared "' +
' dir="'+ editor.lang.dir + '"' +
'>' +
'<span class="' + editor.skinClass + ' ' + editor.id + ' cke_editor_' + editor.name + '">' +
'<span class="' + CKEDITOR.env.cssClass + '">' +
'<span class="cke_wrapper cke_' + editor.lang.dir + '">' +
'<span class="cke_editor">' +
'<div class="cke_' + spaceName + '">' +
'</div></span></span></span></span></span>';
var mainContainer = element.append( CKEDITOR.dom.element.createFromHtml( html, element.getDocument() ) );
// Only the first container starts visible. Others get hidden.
if ( element.getCustomData( 'cke_hasshared' ) )
mainContainer.hide();
else
element.setCustomData( 'cke_hasshared', 1 );
// Get the deeper inner <div>.
container = mainContainer.getChild( [0,0,0,0] );
// Save a reference to the shared space container.
!editor.sharedSpaces && ( editor.sharedSpaces = {} );
editor.sharedSpaces[ spaceName ] = container;
// When the editor gets focus, we show the space container, hiding others.
editor.on( 'focus', function()
{
for ( var i = 0, sibling, children = element.getChildren() ; ( sibling = children.getItem( i ) ) ; i++ )
{
if ( sibling.type == CKEDITOR.NODE_ELEMENT
&& !sibling.equals( mainContainer )
&& sibling.hasClass( 'cke_shared' ) )
{
sibling.hide();
}
}
mainContainer.show();
});
editor.on( 'destroy', function()
{
mainContainer.remove();
});
}
return container;
}
return /** @lends CKEDITOR.theme */ {
build : function( editor, themePath )
{
var name = editor.name,
element = editor.element,
elementMode = editor.elementMode;
if ( !element || elementMode == CKEDITOR.ELEMENT_MODE_NONE )
return;
if ( elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
element.hide();
// Get the HTML for the predefined spaces.
var topHtml = editor.fire( 'themeSpace', { space : 'top', html : '' } ).html;
var contentsHtml = editor.fire( 'themeSpace', { space : 'contents', html : '' } ).html;
var bottomHtml = editor.fireOnce( 'themeSpace', { space : 'bottom', html : '' } ).html;
var height = contentsHtml && editor.config.height;
var tabIndex = editor.config.tabIndex || editor.element.getAttribute( 'tabindex' ) || 0;
// The editor height is considered only if the contents space got filled.
if ( !contentsHtml )
height = 'auto';
else if ( !isNaN( height ) )
height += 'px';
var style = '';
var width = editor.config.width;
if ( width )
{
if ( !isNaN( width ) )
width += 'px';
style += "width: " + width + ";";
}
var sharedTop = topHtml && checkSharedSpace( editor, 'top' ),
sharedBottoms = checkSharedSpace( editor, 'bottom' );
sharedTop && ( sharedTop.setHtml( topHtml ) , topHtml = '' );
sharedBottoms && ( sharedBottoms.setHtml( bottomHtml ), bottomHtml = '' );
var hideSkin = '<style>.' + editor.skinClass + '{visibility:hidden;}</style>';
if ( hiddenSkins[ editor.skinClass ] )
hideSkin = '';
else
hiddenSkins[ editor.skinClass ] = 1;
var container = CKEDITOR.dom.element.createFromHtml( [
'<span' +
' id="cke_', name, '"' +
' class="', editor.skinClass, ' ', editor.id, ' cke_editor_', name, '"' +
' dir="', editor.lang.dir, '"' +
' title="', ( CKEDITOR.env.gecko ? ' ' : '' ), '"' +
' lang="', editor.langCode, '"' +
( CKEDITOR.env.webkit? ' tabindex="' + tabIndex + '"' : '' ) +
' role="application"' +
' aria-labelledby="cke_', name, '_arialbl"' +
( style ? ' style="' + style + '"' : '' ) +
'>' +
'<span id="cke_', name, '_arialbl" class="cke_voice_label">' + editor.lang.editor + '</span>' +
'<span class="' , CKEDITOR.env.cssClass, '" role="presentation">' +
'<span class="cke_wrapper cke_', editor.lang.dir, '" role="presentation">' +
'<table class="cke_editor" border="0" cellspacing="0" cellpadding="0" role="presentation"><tbody>' +
'<tr', topHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_top_' , name, '" class="cke_top" role="presentation">' , topHtml , '</td></tr>' +
'<tr', contentsHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_contents_', name, '" class="cke_contents" style="height:', height, '" role="presentation">', contentsHtml, '</td></tr>' +
'<tr', bottomHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_bottom_' , name, '" class="cke_bottom" role="presentation">' , bottomHtml , '</td></tr>' +
'</tbody></table>' +
//Hide the container when loading skins, later restored by skin css.
hideSkin +
'</span>' +
'</span>' +
'</span>' ].join( '' ) );
container.getChild( [1, 0, 0, 0, 0] ).unselectable();
container.getChild( [1, 0, 0, 0, 2] ).unselectable();
if ( elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
container.insertAfter( element );
else
element.append( container );
/**
* The DOM element that holds the main editor interface.
* @name CKEDITOR.editor.prototype.container
* @type CKEDITOR.dom.element
* @example
* var editor = CKEDITOR.instances.editor1;
* alert( <b>editor.container</b>.getName() ); "span"
*/
editor.container = container;
// Disable browser context menu for editor's chrome.
container.disableContextMenu();
// Use a class to indicate that the current selection is in different direction than the UI.
editor.on( 'contentDirChanged', function( evt )
{
var func = ( editor.lang.dir != evt.data ? 'add' : 'remove' ) + 'Class';
container.getChild( 1 )[ func ]( 'cke_mixed_dir_content' );
// Put the mixed direction class on the respective element also for shared spaces.
var toolbarSpace = this.sharedSpaces && this.sharedSpaces[ this.config.toolbarLocation ];
toolbarSpace && toolbarSpace.getParent().getParent()[ func ]( 'cke_mixed_dir_content' );
});
editor.fireOnce( 'themeLoaded' );
editor.fireOnce( 'uiReady' );
},
buildDialog : function( editor )
{
var baseIdNumber = CKEDITOR.tools.getNextNumber();
var element = CKEDITOR.dom.element.createFromHtml( [
'<div class="', editor.id, '_dialog cke_editor_', editor.name.replace('.', '\\.'), '_dialog cke_skin_', editor.skinName,
'" dir="', editor.lang.dir, '"' +
' lang="', editor.langCode, '"' +
' role="dialog"' +
' aria-labelledby="%title#"' +
'>' +
'<table class="cke_dialog', ' ' + CKEDITOR.env.cssClass,
' cke_', editor.lang.dir, '" style="position:absolute" role="presentation">' +
'<tr><td role="presentation">' +
'<div class="%body" role="presentation">' +
'<div id="%title#" class="%title" role="presentation"></div>' +
'<a id="%close_button#" class="%close_button" href="javascript:void(0)" title="' + editor.lang.common.close+'" role="button"><span class="cke_label">X</span></a>' +
'<div id="%tabs#" class="%tabs" role="tablist"></div>' +
'<table class="%contents" role="presentation">' +
'<tr>' +
'<td id="%contents#" class="%contents" role="presentation"></td>' +
'</tr>' +
'<tr>' +
'<td id="%footer#" class="%footer" role="presentation"></td>' +
'</tr>' +
'</table>' +
'</div>' +
'<div id="%tl#" class="%tl"></div>' +
'<div id="%tc#" class="%tc"></div>' +
'<div id="%tr#" class="%tr"></div>' +
'<div id="%ml#" class="%ml"></div>' +
'<div id="%mr#" class="%mr"></div>' +
'<div id="%bl#" class="%bl"></div>' +
'<div id="%bc#" class="%bc"></div>' +
'<div id="%br#" class="%br"></div>' +
'</td></tr>' +
'</table>',
//Hide the container when loading skins, later restored by skin css.
( CKEDITOR.env.ie ? '' : '<style>.cke_dialog{visibility:hidden;}</style>' ),
'</div>'
].join( '' )
.replace( /#/g, '_' + baseIdNumber )
.replace( /%/g, 'cke_dialog_' ) );
var body = element.getChild( [ 0, 0, 0, 0, 0 ] ),
title = body.getChild( 0 ),
close = body.getChild( 1 );
// IFrame shim for dialog that masks activeX in IE. (#7619)
if ( CKEDITOR.env.ie && !CKEDITOR.env.ie6Compat )
{
var isCustomDomain = CKEDITOR.env.isCustomDomain(),
src = 'javascript:void(function(){' + encodeURIComponent( 'document.open();' + ( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) + 'document.close();' ) + '}())',
iframe = CKEDITOR.dom.element.createFromHtml( '<iframe' +
' frameBorder="0"' +
' class="cke_iframe_shim"' +
' src="' + src + '"' +
' tabIndex="-1"' +
'></iframe>' );
iframe.appendTo( body.getParent() );
}
// Make the Title and Close Button unselectable.
title.unselectable();
close.unselectable();
return {
element : element,
parts :
{
dialog : element.getChild( 0 ),
title : title,
close : close,
tabs : body.getChild( 2 ),
contents : body.getChild( [ 3, 0, 0, 0 ] ),
footer : body.getChild( [ 3, 0, 1, 0 ] )
}
};
},
destroy : function( editor )
{
var container = editor.container,
element = editor.element;
if ( container )
{
container.clearCustomData();
container.remove();
}
if ( element )
{
element.clearCustomData();
editor.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE && element.show();
delete editor.element;
}
}
};
})() );
/**
* Returns the DOM element that represents a theme space. The default theme defines
* three spaces, namely "top", "contents" and "bottom", representing the main
* blocks that compose the editor interface.
* @param {String} spaceName The space name.
* @returns {CKEDITOR.dom.element} The element that represents the space.
* @example
* // Hide the bottom space in the UI.
* var bottom = editor.getThemeSpace( 'bottom' );
* bottom.setStyle( 'display', 'none' );
*/
CKEDITOR.editor.prototype.getThemeSpace = function( spaceName )
{
var spacePrefix = 'cke_' + spaceName;
var space = this._[ spacePrefix ] ||
( this._[ spacePrefix ] = CKEDITOR.document.getById( spacePrefix + '_' + this.name ) );
return space;
};
/**
* Resizes the editor interface.
* @param {Number|String} width The new width. It can be an pixels integer or a
* CSS size value.
* @param {Number|String} height The new height. It can be an pixels integer or
* a CSS size value.
* @param {Boolean} [isContentHeight] Indicates that the provided height is to
* be applied to the editor contents space, not to the entire editor
* interface. Defaults to false.
* @param {Boolean} [resizeInner] Indicates that the first inner interface
* element must receive the size, not the outer element. The default theme
* defines the interface inside a pair of span elements
* (<span><span>...</span></span>). By default the
* first span element receives the sizes. If this parameter is set to
* true, the second span is sized instead.
* @example
* editor.resize( 900, 300 );
* @example
* editor.resize( '100%', 450, true );
*/
CKEDITOR.editor.prototype.resize = function( width, height, isContentHeight, resizeInner )
{
var container = this.container,
contents = CKEDITOR.document.getById( 'cke_contents_' + this.name ),
contentsFrame = CKEDITOR.env.webkit && this.document && this.document.getWindow().$.frameElement,
outer = resizeInner ? container.getChild( 1 ) : container;
// Set as border box width. (#5353)
outer.setSize( 'width', width, true );
// WebKit needs to refresh the iframe size to avoid rendering issues. (1/2) (#8348)
contentsFrame && ( contentsFrame.style.width = '1%' );
// Get the height delta between the outer table and the content area.
// If we're setting the content area's height, then we don't need the delta.
var delta = isContentHeight ? 0 : ( outer.$.offsetHeight || 0 ) - ( contents.$.clientHeight || 0 );
contents.setStyle( 'height', Math.max( height - delta, 0 ) + 'px' );
// WebKit needs to refresh the iframe size to avoid rendering issues. (2/2) (#8348)
contentsFrame && ( contentsFrame.style.width = '100%' );
// Emit a resize event.
this.fire( 'resize' );
};
/**
* Gets the element that can be freely used to check the editor size. This method
* is mainly used by the resize plugin, which adds a UI handle that can be used
* to resize the editor.
* @param {Boolean} forContents Whether to return the "contents" part of the theme instead of the container.
* @returns {CKEDITOR.dom.element} The resizable element.
* @example
*/
CKEDITOR.editor.prototype.getResizable = function( forContents )
{
return forContents ? CKEDITOR.document.getById( 'cke_contents_' + this.name ) : this.container;
};
/**
* Makes it possible to place some of the editor UI blocks, like the toolbar
* and the elements path, into any element in the page.
* The elements used to hold the UI blocks can be shared among several editor
* instances. In that case, only the blocks of the active editor instance will
* display.
* @name CKEDITOR.config.sharedSpaces
* @type Object
* @default undefined
* @example
* // Place the toolbar inside the element with ID "someElementId" and the
* // elements path into the element with ID "anotherId".
* config.sharedSpaces =
* {
* top : 'someElementId',
* bottom : 'anotherId'
* };
* @example
* // Place the toolbar inside the element with ID "someElementId". The
* // elements path will remain attached to the editor UI.
* config.sharedSpaces =
* {
* top : 'someElementId'
* };
*/
/**
* Fired after the editor instance is resized through
* the {@link CKEDITOR.editor.prototype.resize} method.
* @name CKEDITOR.editor#resize
* @event
*/
| JavaScript |
/* Tokenizer for JavaScript code */
var tokenizeJavaScript = (function() {
// Advance the stream until the given character (not preceded by a
// backslash) is encountered, or the end of the line is reached.
function nextUntilUnescaped(source, end) {
var escaped = false;
while (!source.endOfLine()) {
var next = source.next();
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// A map of JavaScript's keywords. The a/b/c keyword distinction is
// very rough, but it gives the parser enough information to parse
// correct code correctly (we don't care that much how we parse
// incorrect code). The style information included in these objects
// is used by the highlighter to pick the correct CSS style for a
// token.
var keywords = function(){
function result(type, style){
return {type: type, style: "js-" + style};
}
// keywords that take a parenthised expression, and then a
// statement (if)
var keywordA = result("keyword a", "keyword");
// keywords that take just a statement (else)
var keywordB = result("keyword b", "keyword");
// keywords that optionally take an expression, and form a
// statement (return)
var keywordC = result("keyword c", "keyword");
var operator = result("operator", "keyword");
var atom = result("atom", "atom");
return {
"if": keywordA, "while": keywordA, "with": keywordA,
"else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB,
"return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC,
"in": operator, "typeof": operator, "instanceof": operator,
"var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"),
"for": result("for", "keyword"), "switch": result("switch", "keyword"),
"case": result("case", "keyword"), "default": result("default", "keyword"),
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
};
}();
// Some helper regexps
var isOperatorChar = /[+\-*&%=<>!?|]/;
var isHexDigit = /[0-9A-Fa-f]/;
var isWordChar = /[\w\$_]/;
// Wrapper around jsToken that helps maintain parser state (whether
// we are inside of a multi-line comment and whether the next token
// could be a regular expression).
function jsTokenState(inside, regexp) {
return function(source, setState) {
var newInside = inside;
var type = jsToken(inside, regexp, source, function(c) {newInside = c;});
var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/);
if (newRegexp != regexp || newInside != inside)
setState(jsTokenState(newInside, newRegexp));
return type;
};
}
// The token reader, inteded to be used by the tokenizer from
// tokenize.js (through jsTokenState). Advances the source stream
// over a token, and returns an object containing the type and style
// of that token.
function jsToken(inside, regexp, source, setInside) {
function readHexNumber(){
source.next(); // skip the 'x'
source.nextWhileMatches(isHexDigit);
return {type: "number", style: "js-atom"};
}
function readNumber() {
source.nextWhileMatches(/[0-9]/);
if (source.equals(".")){
source.next();
source.nextWhileMatches(/[0-9]/);
}
if (source.equals("e") || source.equals("E")){
source.next();
if (source.equals("-"))
source.next();
source.nextWhileMatches(/[0-9]/);
}
return {type: "number", style: "js-atom"};
}
// Read a word, look it up in keywords. If not found, it is a
// variable, otherwise it is a keyword of the type found.
function readWord() {
source.nextWhileMatches(isWordChar);
var word = source.get();
var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word];
return known ? {type: known.type, style: known.style, content: word} :
{type: "variable", style: "js-variable", content: word};
}
function readRegexp() {
nextUntilUnescaped(source, "/");
source.nextWhileMatches(/[gi]/);
return {type: "regexp", style: "js-string"};
}
// Mutli-line comments are tricky. We want to return the newlines
// embedded in them as regular newline tokens, and then continue
// returning a comment token for every line of the comment. So
// some state has to be saved (inside) to indicate whether we are
// inside a /* */ sequence.
function readMultilineComment(start){
var newInside = "/*";
var maybeEnd = (start == "*");
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == "/" && maybeEnd){
newInside = null;
break;
}
maybeEnd = (next == "*");
}
setInside(newInside);
return {type: "comment", style: "js-comment"};
}
function readOperator() {
source.nextWhileMatches(isOperatorChar);
return {type: "operator", style: "js-operator"};
}
function readString(quote) {
var endBackSlash = nextUntilUnescaped(source, quote);
setInside(endBackSlash ? quote : null);
return {type: "string", style: "js-string"};
}
// Fetch the next token. Dispatches on first character in the
// stream, or first two characters when the first is a slash.
if (inside == "\"" || inside == "'")
return readString(inside);
var ch = source.next();
if (inside == "/*")
return readMultilineComment(ch);
else if (ch == "\"" || ch == "'")
return readString(ch);
// with punctuation, the type of the token is the symbol itself
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return {type: ch, style: "js-punctuation"};
else if (ch == "0" && (source.equals("x") || source.equals("X")))
return readHexNumber();
else if (/[0-9]/.test(ch))
return readNumber();
else if (ch == "/"){
if (source.equals("*"))
{ source.next(); return readMultilineComment(ch); }
else if (source.equals("/"))
{ nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};}
else if (regexp)
return readRegexp();
else
return readOperator();
}
else if (isOperatorChar.test(ch))
return readOperator();
else
return readWord();
}
// The external interface to the tokenizer.
return function(source, startState) {
return tokenizer(source, startState || jsTokenState(false, true));
};
})();
| JavaScript |
var SparqlParser = Editor.Parser = (function() {
function wordRegexp(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
"isblank", "isliteral", "union", "a"]);
var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
"ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
"graph", "by", "asc", "desc", ]);
var operatorChars = /[*+\-<>=&|]/;
var tokenizeSparql = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "$" || ch == "?") {
source.nextWhileMatches(/[\w\d]/);
return "sp-var";
}
else if (ch == "<" && !source.matches(/[\s\u00a0=]/)) {
source.nextWhileMatches(/[^\s\u00a0>]/);
if (source.equals(">")) source.next();
return "sp-uri";
}
else if (ch == "\"" || ch == "'") {
setState(inLiteral(ch));
return null;
}
else if (/[{}\(\),\.;\[\]]/.test(ch)) {
return "sp-punc";
}
else if (ch == "#") {
while (!source.endOfLine()) source.next();
return "sp-comment";
}
else if (operatorChars.test(ch)) {
source.nextWhileMatches(operatorChars);
return "sp-operator";
}
else if (ch == ":") {
source.nextWhileMatches(/[\w\d\._\-]/);
return "sp-prefixed";
}
else {
source.nextWhileMatches(/[_\w\d]/);
if (source.equals(":")) {
source.next();
source.nextWhileMatches(/[\w\d_\-]/);
return "sp-prefixed";
}
var word = source.get(), type;
if (ops.test(word))
type = "sp-operator";
else if (keywords.test(word))
type = "sp-keyword";
else
type = "sp-word";
return {style: type, content: word};
}
}
function inLiteral(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped) {
setState(normal);
break;
}
escaped = !escaped && ch == "\\";
}
return "sp-literal";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentSparql(context) {
return function(nextChars) {
var firstChar = nextChars && nextChars.charAt(0);
if (/[\]\}]/.test(firstChar))
while (context && context.type == "pattern") context = context.prev;
var closing = context && firstChar == matching[context.type];
if (!context)
return 0;
else if (context.type == "pattern")
return context.col;
else if (context.align)
return context.col - (closing ? context.width : 0);
else
return context.indent + (closing ? 0 : indentUnit);
}
}
function parseSparql(source) {
var tokens = tokenizeSparql(source);
var context = null, indent = 0, col = 0;
function pushContext(type, width) {
context = {prev: context, indent: indent, col: col, type: type, width: width};
}
function popContext() {
context = context.prev;
}
var iter = {
next: function() {
var token = tokens.next(), type = token.style, content = token.content, width = token.value.length;
if (content == "\n") {
token.indentation = indentSparql(context);
indent = col = 0;
if (context && context.align == null) context.align = false;
}
else if (type == "whitespace" && col == 0) {
indent = width;
}
else if (type != "sp-comment" && context && context.align == null) {
context.align = true;
}
if (content != "\n") col += width;
if (/[\[\{\(]/.test(content)) {
pushContext(content, width);
}
else if (/[\]\}\)]/.test(content)) {
while (context && context.type == "pattern")
popContext();
if (context && content == matching[context.type])
popContext();
}
else if (content == "." && context && context.type == "pattern") {
popContext();
}
else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") &&
context && /[\{\[]/.test(context.type)) {
pushContext("pattern", width);
}
return token;
},
copy: function() {
var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeSparql(source, _tokenState);
context = _context;
indent = _indent;
col = _col;
return iter;
};
}
};
return iter;
}
return {make: parseSparql, electricChars: "}]"};
})();
| JavaScript |
// Minimal framing needed to use CodeMirror-style parsers to highlight
// code. Load this along with tokenize.js, stringstream.js, and your
// parser. Then call highlightText, passing a string as the first
// argument, and as the second argument either a callback function
// that will be called with an array of SPAN nodes for every line in
// the code, or a DOM node to which to append these spans, and
// optionally (not needed if you only loaded one parser) a parser
// object.
// Stuff from util.js that the parsers are using.
var StopIteration = {toString: function() {return "StopIteration"}};
var Editor = {};
var indentUnit = 2;
(function(){
function normaliseString(string) {
var tab = "";
for (var i = 0; i < indentUnit; i++) tab += " ";
string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n");
var pos = 0, parts = [], lines = string.split("\n");
for (var line = 0; line < lines.length; line++) {
if (line != 0) parts.push("\n");
parts.push(lines[line]);
}
return {
next: function() {
if (pos < parts.length) return parts[pos++];
else throw StopIteration;
}
};
}
window.highlightText = function(string, callback, parser) {
parser = (parser || Editor.Parser).make(stringStream(normaliseString(string)));
var line = [];
if (callback.nodeType == 1) {
var node = callback;
callback = function(line) {
for (var i = 0; i < line.length; i++)
node.appendChild(line[i]);
node.appendChild(document.createElement("BR"));
};
}
try {
while (true) {
var token = parser.next();
if (token.value == "\n") {
callback(line);
line = [];
}
else {
var span = document.createElement("SPAN");
span.className = token.style;
span.appendChild(document.createTextNode(token.value));
line.push(span);
}
}
}
catch (e) {
if (e != StopIteration) throw e;
}
if (line.length) callback(line);
}
})();
| JavaScript |
/* This file defines an XML parser, with a few kludges to make it
* useable for HTML. autoSelfClosers defines a set of tag names that
* are expected to not have a closing tag, and doNotIndent specifies
* the tags inside of which no indentation should happen (see Config
* object). These can be disabled by passing the editor an object like
* {useHTMLKludges: false} as parserConfig option.
*/
var XMLParser = Editor.Parser = (function() {
var Kludges = {
autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
"meta": true, "col": true, "frame": true, "base": true, "area": true},
doNotIndent: {"pre": true, "!cdata": true}
};
var NoKludges = {autoSelfClosers: {}, doNotIndent: {"!cdata": true}};
var UseKludges = Kludges;
var alignCDATA = false;
// Simple stateful tokenizer for XML documents. Returns a
// MochiKit-style iterator, with a state property that contains a
// function encapsulating the current state. See tokenize.js.
var tokenizeXML = (function() {
function inText(source, setState) {
var ch = source.next();
if (ch == "<") {
if (source.equals("!")) {
source.next();
if (source.equals("[")) {
if (source.lookAhead("[CDATA[", true)) {
setState(inBlock("xml-cdata", "]]>"));
return null;
}
else {
return "xml-text";
}
}
else if (source.lookAhead("--", true)) {
setState(inBlock("xml-comment", "-->"));
return null;
}
else {
return "xml-text";
}
}
else if (source.equals("?")) {
source.next();
source.nextWhileMatches(/[\w\._\-]/);
setState(inBlock("xml-processing", "?>"));
return "xml-processing";
}
else {
if (source.equals("/")) source.next();
setState(inTag);
return "xml-punctuation";
}
}
else if (ch == "&") {
while (!source.endOfLine()) {
if (source.next() == ";")
break;
}
return "xml-entity";
}
else {
source.nextWhileMatches(/[^&<\n]/);
return "xml-text";
}
}
function inTag(source, setState) {
var ch = source.next();
if (ch == ">") {
setState(inText);
return "xml-punctuation";
}
else if (/[?\/]/.test(ch) && source.equals(">")) {
source.next();
setState(inText);
return "xml-punctuation";
}
else if (ch == "=") {
return "xml-punctuation";
}
else if (/[\'\"]/.test(ch)) {
setState(inAttribute(ch));
return null;
}
else {
source.nextWhileMatches(/[^\s\u00a0=<>\"\'\/?]/);
return "xml-name";
}
}
function inAttribute(quote) {
return function(source, setState) {
while (!source.endOfLine()) {
if (source.next() == quote) {
setState(inTag);
break;
}
}
return "xml-attribute";
};
}
function inBlock(style, terminator) {
return function(source, setState) {
while (!source.endOfLine()) {
if (source.lookAhead(terminator, true)) {
setState(inText);
break;
}
source.next();
}
return style;
};
}
return function(source, startState) {
return tokenizer(source, startState || inText);
};
})();
// The parser. The structure of this function largely follows that of
// parseJavaScript in parsejavascript.js (there is actually a bit more
// shared code than I'd like), but it is quite a bit simpler.
function parseXML(source) {
var tokens = tokenizeXML(source), token;
var cc = [base];
var tokenNr = 0, indented = 0;
var currentTag = null, context = null;
var consume;
function push(fs) {
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
function cont() {
push(arguments);
consume = true;
}
function pass() {
push(arguments);
consume = false;
}
function markErr() {
token.style += " xml-error";
}
function expect(text) {
return function(style, content) {
if (content == text) cont();
else {markErr(); cont(arguments.callee);}
};
}
function pushContext(tagname, startOfLine) {
var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent);
context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent};
}
function popContext() {
context = context.prev;
}
function computeIndentation(baseContext) {
return function(nextChars, current) {
var context = baseContext;
if (context && context.noIndent)
return current;
if (alignCDATA && /<!\[CDATA\[/.test(nextChars))
return 0;
if (context && /^<\//.test(nextChars))
context = context.prev;
while (context && !context.startOfLine)
context = context.prev;
if (context)
return context.indent + indentUnit;
else
return 0;
};
}
function base() {
return pass(element, base);
}
var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true, "xml-processing": true};
function element(style, content) {
if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1));
else if (content == "</") cont(closetagname, expect(">"));
else if (style == "xml-cdata") {
if (!context || context.name != "!cdata") pushContext("!cdata");
if (/\]\]>$/.test(content)) popContext();
cont();
}
else if (harmlessTokens.hasOwnProperty(style)) cont();
else {markErr(); cont();}
}
function tagname(style, content) {
if (style == "xml-name") {
currentTag = content.toLowerCase();
token.style = "xml-tagname";
cont();
}
else {
currentTag = null;
pass();
}
}
function closetagname(style, content) {
if (style == "xml-name") {
token.style = "xml-tagname";
if (context && content.toLowerCase() == context.name) popContext();
else markErr();
}
cont();
}
function endtag(startOfLine) {
return function(style, content) {
if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont();
else if (content == ">") {pushContext(currentTag, startOfLine); cont();}
else {markErr(); cont(arguments.callee);}
};
}
function attributes(style) {
if (style == "xml-name") {token.style = "xml-attname"; cont(attribute, attributes);}
else pass();
}
function attribute(style, content) {
if (content == "=") cont(value);
else if (content == ">" || content == "/>") pass(endtag);
else pass();
}
function value(style) {
if (style == "xml-attribute") cont(value);
else pass();
}
return {
indentation: function() {return indented;},
next: function(){
token = tokens.next();
if (token.style == "whitespace" && tokenNr == 0)
indented = token.value.length;
else
tokenNr++;
if (token.content == "\n") {
indented = tokenNr = 0;
token.indentation = computeIndentation(context);
}
if (token.style == "whitespace" || token.type == "xml-comment")
return token;
while(true){
consume = false;
cc.pop()(token.style, token.content);
if (consume) return token;
}
},
copy: function(){
var _cc = cc.concat([]), _tokenState = tokens.state, _context = context;
var parser = this;
return function(input){
cc = _cc.concat([]);
tokenNr = indented = 0;
context = _context;
tokens = tokenizeXML(input, _tokenState);
return parser;
};
}
};
}
return {
make: parseXML,
electricChars: "/",
configure: function(config) {
if (config.useHTMLKludges != null)
UseKludges = config.useHTMLKludges ? Kludges : NoKludges;
if (config.alignCDATA)
alignCDATA = config.alignCDATA;
}
};
})();
| JavaScript |
/* String streams are the things fed to parsers (which can feed them
* to a tokenizer if they want). They provide peek and next methods
* for looking at the current character (next 'consumes' this
* character, peek does not), and a get method for retrieving all the
* text that was consumed since the last time get was called.
*
* An easy mistake to make is to let a StopIteration exception finish
* the token stream while there are still characters pending in the
* string stream (hitting the end of the buffer while parsing a
* token). To make it easier to detect such errors, the stringstreams
* throw an exception when this happens.
*/
// Make a stringstream stream out of an iterator that returns strings.
// This is applied to the result of traverseDOM (see codemirror.js),
// and the resulting stream is fed to the parser.
var stringStream = function(source){
// String that's currently being iterated over.
var current = "";
// Position in that string.
var pos = 0;
// Accumulator for strings that have been iterated over but not
// get()-ed yet.
var accum = "";
// Make sure there are more characters ready, or throw
// StopIteration.
function ensureChars() {
while (pos == current.length) {
accum += current;
current = ""; // In case source.next() throws
pos = 0;
try {current = source.next();}
catch (e) {
if (e != StopIteration) throw e;
else return false;
}
}
return true;
}
return {
// Return the next character in the stream.
peek: function() {
if (!ensureChars()) return null;
return current.charAt(pos);
},
// Get the next character, throw StopIteration if at end, check
// for unused content.
next: function() {
if (!ensureChars()) {
if (accum.length > 0)
throw "End of stringstream reached without emptying buffer ('" + accum + "').";
else
throw StopIteration;
}
return current.charAt(pos++);
},
// Return the characters iterated over since the last call to
// .get().
get: function() {
var temp = accum;
accum = "";
if (pos > 0){
temp += current.slice(0, pos);
current = current.slice(pos);
pos = 0;
}
return temp;
},
// Push a string back into the stream.
push: function(str) {
current = current.slice(0, pos) + str + current.slice(pos);
},
lookAhead: function(str, consume, skipSpaces, caseInsensitive) {
function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
str = cased(str);
var found = false;
var _accum = accum, _pos = pos;
if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/);
while (true) {
var end = pos + str.length, left = current.length - pos;
if (end <= current.length) {
found = str == cased(current.slice(pos, end));
pos = end;
break;
}
else if (str.slice(0, left) == cased(current.slice(pos))) {
accum += current; current = "";
try {current = source.next();}
catch (e) {break;}
pos = 0;
str = str.slice(left);
}
else {
break;
}
}
if (!(found && consume)) {
current = accum.slice(_accum.length) + current;
pos = _pos;
accum = _accum;
}
return found;
},
// Utils built on top of the above
more: function() {
return this.peek() !== null;
},
applies: function(test) {
var next = this.peek();
return (next !== null && test(next));
},
nextWhile: function(test) {
var next;
while ((next = this.peek()) !== null && test(next))
this.next();
},
matches: function(re) {
var next = this.peek();
return (next !== null && re.test(next));
},
nextWhileMatches: function(re) {
var next;
while ((next = this.peek()) !== null && re.test(next))
this.next();
},
equals: function(ch) {
return ch === this.peek();
},
endOfLine: function() {
var next = this.peek();
return next == null || next == "\n";
}
};
};
| JavaScript |
/* CodeMirror main module
*
* Implements the CodeMirror constructor and prototype, which take care
* of initializing the editor frame, and providing the outside interface.
*/
// The CodeMirrorConfig object is used to specify a default
// configuration. If you specify such an object before loading this
// file, the values you put into it will override the defaults given
// below. You can also assign to it after loading.
var CodeMirrorConfig = window.CodeMirrorConfig || {};
var CodeMirror = (function(){
function setDefaults(object, defaults) {
for (var option in defaults) {
if (!object.hasOwnProperty(option))
object[option] = defaults[option];
}
}
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
// These default options can be overridden by passing a set of
// options to a specific CodeMirror constructor. See manual.html for
// their meaning.
setDefaults(CodeMirrorConfig, {
stylesheet: "",
path: "",
parserfile: [],
basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
iframeClass: null,
passDelay: 200,
passTime: 50,
lineNumberDelay: 200,
lineNumberTime: 50,
continuousScanning: false,
saveFunction: null,
onChange: null,
undoDepth: 50,
undoDelay: 800,
disableSpellcheck: true,
textWrapping: true,
readOnly: false,
width: "",
height: "300px",
autoMatchParens: false,
parserConfig: null,
tabMode: "indent", // or "spaces", "default", "shift"
reindentOnLoad: false,
activeTokens: null,
cursorActivity: null,
lineNumbers: false,
indentUnit: 2
});
function addLineNumberDiv(container) {
var nums = document.createElement("DIV"),
scroller = document.createElement("DIV");
nums.style.position = "absolute";
nums.style.height = "100%";
if (nums.style.setExpression) {
try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");}
catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions
}
nums.style.top = "0px";
nums.style.overflow = "hidden";
container.appendChild(nums);
scroller.className = "CodeMirror-line-numbers";
nums.appendChild(scroller);
return nums;
}
function CodeMirror(place, options) {
// Backward compatibility for deprecated options.
if (options.dumbTabs) options.tabMode = "spaces";
else if (options.normalTab) options.tabMode = "default";
// Use passed options, if any, to override defaults.
this.options = options = options || {};
setDefaults(options, CodeMirrorConfig);
var frame = this.frame = document.createElement("IFRAME");
if (options.iframeClass) frame.className = options.iframeClass;
frame.frameBorder = 0;
frame.src = "javascript:false;";
frame.style.border = "0";
frame.style.width = '100%';
frame.style.height = '100%';
// display: block occasionally suppresses some Firefox bugs, so we
// always add it, redundant as it sounds.
frame.style.display = "block";
var div = this.wrapping = document.createElement("DIV");
div.style.position = "relative";
div.className = "CodeMirror-wrapping";
div.style.width = options.width;
div.style.height = options.height;
if (place.appendChild) place.appendChild(div);
else place(div);
div.appendChild(frame);
if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div);
// Link back to this object, so that the editor can fetch options
// and add a reference to itself.
frame.CodeMirror = this;
this.win = frame.contentWindow;
if (typeof options.parserfile == "string")
options.parserfile = [options.parserfile];
if (typeof options.stylesheet == "string")
options.stylesheet = [options.stylesheet];
var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"];
// Hack to work around a bunch of IE8-specific problems.
html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");
forEach(options.stylesheet, function(file) {
html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + "\"/>");
});
forEach(options.basefiles.concat(options.parserfile), function(file) {
html.push("<script type=\"text/javascript\" src=\"" + options.path + file + "\"><" + "/script>");
});
html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" +
(options.disableSpellcheck ? "false" : "true") + "\"></body></html>");
var doc = this.win.document;
doc.open();
doc.write(html.join(""));
doc.close();
}
CodeMirror.prototype = {
init: function() {
if (this.options.initCallback) this.options.initCallback(this);
if (this.options.lineNumbers) this.activateLineNumbers();
if (this.options.reindentOnLoad) this.reindent();
},
getCode: function() {return this.editor.getCode();},
setCode: function(code) {this.editor.importCode(code);},
selection: function() {this.focusIfIE(); return this.editor.selectedText();},
reindent: function() {this.editor.reindent();},
reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);},
focusIfIE: function() {
// in IE, a lot of selection-related functionality only works when the frame is focused
if (this.win.select.ie_selection) this.focus();
},
focus: function() {
this.win.focus();
if (this.editor.selectionSnapshot) // IE hack
this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot);
},
replaceSelection: function(text) {
this.focus();
this.editor.replaceSelection(text);
return true;
},
replaceChars: function(text, start, end) {
this.editor.replaceChars(text, start, end);
},
getSearchCursor: function(string, fromCursor, caseFold) {
return this.editor.getSearchCursor(string, fromCursor, caseFold);
},
undo: function() {this.editor.history.undo();},
redo: function() {this.editor.history.redo();},
historySize: function() {return this.editor.history.historySize();},
clearHistory: function() {this.editor.history.clear();},
grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);},
ungrabKeys: function() {this.editor.ungrabKeys();},
setParser: function(name) {this.editor.setParser(name);},
setSpellcheck: function(on) {this.win.document.body.spellcheck = on;},
setTextWrapping: function(on) {
if (on == this.options.textWrapping) return;
this.win.document.body.style.whiteSpace = on ? "" : "nowrap";
this.options.textWrapping = on;
if (this.lineNumbers) {
this.setLineNumbers(false);
this.setLineNumbers(true);
}
},
setIndentUnit: function(unit) {this.win.indentUnit = unit;},
setUndoDepth: function(depth) {this.editor.history.maxDepth = depth;},
setTabMode: function(mode) {this.options.tabMode = mode;},
setLineNumbers: function(on) {
if (on && !this.lineNumbers) {
this.lineNumbers = addLineNumberDiv(this.wrapping);
this.activateLineNumbers();
}
else if (!on && this.lineNumbers) {
this.wrapping.removeChild(this.lineNumbers);
this.wrapping.style.marginLeft = "";
this.lineNumbers = null;
}
},
cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);},
firstLine: function() {return this.editor.firstLine();},
lastLine: function() {return this.editor.lastLine();},
nextLine: function(line) {return this.editor.nextLine(line);},
prevLine: function(line) {return this.editor.prevLine(line);},
lineContent: function(line) {return this.editor.lineContent(line);},
setLineContent: function(line, content) {this.editor.setLineContent(line, content);},
removeLine: function(line){this.editor.removeLine(line);},
insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);},
selectLines: function(startLine, startOffset, endLine, endOffset) {
this.win.focus();
this.editor.selectLines(startLine, startOffset, endLine, endOffset);
},
nthLine: function(n) {
var line = this.firstLine();
for (; n > 1 && line !== false; n--)
line = this.nextLine(line);
return line;
},
lineNumber: function(line) {
var num = 0;
while (line !== false) {
num++;
line = this.prevLine(line);
}
return num;
},
// Old number-based line interface
jumpToLine: function(n) {
this.selectLines(this.nthLine(n), 0);
this.win.focus();
},
currentLine: function() {
return this.lineNumber(this.cursorPosition().line);
},
activateLineNumbers: function() {
var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body,
nums = this.lineNumbers, scroller = nums.firstChild, self = this;
var barWidth = null;
function sizeBar() {
if (frame.offsetWidth == 0) return;
for (var root = frame; root.parentNode; root = root.parentNode);
if (!nums.parentNode || root != document || !win.Editor) {
// Clear event handlers (their nodes might already be collected, so try/catch)
try{clear();}catch(e){}
clearInterval(sizeInterval);
return;
}
if (nums.offsetWidth != barWidth) {
barWidth = nums.offsetWidth;
nums.style.left = "-" + (frame.parentNode.style.marginLeft = barWidth + "px");
}
}
function doScroll() {
nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0;
}
// Cleanup function, registered by nonWrapping and wrapping.
var clear = function(){};
sizeBar();
var sizeInterval = setInterval(sizeBar, 500);
function nonWrapping() {
var nextNum = 1;
function update() {
var target = 50 + Math.max(body.offsetHeight, frame.offsetHeight);
while (scroller.offsetHeight < target) {
scroller.appendChild(document.createElement("DIV"));
scroller.lastChild.innerHTML = nextNum++;
}
doScroll();
}
var onScroll = win.addEventHandler(win, "scroll", update, true),
onResize = win.addEventHandler(win, "resize", update, true);
clear = function(){onScroll(); onResize();};
update();
}
function wrapping() {
var node, lineNum, next, pos;
function addNum(n) {
if (!lineNum) lineNum = scroller.appendChild(document.createElement("DIV"));
lineNum.innerHTML = n;
pos = lineNum.offsetHeight + lineNum.offsetTop;
lineNum = lineNum.nextSibling;
}
function work() {
if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return;
var endTime = new Date().getTime() + self.options.lineNumberTime;
while (node) {
addNum(next++);
for (; node && !win.isBR(node); node = node.nextSibling) {
var bott = node.offsetTop + node.offsetHeight;
while (bott - 3 > pos) addNum(" ");
}
if (node) node = node.nextSibling;
if (new Date().getTime() > endTime) {
pending = setTimeout(work, self.options.lineNumberDelay);
return;
}
}
// While there are un-processed number DIVs, or the scroller is smaller than the frame...
var target = 50 + Math.max(body.offsetHeight, frame.offsetHeight);
while (lineNum || scroller.offsetHeight < target) addNum(next++);
doScroll();
}
function start() {
doScroll();
node = body.firstChild;
lineNum = scroller.firstChild;
pos = 0;
next = 1;
work();
}
start();
var pending = null;
function update() {
if (pending) clearTimeout(pending);
if (self.editor.allClean()) start();
else pending = setTimeout(update, 200);
}
self.updateNumbers = update;
var onScroll = win.addEventHandler(win, "scroll", doScroll, true),
onResize = win.addEventHandler(win, "resize", update, true);
clear = function(){
if (pending) clearTimeout(pending);
if (self.updateNumbers == update) self.updateNumbers = null;
onScroll();
onResize();
};
}
(this.options.textWrapping ? wrapping : nonWrapping)();
}
};
CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}};
CodeMirror.replace = function(element) {
if (typeof element == "string")
element = document.getElementById(element);
return function(newElement) {
element.parentNode.replaceChild(newElement, element);
};
};
CodeMirror.fromTextArea = function(area, options) {
if (typeof area == "string")
area = document.getElementById(area);
options = options || {};
if (area.style.width && options.width == null)
options.width = area.style.width;
if (area.style.height && options.height == null)
options.height = area.style.height;
if (options.content == null) options.content = area.value;
if (area.form) {
function updateField() {
area.value = mirror.getCode();
}
if (typeof area.form.addEventListener == "function")
area.form.addEventListener("submit", updateField, false);
else
area.form.attachEvent("onsubmit", updateField);
}
function insert(frame) {
if (area.nextSibling)
area.parentNode.insertBefore(frame, area.nextSibling);
else
area.parentNode.appendChild(frame);
}
area.style.display = "none";
var mirror = new CodeMirror(insert, options);
return mirror;
};
CodeMirror.isProbablySupported = function() {
// This is rather awful, but can be useful.
var match;
if (window.opera)
return Number(window.opera.version()) >= 9.52;
else if (/Apple Computers, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
return Number(match[1]) >= 3;
else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
return Number(match[1]) >= 6;
else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
return Number(match[1]) >= 20050901;
else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/))
return Number(match[1]) >= 525;
else
return null;
};
return CodeMirror;
})();
| JavaScript |
/* Parse function for JavaScript. Makes use of the tokenizer from
* tokenizejavascript.js. Note that your parsers do not have to be
* this complicated -- if you don't want to recognize local variables,
* in many languages it is enough to just look for braces, semicolons,
* parentheses, etc, and know when you are inside a string or comment.
*
* See manual.html for more info about the parser interface.
*/
var JSParser = Editor.Parser = (function() {
// Token types that can be considered to be atoms.
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
// Setting that can be used to have JSON data indent properly.
var json = false;
// Constructor for the lexical context objects.
function JSLexical(indented, column, type, align, prev, info) {
// indentation at start of this line
this.indented = indented;
// column at which this scope was opened
this.column = column;
// type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(')
this.type = type;
// '[', '{', or '(' blocks that have any text after their opening
// character are said to be 'aligned' -- any lines below are
// indented all the way to the opening character.
if (align != null)
this.align = align;
// Parent scope, if any.
this.prev = prev;
this.info = info;
}
// My favourite JavaScript indentation rules.
function indentJS(lexical) {
return function(firstChars) {
var firstChar = firstChars && firstChars.charAt(0), type = lexical.type;
var closing = firstChar == type;
if (type == "vardef")
return lexical.indented + 4;
else if (type == "form" && firstChar == "{")
return lexical.indented;
else if (type == "stat" || type == "form")
return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit);
else if (lexical.align)
return lexical.column - (closing ? 1 : 0);
else
return lexical.indented + (closing ? 0 : indentUnit);
};
}
// The parser-iterator-producing function itself.
function parseJS(input, basecolumn) {
// Wrap the input in a token stream
var tokens = tokenizeJavaScript(input);
// The parser state. cc is a stack of actions that have to be
// performed to finish the current statement. For example we might
// know that we still need to find a closing parenthesis and a
// semicolon. Actions at the end of the stack go first. It is
// initialized with an infinitely looping action that consumes
// whole statements.
var cc = [statements];
// Context contains information about the current local scope, the
// variables defined in that, and the scopes above it.
var context = null;
// The lexical scope, used mostly for indentation.
var lexical = new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false);
// Current column, and the indentation at the start of the current
// line. Used to create lexical scope objects.
var column = 0;
var indented = 0;
// Variables which are used by the mark, cont, and pass functions
// below to communicate with the driver loop in the 'next'
// function.
var consume, marked;
// The iterator object.
var parser = {next: next, copy: copy};
function next(){
// Start by performing any 'lexical' actions (adjusting the
// lexical variable), or the operations below will be working
// with the wrong lexical state.
while(cc[cc.length - 1].lex)
cc.pop()();
// Fetch a token.
var token = tokens.next();
// Adjust column and indented.
if (token.type == "whitespace" && column == 0)
indented = token.value.length;
column += token.value.length;
if (token.content == "\n"){
indented = column = 0;
// If the lexical scope's align property is still undefined at
// the end of the line, it is an un-aligned scope.
if (!("align" in lexical))
lexical.align = false;
// Newline tokens get an indentation function associated with
// them.
token.indentation = indentJS(lexical);
}
// No more processing for meaningless tokens.
if (token.type == "whitespace" || token.type == "comment")
return token;
// When a meaningful token is found and the lexical scope's
// align is undefined, it is an aligned scope.
if (!("align" in lexical))
lexical.align = true;
// Execute actions until one 'consumes' the token and we can
// return it.
while(true) {
consume = marked = false;
// Take and execute the topmost action.
cc.pop()(token.type, token.content);
if (consume){
// Marked is used to change the style of the current token.
if (marked)
token.style = marked;
// Here we differentiate between local and global variables.
else if (token.type == "variable" && inScope(token.content))
token.style = "js-localvariable";
return token;
}
}
}
// This makes a copy of the parser state. It stores all the
// stateful variables in a closure, and returns a function that
// will restore them when called with a new input stream. Note
// that the cc array has to be copied, because it is contantly
// being modified. Lexical objects are not mutated, and context
// objects are not mutated in a harmful way, so they can be shared
// between runs of the parser.
function copy(){
var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;
return function copyParser(input){
context = _context;
lexical = _lexical;
cc = _cc.concat([]); // copies the array
column = indented = 0;
tokens = tokenizeJavaScript(input, _tokenState);
return parser;
};
}
// Helper function for pushing a number of actions onto the cc
// stack in reverse order.
function push(fs){
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
// cont and pass are used by the action functions to add other
// actions to the stack. cont will cause the current token to be
// consumed, pass will leave it for the next action.
function cont(){
push(arguments);
consume = true;
}
function pass(){
push(arguments);
consume = false;
}
// Used to change the style of the current token.
function mark(style){
marked = style;
}
// Push a new scope. Will automatically link the current scope.
function pushcontext(){
context = {prev: context, vars: {"this": true, "arguments": true}};
}
// Pop off the current scope.
function popcontext(){
context = context.prev;
}
// Register a variable in the current scope.
function register(varname){
if (context){
mark("js-variabledef");
context.vars[varname] = true;
}
}
// Check whether a variable is defined in the current scope.
function inScope(varname){
var cursor = context;
while (cursor) {
if (cursor.vars[varname])
return true;
cursor = cursor.prev;
}
return false;
}
// Push a new lexical context of the given type.
function pushlex(type, info) {
var result = function(){
lexical = new JSLexical(indented, column, type, null, lexical, info)
};
result.lex = true;
return result;
}
// Pop off the current lexical context.
function poplex(){
lexical = lexical.prev;
}
poplex.lex = true;
// The 'lex' flag on these actions is used by the 'next' function
// to know they can (and have to) be ran before moving on to the
// next token.
// Creates an action that discards tokens until it finds one of
// the given type.
function expect(wanted){
return function expecting(type){
if (type == wanted) cont();
else cont(arguments.callee);
};
}
// Looks for a statement, and then calls itself.
function statements(type){
return pass(statement, statements);
}
// Dispatches various types of statements based on the type of the
// current token.
function statement(type){
if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex);
else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex);
else if (type == "keyword b") cont(pushlex("form"), statement, poplex);
else if (type == "{" && json) cont(pushlex("}"), commasep(objprop, "}"), poplex);
else if (type == "{") cont(pushlex("}"), block, poplex);
else if (type == "function") cont(functiondef);
else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex);
else if (type == "variable") cont(pushlex("stat"), maybelabel);
else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex);
else if (type == "case") cont(expression, expect(":"));
else if (type == "default") cont(expect(":"));
else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext);
else pass(pushlex("stat"), expression, expect(";"), poplex);
}
// Dispatch expression types.
function expression(type){
if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator);
else if (type == "function") cont(functiondef);
else if (type == "keyword c") cont(expression);
else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
else if (type == "operator") cont(expression);
else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
}
// Called for places where operators, function calls, or
// subscripts are valid. Will skip on to the next action if none
// is found.
function maybeoperator(type){
if (type == "operator") cont(expression);
else if (type == "(") cont(pushlex(")"), expression, commasep(expression, ")"), poplex, maybeoperator);
else if (type == ".") cont(property, maybeoperator);
else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
// When a statement starts with a variable name, it might be a
// label. If no colon follows, it's a regular statement.
function maybelabel(type){
if (type == ":") cont(poplex, statement);
else pass(maybeoperator, expect(";"), poplex);
}
// Property names need to have their style adjusted -- the
// tokenizer thinks they are variables.
function property(type){
if (type == "variable") {mark("js-property"); cont();}
}
// This parses a property and its value in an object literal.
function objprop(type){
if (type == "variable") mark("js-property");
if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression);
}
// Parses a comma-separated list of the things that are recognized
// by the 'what' argument.
function commasep(what, end){
function proceed(type) {
if (type == ",") cont(what, proceed);
else if (type == end) cont();
else cont(expect(end));
}
return function commaSeparated(type) {
if (type == end) cont();
else pass(what, proceed);
};
}
// Look for statements until a closing brace is found.
function block(type){
if (type == "}") cont();
else pass(statement, block);
}
// Variable definitions are split into two actions -- 1 looks for
// a name or the end of the definition, 2 looks for an '=' sign or
// a comma.
function vardef1(type, value){
if (type == "variable"){register(value); cont(vardef2);}
else cont();
}
function vardef2(type, value){
if (value == "=") cont(expression, vardef2);
else if (type == ",") cont(vardef1);
}
// For loops.
function forspec1(type){
if (type == "var") cont(vardef1, forspec2);
else if (type == ";") pass(forspec2);
else if (type == "variable") cont(formaybein);
else pass(forspec2);
}
function formaybein(type, value){
if (value == "in") cont(expression);
else cont(maybeoperator, forspec2);
}
function forspec2(type, value){
if (type == ";") cont(forspec3);
else if (value == "in") cont(expression);
else cont(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type == ")") pass();
else cont(expression);
}
// A function definition creates a new context, and the variables
// in its argument list have to be added to this context.
function functiondef(type, value){
if (type == "variable"){register(value); cont(functiondef);}
else if (type == "(") cont(pushcontext, commasep(funarg, ")"), statement, popcontext);
}
function funarg(type, value){
if (type == "variable"){register(value); cont();}
}
return parser;
}
return {
make: parseJS,
electricChars: "{}:",
configure: function(obj) {
if (obj.json != null) json = obj.json;
}
};
})();
| JavaScript |
/**
* Storage and control for undo information within a CodeMirror
* editor. 'Why on earth is such a complicated mess required for
* that?', I hear you ask. The goal, in implementing this, was to make
* the complexity of storing and reverting undo information depend
* only on the size of the edited or restored content, not on the size
* of the whole document. This makes it necessary to use a kind of
* 'diff' system, which, when applied to a DOM tree, causes some
* complexity and hackery.
*
* In short, the editor 'touches' BR elements as it parses them, and
* the History stores these. When nothing is touched in commitDelay
* milliseconds, the changes are committed: It goes over all touched
* nodes, throws out the ones that did not change since last commit or
* are no longer in the document, and assembles the rest into zero or
* more 'chains' -- arrays of adjacent lines. Links back to these
* chains are added to the BR nodes, while the chain that previously
* spanned these nodes is added to the undo history. Undoing a change
* means taking such a chain off the undo history, restoring its
* content (text is saved per line) and linking it back into the
* document.
*/
// A history object needs to know about the DOM container holding the
// document, the maximum amount of undo levels it should store, the
// delay (of no input) after which it commits a set of changes, and,
// unfortunately, the 'parent' window -- a window that is not in
// designMode, and on which setTimeout works in every browser.
function History(container, maxDepth, commitDelay, editor) {
this.container = container;
this.maxDepth = maxDepth; this.commitDelay = commitDelay;
this.editor = editor; this.parent = editor.parent;
// This line object represents the initial, empty editor.
var initial = {text: "", from: null, to: null};
// As the borders between lines are represented by BR elements, the
// start of the first line and the end of the last one are
// represented by null. Since you can not store any properties
// (links to line objects) in null, these properties are used in
// those cases.
this.first = initial; this.last = initial;
// Similarly, a 'historyTouched' property is added to the BR in
// front of lines that have already been touched, and 'firstTouched'
// is used for the first line.
this.firstTouched = false;
// History is the set of committed changes, touched is the set of
// nodes touched since the last commit.
this.history = []; this.redoHistory = []; this.touched = [];
}
History.prototype = {
// Schedule a commit (if no other touches come in for commitDelay
// milliseconds).
scheduleCommit: function() {
var self = this;
this.parent.clearTimeout(this.commitTimeout);
this.commitTimeout = this.parent.setTimeout(function(){self.tryCommit();}, this.commitDelay);
},
// Mark a node as touched. Null is a valid argument.
touch: function(node) {
this.setTouched(node);
this.scheduleCommit();
},
// Undo the last change.
undo: function() {
// Make sure pending changes have been committed.
this.commit();
if (this.history.length) {
// Take the top diff from the history, apply it, and store its
// shadow in the redo history.
var item = this.history.pop();
this.redoHistory.push(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
// Redo the last undone change.
redo: function() {
this.commit();
if (this.redoHistory.length) {
// The inverse of undo, basically.
var item = this.redoHistory.pop();
this.addUndoLevel(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
clear: function() {
this.history = [];
this.redoHistory = [];
},
// Ask for the size of the un/redo histories.
historySize: function() {
return {undo: this.history.length, redo: this.redoHistory.length};
},
// Push a changeset into the document.
push: function(from, to, lines) {
var chain = [];
for (var i = 0; i < lines.length; i++) {
var end = (i == lines.length - 1) ? to : this.container.ownerDocument.createElement("BR");
chain.push({from: from, to: end, text: cleanText(lines[i])});
from = end;
}
this.pushChains([chain], from == null && to == null);
this.notifyEnvironment();
},
pushChains: function(chains, doNotHighlight) {
this.commit(doNotHighlight);
this.addUndoLevel(this.updateTo(chains, "applyChain"));
this.redoHistory = [];
},
// Retrieve a DOM node from a chain (for scrolling to it after undo/redo).
chainNode: function(chains) {
for (var i = 0; i < chains.length; i++) {
var start = chains[i][0], node = start && (start.from || start.to);
if (node) return node;
}
},
// Clear the undo history, make the current document the start
// position.
reset: function() {
this.history = []; this.redoHistory = [];
},
textAfter: function(br) {
return this.after(br).text;
},
nodeAfter: function(br) {
return this.after(br).to;
},
nodeBefore: function(br) {
return this.before(br).from;
},
// Commit unless there are pending dirty nodes.
tryCommit: function() {
if (!window.History) return; // Stop when frame has been unloaded
if (this.editor.highlightDirty()) this.commit(true);
else this.scheduleCommit();
},
// Check whether the touched nodes hold any changes, if so, commit
// them.
commit: function(doNotHighlight) {
this.parent.clearTimeout(this.commitTimeout);
// Make sure there are no pending dirty nodes.
if (!doNotHighlight) this.editor.highlightDirty(true);
// Build set of chains.
var chains = this.touchedChains(), self = this;
if (chains.length) {
this.addUndoLevel(this.updateTo(chains, "linkChain"));
this.redoHistory = [];
this.notifyEnvironment();
}
},
// [ end of public interface ]
// Update the document with a given set of chains, return its
// shadow. updateFunc should be "applyChain" or "linkChain". In the
// second case, the chains are taken to correspond the the current
// document, and only the state of the line data is updated. In the
// first case, the content of the chains is also pushed iinto the
// document.
updateTo: function(chains, updateFunc) {
var shadows = [], dirty = [];
for (var i = 0; i < chains.length; i++) {
shadows.push(this.shadowChain(chains[i]));
dirty.push(this[updateFunc](chains[i]));
}
if (updateFunc == "applyChain")
this.notifyDirty(dirty);
return shadows;
},
// Notify the editor that some nodes have changed.
notifyDirty: function(nodes) {
forEach(nodes, method(this.editor, "addDirtyNode"))
this.editor.scheduleHighlight();
},
notifyEnvironment: function() {
// Used by the line-wrapping line-numbering code.
if (window.frameElement && window.frameElement.CodeMirror.updateNumbers)
window.frameElement.CodeMirror.updateNumbers();
if (this.onChange) this.onChange();
},
// Link a chain into the DOM nodes (or the first/last links for null
// nodes).
linkChain: function(chain) {
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
if (line.from) line.from.historyAfter = line;
else this.first = line;
if (line.to) line.to.historyBefore = line;
else this.last = line;
}
},
// Get the line object after/before a given node.
after: function(node) {
return node ? node.historyAfter : this.first;
},
before: function(node) {
return node ? node.historyBefore : this.last;
},
// Mark a node as touched if it has not already been marked.
setTouched: function(node) {
if (node) {
if (!node.historyTouched) {
this.touched.push(node);
node.historyTouched = true;
}
}
else {
this.firstTouched = true;
}
},
// Store a new set of undo info, throw away info if there is more of
// it than allowed.
addUndoLevel: function(diffs) {
this.history.push(diffs);
if (this.history.length > this.maxDepth)
this.history.shift();
},
// Build chains from a set of touched nodes.
touchedChains: function() {
var self = this;
// The temp system is a crummy hack to speed up determining
// whether a (currently touched) node has a line object associated
// with it. nullTemp is used to store the object for the first
// line, other nodes get it stored in their historyTemp property.
var nullTemp = null;
function temp(node) {return node ? node.historyTemp : nullTemp;}
function setTemp(node, line) {
if (node) node.historyTemp = line;
else nullTemp = line;
}
function buildLine(node) {
var text = [];
for (var cur = node ? node.nextSibling : self.container.firstChild;
cur && !isBR(cur); cur = cur.nextSibling)
if (cur.currentText) text.push(cur.currentText);
return {from: node, to: cur, text: cleanText(text.join(""))};
}
// Filter out unchanged lines and nodes that are no longer in the
// document. Build up line objects for remaining nodes.
var lines = [];
if (self.firstTouched) self.touched.push(null);
forEach(self.touched, function(node) {
if (node && node.parentNode != self.container) return;
if (node) node.historyTouched = false;
else self.firstTouched = false;
var line = buildLine(node), shadow = self.after(node);
if (!shadow || shadow.text != line.text || shadow.to != line.to) {
lines.push(line);
setTemp(node, line);
}
});
// Get the BR element after/before the given node.
function nextBR(node, dir) {
var link = dir + "Sibling", search = node[link];
while (search && !isBR(search))
search = search[link];
return search;
}
// Assemble line objects into chains by scanning the DOM tree
// around them.
var chains = []; self.touched = [];
forEach(lines, function(line) {
// Note that this makes the loop skip line objects that have
// been pulled into chains by lines before them.
if (!temp(line.from)) return;
var chain = [], curNode = line.from, safe = true;
// Put any line objects (referred to by temp info) before this
// one on the front of the array.
while (true) {
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.unshift(curLine);
setTemp(curNode, null);
if (!curNode) break;
safe = self.after(curNode);
curNode = nextBR(curNode, "previous");
}
curNode = line.to; safe = self.before(line.from);
// Add lines after this one at end of array.
while (true) {
if (!curNode) break;
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.push(curLine);
setTemp(curNode, null);
safe = self.before(curNode);
curNode = nextBR(curNode, "next");
}
chains.push(chain);
});
return chains;
},
// Find the 'shadow' of a given chain by following the links in the
// DOM nodes at its start and end.
shadowChain: function(chain) {
var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
while (true) {
shadows.push(next);
var nextNode = next.to;
if (!nextNode || nextNode == end)
break;
else
next = nextNode.historyAfter || this.before(end);
// (The this.before(end) is a hack -- FF sometimes removes
// properties from BR nodes, in which case the best we can hope
// for is to not break.)
}
return shadows;
},
// Update the DOM tree to contain the lines specified in a given
// chain, link this chain into the DOM nodes.
applyChain: function(chain) {
// Some attempt is made to prevent the cursor from jumping
// randomly when an undo or redo happens. It still behaves a bit
// strange sometimes.
var cursor = select.cursorPos(this.container, false), self = this;
// Remove all nodes in the DOM tree between from and to (null for
// start/end of container).
function removeRange(from, to) {
var pos = from ? from.nextSibling : self.container.firstChild;
while (pos != to) {
var temp = pos.nextSibling;
removeElement(pos);
pos = temp;
}
}
var start = chain[0].from, end = chain[chain.length - 1].to;
// Clear the space where this change has to be made.
removeRange(start, end);
// Insert the content specified by the chain into the DOM tree.
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
// The start and end of the space are already correct, but BR
// tags inside it have to be put back.
if (i > 0)
self.container.insertBefore(line.from, end);
// Add the text.
var node = makePartSpan(fixSpaces(line.text), this.container.ownerDocument);
self.container.insertBefore(node, end);
// See if the cursor was on this line. Put it back, adjusting
// for changed line length, if it was.
if (cursor && cursor.node == line.from) {
var cursordiff = 0;
var prev = this.after(line.from);
if (prev && i == chain.length - 1) {
// Only adjust if the cursor is after the unchanged part of
// the line.
for (var match = 0; match < cursor.offset &&
line.text.charAt(match) == prev.text.charAt(match); match++);
if (cursor.offset > match)
cursordiff = line.text.length - prev.text.length;
}
select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
}
// Cursor was in removed line, this is last new line.
else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
}
}
// Anchor the chain in the DOM tree.
this.linkChain(chain);
return start;
}
};
| JavaScript |
var DummyParser = Editor.Parser = (function() {
function tokenizeDummy(source) {
while (!source.endOfLine()) source.next();
return "text";
}
function parseDummy(source) {
function indentTo(n) {return function() {return n;}}
source = tokenizer(source, tokenizeDummy);
var space = 0;
var iter = {
next: function() {
var tok = source.next();
if (tok.type == "whitespace") {
if (tok.value == "\n") tok.indentation = indentTo(space);
else space = tok.value.length;
}
return tok;
},
copy: function() {
var _space = space;
return function(_source) {
space = _space;
source = tokenizer(_source, tokenizeDummy);
return iter;
};
}
};
return iter;
}
return {make: parseDummy};
})();
| JavaScript |
/* A few useful utility functions. */
// Capture a method on an object.
function method(obj, name) {
return function() {obj[name].apply(obj, arguments);};
}
// The value used to signal the end of a sequence in iterators.
var StopIteration = {toString: function() {return "StopIteration"}};
// Apply a function to each element in a sequence.
function forEach(iter, f) {
if (iter.next) {
try {while (true) f(iter.next());}
catch (e) {if (e != StopIteration) throw e;}
}
else {
for (var i = 0; i < iter.length; i++)
f(iter[i]);
}
}
// Map a function over a sequence, producing an array of results.
function map(iter, f) {
var accum = [];
forEach(iter, function(val) {accum.push(f(val));});
return accum;
}
// Create a predicate function that tests a string againsts a given
// regular expression. No longer used but might be used by 3rd party
// parsers.
function matcher(regexp){
return function(value){return regexp.test(value);};
}
// Test whether a DOM node has a certain CSS class. Much faster than
// the MochiKit equivalent, for some reason.
function hasClass(element, className){
var classes = element.className;
return classes && new RegExp("(^| )" + className + "($| )").test(classes);
}
// Insert a DOM node after another node.
function insertAfter(newNode, oldNode) {
var parent = oldNode.parentNode;
parent.insertBefore(newNode, oldNode.nextSibling);
return newNode;
}
function removeElement(node) {
if (node.parentNode)
node.parentNode.removeChild(node);
}
function clearElement(node) {
while (node.firstChild)
node.removeChild(node.firstChild);
}
// Check whether a node is contained in another one.
function isAncestor(node, child) {
while (child = child.parentNode) {
if (node == child)
return true;
}
return false;
}
// The non-breaking space character.
var nbsp = "\u00a0";
var matching = {"{": "}", "[": "]", "(": ")",
"}": "{", "]": "[", ")": "("};
// Standardize a few unportable event properties.
function normalizeEvent(event) {
if (!event.stopPropagation) {
event.stopPropagation = function() {this.cancelBubble = true;};
event.preventDefault = function() {this.returnValue = false;};
}
if (!event.stop) {
event.stop = function() {
this.stopPropagation();
this.preventDefault();
};
}
if (event.type == "keypress") {
event.code = (event.charCode == null) ? event.keyCode : event.charCode;
event.character = String.fromCharCode(event.code);
}
return event;
}
// Portably register event handlers.
function addEventHandler(node, type, handler, removeFunc) {
function wrapHandler(event) {
handler(normalizeEvent(event || window.event));
}
if (typeof node.addEventListener == "function") {
node.addEventListener(type, wrapHandler, false);
if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);};
}
else {
node.attachEvent("on" + type, wrapHandler);
if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
function nodeText(node) {
return node.textContent || node.innerText || node.nodeValue || "";
}
function nodeTop(node) {
var top = 0;
while (node.offsetParent) {
top += node.offsetTop;
node = node.offsetParent;
}
return top;
}
function isBR(node) {
var nn = node.nodeName;
return nn == "BR" || nn == "br";
}
function isSpan(node) {
var nn = node.nodeName;
return nn == "SPAN" || nn == "span";
}
| JavaScript |
/* Functionality for finding, storing, and restoring selections
*
* This does not provide a generic API, just the minimal functionality
* required by the CodeMirror system.
*/
// Namespace object.
var select = {};
(function() {
select.ie_selection = document.selection && document.selection.createRangeCollection;
// Find the 'top-level' (defined as 'a direct child of the node
// passed as the top argument') node that the given node is
// contained in. Return null if the given node is not inside the top
// node.
function topLevelNodeAt(node, top) {
while (node && node.parentNode != top)
node = node.parentNode;
return node;
}
// Find the top-level node that contains the node before this one.
function topLevelNodeBefore(node, top) {
while (!node.previousSibling && node.parentNode != top)
node = node.parentNode;
return topLevelNodeAt(node.previousSibling, top);
}
var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
select.scrollToNode = function(element) {
if (!element) return;
var doc = element.ownerDocument, body = doc.body,
win = (doc.defaultView || doc.parentWindow),
html = doc.documentElement,
atEnd = !element.nextSibling || !element.nextSibling.nextSibling
|| !element.nextSibling.nextSibling.nextSibling;
// In Opera (and recent Webkit versions), BR elements *always*
// have a offsetTop property of zero.
var compensateHack = 0;
while (element && !element.offsetTop) {
compensateHack++;
element = element.previousSibling;
}
// atEnd is another kludge for these browsers -- if the cursor is
// at the end of the document, and the node doesn't have an
// offset, just scroll to the end.
if (compensateHack == 0) atEnd = false;
var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, pos = element;
while (pos && pos.offsetParent) {
y += pos.offsetTop;
// Don't count X offset for <br> nodes
if (!isBR(pos))
x += pos.offsetLeft;
pos = pos.offsetParent;
}
var scroll_x = body.scrollLeft || html.scrollLeft || 0,
scroll_y = body.scrollTop || html.scrollTop || 0,
screen_x = x - scroll_x, screen_y = y - scroll_y, scroll = false;
if (screen_x < 0 || screen_x > (win.innerWidth || html.clientWidth || 0)) {
scroll_x = x;
scroll = true;
}
if (screen_y < 0 || atEnd || screen_y > (win.innerHeight || html.clientHeight || 0) - 50) {
scroll_y = atEnd ? 1e6 : y;
scroll = true;
}
if (scroll) win.scrollTo(scroll_x, scroll_y);
};
select.scrollToCursor = function(container) {
select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild);
};
// Used to prevent restoring a selection when we do not need to.
var currentSelection = null;
select.snapshotChanged = function() {
if (currentSelection) currentSelection.changed = true;
};
// This is called by the code in editor.js whenever it is replacing
// a text node. The function sees whether the given oldNode is part
// of the current selection, and updates this selection if it is.
// Because nodes are often only partially replaced, the length of
// the part that gets replaced has to be taken into account -- the
// selection might stay in the oldNode if the newNode is smaller
// than the selection's offset. The offset argument is needed in
// case the selection does move to the new object, and the given
// length is not the whole length of the new node (part of it might
// have been used to replace another node).
select.snapshotReplaceNode = function(from, to, length, offset) {
if (!currentSelection) return;
function replace(point) {
if (from == point.node) {
currentSelection.changed = true;
if (length && point.offset > length) {
point.offset -= length;
}
else {
point.node = to;
point.offset += (offset || 0);
}
}
}
replace(currentSelection.start);
replace(currentSelection.end);
};
select.snapshotMove = function(from, to, distance, relative, ifAtStart) {
if (!currentSelection) return;
function move(point) {
if (from == point.node && (!ifAtStart || point.offset == 0)) {
currentSelection.changed = true;
point.node = to;
if (relative) point.offset = Math.max(0, point.offset + distance);
else point.offset = distance;
}
}
move(currentSelection.start);
move(currentSelection.end);
};
// Most functions are defined in two ways, one for the IE selection
// model, one for the W3C one.
if (select.ie_selection) {
function selectionNode(win, start) {
var range = win.document.selection.createRange();
range.collapse(start);
function nodeAfter(node) {
var found = null;
while (!found && node) {
found = node.nextSibling;
node = node.parentNode;
}
return nodeAtStartOf(found);
}
function nodeAtStartOf(node) {
while (node && node.firstChild) node = node.firstChild;
return {node: node, offset: 0};
}
var containing = range.parentElement();
if (!isAncestor(win.document.body, containing)) return null;
if (!containing.firstChild) return nodeAtStartOf(containing);
var working = range.duplicate();
working.moveToElementText(containing);
working.collapse(true);
for (var cur = containing.firstChild; cur; cur = cur.nextSibling) {
if (cur.nodeType == 3) {
var size = cur.nodeValue.length;
working.move("character", size);
}
else {
working.moveToElementText(cur);
working.collapse(false);
}
var dir = range.compareEndPoints("StartToStart", working);
if (dir == 0) return nodeAfter(cur);
if (dir == 1) continue;
if (cur.nodeType != 3) return nodeAtStartOf(cur);
working.setEndPoint("StartToEnd", range);
return {node: cur, offset: size - working.text.length};
}
return nodeAfter(containing);
}
select.markSelection = function(win) {
currentSelection = null;
var sel = win.document.selection;
if (!sel) return;
var start = selectionNode(win, true),
end = selectionNode(win, false);
if (!start || !end) return;
currentSelection = {start: start, end: end, window: win, changed: false};
};
select.selectMarked = function() {
if (!currentSelection || !currentSelection.changed) return;
var win = currentSelection.window, doc = win.document;
function makeRange(point) {
var range = doc.body.createTextRange(),
node = point.node;
if (!node) {
range.moveToElementText(currentSelection.window.document.body);
range.collapse(false);
}
else if (node.nodeType == 3) {
range.moveToElementText(node.parentNode);
var offset = point.offset;
while (node.previousSibling) {
node = node.previousSibling;
offset += (node.innerText || "").length;
}
range.move("character", offset);
}
else {
range.moveToElementText(node);
range.collapse(true);
}
return range;
}
var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end);
start.setEndPoint("StartToEnd", end);
start.select();
};
// Get the top-level node that one end of the cursor is inside or
// after. Note that this returns false for 'no cursor', and null
// for 'start of document'.
select.selectionTopNode = function(container, start) {
var selection = container.ownerDocument.selection;
if (!selection) return false;
var range = selection.createRange(), range2 = range.duplicate();
range.collapse(start);
var around = range.parentElement();
if (around && isAncestor(container, around)) {
// Only use this node if the selection is not at its start.
range2.moveToElementText(around);
if (range.compareEndPoints("StartToStart", range2) == 1)
return topLevelNodeAt(around, container);
}
// Move the start of a range to the start of a node,
// compensating for the fact that you can't call
// moveToElementText with text nodes.
function moveToNodeStart(range, node) {
if (node.nodeType == 3) {
var count = 0, cur = node.previousSibling;
while (cur && cur.nodeType == 3) {
count += cur.nodeValue.length;
cur = cur.previousSibling;
}
if (cur) {
try{range.moveToElementText(cur);}
catch(e){return false;}
range.collapse(false);
}
else range.moveToElementText(node.parentNode);
if (count) range.move("character", count);
}
else {
try{range.moveToElementText(node);}
catch(e){return false;}
}
return true;
}
// Do a binary search through the container object, comparing
// the start of each node to the selection
var start = 0, end = container.childNodes.length - 1;
while (start < end) {
var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle];
if (!node) return false; // Don't ask. IE6 manages this sometimes.
if (!moveToNodeStart(range2, node)) return false;
if (range.compareEndPoints("StartToStart", range2) == 1)
start = middle;
else
end = middle - 1;
}
return container.childNodes[start] || null;
};
// Place the cursor after this.start. This is only useful when
// manually moving the cursor instead of restoring it to its old
// position.
select.focusAfterNode = function(node, container) {
var range = container.ownerDocument.body.createTextRange();
range.moveToElementText(node || container);
range.collapse(!node);
range.select();
};
select.somethingSelected = function(win) {
var sel = win.document.selection;
return sel && (sel.createRange().text != "");
};
function insertAtCursor(window, html) {
var selection = window.document.selection;
if (selection) {
var range = selection.createRange();
range.pasteHTML(html);
range.collapse(false);
range.select();
}
}
// Used to normalize the effect of the enter key, since browsers
// do widely different things when pressing enter in designMode.
select.insertNewlineAtCursor = function(window) {
insertAtCursor(window, "<br>");
};
select.insertTabAtCursor = function(window) {
insertAtCursor(window, fourSpaces);
};
// Get the BR node at the start of the line on which the cursor
// currently is, and the offset into the line. Returns null as
// node if cursor is on first line.
select.cursorPos = function(container, start) {
var selection = container.ownerDocument.selection;
if (!selection) return null;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
var range = selection.createRange(), range2 = range.duplicate();
range.collapse(start);
if (topNode) {
range2.moveToElementText(topNode);
range2.collapse(false);
}
else {
// When nothing is selected, we can get all kinds of funky errors here.
try { range2.moveToElementText(container); }
catch (e) { return null; }
range2.collapse(true);
}
range.setEndPoint("StartToStart", range2);
return {node: topNode, offset: range.text.length};
};
select.setCursorPos = function(container, from, to) {
function rangeAt(pos) {
var range = container.ownerDocument.body.createTextRange();
if (!pos.node) {
range.moveToElementText(container);
range.collapse(true);
}
else {
range.moveToElementText(pos.node);
range.collapse(false);
}
range.move("character", pos.offset);
return range;
}
var range = rangeAt(from);
if (to && to != from)
range.setEndPoint("EndToEnd", rangeAt(to));
range.select();
}
// Some hacks for storing and re-storing the selection when the editor loses and regains focus.
select.getBookmark = function (container) {
var from = select.cursorPos(container, true), to = select.cursorPos(container, false);
if (from && to) return {from: from, to: to};
};
// Restore a stored selection.
select.setBookmark = function(container, mark) {
if (!mark) return;
select.setCursorPos(container, mark.from, mark.to);
};
}
// W3C model
else {
// Store start and end nodes, and offsets within these, and refer
// back to the selection object from those nodes, so that this
// object can be updated when the nodes are replaced before the
// selection is restored.
select.markSelection = function (win) {
var selection = win.getSelection();
if (!selection || selection.rangeCount == 0)
return (currentSelection = null);
var range = selection.getRangeAt(0);
currentSelection = {
start: {node: range.startContainer, offset: range.startOffset},
end: {node: range.endContainer, offset: range.endOffset},
window: win,
changed: false
};
// We want the nodes right at the cursor, not one of their
// ancestors with a suitable offset. This goes down the DOM tree
// until a 'leaf' is reached (or is it *up* the DOM tree?).
function normalize(point){
while (point.node.nodeType != 3 && !isBR(point.node)) {
var newNode = point.node.childNodes[point.offset] || point.node.nextSibling;
point.offset = 0;
while (!newNode && point.node.parentNode) {
point.node = point.node.parentNode;
newNode = point.node.nextSibling;
}
point.node = newNode;
if (!newNode)
break;
}
}
normalize(currentSelection.start);
normalize(currentSelection.end);
};
select.selectMarked = function () {
var cs = currentSelection;
// on webkit-based browsers, it is apparently possible that the
// selection gets reset even when a node that is not one of the
// endpoints get messed with. the most common situation where
// this occurs is when a selection is deleted or overwitten. we
// check for that here.
function focusIssue() {
return cs.start.node == cs.end.node && cs.start.offset == 0 && cs.end.offset == 0;
}
if (!cs || !(cs.changed || (webkit && focusIssue()))) return;
var win = cs.window, range = win.document.createRange();
function setPoint(point, which) {
if (point.node) {
// Some magic to generalize the setting of the start and end
// of a range.
if (point.offset == 0)
range["set" + which + "Before"](point.node);
else
range["set" + which](point.node, point.offset);
}
else {
range.setStartAfter(win.document.body.lastChild || win.document.body);
}
}
setPoint(cs.end, "End");
setPoint(cs.start, "Start");
selectRange(range, win);
};
// Helper for selecting a range object.
function selectRange(range, window) {
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
function selectionRange(window) {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0)
return false;
else
return selection.getRangeAt(0);
}
// Finding the top-level node at the cursor in the W3C is, as you
// can see, quite an involved process.
select.selectionTopNode = function(container, start) {
var range = selectionRange(container.ownerDocument.defaultView);
if (!range) return false;
var node = start ? range.startContainer : range.endContainer;
var offset = start ? range.startOffset : range.endOffset;
// Work around (yet another) bug in Opera's selection model.
if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset]))
offset--;
// For text nodes, we look at the node itself if the cursor is
// inside, or at the node before it if the cursor is at the
// start.
if (node.nodeType == 3){
if (offset > 0)
return topLevelNodeAt(node, container);
else
return topLevelNodeBefore(node, container);
}
// Occasionally, browsers will return the HTML node as
// selection. If the offset is 0, we take the start of the frame
// ('after null'), otherwise, we take the last node.
else if (node.nodeName.toUpperCase() == "HTML") {
return (offset == 1 ? null : container.lastChild);
}
// If the given node is our 'container', we just look up the
// correct node by using the offset.
else if (node == container) {
return (offset == 0) ? null : node.childNodes[offset - 1];
}
// In any other case, we have a regular node. If the cursor is
// at the end of the node, we use the node itself, if it is at
// the start, we use the node before it, and in any other
// case, we look up the child before the cursor and use that.
else {
if (offset == node.childNodes.length)
return topLevelNodeAt(node, container);
else if (offset == 0)
return topLevelNodeBefore(node, container);
else
return topLevelNodeAt(node.childNodes[offset - 1], container);
}
};
select.focusAfterNode = function(node, container) {
var win = container.ownerDocument.defaultView,
range = win.document.createRange();
range.setStartBefore(container.firstChild || container);
// In Opera, setting the end of a range at the end of a line
// (before a BR) will cause the cursor to appear on the next
// line, so we set the end inside of the start node when
// possible.
if (node && !node.firstChild)
range.setEndAfter(node);
else if (node)
range.setEnd(node, node.childNodes.length);
else
range.setEndBefore(container.firstChild || container);
range.collapse(false);
selectRange(range, win);
};
select.somethingSelected = function(win) {
var range = selectionRange(win);
return range && !range.collapsed;
};
function insertNodeAtCursor(window, node) {
var range = selectionRange(window);
if (!range) return;
range.deleteContents();
range.insertNode(node);
webkitLastLineHack(window.document.body);
range = window.document.createRange();
range.selectNode(node);
range.collapse(false);
selectRange(range, window);
}
select.insertNewlineAtCursor = function(window) {
insertNodeAtCursor(window, window.document.createElement("BR"));
};
select.insertTabAtCursor = function(window) {
insertNodeAtCursor(window, window.document.createTextNode(fourSpaces));
};
select.cursorPos = function(container, start) {
var range = selectionRange(window);
if (!range) return;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
range = range.cloneRange();
range.collapse(start);
if (topNode)
range.setStartAfter(topNode);
else
range.setStartBefore(container);
return {node: topNode, offset: range.toString().length};
};
select.setCursorPos = function(container, from, to) {
var win = container.ownerDocument.defaultView,
range = win.document.createRange();
function setPoint(node, offset, side) {
if (offset == 0 && node && !node.nextSibling) {
range["set" + side + "After"](node);
return true;
}
if (!node)
node = container.firstChild;
else
node = node.nextSibling;
if (!node) return;
if (offset == 0) {
range["set" + side + "Before"](node);
return true;
}
var backlog = []
function decompose(node) {
if (node.nodeType == 3)
backlog.push(node);
else
forEach(node.childNodes, decompose);
}
while (true) {
while (node && !backlog.length) {
decompose(node);
node = node.nextSibling;
}
var cur = backlog.shift();
if (!cur) return false;
var length = cur.nodeValue.length;
if (length >= offset) {
range["set" + side](cur, offset);
return true;
}
offset -= length;
}
}
to = to || from;
if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
selectRange(range, win);
};
}
})();
| JavaScript |
/* Simple parser for CSS */
var CSSParser = Editor.Parser = (function() {
var tokenizeCSS = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "@") {
source.nextWhileMatches(/\w/);
return "css-at";
}
else if (ch == "/" && source.equals("*")) {
setState(inCComment);
return null;
}
else if (ch == "<" && source.equals("!")) {
setState(inSGMLComment);
return null;
}
else if (ch == "=") {
return "css-compare";
}
else if (source.equals("=") && (ch == "~" || ch == "|")) {
source.next();
return "css-compare";
}
else if (ch == "\"" || ch == "'") {
setState(inString(ch));
return null;
}
else if (ch == "#") {
source.nextWhileMatches(/\w/);
return "css-hash";
}
else if (ch == "!") {
source.nextWhileMatches(/[ \t]/);
source.nextWhileMatches(/\w/);
return "css-important";
}
else if (/\d/.test(ch)) {
source.nextWhileMatches(/[\w.%]/);
return "css-unit";
}
else if (/[,.+>*\/]/.test(ch)) {
return "css-select-op";
}
else if (/[;{}:\[\]]/.test(ch)) {
return "css-punctuation";
}
else {
source.nextWhileMatches(/[\w\\\-_]/);
return "css-identifier";
}
}
function inCComment(source, setState) {
var maybeEnd = false;
while (!source.endOfLine()) {
var ch = source.next();
if (maybeEnd && ch == "/") {
setState(normal);
break;
}
maybeEnd = (ch == "*");
}
return "css-comment";
}
function inSGMLComment(source, setState) {
var dashes = 0;
while (!source.endOfLine()) {
var ch = source.next();
if (dashes >= 2 && ch == ">") {
setState(normal);
break;
}
dashes = (ch == "-") ? dashes + 1 : 0;
}
return "css-comment";
}
function inString(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped)
setState(normal);
return "css-string";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentCSS(inBraces, inRule, base) {
return function(nextChars) {
if (!inBraces || /^\}/.test(nextChars)) return base;
else if (inRule) return base + indentUnit * 2;
else return base + indentUnit;
};
}
// This is a very simplistic parser -- since CSS does not really
// nest, it works acceptably well, but some nicer colouroing could
// be provided with a more complicated parser.
function parseCSS(source, basecolumn) {
basecolumn = basecolumn || 0;
var tokens = tokenizeCSS(source);
var inBraces = false, inRule = false;
var iter = {
next: function() {
var token = tokens.next(), style = token.style, content = token.content;
if (style == "css-identifier" && inRule)
token.style = "css-value";
if (style == "css-hash")
token.style = inRule ? "css-colorcode" : "css-identifier";
if (content == "\n")
token.indentation = indentCSS(inBraces, inRule, basecolumn);
if (content == "{")
inBraces = true;
else if (content == "}")
inBraces = inRule = false;
else if (inBraces && content == ";")
inRule = false;
else if (inBraces && style != "css-comment" && style != "whitespace")
inRule = true;
return token;
},
copy: function() {
var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeCSS(source, _tokenState);
inBraces = _inBraces;
inRule = _inRule;
return iter;
};
}
};
return iter;
}
return {make: parseCSS, electricChars: "}"};
})();
| JavaScript |
// A framework for simple tokenizers. Takes care of newlines and
// white-space, and of getting the text from the source stream into
// the token object. A state is a function of two arguments -- a
// string stream and a setState function. The second can be used to
// change the tokenizer's state, and can be ignored for stateless
// tokenizers. This function should advance the stream over a token
// and return a string or object containing information about the next
// token, or null to pass and have the (new) state be called to finish
// the token. When a string is given, it is wrapped in a {style, type}
// object. In the resulting object, the characters consumed are stored
// under the content property. Any whitespace following them is also
// automatically consumed, and added to the value property. (Thus,
// content is the actual meaningful part of the token, while value
// contains all the text it spans.)
function tokenizer(source, state) {
// Newlines are always a separate token.
function isWhiteSpace(ch) {
// The messy regexp is because IE's regexp matcher is of the
// opinion that non-breaking spaces are no whitespace.
return ch != "\n" && /^[\s\u00a0]*$/.test(ch);
}
var tokenizer = {
state: state,
take: function(type) {
if (typeof(type) == "string")
type = {style: type, type: type};
type.content = (type.content || "") + source.get();
if (!/\n$/.test(type.content))
source.nextWhile(isWhiteSpace);
type.value = type.content + source.get();
return type;
},
next: function () {
if (!source.more()) throw StopIteration;
var type;
if (source.equals("\n")) {
source.next();
return this.take("whitespace");
}
if (source.applies(isWhiteSpace))
type = "whitespace";
else
while (!type)
type = this.state(source, function(s) {tokenizer.state = s;});
return this.take(type);
}
};
return tokenizer;
}
| JavaScript |
var HTMLMixedParser = Editor.Parser = (function() {
if (!(CSSParser && JSParser && XMLParser))
throw new Error("CSS, JS, and XML parsers must be loaded for HTML mixed mode to work.");
XMLParser.configure({useHTMLKludges: true});
function parseMixed(stream) {
var htmlParser = XMLParser.make(stream), localParser = null, inTag = false;
var iter = {next: top, copy: copy};
function top() {
var token = htmlParser.next();
if (token.content == "<")
inTag = true;
else if (token.style == "xml-tagname" && inTag === true)
inTag = token.content.toLowerCase();
else if (token.content == ">") {
if (inTag == "script")
iter.next = local(JSParser, "</script");
else if (inTag == "style")
iter.next = local(CSSParser, "</style");
inTag = false;
}
return token;
}
function local(parser, tag) {
var baseIndent = htmlParser.indentation();
localParser = parser.make(stream, baseIndent + indentUnit);
return function() {
if (stream.lookAhead(tag, false, false, true)) {
localParser = null;
iter.next = top;
return top();
}
var token = localParser.next();
var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length);
if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) &&
stream.lookAhead(tag.slice(sz), false, false, true)) {
stream.push(token.value.slice(lt));
token.value = token.value.slice(0, lt);
}
if (token.indentation) {
var oldIndent = token.indentation;
token.indentation = function(chars) {
if (chars == "</")
return baseIndent;
else
return oldIndent(chars);
}
}
return token;
};
}
function copy() {
var _html = htmlParser.copy(), _local = localParser && localParser.copy(),
_next = iter.next, _inTag = inTag;
return function(_stream) {
stream = _stream;
htmlParser = _html(_stream);
localParser = _local && _local(_stream);
iter.next = _next;
inTag = _inTag;
return iter;
};
}
return iter;
}
return {make: parseMixed, electricChars: "{}/:"};
})();
| JavaScript |
/* Demonstration of embedding CodeMirror in a bigger application. The
* interface defined here is a mess of prompts and confirms, and
* should probably not be used in a real project.
*/
function MirrorFrame(place, options) {
this.home = document.createElement("DIV");
if (place.appendChild)
place.appendChild(this.home);
else
place(this.home);
var self = this;
function makeButton(name, action) {
var button = document.createElement("INPUT");
button.type = "button";
button.value = name;
self.home.appendChild(button);
button.onclick = function(){self[action].call(self);};
}
makeButton("Search", "search");
makeButton("Replace", "replace");
makeButton("Current line", "line");
makeButton("Jump to line", "jump");
makeButton("Insert constructor", "macro");
makeButton("Indent all", "reindent");
this.mirror = new CodeMirror(this.home, options);
}
MirrorFrame.prototype = {
search: function() {
var text = prompt("Enter search term:", "");
if (!text) return;
var first = true;
do {
var cursor = this.mirror.getSearchCursor(text, first, true);
first = false;
while (cursor.findNext()) {
cursor.select();
if (!confirm("Search again?"))
return;
}
} while (confirm("End of document reached. Start over?"));
},
replace: function() {
// This is a replace-all, but it is possible to implement a
// prompting replace.
var from = prompt("Enter search string:", ""), to;
if (from) to = prompt("What should it be replaced with?", "");
if (to == null) return;
var cursor = this.mirror.getSearchCursor(from, false);
while (cursor.findNext())
cursor.replace(to);
},
jump: function() {
var line = prompt("Jump to line:", "");
if (line && !isNaN(Number(line)))
this.mirror.jumpToLine(Number(line));
},
line: function() {
alert("The cursor is currently at line " + this.mirror.currentLine());
this.mirror.focus();
},
macro: function() {
var name = prompt("Name your constructor:", "");
if (name)
this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n");
},
reindent: function() {
this.mirror.reindent();
}
};
| JavaScript |
/* The Editor object manages the content of the editable frame. It
* catches events, colours nodes, and indents lines. This file also
* holds some functions for transforming arbitrary DOM structures into
* plain sequences of <span> and <br> elements
*/
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
var webkit = /AppleWebKit/.test(navigator.userAgent);
var safari = /Apple Computers, Inc/.test(navigator.vendor);
var gecko = /gecko\/(\d{8})/i.test(navigator.userAgent);
// Make sure a string does not contain two consecutive 'collapseable'
// whitespace characters.
function makeWhiteSpace(n) {
var buffer = [], nb = true;
for (; n > 0; n--) {
buffer.push((nb || n == 1) ? nbsp : " ");
nb = !nb;
}
return buffer.join("");
}
// Create a set of white-space characters that will not be collapsed
// by the browser, but will not break text-wrapping either.
function fixSpaces(string) {
if (string.charAt(0) == " ") string = nbsp + string.slice(1);
return string.replace(/\t/g, function(){return makeWhiteSpace(indentUnit);})
.replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
}
function cleanText(text) {
return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
}
// Create a SPAN node with the expected properties for document part
// spans.
function makePartSpan(value, doc) {
var text = value;
if (value.nodeType == 3) text = value.nodeValue;
else value = doc.createTextNode(text);
var span = doc.createElement("SPAN");
span.isPart = true;
span.appendChild(value);
span.currentText = text;
return span;
}
// On webkit, when the last BR of the document does not have text
// behind it, the cursor can not be put on the line after it. This
// makes pressing enter at the end of the document occasionally do
// nothing (or at least seem to do nothing). To work around it, this
// function makes sure the document ends with a span containing a
// zero-width space character. The traverseDOM iterator filters such
// character out again, so that the parsers won't see them. This
// function is called from a few strategic places to make sure the
// zwsp is restored after the highlighting process eats it.
var webkitLastLineHack = webkit ?
function(container) {
var last = container.lastChild;
if (!last || !last.isPart || last.textContent != "\u200b")
container.appendChild(makePartSpan("\u200b", container.ownerDocument));
} : function() {};
var Editor = (function(){
// The HTML elements whose content should be suffixed by a newline
// when converting them to flat text.
var newlineElements = {"P": true, "DIV": true, "LI": true};
function asEditorLines(string) {
var tab = makeWhiteSpace(indentUnit);
return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
}
// Helper function for traverseDOM. Flattens an arbitrary DOM node
// into an array of textnodes and <br> tags.
function simplifyDOM(root, atEnd) {
var doc = root.ownerDocument;
var result = [];
var leaving = true;
function simplifyNode(node, top) {
if (node.nodeType == 3) {
var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
if (text.length) leaving = false;
result.push(node);
}
else if (isBR(node) && node.childNodes.length == 0) {
leaving = true;
result.push(node);
}
else {
forEach(node.childNodes, simplifyNode);
if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
leaving = true;
if (!atEnd || !top)
result.push(doc.createElement("BR"));
}
}
}
simplifyNode(root, true);
return result;
}
// Creates a MochiKit-style iterator that goes over a series of DOM
// nodes. The values it yields are strings, the textual content of
// the nodes. It makes sure that all nodes up to and including the
// one whose text is being yielded have been 'normalized' to be just
// <span> and <br> elements.
// See the story.html file for some short remarks about the use of
// continuation-passing style in this iterator.
function traverseDOM(start){
function _yield(value, c){cc = c; return value;}
function push(fun, arg, c){return function(){return fun(arg, c);};}
function stop(){cc = stop; throw StopIteration;};
var cc = push(scanNode, start, stop);
var owner = start.ownerDocument;
var nodeQueue = [];
// Create a function that can be used to insert nodes after the
// one given as argument.
function pointAt(node){
var parent = node.parentNode;
var next = node.nextSibling;
return function(newnode) {
parent.insertBefore(newnode, next);
};
}
var point = null;
// This an Opera-specific hack -- always insert an empty span
// between two BRs, because Opera's cursor code gets terribly
// confused when the cursor is between two BRs.
var afterBR = true;
// Insert a normalized node at the current point. If it is a text
// node, wrap it in a <span>, and give that span a currentText
// property -- this is used to cache the nodeValue, because
// directly accessing nodeValue is horribly slow on some browsers.
// The dirty property is used by the highlighter to determine
// which parts of the document have to be re-highlighted.
function insertPart(part){
var text = "\n";
if (part.nodeType == 3) {
select.snapshotChanged();
part = makePartSpan(part, owner);
text = part.currentText;
afterBR = false;
}
else {
if (afterBR && window.opera)
point(makePartSpan("", owner));
afterBR = true;
}
part.dirty = true;
nodeQueue.push(part);
point(part);
return text;
}
// Extract the text and newlines from a DOM node, insert them into
// the document, and yield the textual content. Used to replace
// non-normalized nodes.
function writeNode(node, c, end) {
var toYield = [];
forEach(simplifyDOM(node, end), function(part) {
toYield.push(insertPart(part));
});
return _yield(toYield.join(""), c);
}
// Check whether a node is a normalized <span> element.
function partNode(node){
if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
node.currentText = node.firstChild.nodeValue;
return !/[\n\t\r]/.test(node.currentText);
}
return false;
}
// Handle a node. Add its successor to the continuation if there
// is one, find out whether the node is normalized. If it is,
// yield its content, otherwise, normalize it (writeNode will take
// care of yielding).
function scanNode(node, c){
if (node.nextSibling)
c = push(scanNode, node.nextSibling, c);
if (partNode(node)){
nodeQueue.push(node);
afterBR = false;
return _yield(node.currentText, c);
}
else if (isBR(node)) {
if (afterBR && window.opera)
node.parentNode.insertBefore(makePartSpan("", owner), node);
nodeQueue.push(node);
afterBR = true;
return _yield("\n", c);
}
else {
var end = !node.nextSibling;
point = pointAt(node);
removeElement(node);
return writeNode(node, c, end);
}
}
// MochiKit iterators are objects with a next function that
// returns the next value or throws StopIteration when there are
// no more values.
return {next: function(){return cc();}, nodes: nodeQueue};
}
// Determine the text size of a processed node.
function nodeSize(node) {
return isBR(node) ? 1 : node.currentText.length;
}
// Search backwards through the top-level nodes until the next BR or
// the start of the frame.
function startOfLine(node) {
while (node && !isBR(node)) node = node.previousSibling;
return node;
}
function endOfLine(node, container) {
if (!node) node = container.firstChild;
else if (isBR(node)) node = node.nextSibling;
while (node && !isBR(node)) node = node.nextSibling;
return node;
}
function time() {return new Date().getTime();}
// Client interface for searching the content of the editor. Create
// these by calling CodeMirror.getSearchCursor. To use, call
// findNext on the resulting object -- this returns a boolean
// indicating whether anything was found, and can be called again to
// skip to the next find. Use the select and replace methods to
// actually do something with the found locations.
function SearchCursor(editor, string, fromCursor, caseFold) {
this.editor = editor;
this.caseFold = caseFold;
if (caseFold) string = string.toLowerCase();
this.history = editor.history;
this.history.commit();
// Are we currently at an occurrence of the search string?
this.atOccurrence = false;
// The object stores a set of nodes coming after its current
// position, so that when the current point is taken out of the
// DOM tree, we can still try to continue.
this.fallbackSize = 15;
var cursor;
// Start from the cursor when specified and a cursor can be found.
if (fromCursor && (cursor = select.cursorPos(this.editor.container))) {
this.line = cursor.node;
this.offset = cursor.offset;
}
else {
this.line = null;
this.offset = 0;
}
this.valid = !!string;
// Create a matcher function based on the kind of string we have.
var target = string.split("\n"), self = this;
this.matches = (target.length == 1) ?
// For one-line strings, searching can be done simply by calling
// indexOf on the current line.
function() {
var line = cleanText(self.history.textAfter(self.line).slice(self.offset));
var match = (self.caseFold ? line.toLowerCase() : line).indexOf(string);
if (match > -1)
return {from: {node: self.line, offset: self.offset + match},
to: {node: self.line, offset: self.offset + match + string.length}};
} :
// Multi-line strings require internal iteration over lines, and
// some clunky checks to make sure the first match ends at the
// end of the line and the last match starts at the start.
function() {
var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset));
var match = (self.caseFold ? firstLine.toLowerCase() : firstLine).lastIndexOf(target[0]);
if (match == -1 || match != firstLine.length - target[0].length)
return false;
var startOffset = self.offset + match;
var line = self.history.nodeAfter(self.line);
for (var i = 1; i < target.length - 1; i++) {
var lineText = cleanText(self.history.textAfter(line));
if ((self.caseFold ? lineText.toLowerCase() : lineText) != target[i])
return false;
line = self.history.nodeAfter(line);
}
var lastLine = cleanText(self.history.textAfter(line));
if ((self.caseFold ? lastLine.toLowerCase() : lastLine).indexOf(target[target.length - 1]) != 0)
return false;
return {from: {node: self.line, offset: startOffset},
to: {node: line, offset: target[target.length - 1].length}};
};
}
SearchCursor.prototype = {
findNext: function() {
if (!this.valid) return false;
this.atOccurrence = false;
var self = this;
// Go back to the start of the document if the current line is
// no longer in the DOM tree.
if (this.line && !this.line.parentNode) {
this.line = null;
this.offset = 0;
}
// Set the cursor's position one character after the given
// position.
function saveAfter(pos) {
if (self.history.textAfter(pos.node).length > pos.offset) {
self.line = pos.node;
self.offset = pos.offset + 1;
}
else {
self.line = self.history.nodeAfter(pos.node);
self.offset = 0;
}
}
while (true) {
var match = this.matches();
// Found the search string.
if (match) {
this.atOccurrence = match;
saveAfter(match.from);
return true;
}
this.line = this.history.nodeAfter(this.line);
this.offset = 0;
// End of document.
if (!this.line) {
this.valid = false;
return false;
}
}
},
select: function() {
if (this.atOccurrence) {
select.setCursorPos(this.editor.container, this.atOccurrence.from, this.atOccurrence.to);
select.scrollToCursor(this.editor.container);
}
},
replace: function(string) {
if (this.atOccurrence) {
var end = this.editor.replaceRange(this.atOccurrence.from, this.atOccurrence.to, string);
this.line = end.node;
this.offset = end.offset;
this.atOccurrence = false;
}
}
};
// The Editor object is the main inside-the-iframe interface.
function Editor(options) {
this.options = options;
window.indentUnit = options.indentUnit;
this.parent = parent;
this.doc = document;
var container = this.container = this.doc.body;
this.win = window;
this.history = new History(container, options.undoDepth, options.undoDelay, this);
var self = this;
if (!Editor.Parser)
throw "No parser loaded.";
if (options.parserConfig && Editor.Parser.configure)
Editor.Parser.configure(options.parserConfig);
if (!options.readOnly)
select.setCursorPos(container, {node: null, offset: 0});
this.dirty = [];
this.importCode(options.content || "");
this.history.onChange = options.onChange;
if (!options.readOnly) {
if (options.continuousScanning !== false) {
this.scanner = this.documentScanner(options.passTime);
this.delayScanning();
}
function setEditable() {
// In IE, designMode frames can not run any scripts, so we use
// contentEditable instead.
if (document.body.contentEditable != undefined && internetExplorer)
document.body.contentEditable = "true";
else
document.designMode = "on";
document.documentElement.style.borderWidth = "0";
if (!options.textWrapping)
container.style.whiteSpace = "nowrap";
}
// If setting the frame editable fails, try again when the user
// focus it (happens when the frame is not visible on
// initialisation, in Firefox).
try {
setEditable();
}
catch(e) {
var focusEvent = addEventHandler(document, "focus", function() {
focusEvent();
setEditable();
}, true);
}
addEventHandler(document, "keydown", method(this, "keyDown"));
addEventHandler(document, "keypress", method(this, "keyPress"));
addEventHandler(document, "keyup", method(this, "keyUp"));
function cursorActivity() {self.cursorActivity(false);}
addEventHandler(document.body, "mouseup", cursorActivity);
addEventHandler(document.body, "cut", cursorActivity);
// workaround for a gecko bug [?] where going forward and then
// back again breaks designmode (no more cursor)
if (gecko)
addEventHandler(this.win, "pagehide", function(){self.unloaded = true;});
addEventHandler(document.body, "paste", function(event) {
cursorActivity();
var text = null;
try {
var clipboardData = event.clipboardData || window.clipboardData;
if (clipboardData) text = clipboardData.getData('Text');
}
catch(e) {}
if (text !== null) {
event.stop();
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
});
if (this.options.autoMatchParens)
addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
}
else if (!options.textWrapping) {
container.style.whiteSpace = "nowrap";
}
}
function isSafeKey(code) {
return (code >= 16 && code <= 18) || // shift, control, alt
(code >= 33 && code <= 40); // arrows, home, end
}
Editor.prototype = {
// Import a piece of code into the editor.
importCode: function(code) {
this.history.push(null, null, asEditorLines(code));
this.history.reset();
},
// Extract the code from the editor.
getCode: function() {
if (!this.container.firstChild)
return "";
var accum = [];
select.markSelection(this.win);
forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
webkitLastLineHack(this.container);
select.selectMarked();
return cleanText(accum.join(""));
},
checkLine: function(node) {
if (node === false || !(node == null || node.parentNode == this.container))
throw parent.CodeMirror.InvalidLineHandle;
},
cursorPosition: function(start) {
if (start == null) start = true;
var pos = select.cursorPos(this.container, start);
if (pos) return {line: pos.node, character: pos.offset};
else return {line: null, character: 0};
},
firstLine: function() {
return null;
},
lastLine: function() {
if (this.container.lastChild) return startOfLine(this.container.lastChild);
else return null;
},
nextLine: function(line) {
this.checkLine(line);
var end = endOfLine(line, this.container);
return end || false;
},
prevLine: function(line) {
this.checkLine(line);
if (line == null) return false;
return startOfLine(line.previousSibling);
},
selectLines: function(startLine, startOffset, endLine, endOffset) {
this.checkLine(startLine);
var start = {node: startLine, offset: startOffset}, end = null;
if (endOffset !== undefined) {
this.checkLine(endLine);
end = {node: endLine, offset: endOffset};
}
select.setCursorPos(this.container, start, end);
select.scrollToCursor(this.container);
},
lineContent: function(line) {
var accum = [];
for (line = line ? line.nextSibling : this.container.firstChild;
line && !isBR(line); line = line.nextSibling)
accum.push(nodeText(line));
return cleanText(accum.join(""));
},
setLineContent: function(line, content) {
this.history.commit();
this.replaceRange({node: line, offset: 0},
{node: line, offset: this.history.textAfter(line).length},
content);
this.addDirtyNode(line);
this.scheduleHighlight();
},
removeLine: function(line) {
var node = line ? line.nextSibling : this.container.firstChild;
while (node) {
var next = node.nextSibling;
removeElement(node);
if (isBR(node)) break;
node = next;
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
insertIntoLine: function(line, position, content) {
var before = null;
if (position == "end") {
before = endOfLine(line, this.container);
}
else {
for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
if (position == 0) {
before = cur;
break;
}
var text = nodeText(cur);
if (text.length > position) {
before = cur.nextSibling;
content = text.slice(0, position) + content + text.slice(position);
removeElement(cur);
break;
}
position -= text.length;
}
}
var lines = asEditorLines(content), doc = this.container.ownerDocument;
for (var i = 0; i < lines.length; i++) {
if (i > 0) this.container.insertBefore(doc.createElement("BR"), before);
this.container.insertBefore(makePartSpan(lines[i], doc), before);
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
// Retrieve the selected text.
selectedText: function() {
var h = this.history;
h.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return "";
if (start.node == end.node)
return h.textAfter(start.node).slice(start.offset, end.offset);
var text = [h.textAfter(start.node).slice(start.offset)];
for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
text.push(h.textAfter(pos));
text.push(h.textAfter(end.node).slice(0, end.offset));
return cleanText(text.join("\n"));
},
// Replace the selection with another piece of text.
replaceSelection: function(text) {
this.history.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return;
end = this.replaceRange(start, end, text);
select.setCursorPos(this.container, end);
webkitLastLineHack(this.container);
},
reroutePasteEvent: function() {
if (this.capturingPaste || window.opera) return;
this.capturingPaste = true;
var te = parent.document.createElement("TEXTAREA");
te.style.position = "absolute";
te.style.left = "-10000px";
te.style.width = "10px";
te.style.top = nodeTop(frameElement) + "px";
var wrap = window.frameElement.CodeMirror.wrapping;
wrap.parentNode.insertBefore(te, wrap);
parent.focus();
te.focus();
var self = this;
this.parent.setTimeout(function() {
self.capturingPaste = false;
self.win.focus();
if (self.selectionSnapshot) // IE hack
self.win.select.setBookmark(self.container, self.selectionSnapshot);
var text = te.value;
if (text) {
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
removeElement(te);
}, 10);
},
replaceRange: function(from, to, text) {
var lines = asEditorLines(text);
lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
var lastLine = lines[lines.length - 1];
lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
var end = this.history.nodeAfter(to.node);
this.history.push(from.node, end, lines);
return {node: this.history.nodeBefore(end),
offset: lastLine.length};
},
getSearchCursor: function(string, fromCursor, caseFold) {
return new SearchCursor(this, string, fromCursor, caseFold);
},
// Re-indent the whole buffer
reindent: function() {
if (this.container.firstChild)
this.indentRegion(null, this.container.lastChild);
},
reindentSelection: function(direction) {
if (!select.somethingSelected(this.win)) {
this.indentAtCursor(direction);
}
else {
var start = select.selectionTopNode(this.container, true),
end = select.selectionTopNode(this.container, false);
if (start === false || end === false) return;
this.indentRegion(start, end, direction);
}
},
grabKeys: function(eventHandler, filter) {
this.frozen = eventHandler;
this.keyFilter = filter;
},
ungrabKeys: function() {
this.frozen = "leave";
this.keyFilter = null;
},
setParser: function(name) {
Editor.Parser = window[name];
if (this.container.firstChild) {
forEach(this.container.childNodes, function(n) {
if (n.nodeType != 3) n.dirty = true;
});
this.addDirtyNode(this.firstChild);
this.scheduleHighlight();
}
},
// Intercept enter and tab, and assign their new functions.
keyDown: function(event) {
if (this.frozen == "leave") this.frozen = null;
if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) {
event.stop();
this.frozen(event);
return;
}
var code = event.keyCode;
// Don't scan when the user is typing.
this.delayScanning();
// Schedule a paren-highlight event, if configured.
if (this.options.autoMatchParens)
this.scheduleParenHighlight();
// The various checks for !altKey are there because AltGr sets both
// ctrlKey and altKey to true, and should not be recognised as
// Control.
if (code == 13) { // enter
if (event.ctrlKey && !event.altKey) {
this.reparseBuffer();
}
else {
select.insertNewlineAtCursor(this.win);
this.indentAtCursor();
select.scrollToCursor(this.container);
}
event.stop();
}
else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab
this.handleTab(!event.shiftKey);
event.stop();
}
else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
this.handleTab(true);
event.stop();
}
else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
if (this.home()) event.stop();
}
else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end
if (this.end()) event.stop();
}
else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
this.highlightParens(event.shiftKey, true);
event.stop();
}
else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
var cursor = select.selectionTopNode(this.container);
if (cursor === false || !this.container.firstChild) return;
if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
else {
var end = endOfLine(cursor, this.container);
select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
}
event.stop();
}
else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
select.scrollToNode(this.history.redo());
event.stop();
}
else if (code == 90 || (safari && code == 8)) { // Z, backspace
select.scrollToNode(this.history.undo());
event.stop();
}
else if (code == 83 && this.options.saveFunction) { // S
this.options.saveFunction();
event.stop();
}
else if (internetExplorer && code == 86) {
this.reroutePasteEvent();
}
}
},
// Check for characters that should re-indent the current line,
// and prevent Opera from handling enter and tab anyway.
keyPress: function(event) {
var electric = Editor.Parser.electricChars, self = this;
// Hack for Opera, and Firefox on OS X, in which stopping a
// keydown event does not prevent the associated keypress event
// from happening, so we have to cancel enter and tab again
// here.
if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) ||
event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
(event.keyCode == 32 && event.shiftKey && this.options.tabMode == "default"))
event.stop();
else if (electric && electric.indexOf(event.character) != -1)
this.parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
else if ((event.character == "v" || event.character == "V")
&& (event.ctrlKey || event.metaKey) && !event.altKey) // ctrl-V
this.reroutePasteEvent();
},
// Mark the node at the cursor dirty when a non-safe key is
// released.
keyUp: function(event) {
this.cursorActivity(isSafeKey(event.keyCode));
},
// Indent the line following a given <br>, or null for the first
// line. If given a <br> element, this must have been highlighted
// so that it has an indentation method. Returns the whitespace
// element that has been modified or created (if any).
indentLineAfter: function(start, direction) {
// whiteSpace is the whitespace span at the start of the line,
// or null if there is no such node.
var whiteSpace = start ? start.nextSibling : this.container.firstChild;
if (whiteSpace && !hasClass(whiteSpace, "whitespace"))
whiteSpace = null;
// Sometimes the start of the line can influence the correct
// indentation, so we retrieve it.
var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
// Ask the lexical context for the correct indentation, and
// compute how much this differs from the current indentation.
var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
if (direction != null && this.options.tabMode == "shift")
newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
else if (start)
newIndent = start.indentation(nextChars, curIndent, direction);
else if (Editor.Parser.firstIndentation)
newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction);
var indentDiff = newIndent - curIndent;
// If there is too much, this is just a matter of shrinking a span.
if (indentDiff < 0) {
if (newIndent == 0) {
if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild, 0);
removeElement(whiteSpace);
whiteSpace = null;
}
else {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
}
// Not enough...
else if (indentDiff > 0) {
// If there is whitespace, we grow it.
if (whiteSpace) {
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
// Otherwise, we have to add a new whitespace node.
else {
whiteSpace = makePartSpan(makeWhiteSpace(newIndent), this.doc);
whiteSpace.className = "whitespace";
if (start) insertAfter(whiteSpace, start);
else this.container.insertBefore(whiteSpace, this.container.firstChild);
}
if (firstText) select.snapshotMove(firstText.firstChild, whiteSpace.firstChild, curIndent, false, true);
}
if (indentDiff != 0) this.addDirtyNode(start);
return whiteSpace;
},
// Re-highlight the selected part of the document.
highlightAtCursor: function() {
var pos = select.selectionTopNode(this.container, true);
var to = select.selectionTopNode(this.container, false);
if (pos === false || to === false) return false;
select.markSelection(this.win);
if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
return false;
select.selectMarked();
return true;
},
// When tab is pressed with text selected, the whole selection is
// re-indented, when nothing is selected, the line with the cursor
// is re-indented.
handleTab: function(direction) {
if (this.options.tabMode == "spaces")
select.insertTabAtCursor(this.win);
else
this.reindentSelection(direction);
},
// Custom home behaviour that doesn't land the cursor in front of
// leading whitespace unless pressed twice.
home: function() {
var cur = select.selectionTopNode(this.container, true), start = cur;
if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
return false;
while (cur && !isBR(cur)) cur = cur.previousSibling;
var next = cur ? cur.nextSibling : this.container.firstChild;
if (next && next != start && next.isPart && hasClass(next, "whitespace"))
select.focusAfterNode(next, this.container);
else
select.focusAfterNode(cur, this.container);
select.scrollToCursor(this.container);
return true;
},
// Some browsers (Opera) don't manage to handle the end key
// properly in the face of vertical scrolling.
end: function() {
var cur = select.selectionTopNode(this.container, true);
if (cur === false) return false;
cur = endOfLine(cur, this.container);
if (!cur) return false;
select.focusAfterNode(cur.previousSibling, this.container);
select.scrollToCursor(this.container);
return true;
},
// Delay (or initiate) the next paren highlight event.
scheduleParenHighlight: function() {
if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
var self = this;
this.parenEvent = this.parent.setTimeout(function(){self.highlightParens();}, 300);
},
// Take the token before the cursor. If it contains a character in
// '()[]{}', search for the matching paren/brace/bracket, and
// highlight them in green for a moment, or red if no proper match
// was found.
highlightParens: function(jump, fromKey) {
var self = this;
// give the relevant nodes a colour.
function highlight(node, ok) {
if (!node) return;
if (self.options.markParen) {
self.options.markParen(node, ok);
}
else {
node.style.fontWeight = "bold";
node.style.color = ok ? "#8F8" : "#F88";
}
}
function unhighlight(node) {
if (!node) return;
if (self.options.unmarkParen) {
self.options.unmarkParen(node);
}
else {
node.style.fontWeight = "";
node.style.color = "";
}
}
if (!fromKey && self.highlighted) {
unhighlight(self.highlighted[0]);
unhighlight(self.highlighted[1]);
}
if (!window.select) return;
// Clear the event property.
if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
this.parenEvent = null;
// Extract a 'paren' from a piece of text.
function paren(node) {
if (node.currentText) {
var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
return match && match[1];
}
}
// Determine the direction a paren is facing.
function forward(ch) {
return /[\(\[\{]/.test(ch);
}
var ch, cursor = select.selectionTopNode(this.container, true);
if (!cursor || !this.highlightAtCursor()) return;
cursor = select.selectionTopNode(this.container, true);
if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
return;
// We only look for tokens with the same className.
var className = cursor.className, dir = forward(ch), match = matching[ch];
// Since parts of the document might not have been properly
// highlighted, and it is hard to know in advance which part we
// have to scan, we just try, and when we find dirty nodes we
// abort, parse them, and re-try.
function tryFindMatch() {
var stack = [], ch, ok = true;
for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
if (forward(ch) == dir)
stack.push(ch);
else if (!stack.length)
ok = false;
else if (stack.pop() != matching[ch])
ok = false;
if (!stack.length) break;
}
else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
return {node: runner, status: "dirty"};
}
}
return {node: runner, status: runner && ok};
}
while (true) {
var found = tryFindMatch();
if (found.status == "dirty") {
this.highlight(found.node, endOfLine(found.node));
// Needed because in some corner cases a highlight does not
// reach a node.
found.node.dirty = false;
continue;
}
else {
highlight(cursor, found.status);
highlight(found.node, found.status);
if (fromKey)
self.parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500);
else
self.highlighted = [cursor, found.node];
if (jump && found.node)
select.focusAfterNode(found.node.previousSibling, this.container);
break;
}
}
},
// Adjust the amount of whitespace at the start of the line that
// the cursor is on so that it is indented properly.
indentAtCursor: function(direction) {
if (!this.container.firstChild) return;
// The line has to have up-to-date lexical information, so we
// highlight it first.
if (!this.highlightAtCursor()) return;
var cursor = select.selectionTopNode(this.container, false);
// If we couldn't determine the place of the cursor,
// there's nothing to indent.
if (cursor === false)
return;
var lineStart = startOfLine(cursor);
var whiteSpace = this.indentLineAfter(lineStart, direction);
if (cursor == lineStart && whiteSpace)
cursor = whiteSpace;
// This means the indentation has probably messed up the cursor.
if (cursor == whiteSpace)
select.focusAfterNode(cursor, this.container);
},
// Indent all lines whose start falls inside of the current
// selection.
indentRegion: function(start, end, direction) {
var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
if (!isBR(end)) end = endOfLine(end, this.container);
this.addDirtyNode(start);
do {
var next = endOfLine(current, this.container);
if (current) this.highlight(before, next, true);
this.indentLineAfter(current, direction);
before = current;
current = next;
} while (current != end);
select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
},
// Find the node that the cursor is in, mark it as dirty, and make
// sure a highlight pass is scheduled.
cursorActivity: function(safe) {
// pagehide event hack above
if (this.unloaded) {
this.win.document.designMode = "off";
this.win.document.designMode = "on";
this.unloaded = false;
}
if (internetExplorer) {
this.container.createTextRange().execCommand("unlink");
this.selectionSnapshot = select.getBookmark(this.container);
}
var activity = this.options.cursorActivity;
if (!safe || activity) {
var cursor = select.selectionTopNode(this.container, false);
if (cursor === false || !this.container.firstChild) return;
cursor = cursor || this.container.firstChild;
if (activity) activity(cursor);
if (!safe) {
this.scheduleHighlight();
this.addDirtyNode(cursor);
}
}
},
reparseBuffer: function() {
forEach(this.container.childNodes, function(node) {node.dirty = true;});
if (this.container.firstChild)
this.addDirtyNode(this.container.firstChild);
},
// Add a node to the set of dirty nodes, if it isn't already in
// there.
addDirtyNode: function(node) {
node = node || this.container.firstChild;
if (!node) return;
for (var i = 0; i < this.dirty.length; i++)
if (this.dirty[i] == node) return;
if (node.nodeType != 3)
node.dirty = true;
this.dirty.push(node);
},
allClean: function() {
return !this.dirty.length;
},
// Cause a highlight pass to happen in options.passDelay
// milliseconds. Clear the existing timeout, if one exists. This
// way, the passes do not happen while the user is typing, and
// should as unobtrusive as possible.
scheduleHighlight: function() {
// Timeouts are routed through the parent window, because on
// some browsers designMode windows do not fire timeouts.
var self = this;
this.parent.clearTimeout(this.highlightTimeout);
this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
},
// Fetch one dirty node, and remove it from the dirty set.
getDirtyNode: function() {
while (this.dirty.length > 0) {
var found = this.dirty.pop();
// IE8 sometimes throws an unexplainable 'invalid argument'
// exception for found.parentNode
try {
// If the node has been coloured in the meantime, or is no
// longer in the document, it should not be returned.
while (found && found.parentNode != this.container)
found = found.parentNode;
if (found && (found.dirty || found.nodeType == 3))
return found;
} catch (e) {}
}
return null;
},
// Pick dirty nodes, and highlight them, until options.passTime
// milliseconds have gone by. The highlight method will continue
// to next lines as long as it finds dirty nodes. It returns
// information about the place where it stopped. If there are
// dirty nodes left after this function has spent all its lines,
// it shedules another highlight to finish the job.
highlightDirty: function(force) {
// Prevent FF from raising an error when it is firing timeouts
// on a page that's no longer loaded.
if (!window.select) return false;
if (!this.options.readOnly) select.markSelection(this.win);
var start, endTime = force ? null : time() + this.options.passTime;
while ((time() < endTime || force) && (start = this.getDirtyNode())) {
var result = this.highlight(start, endTime);
if (result && result.node && result.dirty)
this.addDirtyNode(result.node);
}
if (!this.options.readOnly) select.selectMarked();
if (start) this.scheduleHighlight();
return this.dirty.length == 0;
},
// Creates a function that, when called through a timeout, will
// continuously re-parse the document.
documentScanner: function(passTime) {
var self = this, pos = null;
return function() {
// FF timeout weirdness workaround.
if (!window.select) return;
// If the current node is no longer in the document... oh
// well, we start over.
if (pos && pos.parentNode != self.container)
pos = null;
select.markSelection(self.win);
var result = self.highlight(pos, time() + passTime, true);
select.selectMarked();
var newPos = result ? (result.node && result.node.nextSibling) : null;
pos = (pos == newPos) ? null : newPos;
self.delayScanning();
};
},
// Starts the continuous scanning process for this document after
// a given interval.
delayScanning: function() {
if (this.scanner) {
this.parent.clearTimeout(this.documentScan);
this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
}
},
// The function that does the actual highlighting/colouring (with
// help from the parser and the DOM normalizer). Its interface is
// rather overcomplicated, because it is used in different
// situations: ensuring that a certain line is highlighted, or
// highlighting up to X milliseconds starting from a certain
// point. The 'from' argument gives the node at which it should
// start. If this is null, it will start at the beginning of the
// document. When a timestamp is given with the 'target' argument,
// it will stop highlighting at that time. If this argument holds
// a DOM node, it will highlight until it reaches that node. If at
// any time it comes across two 'clean' lines (no dirty nodes), it
// will stop, except when 'cleanLines' is true. maxBacktrack is
// the maximum number of lines to backtrack to find an existing
// parser instance. This is used to give up in situations where a
// highlight would take too long and freeze the browser interface.
highlight: function(from, target, cleanLines, maxBacktrack){
var container = this.container, self = this, active = this.options.activeTokens;
var endTime = (typeof target == "number" ? target : null);
if (!container.firstChild)
return false;
// Backtrack to the first node before from that has a partial
// parse stored.
while (from && (!from.parserFromHere || from.dirty)) {
if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
return false;
from = from.previousSibling;
}
// If we are at the end of the document, do nothing.
if (from && !from.nextSibling)
return false;
// Check whether a part (<span> node) and the corresponding token
// match.
function correctPart(token, part){
return !part.reduced && part.currentText == token.value && part.className == token.style;
}
// Shorten the text associated with a part by chopping off
// characters from the front. Note that only the currentText
// property gets changed. For efficiency reasons, we leave the
// nodeValue alone -- we set the reduced flag to indicate that
// this part must be replaced.
function shortenPart(part, minus){
part.currentText = part.currentText.substring(minus);
part.reduced = true;
}
// Create a part corresponding to a given token.
function tokenPart(token){
var part = makePartSpan(token.value, self.doc);
part.className = token.style;
return part;
}
function maybeTouch(node) {
if (node) {
var old = node.oldNextSibling;
if (lineDirty || old === undefined || node.nextSibling != old)
self.history.touch(node);
node.oldNextSibling = node.nextSibling;
}
else {
var old = self.container.oldFirstChild;
if (lineDirty || old === undefined || self.container.firstChild != old)
self.history.touch(null);
self.container.oldFirstChild = self.container.firstChild;
}
}
// Get the token stream. If from is null, we start with a new
// parser from the start of the frame, otherwise a partial parse
// is resumed.
var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
stream = stringStream(traversal),
parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
function surroundedByBRs(node) {
return (node.previousSibling == null || isBR(node.previousSibling)) &&
(node.nextSibling == null || isBR(node.nextSibling));
}
// parts is an interface to make it possible to 'delay' fetching
// the next DOM node until we are completely done with the one
// before it. This is necessary because often the next node is
// not yet available when we want to proceed past the current
// one.
var parts = {
current: null,
// Fetch current node.
get: function(){
if (!this.current)
this.current = traversal.nodes.shift();
return this.current;
},
// Advance to the next part (do not fetch it yet).
next: function(){
this.current = null;
},
// Remove the current part from the DOM tree, and move to the
// next.
remove: function(){
container.removeChild(this.get());
this.current = null;
},
// Advance to the next part that is not empty, discarding empty
// parts.
getNonEmpty: function(){
var part = this.get();
// Allow empty nodes when they are alone on a line, needed
// for the FF cursor bug workaround (see select.js,
// insertNewlineAtCursor).
while (part && isSpan(part) && part.currentText == "") {
// Leave empty nodes that are alone on a line alone in
// Opera, since that browsers doesn't deal well with
// having 2 BRs in a row.
if (window.opera && surroundedByBRs(part)) {
this.next();
part = this.get();
}
else {
var old = part;
this.remove();
part = this.get();
// Adjust selection information, if any. See select.js for details.
select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
}
}
return part;
}
};
var lineDirty = false, prevLineDirty = true, lineNodes = 0;
// This forEach loops over the tokens from the parsed stream, and
// at the same time uses the parts object to proceed through the
// corresponding DOM nodes.
forEach(parsed, function(token){
var part = parts.getNonEmpty();
if (token.value == "\n"){
// The idea of the two streams actually staying synchronized
// is such a long shot that we explicitly check.
if (!isBR(part))
throw "Parser out of sync. Expected BR.";
if (part.dirty || !part.indentation) lineDirty = true;
maybeTouch(from);
from = part;
// Every <br> gets a copy of the parser state and a lexical
// context assigned to it. The first is used to be able to
// later resume parsing from this point, the second is used
// for indentation.
part.parserFromHere = parsed.copy();
part.indentation = token.indentation;
part.dirty = false;
// If the target argument wasn't an integer, go at least
// until that node.
if (endTime == null && part == target) throw StopIteration;
// A clean line with more than one node means we are done.
// Throwing a StopIteration is the way to break out of a
// MochiKit forEach loop.
if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
throw StopIteration;
prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
parts.next();
}
else {
if (!isSpan(part))
throw "Parser out of sync. Expected SPAN.";
if (part.dirty)
lineDirty = true;
lineNodes++;
// If the part matches the token, we can leave it alone.
if (correctPart(token, part)){
part.dirty = false;
parts.next();
}
// Otherwise, we have to fix it.
else {
lineDirty = true;
// Insert the correct part.
var newPart = tokenPart(token);
container.insertBefore(newPart, part);
if (active) active(newPart, token, self);
var tokensize = token.value.length;
var offset = 0;
// Eat up parts until the text for this token has been
// removed, adjusting the stored selection info (see
// select.js) in the process.
while (tokensize > 0) {
part = parts.get();
var partsize = part.currentText.length;
select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
if (partsize > tokensize){
shortenPart(part, tokensize);
tokensize = 0;
}
else {
tokensize -= partsize;
offset += partsize;
parts.remove();
}
}
}
}
});
maybeTouch(from);
webkitLastLineHack(this.container);
// The function returns some status information that is used by
// hightlightDirty to determine whether and where it has to
// continue.
return {node: parts.getNonEmpty(),
dirty: lineDirty};
}
};
return Editor;
})();
addEventHandler(window, "load", function() {
var CodeMirror = window.frameElement.CodeMirror;
var e = CodeMirror.editor = new Editor(CodeMirror.options);
this.parent.setTimeout(method(CodeMirror, "init"), 0);
});
| JavaScript |
/*
Copyright (c) 2008-2010 Yahoo! Inc. All rights reserved.
The copyrights embodied in the content of this file are licensed by
Yahoo! Inc. under the BSD (revised) open source license
@author Dan Vlad Dascalescu <dandv@yahoo-inc.com>
Parse function for PHP. Makes use of the tokenizer from tokenizephp.js.
Based on parsejavascript.js by Marijn Haverbeke.
Features:
+ special "deprecated" style for PHP4 keywords like 'var'
+ support for PHP 5.3 keywords: 'namespace', 'use'
+ 911 predefined constants, 1301 predefined functions, 105 predeclared classes
from a typical PHP installation in a LAMP environment
+ new feature: syntax error flagging, thus enabling strict parsing of:
+ function definitions with explicitly or implicitly typed arguments and default values
+ modifiers (public, static etc.) applied to method and member definitions
+ foreach(array_expression as $key [=> $value]) loops
+ differentiation between single-quoted strings and double-quoted interpolating strings
*/
// add the Array.indexOf method for JS engines that don't support it (e.g. IE)
// code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/IndexOf
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
var PHPParser = Editor.Parser = (function() {
// Token types that can be considered to be atoms, part of operator expressions
var atomicTypes = {
"atom": true, "number": true, "variable": true, "string": true
};
// Constructor for the lexical context objects.
function PHPLexical(indented, column, type, align, prev, info) {
// indentation at start of this line
this.indented = indented;
// column at which this scope was opened
this.column = column;
// type of scope ('stat' (statement), 'form' (special form), '[', '{', or '(')
this.type = type;
// '[', '{', or '(' blocks that have any text after their opening
// character are said to be 'aligned' -- any lines below are
// indented all the way to the opening character.
if (align != null)
this.align = align;
// Parent scope, if any.
this.prev = prev;
this.info = info;
}
// PHP indentation rules
function indentPHP(lexical) {
return function(firstChars) {
var firstChar = firstChars && firstChars.charAt(0), type = lexical.type;
var closing = firstChar == type;
if (type == "form" && firstChar == "{")
return lexical.indented;
else if (type == "stat" || type == "form")
return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit);
else if (lexical.align)
return lexical.column - (closing ? 1 : 0);
else
return lexical.indented + (closing ? 0 : indentUnit);
};
}
// The parser-iterator-producing function itself.
function parsePHP(input, basecolumn) {
// Wrap the input in a token stream
var tokens = tokenizePHP(input);
// The parser state. cc is a stack of actions that have to be
// performed to finish the current statement. For example we might
// know that we still need to find a closing parenthesis and a
// semicolon. Actions at the end of the stack go first. It is
// initialized with an infinitely looping action that consumes
// whole statements.
var cc = [statements];
// The lexical scope, used mostly for indentation.
var lexical = new PHPLexical((basecolumn || 0) - indentUnit, 0, "block", false);
// Current column, and the indentation at the start of the current
// line. Used to create lexical scope objects.
var column = 0;
var indented = 0;
// Variables which are used by the mark, cont, and pass functions
// below to communicate with the driver loop in the 'next' function.
var consume, marked;
// The iterator object.
var parser = {next: next, copy: copy};
// parsing is accomplished by calling next() repeatedly
function next(){
// Start by performing any 'lexical' actions (adjusting the
// lexical variable), or the operations below will be working
// with the wrong lexical state.
while(cc[cc.length - 1].lex)
cc.pop()();
// Fetch the next token.
var token = tokens.next();
// Adjust column and indented.
if (token.type == "whitespace" && column == 0)
indented = token.value.length;
column += token.value.length;
if (token.content == "\n"){
indented = column = 0;
// If the lexical scope's align property is still undefined at
// the end of the line, it is an un-aligned scope.
if (!("align" in lexical))
lexical.align = false;
// Newline tokens get an indentation function associated with
// them.
token.indentation = indentPHP(lexical);
}
// No more processing for meaningless tokens.
if (token.type == "whitespace" || token.type == "comment"
|| token.type == "string_not_terminated" )
return token;
// When a meaningful token is found and the lexical scope's
// align is undefined, it is an aligned scope.
if (!("align" in lexical))
lexical.align = true;
// Execute actions until one 'consumes' the token and we can
// return it. 'marked' is used to change the style of the current token.
while(true) {
consume = marked = false;
// Take and execute the topmost action.
var action = cc.pop();
action(token);
if (consume){
if (marked)
token.style = marked;
// Here we differentiate between local and global variables.
return token;
}
}
return 1; // Firebug workaround for http://code.google.com/p/fbug/issues/detail?id=1239#c1
}
// This makes a copy of the parser state. It stores all the
// stateful variables in a closure, and returns a function that
// will restore them when called with a new input stream. Note
// that the cc array has to be copied, because it is contantly
// being modified. Lexical objects are not mutated, so they can
// be shared between runs of the parser.
function copy(){
var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;
return function copyParser(input){
lexical = _lexical;
cc = _cc.concat([]); // copies the array
column = indented = 0;
tokens = tokenizePHP(input, _tokenState);
return parser;
};
}
// Helper function for pushing a number of actions onto the cc
// stack in reverse order.
function push(fs){
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
// cont and pass are used by the action functions to add other
// actions to the stack. cont will cause the current token to be
// consumed, pass will leave it for the next action.
function cont(){
push(arguments);
consume = true;
}
function pass(){
push(arguments);
consume = false;
}
// Used to change the style of the current token.
function mark(style){
marked = style;
}
// Add a lyer of style to the current token, for example syntax-error
function mark_add(style){
marked = marked + ' ' + style;
}
// Push a new lexical context of the given type.
function pushlex(type, info) {
var result = function pushlexing() {
lexical = new PHPLexical(indented, column, type, null, lexical, info)
};
result.lex = true;
return result;
}
// Pop off the current lexical context.
function poplex(){
lexical = lexical.prev;
}
poplex.lex = true;
// The 'lex' flag on these actions is used by the 'next' function
// to know they can (and have to) be ran before moving on to the
// next token.
// Creates an action that discards tokens until it finds one of
// the given type. This will ignore (and recover from) syntax errors.
function expect(wanted){
return function expecting(token){
if (token.type == wanted) cont(); // consume the token
else {
cont(arguments.callee); // continue expecting() - call itself
}
};
}
// Require a specific token type, or one of the tokens passed in the 'wanted' array
// Used to detect blatant syntax errors. 'execute' is used to pass extra code
// to be executed if the token is matched. For example, a '(' match could
// 'execute' a cont( compasep(funcarg), require(")") )
function require(wanted, execute){
return function requiring(token){
var ok;
var type = token.type;
if (typeof(wanted) == "string")
ok = (type == wanted) -1;
else
ok = wanted.indexOf(type);
if (ok >= 0) {
if (execute && typeof(execute[ok]) == "function")
execute[ok](token);
cont(); // just consume the token
}
else {
if (!marked) mark(token.style);
mark_add("syntax-error");
cont(arguments.callee);
}
};
}
// Looks for a statement, and then calls itself.
function statements(token){
return pass(statement, statements);
}
// Dispatches various types of statements based on the type of the current token.
function statement(token){
var type = token.type;
if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex);
else if (type == "keyword b") cont(pushlex("form"), statement, poplex);
else if (type == "{") cont(pushlex("}"), block, poplex);
else if (type == "function") funcdef();
// technically, "class implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function
else if (type == "class") cont(require("t_string"), expect("{"), pushlex("}"), block, poplex);
else if (type == "foreach") cont(pushlex("form"), require("("), pushlex(")"), expression, require("as"), require("variable"), /* => $value */ expect(")"), poplex, statement, poplex);
else if (type == "for") cont(pushlex("form"), require("("), pushlex(")"), expression, require(";"), expression, require(";"), expression, require(")"), poplex, statement, poplex);
// public final function foo(), protected static $bar;
else if (type == "modifier") cont(require(["modifier", "variable", "function"], [null, null, funcdef]));
else if (type == "switch") cont(pushlex("form"), require("("), expression, require(")"), pushlex("}", "switch"), require([":", "{"]), block, poplex, poplex);
else if (type == "case") cont(expression, require(":"));
else if (type == "default") cont(require(":"));
else if (type == "catch") cont(pushlex("form"), require("("), require("t_string"), require("variable"), require(")"), statement, poplex);
else if (type == "const") cont(require("t_string")); // 'const static x=5' is a syntax error
// technically, "namespace implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function
else if (type == "namespace") cont(namespacedef, require(";"));
// $variables may be followed by operators, () for variable function calls, or [] subscripts
else pass(pushlex("stat"), expression, require(";"), poplex);
}
// Dispatch expression types.
function expression(token){
var type = token.type;
if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator);
else if (type == "<<<") cont(require("string"), maybeoperator); // heredoc/nowdoc
else if (type == "t_string") cont(maybe_double_colon, maybeoperator);
else if (type == "keyword c") cont(expression);
// function call or parenthesized expression: $a = ($b + 1) * 2;
else if (type == "(") cont(pushlex(")"), commasep(expression), require(")"), poplex, maybeoperator);
else if (type == "operator") cont(expression);
}
// Called for places where operators, function calls, or subscripts are
// valid. Will skip on to the next action if none is found.
function maybeoperator(token){
var type = token.type;
if (type == "operator") {
if (token.content == "?") cont(expression, require(":"), expression); // ternary operator
else cont(expression);
}
else if (type == "(") cont(pushlex(")"), expression, commasep(expression), require(")"), poplex, maybeoperator /* $varfunc() + 3 */);
else if (type == "[") cont(pushlex("]"), expression, require("]"), maybeoperator /* for multidimensional arrays, or $func[$i]() */, poplex);
}
// A regular use of the double colon to specify a class, as in self::func() or myclass::$var;
// Differs from `namespace` or `use` in that only one class can be the parent; chains (A::B::$var) are a syntax error.
function maybe_double_colon(token) {
if (token.type == "t_double_colon")
// A::$var, A::func(), A::const
cont(require(["t_string", "variable"]), maybeoperator);
else {
// a t_string wasn't followed by ::, such as in a function call: foo()
pass(expression)
}
}
// the declaration or definition of a function
function funcdef() {
cont(require("t_string"), require("("), pushlex(")"), commasep(funcarg), require(")"), poplex, block);
}
// Parses a comma-separated list of the things that are recognized
// by the 'what' argument.
function commasep(what){
function proceed(token) {
if (token.type == ",") cont(what, proceed);
}
return function commaSeparated() {
pass(what, proceed);
};
}
// Look for statements until a closing brace is found.
function block(token) {
if (token.type == "}") cont();
else pass(statement, block);
}
function maybedefaultparameter(token){
if (token.content == "=") cont(expression);
}
// support for default arguments: http://us.php.net/manual/en/functions.arguments.php#functions.arguments.default
function funcarg(token){
// function foo(myclass $obj) {...}
if (token.type == "t_string") cont(require("variable"), maybedefaultparameter);
// function foo($string) {...}
else if (token.type == "variable") cont(maybedefaultparameter);
}
// A namespace definition or use
function maybe_double_colon_def(token) {
if (token.type == "t_double_colon")
cont(namespacedef);
}
function namespacedef(token) {
pass(require("t_string"), maybe_double_colon_def);
}
return parser;
}
return {make: parsePHP, electricChars: "{}:"};
})();
| JavaScript |
/*
Copyright (c) 2008-2010 Yahoo! Inc. All rights reserved.
The copyrights embodied in the content of this file are licensed by
Yahoo! Inc. under the BSD (revised) open source license
@author Vlad Dan Dascalescu <dandv@yahoo-inc.com>
Tokenizer for PHP code
References:
+ http://php.net/manual/en/reserved.php
+ http://php.net/tokens
+ get_defined_constants(), get_defined_functions(), get_declared_classes()
executed on a realistic (not vanilla) PHP installation with typical LAMP modules.
Specifically, the PHP bundled with the Uniform Web Server (www.uniformserver.com).
*/
// add the forEach method for JS engines that don't support it (e.g. IE)
// code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
var tokenizePHP = (function() {
/* A map of PHP's reserved words (keywords, predefined classes, functions and
constants. Each token has a type ('keyword', 'operator' etc.) and a style.
The style corresponds to the CSS span class in phpcolors.css.
Keywords can be of three types:
a - takes an expression and forms a statement - e.g. if
b - takes just a statement - e.g. else
c - takes an optinoal expression, but no statement - e.g. return
This distinction gives the parser enough information to parse
correct code correctly (we don't care that much how we parse
incorrect code).
Reference: http://us.php.net/manual/en/reserved.php
*/
var keywords = function(){
function token(type, style){
return {type: type, style: style};
}
var result = {};
// for each(var element in ["...", "..."]) can pick up elements added to
// Array.prototype, so we'll use the loop structure below. See also
// http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in
// keywords that take an expression and form a statement
["if", "elseif", "while", "declare"].forEach(function(element, index, array) {
result[element] = token("keyword a", "php-keyword");
});
// keywords that take just a statement
["do", "else", "try" ].forEach(function(element, index, array) {
result[element] = token("keyword b", "php-keyword");
});
// keywords that take an optional expression, but no statement
["return", "break", "continue", // the expression is optional
"new", "clone", "throw" // the expression is mandatory
].forEach(function(element, index, array) {
result[element] = token("keyword c", "php-keyword");
});
["__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__METHOD__", "__NAMESPACE__"].forEach(function(element, index, array) {
result[element] = token("atom", "php-compile-time-constant");
});
["true", "false", "null"].forEach(function(element, index, array) {
result[element] = token("atom", "php-atom");
});
["and", "or", "xor", "instanceof"].forEach(function(element, index, array) {
result[element] = token("operator", "php-keyword php-operator");
});
["class", "interface"].forEach(function(element, index, array) {
result[element] = token("class", "php-keyword");
});
["namespace", "use", "extends", "implements"].forEach(function(element, index, array) {
result[element] = token("namespace", "php-keyword");
});
// reserved "language constructs"... http://php.net/manual/en/reserved.php
[ "die", "echo", "empty", "exit", "eval", "include", "include_once", "isset",
"list", "require", "require_once", "return", "print", "unset",
"array" // a keyword rather, but mandates a parenthesized parameter list
].forEach(function(element, index, array) {
result[element] = token("t_string", "php-reserved-language-construct");
});
result["switch"] = token("switch", "php-keyword");
result["case"] = token("case", "php-keyword");
result["default"] = token("default", "php-keyword");
result["catch"] = token("catch", "php-keyword");
result["function"] = token("function", "php-keyword");
// http://php.net/manual/en/control-structures.alternative-syntax.php must be followed by a ':'
["endif", "endwhile", "endfor", "endforeach", "endswitch", "enddeclare"].forEach(function(element, index, array) {
result[element] = token("default", "php-keyword");
});
result["const"] = token("const", "php-keyword");
["abstract", "final", "private", "protected", "public", "global", "static"].forEach(function(element, index, array) {
result[element] = token("modifier", "php-keyword");
});
result["var"] = token("modifier", "php-keyword deprecated");
result["foreach"] = token("foreach", "php-keyword");
result["as"] = token("as", "php-keyword");
result["for"] = token("for", "php-keyword");
// PHP built-in functions - output of get_defined_functions()["internal"]
[ "zend_version", "func_num_args", "func_get_arg", "func_get_args", "strlen",
"strcmp", "strncmp", "strcasecmp", "strncasecmp", "each", "error_reporting",
"define", "defined", "get_class", "get_parent_class", "method_exists",
"property_exists", "class_exists", "interface_exists", "function_exists",
"get_included_files", "get_required_files", "is_subclass_of", "is_a",
"get_class_vars", "get_object_vars", "get_class_methods", "trigger_error",
"user_error", "set_error_handler", "restore_error_handler",
"set_exception_handler", "restore_exception_handler", "get_declared_classes",
"get_declared_interfaces", "get_defined_functions", "get_defined_vars",
"create_function", "get_resource_type", "get_loaded_extensions",
"extension_loaded", "get_extension_funcs", "get_defined_constants",
"debug_backtrace", "debug_print_backtrace", "bcadd", "bcsub", "bcmul", "bcdiv",
"bcmod", "bcpow", "bcsqrt", "bcscale", "bccomp", "bcpowmod", "jdtogregorian",
"gregoriantojd", "jdtojulian", "juliantojd", "jdtojewish", "jewishtojd",
"jdtofrench", "frenchtojd", "jddayofweek", "jdmonthname", "easter_date",
"easter_days", "unixtojd", "jdtounix", "cal_to_jd", "cal_from_jd",
"cal_days_in_month", "cal_info", "variant_set", "variant_add", "variant_cat",
"variant_sub", "variant_mul", "variant_and", "variant_div", "variant_eqv",
"variant_idiv", "variant_imp", "variant_mod", "variant_or", "variant_pow",
"variant_xor", "variant_abs", "variant_fix", "variant_int", "variant_neg",
"variant_not", "variant_round", "variant_cmp", "variant_date_to_timestamp",
"variant_date_from_timestamp", "variant_get_type", "variant_set_type",
"variant_cast", "com_create_guid", "com_event_sink", "com_print_typeinfo",
"com_message_pump", "com_load_typelib", "com_get_active_object", "ctype_alnum",
"ctype_alpha", "ctype_cntrl", "ctype_digit", "ctype_lower", "ctype_graph",
"ctype_print", "ctype_punct", "ctype_space", "ctype_upper", "ctype_xdigit",
"strtotime", "date", "idate", "gmdate", "mktime", "gmmktime", "checkdate",
"strftime", "gmstrftime", "time", "localtime", "getdate", "date_create",
"date_parse", "date_format", "date_modify", "date_timezone_get",
"date_timezone_set", "date_offset_get", "date_time_set", "date_date_set",
"date_isodate_set", "timezone_open", "timezone_name_get",
"timezone_name_from_abbr", "timezone_offset_get", "timezone_transitions_get",
"timezone_identifiers_list", "timezone_abbreviations_list",
"date_default_timezone_set", "date_default_timezone_get", "date_sunrise",
"date_sunset", "date_sun_info", "filter_input", "filter_var",
"filter_input_array", "filter_var_array", "filter_list", "filter_has_var",
"filter_id", "ftp_connect", "ftp_login", "ftp_pwd", "ftp_cdup", "ftp_chdir",
"ftp_exec", "ftp_raw", "ftp_mkdir", "ftp_rmdir", "ftp_chmod", "ftp_alloc",
"ftp_nlist", "ftp_rawlist", "ftp_systype", "ftp_pasv", "ftp_get", "ftp_fget",
"ftp_put", "ftp_fput", "ftp_size", "ftp_mdtm", "ftp_rename", "ftp_delete",
"ftp_site", "ftp_close", "ftp_set_option", "ftp_get_option", "ftp_nb_fget",
"ftp_nb_get", "ftp_nb_continue", "ftp_nb_put", "ftp_nb_fput", "ftp_quit",
"hash", "hash_file", "hash_hmac", "hash_hmac_file", "hash_init", "hash_update",
"hash_update_stream", "hash_update_file", "hash_final", "hash_algos", "iconv",
"ob_iconv_handler", "iconv_get_encoding", "iconv_set_encoding", "iconv_strlen",
"iconv_substr", "iconv_strpos", "iconv_strrpos", "iconv_mime_encode",
"iconv_mime_decode", "iconv_mime_decode_headers", "json_encode", "json_decode",
"odbc_autocommit", "odbc_binmode", "odbc_close", "odbc_close_all",
"odbc_columns", "odbc_commit", "odbc_connect", "odbc_cursor",
"odbc_data_source", "odbc_execute", "odbc_error", "odbc_errormsg", "odbc_exec",
"odbc_fetch_array", "odbc_fetch_object", "odbc_fetch_row", "odbc_fetch_into",
"odbc_field_len", "odbc_field_scale", "odbc_field_name", "odbc_field_type",
"odbc_field_num", "odbc_free_result", "odbc_gettypeinfo", "odbc_longreadlen",
"odbc_next_result", "odbc_num_fields", "odbc_num_rows", "odbc_pconnect",
"odbc_prepare", "odbc_result", "odbc_result_all", "odbc_rollback",
"odbc_setoption", "odbc_specialcolumns", "odbc_statistics", "odbc_tables",
"odbc_primarykeys", "odbc_columnprivileges", "odbc_tableprivileges",
"odbc_foreignkeys", "odbc_procedures", "odbc_procedurecolumns", "odbc_do",
"odbc_field_precision", "preg_match", "preg_match_all", "preg_replace",
"preg_replace_callback", "preg_split", "preg_quote", "preg_grep",
"preg_last_error", "session_name", "session_module_name", "session_save_path",
"session_id", "session_regenerate_id", "session_decode", "session_register",
"session_unregister", "session_is_registered", "session_encode",
"session_start", "session_destroy", "session_unset",
"session_set_save_handler", "session_cache_limiter", "session_cache_expire",
"session_set_cookie_params", "session_get_cookie_params",
"session_write_close", "session_commit", "spl_classes", "spl_autoload",
"spl_autoload_extensions", "spl_autoload_register", "spl_autoload_unregister",
"spl_autoload_functions", "spl_autoload_call", "class_parents",
"class_implements", "spl_object_hash", "iterator_to_array", "iterator_count",
"iterator_apply", "constant", "bin2hex", "sleep", "usleep", "flush",
"wordwrap", "htmlspecialchars", "htmlentities", "html_entity_decode",
"htmlspecialchars_decode", "get_html_translation_table", "sha1", "sha1_file",
"md5", "md5_file", "crc32", "iptcparse", "iptcembed", "getimagesize",
"image_type_to_mime_type", "image_type_to_extension", "phpinfo", "phpversion",
"phpcredits", "php_logo_guid", "php_real_logo_guid", "php_egg_logo_guid",
"zend_logo_guid", "php_sapi_name", "php_uname", "php_ini_scanned_files",
"strnatcmp", "strnatcasecmp", "substr_count", "strspn", "strcspn", "strtok",
"strtoupper", "strtolower", "strpos", "stripos", "strrpos", "strripos",
"strrev", "hebrev", "hebrevc", "nl2br", "basename", "dirname", "pathinfo",
"stripslashes", "stripcslashes", "strstr", "stristr", "strrchr", "str_shuffle",
"str_word_count", "str_split", "strpbrk", "substr_compare", "strcoll",
"substr", "substr_replace", "quotemeta", "ucfirst", "ucwords", "strtr",
"addslashes", "addcslashes", "rtrim", "str_replace", "str_ireplace",
"str_repeat", "count_chars", "chunk_split", "trim", "ltrim", "strip_tags",
"similar_text", "explode", "implode", "setlocale", "localeconv", "soundex",
"levenshtein", "chr", "ord", "parse_str", "str_pad", "chop", "strchr",
"sprintf", "printf", "vprintf", "vsprintf", "fprintf", "vfprintf", "sscanf",
"fscanf", "parse_url", "urlencode", "urldecode", "rawurlencode",
"rawurldecode", "http_build_query", "unlink", "exec", "system",
"escapeshellcmd", "escapeshellarg", "passthru", "shell_exec", "proc_open",
"proc_close", "proc_terminate", "proc_get_status", "rand", "srand",
"getrandmax", "mt_rand", "mt_srand", "mt_getrandmax", "getservbyname",
"getservbyport", "getprotobyname", "getprotobynumber", "getmyuid", "getmygid",
"getmypid", "getmyinode", "getlastmod", "base64_decode", "base64_encode",
"convert_uuencode", "convert_uudecode", "abs", "ceil", "floor", "round", "sin",
"cos", "tan", "asin", "acos", "atan", "atan2", "sinh", "cosh", "tanh", "pi",
"is_finite", "is_nan", "is_infinite", "pow", "exp", "log", "log10", "sqrt",
"hypot", "deg2rad", "rad2deg", "bindec", "hexdec", "octdec", "decbin",
"decoct", "dechex", "base_convert", "number_format", "fmod", "ip2long",
"long2ip", "getenv", "putenv", "microtime", "gettimeofday", "uniqid",
"quoted_printable_decode", "convert_cyr_string", "get_current_user",
"set_time_limit", "get_cfg_var", "magic_quotes_runtime",
"set_magic_quotes_runtime", "get_magic_quotes_gpc", "get_magic_quotes_runtime",
"import_request_variables", "error_log", "error_get_last", "call_user_func",
"call_user_func_array", "call_user_method", "call_user_method_array",
"serialize", "unserialize", "var_dump", "var_export", "debug_zval_dump",
"print_r", "memory_get_usage", "memory_get_peak_usage",
"register_shutdown_function", "register_tick_function",
"unregister_tick_function", "highlight_file", "show_source",
"highlight_string", "php_strip_whitespace", "ini_get", "ini_get_all",
"ini_set", "ini_alter", "ini_restore", "get_include_path", "set_include_path",
"restore_include_path", "setcookie", "setrawcookie", "header", "headers_sent",
"headers_list", "connection_aborted", "connection_status", "ignore_user_abort",
"parse_ini_file", "is_uploaded_file", "move_uploaded_file", "gethostbyaddr",
"gethostbyname", "gethostbynamel", "intval", "floatval", "doubleval", "strval",
"gettype", "settype", "is_null", "is_resource", "is_bool", "is_long",
"is_float", "is_int", "is_integer", "is_double", "is_real", "is_numeric",
"is_string", "is_array", "is_object", "is_scalar", "is_callable", "ereg",
"ereg_replace", "eregi", "eregi_replace", "split", "spliti", "join",
"sql_regcase", "dl", "pclose", "popen", "readfile", "rewind", "rmdir", "umask",
"fclose", "feof", "fgetc", "fgets", "fgetss", "fread", "fopen", "fpassthru",
"ftruncate", "fstat", "fseek", "ftell", "fflush", "fwrite", "fputs", "mkdir",
"rename", "copy", "tempnam", "tmpfile", "file", "file_get_contents",
"file_put_contents", "stream_select", "stream_context_create",
"stream_context_set_params", "stream_context_set_option",
"stream_context_get_options", "stream_context_get_default",
"stream_filter_prepend", "stream_filter_append", "stream_filter_remove",
"stream_socket_client", "stream_socket_server", "stream_socket_accept",
"stream_socket_get_name", "stream_socket_recvfrom", "stream_socket_sendto",
"stream_socket_enable_crypto", "stream_socket_shutdown",
"stream_copy_to_stream", "stream_get_contents", "fgetcsv", "fputcsv", "flock",
"get_meta_tags", "stream_set_write_buffer", "set_file_buffer",
"set_socket_blocking", "stream_set_blocking", "socket_set_blocking",
"stream_get_meta_data", "stream_get_line", "stream_wrapper_register",
"stream_register_wrapper", "stream_wrapper_unregister",
"stream_wrapper_restore", "stream_get_wrappers", "stream_get_transports",
"get_headers", "stream_set_timeout", "socket_set_timeout", "socket_get_status",
"realpath", "fsockopen", "pfsockopen", "pack", "unpack", "get_browser",
"crypt", "opendir", "closedir", "chdir", "getcwd", "rewinddir", "readdir",
"dir", "scandir", "glob", "fileatime", "filectime", "filegroup", "fileinode",
"filemtime", "fileowner", "fileperms", "filesize", "filetype", "file_exists",
"is_writable", "is_writeable", "is_readable", "is_executable", "is_file",
"is_dir", "is_link", "stat", "lstat", "chown", "chgrp", "chmod", "touch",
"clearstatcache", "disk_total_space", "disk_free_space", "diskfreespace",
"mail", "ezmlm_hash", "openlog", "syslog", "closelog",
"define_syslog_variables", "lcg_value", "metaphone", "ob_start", "ob_flush",
"ob_clean", "ob_end_flush", "ob_end_clean", "ob_get_flush", "ob_get_clean",
"ob_get_length", "ob_get_level", "ob_get_status", "ob_get_contents",
"ob_implicit_flush", "ob_list_handlers", "ksort", "krsort", "natsort",
"natcasesort", "asort", "arsort", "sort", "rsort", "usort", "uasort", "uksort",
"shuffle", "array_walk", "array_walk_recursive", "count", "end", "prev",
"next", "reset", "current", "key", "min", "max", "in_array", "array_search",
"extract", "compact", "array_fill", "array_fill_keys", "range",
"array_multisort", "array_push", "array_pop", "array_shift", "array_unshift",
"array_splice", "array_slice", "array_merge", "array_merge_recursive",
"array_keys", "array_values", "array_count_values", "array_reverse",
"array_reduce", "array_pad", "array_flip", "array_change_key_case",
"array_rand", "array_unique", "array_intersect", "array_intersect_key",
"array_intersect_ukey", "array_uintersect", "array_intersect_assoc",
"array_uintersect_assoc", "array_intersect_uassoc", "array_uintersect_uassoc",
"array_diff", "array_diff_key", "array_diff_ukey", "array_udiff",
"array_diff_assoc", "array_udiff_assoc", "array_diff_uassoc",
"array_udiff_uassoc", "array_sum", "array_product", "array_filter",
"array_map", "array_chunk", "array_combine", "array_key_exists", "pos",
"sizeof", "key_exists", "assert", "assert_options", "version_compare",
"str_rot13", "stream_get_filters", "stream_filter_register",
"stream_bucket_make_writeable", "stream_bucket_prepend",
"stream_bucket_append", "stream_bucket_new", "output_add_rewrite_var",
"output_reset_rewrite_vars", "sys_get_temp_dir", "token_get_all", "token_name",
"readgzfile", "gzrewind", "gzclose", "gzeof", "gzgetc", "gzgets", "gzgetss",
"gzread", "gzopen", "gzpassthru", "gzseek", "gztell", "gzwrite", "gzputs",
"gzfile", "gzcompress", "gzuncompress", "gzdeflate", "gzinflate", "gzencode",
"ob_gzhandler", "zlib_get_coding_type", "libxml_set_streams_context",
"libxml_use_internal_errors", "libxml_get_last_error", "libxml_clear_errors",
"libxml_get_errors", "dom_import_simplexml", "simplexml_load_file",
"simplexml_load_string", "simplexml_import_dom", "wddx_serialize_value",
"wddx_serialize_vars", "wddx_packet_start", "wddx_packet_end", "wddx_add_vars",
"wddx_deserialize", "xml_parser_create", "xml_parser_create_ns",
"xml_set_object", "xml_set_element_handler", "xml_set_character_data_handler",
"xml_set_processing_instruction_handler", "xml_set_default_handler",
"xml_set_unparsed_entity_decl_handler", "xml_set_notation_decl_handler",
"xml_set_external_entity_ref_handler", "xml_set_start_namespace_decl_handler",
"xml_set_end_namespace_decl_handler", "xml_parse", "xml_parse_into_struct",
"xml_get_error_code", "xml_error_string", "xml_get_current_line_number",
"xml_get_current_column_number", "xml_get_current_byte_index",
"xml_parser_free", "xml_parser_set_option", "xml_parser_get_option",
"utf8_encode", "utf8_decode", "xmlwriter_open_uri", "xmlwriter_open_memory",
"xmlwriter_set_indent", "xmlwriter_set_indent_string",
"xmlwriter_start_comment", "xmlwriter_end_comment",
"xmlwriter_start_attribute", "xmlwriter_end_attribute",
"xmlwriter_write_attribute", "xmlwriter_start_attribute_ns",
"xmlwriter_write_attribute_ns", "xmlwriter_start_element",
"xmlwriter_end_element", "xmlwriter_full_end_element",
"xmlwriter_start_element_ns", "xmlwriter_write_element",
"xmlwriter_write_element_ns", "xmlwriter_start_pi", "xmlwriter_end_pi",
"xmlwriter_write_pi", "xmlwriter_start_cdata", "xmlwriter_end_cdata",
"xmlwriter_write_cdata", "xmlwriter_text", "xmlwriter_write_raw",
"xmlwriter_start_document", "xmlwriter_end_document",
"xmlwriter_write_comment", "xmlwriter_start_dtd", "xmlwriter_end_dtd",
"xmlwriter_write_dtd", "xmlwriter_start_dtd_element",
"xmlwriter_end_dtd_element", "xmlwriter_write_dtd_element",
"xmlwriter_start_dtd_attlist", "xmlwriter_end_dtd_attlist",
"xmlwriter_write_dtd_attlist", "xmlwriter_start_dtd_entity",
"xmlwriter_end_dtd_entity", "xmlwriter_write_dtd_entity",
"xmlwriter_output_memory", "xmlwriter_flush", "gd_info", "imagearc",
"imageellipse", "imagechar", "imagecharup", "imagecolorat",
"imagecolorallocate", "imagepalettecopy", "imagecreatefromstring",
"imagecolorclosest", "imagecolordeallocate", "imagecolorresolve",
"imagecolorexact", "imagecolorset", "imagecolortransparent",
"imagecolorstotal", "imagecolorsforindex", "imagecopy", "imagecopymerge",
"imagecopymergegray", "imagecopyresized", "imagecreate",
"imagecreatetruecolor", "imageistruecolor", "imagetruecolortopalette",
"imagesetthickness", "imagefilledarc", "imagefilledellipse",
"imagealphablending", "imagesavealpha", "imagecolorallocatealpha",
"imagecolorresolvealpha", "imagecolorclosestalpha", "imagecolorexactalpha",
"imagecopyresampled", "imagegrabwindow", "imagegrabscreen", "imagerotate",
"imageantialias", "imagesettile", "imagesetbrush", "imagesetstyle",
"imagecreatefrompng", "imagecreatefromgif", "imagecreatefromjpeg",
"imagecreatefromwbmp", "imagecreatefromxbm", "imagecreatefromgd",
"imagecreatefromgd2", "imagecreatefromgd2part", "imagepng", "imagegif",
"imagejpeg", "imagewbmp", "imagegd", "imagegd2", "imagedestroy",
"imagegammacorrect", "imagefill", "imagefilledpolygon", "imagefilledrectangle",
"imagefilltoborder", "imagefontwidth", "imagefontheight", "imageinterlace",
"imageline", "imageloadfont", "imagepolygon", "imagerectangle",
"imagesetpixel", "imagestring", "imagestringup", "imagesx", "imagesy",
"imagedashedline", "imagettfbbox", "imagettftext", "imageftbbox",
"imagefttext", "imagepsloadfont", "imagepsfreefont", "imagepsencodefont",
"imagepsextendfont", "imagepsslantfont", "imagepstext", "imagepsbbox",
"imagetypes", "jpeg2wbmp", "png2wbmp", "image2wbmp", "imagelayereffect",
"imagecolormatch", "imagexbm", "imagefilter", "imageconvolution",
"mb_convert_case", "mb_strtoupper", "mb_strtolower", "mb_language",
"mb_internal_encoding", "mb_http_input", "mb_http_output", "mb_detect_order",
"mb_substitute_character", "mb_parse_str", "mb_output_handler",
"mb_preferred_mime_name", "mb_strlen", "mb_strpos", "mb_strrpos", "mb_stripos",
"mb_strripos", "mb_strstr", "mb_strrchr", "mb_stristr", "mb_strrichr",
"mb_substr_count", "mb_substr", "mb_strcut", "mb_strwidth", "mb_strimwidth",
"mb_convert_encoding", "mb_detect_encoding", "mb_list_encodings",
"mb_convert_kana", "mb_encode_mimeheader", "mb_decode_mimeheader",
"mb_convert_variables", "mb_encode_numericentity", "mb_decode_numericentity",
"mb_send_mail", "mb_get_info", "mb_check_encoding", "mb_regex_encoding",
"mb_regex_set_options", "mb_ereg", "mb_eregi", "mb_ereg_replace",
"mb_eregi_replace", "mb_split", "mb_ereg_match", "mb_ereg_search",
"mb_ereg_search_pos", "mb_ereg_search_regs", "mb_ereg_search_init",
"mb_ereg_search_getregs", "mb_ereg_search_getpos", "mb_ereg_search_setpos",
"mbregex_encoding", "mbereg", "mberegi", "mbereg_replace", "mberegi_replace",
"mbsplit", "mbereg_match", "mbereg_search", "mbereg_search_pos",
"mbereg_search_regs", "mbereg_search_init", "mbereg_search_getregs",
"mbereg_search_getpos", "mbereg_search_setpos", "mysql_connect",
"mysql_pconnect", "mysql_close", "mysql_select_db", "mysql_query",
"mysql_unbuffered_query", "mysql_db_query", "mysql_list_dbs",
"mysql_list_tables", "mysql_list_fields", "mysql_list_processes",
"mysql_error", "mysql_errno", "mysql_affected_rows", "mysql_insert_id",
"mysql_result", "mysql_num_rows", "mysql_num_fields", "mysql_fetch_row",
"mysql_fetch_array", "mysql_fetch_assoc", "mysql_fetch_object",
"mysql_data_seek", "mysql_fetch_lengths", "mysql_fetch_field",
"mysql_field_seek", "mysql_free_result", "mysql_field_name",
"mysql_field_table", "mysql_field_len", "mysql_field_type",
"mysql_field_flags", "mysql_escape_string", "mysql_real_escape_string",
"mysql_stat", "mysql_thread_id", "mysql_client_encoding", "mysql_ping",
"mysql_get_client_info", "mysql_get_host_info", "mysql_get_proto_info",
"mysql_get_server_info", "mysql_info", "mysql_set_charset", "mysql",
"mysql_fieldname", "mysql_fieldtable", "mysql_fieldlen", "mysql_fieldtype",
"mysql_fieldflags", "mysql_selectdb", "mysql_freeresult", "mysql_numfields",
"mysql_numrows", "mysql_listdbs", "mysql_listtables", "mysql_listfields",
"mysql_db_name", "mysql_dbname", "mysql_tablename", "mysql_table_name",
"mysqli_affected_rows", "mysqli_autocommit", "mysqli_change_user",
"mysqli_character_set_name", "mysqli_close", "mysqli_commit", "mysqli_connect",
"mysqli_connect_errno", "mysqli_connect_error", "mysqli_data_seek",
"mysqli_debug", "mysqli_disable_reads_from_master", "mysqli_disable_rpl_parse",
"mysqli_dump_debug_info", "mysqli_enable_reads_from_master",
"mysqli_enable_rpl_parse", "mysqli_embedded_server_end",
"mysqli_embedded_server_start", "mysqli_errno", "mysqli_error",
"mysqli_stmt_execute", "mysqli_execute", "mysqli_fetch_field",
"mysqli_fetch_fields", "mysqli_fetch_field_direct", "mysqli_fetch_lengths",
"mysqli_fetch_array", "mysqli_fetch_assoc", "mysqli_fetch_object",
"mysqli_fetch_row", "mysqli_field_count", "mysqli_field_seek",
"mysqli_field_tell", "mysqli_free_result", "mysqli_get_charset",
"mysqli_get_client_info", "mysqli_get_client_version", "mysqli_get_host_info",
"mysqli_get_proto_info", "mysqli_get_server_info", "mysqli_get_server_version",
"mysqli_get_warnings", "mysqli_init", "mysqli_info", "mysqli_insert_id",
"mysqli_kill", "mysqli_set_local_infile_default",
"mysqli_set_local_infile_handler", "mysqli_master_query",
"mysqli_more_results", "mysqli_multi_query", "mysqli_next_result",
"mysqli_num_fields", "mysqli_num_rows", "mysqli_options", "mysqli_ping",
"mysqli_prepare", "mysqli_report", "mysqli_query", "mysqli_real_connect",
"mysqli_real_escape_string", "mysqli_real_query", "mysqli_rollback",
"mysqli_rpl_parse_enabled", "mysqli_rpl_probe", "mysqli_rpl_query_type",
"mysqli_select_db", "mysqli_set_charset", "mysqli_stmt_attr_get",
"mysqli_stmt_attr_set", "mysqli_stmt_field_count", "mysqli_stmt_init",
"mysqli_stmt_prepare", "mysqli_stmt_result_metadata",
"mysqli_stmt_send_long_data", "mysqli_stmt_bind_param",
"mysqli_stmt_bind_result", "mysqli_stmt_fetch", "mysqli_stmt_free_result",
"mysqli_stmt_get_warnings", "mysqli_stmt_insert_id", "mysqli_stmt_reset",
"mysqli_stmt_param_count", "mysqli_send_query", "mysqli_slave_query",
"mysqli_sqlstate", "mysqli_ssl_set", "mysqli_stat",
"mysqli_stmt_affected_rows", "mysqli_stmt_close", "mysqli_stmt_data_seek",
"mysqli_stmt_errno", "mysqli_stmt_error", "mysqli_stmt_num_rows",
"mysqli_stmt_sqlstate", "mysqli_store_result", "mysqli_stmt_store_result",
"mysqli_thread_id", "mysqli_thread_safe", "mysqli_use_result",
"mysqli_warning_count", "mysqli_bind_param", "mysqli_bind_result",
"mysqli_client_encoding", "mysqli_escape_string", "mysqli_fetch",
"mysqli_param_count", "mysqli_get_metadata", "mysqli_send_long_data",
"mysqli_set_opt", "pdo_drivers", "socket_select", "socket_create",
"socket_create_listen", "socket_accept", "socket_set_nonblock",
"socket_set_block", "socket_listen", "socket_close", "socket_write",
"socket_read", "socket_getsockname", "socket_getpeername", "socket_connect",
"socket_strerror", "socket_bind", "socket_recv", "socket_send",
"socket_recvfrom", "socket_sendto", "socket_get_option", "socket_set_option",
"socket_shutdown", "socket_last_error", "socket_clear_error", "socket_getopt",
"socket_setopt", "eaccelerator_put", "eaccelerator_get", "eaccelerator_rm",
"eaccelerator_gc", "eaccelerator_lock", "eaccelerator_unlock",
"eaccelerator_caching", "eaccelerator_optimizer", "eaccelerator_clear",
"eaccelerator_clean", "eaccelerator_info", "eaccelerator_purge",
"eaccelerator_cached_scripts", "eaccelerator_removed_scripts",
"eaccelerator_list_keys", "eaccelerator_encode", "eaccelerator_load",
"_eaccelerator_loader_file", "_eaccelerator_loader_line",
"eaccelerator_set_session_handlers", "_eaccelerator_output_handler",
"eaccelerator_cache_page", "eaccelerator_rm_page", "eaccelerator_cache_output",
"eaccelerator_cache_result", "xdebug_get_stack_depth",
"xdebug_get_function_stack", "xdebug_print_function_stack",
"xdebug_get_declared_vars", "xdebug_call_class", "xdebug_call_function",
"xdebug_call_file", "xdebug_call_line", "xdebug_var_dump", "xdebug_debug_zval",
"xdebug_debug_zval_stdout", "xdebug_enable", "xdebug_disable",
"xdebug_is_enabled", "xdebug_break", "xdebug_start_trace", "xdebug_stop_trace",
"xdebug_get_tracefile_name", "xdebug_get_profiler_filename",
"xdebug_dump_aggr_profiling_data", "xdebug_clear_aggr_profiling_data",
"xdebug_memory_usage", "xdebug_peak_memory_usage", "xdebug_time_index",
"xdebug_start_error_collection", "xdebug_stop_error_collection",
"xdebug_get_collected_errors", "xdebug_start_code_coverage",
"xdebug_stop_code_coverage", "xdebug_get_code_coverage",
"xdebug_get_function_count", "xdebug_dump_superglobals",
"_" // alias for gettext()
].forEach(function(element, index, array) {
result[element] = token("t_string", "php-predefined-function");
});
// output of get_defined_constants(). Differs significantly from http://php.net/manual/en/reserved.constants.php
[ "E_ERROR", "E_RECOVERABLE_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE",
"E_STRICT", "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR",
"E_COMPILE_WARNING", "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE",
"E_ALL", "TRUE", "FALSE", "NULL", "ZEND_THREAD_SAFE", "PHP_VERSION", "PHP_OS",
"PHP_SAPI", "DEFAULT_INCLUDE_PATH", "PEAR_INSTALL_DIR", "PEAR_EXTENSION_DIR",
"PHP_EXTENSION_DIR", "PHP_PREFIX", "PHP_BINDIR", "PHP_LIBDIR", "PHP_DATADIR",
"PHP_SYSCONFDIR", "PHP_LOCALSTATEDIR", "PHP_CONFIG_FILE_PATH",
"PHP_CONFIG_FILE_SCAN_DIR", "PHP_SHLIB_SUFFIX", "PHP_EOL", "PHP_EOL",
"PHP_INT_MAX", "PHP_INT_SIZE", "PHP_OUTPUT_HANDLER_START",
"PHP_OUTPUT_HANDLER_CONT", "PHP_OUTPUT_HANDLER_END", "UPLOAD_ERR_OK",
"UPLOAD_ERR_INI_SIZE", "UPLOAD_ERR_FORM_SIZE", "UPLOAD_ERR_PARTIAL",
"UPLOAD_ERR_NO_FILE", "UPLOAD_ERR_NO_TMP_DIR", "UPLOAD_ERR_CANT_WRITE",
"UPLOAD_ERR_EXTENSION", "CAL_GREGORIAN", "CAL_JULIAN", "CAL_JEWISH",
"CAL_FRENCH", "CAL_NUM_CALS", "CAL_DOW_DAYNO", "CAL_DOW_SHORT", "CAL_DOW_LONG",
"CAL_MONTH_GREGORIAN_SHORT", "CAL_MONTH_GREGORIAN_LONG",
"CAL_MONTH_JULIAN_SHORT", "CAL_MONTH_JULIAN_LONG", "CAL_MONTH_JEWISH",
"CAL_MONTH_FRENCH", "CAL_EASTER_DEFAULT", "CAL_EASTER_ROMAN",
"CAL_EASTER_ALWAYS_GREGORIAN", "CAL_EASTER_ALWAYS_JULIAN",
"CAL_JEWISH_ADD_ALAFIM_GERESH", "CAL_JEWISH_ADD_ALAFIM",
"CAL_JEWISH_ADD_GERESHAYIM", "CLSCTX_INPROC_SERVER", "CLSCTX_INPROC_HANDLER",
"CLSCTX_LOCAL_SERVER", "CLSCTX_REMOTE_SERVER", "CLSCTX_SERVER", "CLSCTX_ALL",
"VT_NULL", "VT_EMPTY", "VT_UI1", "VT_I1", "VT_UI2", "VT_I2", "VT_UI4", "VT_I4",
"VT_R4", "VT_R8", "VT_BOOL", "VT_ERROR", "VT_CY", "VT_DATE", "VT_BSTR",
"VT_DECIMAL", "VT_UNKNOWN", "VT_DISPATCH", "VT_VARIANT", "VT_INT", "VT_UINT",
"VT_ARRAY", "VT_BYREF", "CP_ACP", "CP_MACCP", "CP_OEMCP", "CP_UTF7", "CP_UTF8",
"CP_SYMBOL", "CP_THREAD_ACP", "VARCMP_LT", "VARCMP_EQ", "VARCMP_GT",
"VARCMP_NULL", "NORM_IGNORECASE", "NORM_IGNORENONSPACE", "NORM_IGNORESYMBOLS",
"NORM_IGNOREWIDTH", "NORM_IGNOREKANATYPE", "DISP_E_DIVBYZERO",
"DISP_E_OVERFLOW", "DISP_E_BADINDEX", "MK_E_UNAVAILABLE", "INPUT_POST",
"INPUT_GET", "INPUT_COOKIE", "INPUT_ENV", "INPUT_SERVER", "INPUT_SESSION",
"INPUT_REQUEST", "FILTER_FLAG_NONE", "FILTER_REQUIRE_SCALAR",
"FILTER_REQUIRE_ARRAY", "FILTER_FORCE_ARRAY", "FILTER_NULL_ON_FAILURE",
"FILTER_VALIDATE_INT", "FILTER_VALIDATE_BOOLEAN", "FILTER_VALIDATE_FLOAT",
"FILTER_VALIDATE_REGEXP", "FILTER_VALIDATE_URL", "FILTER_VALIDATE_EMAIL",
"FILTER_VALIDATE_IP", "FILTER_DEFAULT", "FILTER_UNSAFE_RAW",
"FILTER_SANITIZE_STRING", "FILTER_SANITIZE_STRIPPED",
"FILTER_SANITIZE_ENCODED", "FILTER_SANITIZE_SPECIAL_CHARS",
"FILTER_SANITIZE_EMAIL", "FILTER_SANITIZE_URL", "FILTER_SANITIZE_NUMBER_INT",
"FILTER_SANITIZE_NUMBER_FLOAT", "FILTER_SANITIZE_MAGIC_QUOTES",
"FILTER_CALLBACK", "FILTER_FLAG_ALLOW_OCTAL", "FILTER_FLAG_ALLOW_HEX",
"FILTER_FLAG_STRIP_LOW", "FILTER_FLAG_STRIP_HIGH", "FILTER_FLAG_ENCODE_LOW",
"FILTER_FLAG_ENCODE_HIGH", "FILTER_FLAG_ENCODE_AMP",
"FILTER_FLAG_NO_ENCODE_QUOTES", "FILTER_FLAG_EMPTY_STRING_NULL",
"FILTER_FLAG_ALLOW_FRACTION", "FILTER_FLAG_ALLOW_THOUSAND",
"FILTER_FLAG_ALLOW_SCIENTIFIC", "FILTER_FLAG_SCHEME_REQUIRED",
"FILTER_FLAG_HOST_REQUIRED", "FILTER_FLAG_PATH_REQUIRED",
"FILTER_FLAG_QUERY_REQUIRED", "FILTER_FLAG_IPV4", "FILTER_FLAG_IPV6",
"FILTER_FLAG_NO_RES_RANGE", "FILTER_FLAG_NO_PRIV_RANGE", "FTP_ASCII",
"FTP_TEXT", "FTP_BINARY", "FTP_IMAGE", "FTP_AUTORESUME", "FTP_TIMEOUT_SEC",
"FTP_AUTOSEEK", "FTP_FAILED", "FTP_FINISHED", "FTP_MOREDATA", "HASH_HMAC",
"ICONV_IMPL", "ICONV_VERSION", "ICONV_MIME_DECODE_STRICT",
"ICONV_MIME_DECODE_CONTINUE_ON_ERROR", "ODBC_TYPE", "ODBC_BINMODE_PASSTHRU",
"ODBC_BINMODE_RETURN", "ODBC_BINMODE_CONVERT", "SQL_ODBC_CURSORS",
"SQL_CUR_USE_DRIVER", "SQL_CUR_USE_IF_NEEDED", "SQL_CUR_USE_ODBC",
"SQL_CONCURRENCY", "SQL_CONCUR_READ_ONLY", "SQL_CONCUR_LOCK",
"SQL_CONCUR_ROWVER", "SQL_CONCUR_VALUES", "SQL_CURSOR_TYPE",
"SQL_CURSOR_FORWARD_ONLY", "SQL_CURSOR_KEYSET_DRIVEN", "SQL_CURSOR_DYNAMIC",
"SQL_CURSOR_STATIC", "SQL_KEYSET_SIZE", "SQL_FETCH_FIRST", "SQL_FETCH_NEXT",
"SQL_CHAR", "SQL_VARCHAR", "SQL_LONGVARCHAR", "SQL_DECIMAL", "SQL_NUMERIC",
"SQL_BIT", "SQL_TINYINT", "SQL_SMALLINT", "SQL_INTEGER", "SQL_BIGINT",
"SQL_REAL", "SQL_FLOAT", "SQL_DOUBLE", "SQL_BINARY", "SQL_VARBINARY",
"SQL_LONGVARBINARY", "SQL_DATE", "SQL_TIME", "SQL_TIMESTAMP",
"PREG_PATTERN_ORDER", "PREG_SET_ORDER", "PREG_OFFSET_CAPTURE",
"PREG_SPLIT_NO_EMPTY", "PREG_SPLIT_DELIM_CAPTURE", "PREG_SPLIT_OFFSET_CAPTURE",
"PREG_GREP_INVERT", "PREG_NO_ERROR", "PREG_INTERNAL_ERROR",
"PREG_BACKTRACK_LIMIT_ERROR", "PREG_RECURSION_LIMIT_ERROR",
"PREG_BAD_UTF8_ERROR", "DATE_ATOM", "DATE_COOKIE", "DATE_ISO8601",
"DATE_RFC822", "DATE_RFC850", "DATE_RFC1036", "DATE_RFC1123", "DATE_RFC2822",
"DATE_RFC3339", "DATE_RSS", "DATE_W3C", "SUNFUNCS_RET_TIMESTAMP",
"SUNFUNCS_RET_STRING", "SUNFUNCS_RET_DOUBLE", "LIBXML_VERSION",
"LIBXML_DOTTED_VERSION", "LIBXML_NOENT", "LIBXML_DTDLOAD", "LIBXML_DTDATTR",
"LIBXML_DTDVALID", "LIBXML_NOERROR", "LIBXML_NOWARNING", "LIBXML_NOBLANKS",
"LIBXML_XINCLUDE", "LIBXML_NSCLEAN", "LIBXML_NOCDATA", "LIBXML_NONET",
"LIBXML_COMPACT", "LIBXML_NOXMLDECL", "LIBXML_NOEMPTYTAG", "LIBXML_ERR_NONE",
"LIBXML_ERR_WARNING", "LIBXML_ERR_ERROR", "LIBXML_ERR_FATAL",
"CONNECTION_ABORTED", "CONNECTION_NORMAL", "CONNECTION_TIMEOUT", "INI_USER",
"INI_PERDIR", "INI_SYSTEM", "INI_ALL", "PHP_URL_SCHEME", "PHP_URL_HOST",
"PHP_URL_PORT", "PHP_URL_USER", "PHP_URL_PASS", "PHP_URL_PATH",
"PHP_URL_QUERY", "PHP_URL_FRAGMENT", "M_E", "M_LOG2E", "M_LOG10E", "M_LN2",
"M_LN10", "M_PI", "M_PI_2", "M_PI_4", "M_1_PI", "M_2_PI", "M_SQRTPI",
"M_2_SQRTPI", "M_LNPI", "M_EULER", "M_SQRT2", "M_SQRT1_2", "M_SQRT3", "INF",
"NAN", "INFO_GENERAL", "INFO_CREDITS", "INFO_CONFIGURATION", "INFO_MODULES",
"INFO_ENVIRONMENT", "INFO_VARIABLES", "INFO_LICENSE", "INFO_ALL",
"CREDITS_GROUP", "CREDITS_GENERAL", "CREDITS_SAPI", "CREDITS_MODULES",
"CREDITS_DOCS", "CREDITS_FULLPAGE", "CREDITS_QA", "CREDITS_ALL",
"HTML_SPECIALCHARS", "HTML_ENTITIES", "ENT_COMPAT", "ENT_QUOTES",
"ENT_NOQUOTES", "STR_PAD_LEFT", "STR_PAD_RIGHT", "STR_PAD_BOTH",
"PATHINFO_DIRNAME", "PATHINFO_BASENAME", "PATHINFO_EXTENSION",
"PATHINFO_FILENAME", "CHAR_MAX", "LC_CTYPE", "LC_NUMERIC", "LC_TIME",
"LC_COLLATE", "LC_MONETARY", "LC_ALL", "SEEK_SET", "SEEK_CUR", "SEEK_END",
"LOCK_SH", "LOCK_EX", "LOCK_UN", "LOCK_NB", "STREAM_NOTIFY_CONNECT",
"STREAM_NOTIFY_AUTH_REQUIRED", "STREAM_NOTIFY_AUTH_RESULT",
"STREAM_NOTIFY_MIME_TYPE_IS", "STREAM_NOTIFY_FILE_SIZE_IS",
"STREAM_NOTIFY_REDIRECTED", "STREAM_NOTIFY_PROGRESS", "STREAM_NOTIFY_FAILURE",
"STREAM_NOTIFY_COMPLETED", "STREAM_NOTIFY_RESOLVE",
"STREAM_NOTIFY_SEVERITY_INFO", "STREAM_NOTIFY_SEVERITY_WARN",
"STREAM_NOTIFY_SEVERITY_ERR", "STREAM_FILTER_READ", "STREAM_FILTER_WRITE",
"STREAM_FILTER_ALL", "STREAM_CLIENT_PERSISTENT", "STREAM_CLIENT_ASYNC_CONNECT",
"STREAM_CLIENT_CONNECT", "STREAM_CRYPTO_METHOD_SSLv2_CLIENT",
"STREAM_CRYPTO_METHOD_SSLv3_CLIENT", "STREAM_CRYPTO_METHOD_SSLv23_CLIENT",
"STREAM_CRYPTO_METHOD_TLS_CLIENT", "STREAM_CRYPTO_METHOD_SSLv2_SERVER",
"STREAM_CRYPTO_METHOD_SSLv3_SERVER", "STREAM_CRYPTO_METHOD_SSLv23_SERVER",
"STREAM_CRYPTO_METHOD_TLS_SERVER", "STREAM_SHUT_RD", "STREAM_SHUT_WR",
"STREAM_SHUT_RDWR", "STREAM_PF_INET", "STREAM_PF_INET6", "STREAM_PF_UNIX",
"STREAM_IPPROTO_IP", "STREAM_IPPROTO_TCP", "STREAM_IPPROTO_UDP",
"STREAM_IPPROTO_ICMP", "STREAM_IPPROTO_RAW", "STREAM_SOCK_STREAM",
"STREAM_SOCK_DGRAM", "STREAM_SOCK_RAW", "STREAM_SOCK_SEQPACKET",
"STREAM_SOCK_RDM", "STREAM_PEEK", "STREAM_OOB", "STREAM_SERVER_BIND",
"STREAM_SERVER_LISTEN", "FILE_USE_INCLUDE_PATH", "FILE_IGNORE_NEW_LINES",
"FILE_SKIP_EMPTY_LINES", "FILE_APPEND", "FILE_NO_DEFAULT_CONTEXT",
"PSFS_PASS_ON", "PSFS_FEED_ME", "PSFS_ERR_FATAL", "PSFS_FLAG_NORMAL",
"PSFS_FLAG_FLUSH_INC", "PSFS_FLAG_FLUSH_CLOSE", "CRYPT_SALT_LENGTH",
"CRYPT_STD_DES", "CRYPT_EXT_DES", "CRYPT_MD5", "CRYPT_BLOWFISH",
"DIRECTORY_SEPARATOR", "PATH_SEPARATOR", "GLOB_BRACE", "GLOB_MARK",
"GLOB_NOSORT", "GLOB_NOCHECK", "GLOB_NOESCAPE", "GLOB_ERR", "GLOB_ONLYDIR",
"LOG_EMERG", "LOG_ALERT", "LOG_CRIT", "LOG_ERR", "LOG_WARNING", "LOG_NOTICE",
"LOG_INFO", "LOG_DEBUG", "LOG_KERN", "LOG_USER", "LOG_MAIL", "LOG_DAEMON",
"LOG_AUTH", "LOG_SYSLOG", "LOG_LPR", "LOG_NEWS", "LOG_UUCP", "LOG_CRON",
"LOG_AUTHPRIV", "LOG_PID", "LOG_CONS", "LOG_ODELAY", "LOG_NDELAY",
"LOG_NOWAIT", "LOG_PERROR", "EXTR_OVERWRITE", "EXTR_SKIP", "EXTR_PREFIX_SAME",
"EXTR_PREFIX_ALL", "EXTR_PREFIX_INVALID", "EXTR_PREFIX_IF_EXISTS",
"EXTR_IF_EXISTS", "EXTR_REFS", "SORT_ASC", "SORT_DESC", "SORT_REGULAR",
"SORT_NUMERIC", "SORT_STRING", "SORT_LOCALE_STRING", "CASE_LOWER",
"CASE_UPPER", "COUNT_NORMAL", "COUNT_RECURSIVE", "ASSERT_ACTIVE",
"ASSERT_CALLBACK", "ASSERT_BAIL", "ASSERT_WARNING", "ASSERT_QUIET_EVAL",
"STREAM_USE_PATH", "STREAM_IGNORE_URL", "STREAM_ENFORCE_SAFE_MODE",
"STREAM_REPORT_ERRORS", "STREAM_MUST_SEEK", "STREAM_URL_STAT_LINK",
"STREAM_URL_STAT_QUIET", "STREAM_MKDIR_RECURSIVE", "IMAGETYPE_GIF",
"IMAGETYPE_JPEG", "IMAGETYPE_PNG", "IMAGETYPE_SWF", "IMAGETYPE_PSD",
"IMAGETYPE_BMP", "IMAGETYPE_TIFF_II", "IMAGETYPE_TIFF_MM", "IMAGETYPE_JPC",
"IMAGETYPE_JP2", "IMAGETYPE_JPX", "IMAGETYPE_JB2", "IMAGETYPE_SWC",
"IMAGETYPE_IFF", "IMAGETYPE_WBMP", "IMAGETYPE_JPEG2000", "IMAGETYPE_XBM",
"T_INCLUDE", "T_INCLUDE_ONCE", "T_EVAL", "T_REQUIRE", "T_REQUIRE_ONCE",
"T_LOGICAL_OR", "T_LOGICAL_XOR", "T_LOGICAL_AND", "T_PRINT", "T_PLUS_EQUAL",
"T_MINUS_EQUAL", "T_MUL_EQUAL", "T_DIV_EQUAL", "T_CONCAT_EQUAL", "T_MOD_EQUAL",
"T_AND_EQUAL", "T_OR_EQUAL", "T_XOR_EQUAL", "T_SL_EQUAL", "T_SR_EQUAL",
"T_BOOLEAN_OR", "T_BOOLEAN_AND", "T_IS_EQUAL", "T_IS_NOT_EQUAL",
"T_IS_IDENTICAL", "T_IS_NOT_IDENTICAL", "T_IS_SMALLER_OR_EQUAL",
"T_IS_GREATER_OR_EQUAL", "T_SL", "T_SR", "T_INC", "T_DEC", "T_INT_CAST",
"T_DOUBLE_CAST", "T_STRING_CAST", "T_ARRAY_CAST", "T_OBJECT_CAST",
"T_BOOL_CAST", "T_UNSET_CAST", "T_NEW", "T_EXIT", "T_IF", "T_ELSEIF", "T_ELSE",
"T_ENDIF", "T_LNUMBER", "T_DNUMBER", "T_STRING", "T_STRING_VARNAME",
"T_VARIABLE", "T_NUM_STRING", "T_INLINE_HTML", "T_CHARACTER",
"T_BAD_CHARACTER", "T_ENCAPSED_AND_WHITESPACE", "T_CONSTANT_ENCAPSED_STRING",
"T_ECHO", "T_DO", "T_WHILE", "T_ENDWHILE", "T_FOR", "T_ENDFOR", "T_FOREACH",
"T_ENDFOREACH", "T_DECLARE", "T_ENDDECLARE", "T_AS", "T_SWITCH", "T_ENDSWITCH",
"T_CASE", "T_DEFAULT", "T_BREAK", "T_CONTINUE", "T_FUNCTION", "T_CONST",
"T_RETURN", "T_USE", "T_GLOBAL", "T_STATIC", "T_VAR", "T_UNSET", "T_ISSET",
"T_EMPTY", "T_CLASS", "T_EXTENDS", "T_INTERFACE", "T_IMPLEMENTS",
"T_OBJECT_OPERATOR", "T_DOUBLE_ARROW", "T_LIST", "T_ARRAY", "T_CLASS_C",
"T_FUNC_C", "T_METHOD_C", "T_LINE", "T_FILE", "T_COMMENT", "T_DOC_COMMENT",
"T_OPEN_TAG", "T_OPEN_TAG_WITH_ECHO", "T_CLOSE_TAG", "T_WHITESPACE",
"T_START_HEREDOC", "T_END_HEREDOC", "T_DOLLAR_OPEN_CURLY_BRACES",
"T_CURLY_OPEN", "T_PAAMAYIM_NEKUDOTAYIM", "T_DOUBLE_COLON", "T_ABSTRACT",
"T_CATCH", "T_FINAL", "T_INSTANCEOF", "T_PRIVATE", "T_PROTECTED", "T_PUBLIC",
"T_THROW", "T_TRY", "T_CLONE", "T_HALT_COMPILER", "FORCE_GZIP",
"FORCE_DEFLATE", "XML_ELEMENT_NODE", "XML_ATTRIBUTE_NODE", "XML_TEXT_NODE",
"XML_CDATA_SECTION_NODE", "XML_ENTITY_REF_NODE", "XML_ENTITY_NODE",
"XML_PI_NODE", "XML_COMMENT_NODE", "XML_DOCUMENT_NODE",
"XML_DOCUMENT_TYPE_NODE", "XML_DOCUMENT_FRAG_NODE", "XML_NOTATION_NODE",
"XML_HTML_DOCUMENT_NODE", "XML_DTD_NODE", "XML_ELEMENT_DECL_NODE",
"XML_ATTRIBUTE_DECL_NODE", "XML_ENTITY_DECL_NODE", "XML_NAMESPACE_DECL_NODE",
"XML_LOCAL_NAMESPACE", "XML_ATTRIBUTE_CDATA", "XML_ATTRIBUTE_ID",
"XML_ATTRIBUTE_IDREF", "XML_ATTRIBUTE_IDREFS", "XML_ATTRIBUTE_ENTITY",
"XML_ATTRIBUTE_NMTOKEN", "XML_ATTRIBUTE_NMTOKENS", "XML_ATTRIBUTE_ENUMERATION",
"XML_ATTRIBUTE_NOTATION", "DOM_PHP_ERR", "DOM_INDEX_SIZE_ERR",
"DOMSTRING_SIZE_ERR", "DOM_HIERARCHY_REQUEST_ERR", "DOM_WRONG_DOCUMENT_ERR",
"DOM_INVALID_CHARACTER_ERR", "DOM_NO_DATA_ALLOWED_ERR",
"DOM_NO_MODIFICATION_ALLOWED_ERR", "DOM_NOT_FOUND_ERR",
"DOM_NOT_SUPPORTED_ERR", "DOM_INUSE_ATTRIBUTE_ERR", "DOM_INVALID_STATE_ERR",
"DOM_SYNTAX_ERR", "DOM_INVALID_MODIFICATION_ERR", "DOM_NAMESPACE_ERR",
"DOM_INVALID_ACCESS_ERR", "DOM_VALIDATION_ERR", "XML_ERROR_NONE",
"XML_ERROR_NO_MEMORY", "XML_ERROR_SYNTAX", "XML_ERROR_NO_ELEMENTS",
"XML_ERROR_INVALID_TOKEN", "XML_ERROR_UNCLOSED_TOKEN",
"XML_ERROR_PARTIAL_CHAR", "XML_ERROR_TAG_MISMATCH",
"XML_ERROR_DUPLICATE_ATTRIBUTE", "XML_ERROR_JUNK_AFTER_DOC_ELEMENT",
"XML_ERROR_PARAM_ENTITY_REF", "XML_ERROR_UNDEFINED_ENTITY",
"XML_ERROR_RECURSIVE_ENTITY_REF", "XML_ERROR_ASYNC_ENTITY",
"XML_ERROR_BAD_CHAR_REF", "XML_ERROR_BINARY_ENTITY_REF",
"XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", "XML_ERROR_MISPLACED_XML_PI",
"XML_ERROR_UNKNOWN_ENCODING", "XML_ERROR_INCORRECT_ENCODING",
"XML_ERROR_UNCLOSED_CDATA_SECTION", "XML_ERROR_EXTERNAL_ENTITY_HANDLING",
"XML_OPTION_CASE_FOLDING", "XML_OPTION_TARGET_ENCODING",
"XML_OPTION_SKIP_TAGSTART", "XML_OPTION_SKIP_WHITE", "XML_SAX_IMPL", "IMG_GIF",
"IMG_JPG", "IMG_JPEG", "IMG_PNG", "IMG_WBMP", "IMG_XPM", "IMG_COLOR_TILED",
"IMG_COLOR_STYLED", "IMG_COLOR_BRUSHED", "IMG_COLOR_STYLEDBRUSHED",
"IMG_COLOR_TRANSPARENT", "IMG_ARC_ROUNDED", "IMG_ARC_PIE", "IMG_ARC_CHORD",
"IMG_ARC_NOFILL", "IMG_ARC_EDGED", "IMG_GD2_RAW", "IMG_GD2_COMPRESSED",
"IMG_EFFECT_REPLACE", "IMG_EFFECT_ALPHABLEND", "IMG_EFFECT_NORMAL",
"IMG_EFFECT_OVERLAY", "GD_BUNDLED", "IMG_FILTER_NEGATE",
"IMG_FILTER_GRAYSCALE", "IMG_FILTER_BRIGHTNESS", "IMG_FILTER_CONTRAST",
"IMG_FILTER_COLORIZE", "IMG_FILTER_EDGEDETECT", "IMG_FILTER_GAUSSIAN_BLUR",
"IMG_FILTER_SELECTIVE_BLUR", "IMG_FILTER_EMBOSS", "IMG_FILTER_MEAN_REMOVAL",
"IMG_FILTER_SMOOTH", "PNG_NO_FILTER", "PNG_FILTER_NONE", "PNG_FILTER_SUB",
"PNG_FILTER_UP", "PNG_FILTER_AVG", "PNG_FILTER_PAETH", "PNG_ALL_FILTERS",
"MB_OVERLOAD_MAIL", "MB_OVERLOAD_STRING", "MB_OVERLOAD_REGEX", "MB_CASE_UPPER",
"MB_CASE_LOWER", "MB_CASE_TITLE", "MYSQL_ASSOC", "MYSQL_NUM", "MYSQL_BOTH",
"MYSQL_CLIENT_COMPRESS", "MYSQL_CLIENT_SSL", "MYSQL_CLIENT_INTERACTIVE",
"MYSQL_CLIENT_IGNORE_SPACE", "MYSQLI_READ_DEFAULT_GROUP",
"MYSQLI_READ_DEFAULT_FILE", "MYSQLI_OPT_CONNECT_TIMEOUT",
"MYSQLI_OPT_LOCAL_INFILE", "MYSQLI_INIT_COMMAND", "MYSQLI_CLIENT_SSL",
"MYSQLI_CLIENT_COMPRESS", "MYSQLI_CLIENT_INTERACTIVE",
"MYSQLI_CLIENT_IGNORE_SPACE", "MYSQLI_CLIENT_NO_SCHEMA",
"MYSQLI_CLIENT_FOUND_ROWS", "MYSQLI_STORE_RESULT", "MYSQLI_USE_RESULT",
"MYSQLI_ASSOC", "MYSQLI_NUM", "MYSQLI_BOTH",
"MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH", "MYSQLI_STMT_ATTR_CURSOR_TYPE",
"MYSQLI_CURSOR_TYPE_NO_CURSOR", "MYSQLI_CURSOR_TYPE_READ_ONLY",
"MYSQLI_CURSOR_TYPE_FOR_UPDATE", "MYSQLI_CURSOR_TYPE_SCROLLABLE",
"MYSQLI_STMT_ATTR_PREFETCH_ROWS", "MYSQLI_NOT_NULL_FLAG",
"MYSQLI_PRI_KEY_FLAG", "MYSQLI_UNIQUE_KEY_FLAG", "MYSQLI_MULTIPLE_KEY_FLAG",
"MYSQLI_BLOB_FLAG", "MYSQLI_UNSIGNED_FLAG", "MYSQLI_ZEROFILL_FLAG",
"MYSQLI_AUTO_INCREMENT_FLAG", "MYSQLI_TIMESTAMP_FLAG", "MYSQLI_SET_FLAG",
"MYSQLI_NUM_FLAG", "MYSQLI_PART_KEY_FLAG", "MYSQLI_GROUP_FLAG",
"MYSQLI_TYPE_DECIMAL", "MYSQLI_TYPE_TINY", "MYSQLI_TYPE_SHORT",
"MYSQLI_TYPE_LONG", "MYSQLI_TYPE_FLOAT", "MYSQLI_TYPE_DOUBLE",
"MYSQLI_TYPE_NULL", "MYSQLI_TYPE_TIMESTAMP", "MYSQLI_TYPE_LONGLONG",
"MYSQLI_TYPE_INT24", "MYSQLI_TYPE_DATE", "MYSQLI_TYPE_TIME",
"MYSQLI_TYPE_DATETIME", "MYSQLI_TYPE_YEAR", "MYSQLI_TYPE_NEWDATE",
"MYSQLI_TYPE_ENUM", "MYSQLI_TYPE_SET", "MYSQLI_TYPE_TINY_BLOB",
"MYSQLI_TYPE_MEDIUM_BLOB", "MYSQLI_TYPE_LONG_BLOB", "MYSQLI_TYPE_BLOB",
"MYSQLI_TYPE_VAR_STRING", "MYSQLI_TYPE_STRING", "MYSQLI_TYPE_CHAR",
"MYSQLI_TYPE_INTERVAL", "MYSQLI_TYPE_GEOMETRY", "MYSQLI_TYPE_NEWDECIMAL",
"MYSQLI_TYPE_BIT", "MYSQLI_RPL_MASTER", "MYSQLI_RPL_SLAVE", "MYSQLI_RPL_ADMIN",
"MYSQLI_NO_DATA", "MYSQLI_DATA_TRUNCATED", "MYSQLI_REPORT_INDEX",
"MYSQLI_REPORT_ERROR", "MYSQLI_REPORT_STRICT", "MYSQLI_REPORT_ALL",
"MYSQLI_REPORT_OFF", "AF_UNIX", "AF_INET", "AF_INET6", "SOCK_STREAM",
"SOCK_DGRAM", "SOCK_RAW", "SOCK_SEQPACKET", "SOCK_RDM", "MSG_OOB",
"MSG_WAITALL", "MSG_PEEK", "MSG_DONTROUTE", "SO_DEBUG", "SO_REUSEADDR",
"SO_KEEPALIVE", "SO_DONTROUTE", "SO_LINGER", "SO_BROADCAST", "SO_OOBINLINE",
"SO_SNDBUF", "SO_RCVBUF", "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO",
"SO_RCVTIMEO", "SO_TYPE", "SO_ERROR", "SOL_SOCKET", "SOMAXCONN",
"PHP_NORMAL_READ", "PHP_BINARY_READ", "SOCKET_EINTR", "SOCKET_EBADF",
"SOCKET_EACCES", "SOCKET_EFAULT", "SOCKET_EINVAL", "SOCKET_EMFILE",
"SOCKET_EWOULDBLOCK", "SOCKET_EINPROGRESS", "SOCKET_EALREADY",
"SOCKET_ENOTSOCK", "SOCKET_EDESTADDRREQ", "SOCKET_EMSGSIZE",
"SOCKET_EPROTOTYPE", "SOCKET_ENOPROTOOPT", "SOCKET_EPROTONOSUPPORT",
"SOCKET_ESOCKTNOSUPPORT", "SOCKET_EOPNOTSUPP", "SOCKET_EPFNOSUPPORT",
"SOCKET_EAFNOSUPPORT", "SOCKET_EADDRINUSE", "SOCKET_EADDRNOTAVAIL",
"SOCKET_ENETDOWN", "SOCKET_ENETUNREACH", "SOCKET_ENETRESET",
"SOCKET_ECONNABORTED", "SOCKET_ECONNRESET", "SOCKET_ENOBUFS", "SOCKET_EISCONN",
"SOCKET_ENOTCONN", "SOCKET_ESHUTDOWN", "SOCKET_ETOOMANYREFS",
"SOCKET_ETIMEDOUT", "SOCKET_ECONNREFUSED", "SOCKET_ELOOP",
"SOCKET_ENAMETOOLONG", "SOCKET_EHOSTDOWN", "SOCKET_EHOSTUNREACH",
"SOCKET_ENOTEMPTY", "SOCKET_EPROCLIM", "SOCKET_EUSERS", "SOCKET_EDQUOT",
"SOCKET_ESTALE", "SOCKET_EREMOTE", "SOCKET_EDISCON", "SOCKET_SYSNOTREADY",
"SOCKET_VERNOTSUPPORTED", "SOCKET_NOTINITIALISED", "SOCKET_HOST_NOT_FOUND",
"SOCKET_TRY_AGAIN", "SOCKET_NO_RECOVERY", "SOCKET_NO_DATA",
"SOCKET_NO_ADDRESS", "SOL_TCP", "SOL_UDP", "EACCELERATOR_VERSION",
"EACCELERATOR_SHM_AND_DISK", "EACCELERATOR_SHM", "EACCELERATOR_SHM_ONLY",
"EACCELERATOR_DISK_ONLY", "EACCELERATOR_NONE", "XDEBUG_TRACE_APPEND",
"XDEBUG_TRACE_COMPUTERIZED", "XDEBUG_TRACE_HTML", "XDEBUG_CC_UNUSED",
"XDEBUG_CC_DEAD_CODE", "STDIN", "STDOUT", "STDERR",
].forEach(function(element, index, array) {
result[element] = token("atom", "php-predefined-constant");
});
// PHP declared classes - output of get_declared_classes(). Differs from http://php.net/manual/en/reserved.classes.php
[ "stdClass", "Exception", "ErrorException", "COMPersistHelper", "com_exception",
"com_safearray_proxy", "variant", "com", "dotnet", "ReflectionException",
"Reflection", "ReflectionFunctionAbstract", "ReflectionFunction",
"ReflectionParameter", "ReflectionMethod", "ReflectionClass",
"ReflectionObject", "ReflectionProperty", "ReflectionExtension", "DateTime",
"DateTimeZone", "LibXMLError", "__PHP_Incomplete_Class", "php_user_filter",
"Directory", "SimpleXMLElement", "DOMException", "DOMStringList",
"DOMNameList", "DOMImplementationList", "DOMImplementationSource",
"DOMImplementation", "DOMNode", "DOMNameSpaceNode", "DOMDocumentFragment",
"DOMDocument", "DOMNodeList", "DOMNamedNodeMap", "DOMCharacterData", "DOMAttr",
"DOMElement", "DOMText", "DOMComment", "DOMTypeinfo", "DOMUserDataHandler",
"DOMDomError", "DOMErrorHandler", "DOMLocator", "DOMConfiguration",
"DOMCdataSection", "DOMDocumentType", "DOMNotation", "DOMEntity",
"DOMEntityReference", "DOMProcessingInstruction", "DOMStringExtend",
"DOMXPath", "RecursiveIteratorIterator", "IteratorIterator", "FilterIterator",
"RecursiveFilterIterator", "ParentIterator", "LimitIterator",
"CachingIterator", "RecursiveCachingIterator", "NoRewindIterator",
"AppendIterator", "InfiniteIterator", "RegexIterator",
"RecursiveRegexIterator", "EmptyIterator", "ArrayObject", "ArrayIterator",
"RecursiveArrayIterator", "SplFileInfo", "DirectoryIterator",
"RecursiveDirectoryIterator", "SplFileObject", "SplTempFileObject",
"SimpleXMLIterator", "LogicException", "BadFunctionCallException",
"BadMethodCallException", "DomainException", "InvalidArgumentException",
"LengthException", "OutOfRangeException", "RuntimeException",
"OutOfBoundsException", "OverflowException", "RangeException",
"UnderflowException", "UnexpectedValueException", "SplObjectStorage",
"XMLReader", "XMLWriter", "mysqli_sql_exception", "mysqli_driver", "mysqli",
"mysqli_warning", "mysqli_result", "mysqli_stmt", "PDOException", "PDO",
"PDOStatement", "PDORow"
].forEach(function(element, index, array) {
result[element] = token("t_string", "php-predefined-class");
});
return result;
}();
// Helper regexps
var isOperatorChar = /[+*&%\/=<>!?.|-]/;
var isHexDigit = /[0-9A-Fa-f]/;
var isWordChar = /[\w\$_]/;
// Wrapper around phpToken that helps maintain parser state (whether
// we are inside of a multi-line comment)
function phpTokenState(inside) {
return function(source, setState) {
var newInside = inside;
var type = phpToken(inside, source, function(c) {newInside = c;});
if (newInside != inside)
setState(phpTokenState(newInside));
return type;
};
}
// The token reader, inteded to be used by the tokenizer from
// tokenize.js (through phpTokenState). Advances the source stream
// over a token, and returns an object containing the type and style
// of that token.
function phpToken(inside, source, setInside) {
function readHexNumber(){
source.next(); // skip the 'x'
source.nextWhileMatches(isHexDigit);
return {type: "number", style: "php-atom"};
}
function readNumber() {
source.nextWhileMatches(/[0-9]/);
if (source.equals(".")){
source.next();
source.nextWhileMatches(/[0-9]/);
}
if (source.equals("e") || source.equals("E")){
source.next();
if (source.equals("-"))
source.next();
source.nextWhileMatches(/[0-9]/);
}
return {type: "number", style: "php-atom"};
}
// Read a word and look it up in the keywords array. If found, it's a
// keyword of that type; otherwise it's a PHP T_STRING.
function readWord() {
source.nextWhileMatches(isWordChar);
var word = source.get();
var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word];
// since we called get(), tokenize::take won't get() anything. Thus, we must set token.content
return known ? {type: known.type, style: known.style, content: word} :
{type: "t_string", style: "php-t_string", content: word};
}
function readVariable() {
source.nextWhileMatches(isWordChar);
var word = source.get();
// in PHP, '$this' is a reserved word, but 'this' isn't. You can have function this() {...}
if (word == "$this")
return {type: "variable", style: "php-keyword", content: word};
else
return {type: "variable", style: "php-variable", content: word};
}
// Advance the stream until the given character (not preceded by a
// backslash) is encountered, or the end of the line is reached.
function nextUntilUnescaped(source, end) {
var escaped = false;
while(!source.endOfLine()){
var next = source.next();
if (next == end && !escaped)
return false;
escaped = next == "\\";
}
return escaped;
}
function readSingleLineComment() {
// read until the end of the line or until ?>, which terminates single-line comments
// `<?php echo 1; // comment ?> foo` will display "1 foo"
while(!source.lookAhead("?>") && !source.endOfLine())
source.next();
return {type: "comment", style: "php-comment"};
}
/* For multi-line comments, we want to return a comment token for
every line of the comment, but we also want to return the newlines
in them as regular newline tokens. We therefore need to save a
state variable ("inside") to indicate whether we are inside a
multi-line comment.
*/
function readMultilineComment(start){
var newInside = "/*";
var maybeEnd = (start == "*");
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == "/" && maybeEnd){
newInside = null;
break;
}
maybeEnd = (next == "*");
}
setInside(newInside);
return {type: "comment", style: "php-comment"};
}
// similar to readMultilineComment and nextUntilUnescaped
// unlike comments, strings are not stopped by ?>
function readMultilineString(start){
var newInside = start;
var escaped = false;
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == start && !escaped){
newInside = null; // we're outside of the string now
break;
}
escaped = (next == "\\");
}
setInside(newInside);
return {
type: newInside == null? "string" : "string_not_terminated",
style: (start == "'"? "php-string-single-quoted" : "php-string-double-quoted")
};
}
// http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
// See also 'nowdoc' on the page. Heredocs are not interrupted by the '?>' token.
function readHeredoc(identifier){
var token = {};
if (identifier == "<<<") {
// on our first invocation after reading the <<<, we must determine the closing identifier
if (source.equals("'")) {
// nowdoc
source.nextWhileMatches(isWordChar);
identifier = "'" + source.get() + "'";
source.next(); // consume the closing "'"
} else if (source.matches(/[A-Za-z_]/)) {
// heredoc
source.nextWhileMatches(isWordChar);
identifier = source.get();
} else {
// syntax error
setInside(null);
return { type: "error", style: "syntax-error" };
}
setInside(identifier);
token.type = "string_not_terminated";
token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted";
token.content = identifier;
} else {
token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted";
// consume a line of heredoc and check if it equals the closing identifier plus an optional semicolon
if (source.lookAhead(identifier, true) && (source.lookAhead(";\n") || source.endOfLine())) {
// the closing identifier can only appear at the beginning of the line
// note that even whitespace after the ";" is forbidden by the PHP heredoc syntax
token.type = "string";
token.content = source.get(); // don't get the ";" if there is one
setInside(null);
} else {
token.type = "string_not_terminated";
source.nextWhileMatches(/[^\n]/);
token.content = source.get();
}
}
return token;
}
function readOperator() {
source.nextWhileMatches(isOperatorChar);
return {type: "operator", style: "php-operator"};
}
function readStringSingleQuoted() {
var endBackSlash = nextUntilUnescaped(source, "'", false);
setInside(endBackSlash ? "'" : null);
return {type: "string", style: "php-string-single-quoted"};
}
function readStringDoubleQuoted() {
var endBackSlash = nextUntilUnescaped(source, "\"", false);
setInside(endBackSlash ? "\"": null);
return {type: "string", style: "php-string-double-quoted"};
}
// Fetch the next token. Dispatches on first character in the
// stream, or first two characters when the first is a slash.
switch (inside) {
case null:
case false: break;
case "'":
case "\"": return readMultilineString(inside);
case "/*": return readMultilineComment(source.next());
default: return readHeredoc(inside);
}
var ch = source.next();
if (ch == "'" || ch == "\"")
return readMultilineString(ch)
else if (ch == "#")
return readSingleLineComment();
else if (ch == "$")
return readVariable();
else if (ch == ":" && source.equals(":")) {
source.next();
// the T_DOUBLE_COLON can only follow a T_STRING (class name)
return {type: "t_double_colon", style: "php-operator"}
}
// with punctuation, the type of the token is the symbol itself
else if (/[\[\]{}\(\),;:]/.test(ch)) {
return {type: ch, style: "php-punctuation"};
}
else if (ch == "0" && (source.equals("x") || source.equals("X")))
return readHexNumber();
else if (/[0-9]/.test(ch))
return readNumber();
else if (ch == "/") {
if (source.equals("*"))
{ source.next(); return readMultilineComment(ch); }
else if (source.equals("/"))
return readSingleLineComment();
else
return readOperator();
}
else if (ch == "<") {
if (source.lookAhead("<<", true)) {
setInside("<<<");
return {type: "<<<", style: "php-punctuation"};
}
else
return readOperator();
}
else if (isOperatorChar.test(ch))
return readOperator();
else
return readWord();
}
// The external interface to the tokenizer.
return function(source, startState) {
return tokenizer(source, startState || phpTokenState(false, true));
};
})();
| JavaScript |
/*
Copyright (c) 2008-2010 Yahoo! Inc. All rights reserved.
The copyrights embodied in the content of this file are licensed by
Yahoo! Inc. under the BSD (revised) open source license
@author Dan Vlad Dascalescu <dandv@yahoo-inc.com>
Based on parsehtmlmixed.js by Marijn Haverbeke.
*/
var PHPHTMLMixedParser = Editor.Parser = (function() {
if (!(PHPParser && CSSParser && JSParser && XMLParser))
throw new Error("PHP, CSS, JS, and XML parsers must be loaded for PHP+HTML mixed mode to work.");
XMLParser.configure({useHTMLKludges: true});
function parseMixed(stream) {
var htmlParser = XMLParser.make(stream), localParser = null, inTag = false;
var iter = {next: top, copy: copy};
function top() {
var token = htmlParser.next();
if (token.content == "<")
inTag = true;
else if (token.style == "xml-tagname" && inTag === true)
inTag = token.content.toLowerCase();
else if (token.type == "xml-processing") {
// dispatch on PHP
if (token.content == "<?php")
iter.next = local(PHPParser, "?>");
}
// "xml-processing" tokens are ignored, because they should be handled by a specific local parser
else if (token.content == ">") {
if (inTag == "script")
iter.next = local(JSParser, "</script");
else if (inTag == "style")
iter.next = local(CSSParser, "</style");
inTag = false;
}
return token;
}
function local(parser, tag) {
var baseIndent = htmlParser.indentation();
localParser = parser.make(stream, baseIndent + indentUnit);
return function() {
if (stream.lookAhead(tag, false, false, true)) {
localParser = null;
iter.next = top;
return top(); // pass the ending tag to the enclosing parser
}
var token = localParser.next();
var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length);
if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) &&
stream.lookAhead(tag.slice(sz), false, false, true)) {
stream.push(token.value.slice(lt));
token.value = token.value.slice(0, lt);
}
if (token.indentation) {
var oldIndent = token.indentation;
token.indentation = function(chars) {
if (chars == "</")
return baseIndent;
else
return oldIndent(chars);
}
}
return token;
};
}
function copy() {
var _html = htmlParser.copy(), _local = localParser && localParser.copy(),
_next = iter.next, _inTag = inTag;
return function(_stream) {
stream = _stream;
htmlParser = _html(_stream);
localParser = _local && _local(_stream);
iter.next = _next;
inTag = _inTag;
return iter;
};
}
return iter;
}
return {make: parseMixed, electricChars: "{}/:"};
})();
| JavaScript |
CKFinder.addPlugin( 'fileeditor', function( api ) {
var regexExt = /^(.*)\.([^\.]+)$/,
regexTextExt = /^(txt|css|html|htm|js|asp|cfm|cfc|ascx|php|inc|xml|xslt|xsl)$/i,
regexCodeMirrorExt = /^(css|html|htm|js|xml|xsl|php)$/i,
codemirror,
file,
fileLoaded = false,
doc;
var codemirrorPath = CKFinder.getPluginPath('fileeditor') + 'codemirror/';
var codeMirrorParsers = {
css : 'parsecss.js',
js : [ 'tokenizejavascript.js', 'parsejavascript.js' ],
xml : 'parsexml.js',
php : ['parsexml.js', 'parsecss.js', 'tokenizejavascript.js', 'parsejavascript.js', '../contrib/php/js/tokenizephp.js', '../contrib/php/js/parsephp.js', '../contrib/php/js/parsephphtmlmixed.js']
};
var codeMirrorCss = {
css : codemirrorPath + 'css/csscolors.css',
js : codemirrorPath + 'css/jscolors.css',
xml : codemirrorPath + 'css/xmlcolors.css',
php : [ codemirrorPath + 'css/xmlcolors.css', codemirrorPath + 'css/jscolors.css', codemirrorPath + 'css/csscolors.css', codemirrorPath + 'contrib/php/css/phpcolors.css' ]
};
codeMirrorCss.xsl = codeMirrorCss.xml;
codeMirrorCss.htm = codeMirrorCss.xml;
codeMirrorCss.html = codeMirrorCss.xml;
codeMirrorParsers.xsl = codeMirrorParsers.xml;
codeMirrorParsers.htm = codeMirrorParsers.xml;
codeMirrorParsers.html = codeMirrorParsers.xml;
var isTextFile = function( file )
{
return regexTextExt.test( file.ext );
};
CKFinder.dialog.add( 'fileEditor', function( api )
{
var height, width;
var saveButton = (function()
{
return {
id : 'save',
label : api.lang.Fileeditor.save,
type : 'button',
onClick : function ( evt ) {
if ( !fileLoaded )
return true;
var dialog = evt.data.dialog;
var content = codemirror ? codemirror.getCode() : doc.getById( 'fileContent' ).getValue();
api.connector.sendCommandPost( "SaveFile", null, {
content : content,
fileName : file.name
},
function( xml ) {
if ( xml.checkError() )
return false;
api.openMsgDialog( '', api.lang.Fileeditor.fileSaveSuccess );
dialog.hide();
return undefined;
},
file.folder.type,
file.folder
);
return false;
}
};
})();
if ( api.inPopup )
{
width = api.document.documentElement.offsetWidth;
height = api.document.documentElement.offsetHeight;
}
else
{
var parentWindow = ( api.document.parentWindow || api.document.defaultView ).parent;
width = parentWindow.innerWidth ? parentWindow.innerWidth : parentWindow.document.documentElement.clientWidth;
height = parentWindow.innerHeight ? parentWindow.innerHeight : parentWindow.document.documentElement.clientHeight;
}
return {
title : api.getSelectedFile().name,
// TODO CKFINDER.DIALOG_RESIZE_BOTH
// resizable : CKFINDER.DIALOG_RESIZE_BOTH,
minWidth : parseInt( width, 10 ) * 0.6,
minHeight : parseInt( height, 10 ) * 0.7,
onHide : function() {
if ( fileLoaded )
{
var fileContent = doc.getById( 'fileContent' );
if ( fileContent )
fileContent.remove();
}
},
onShow : function() {
var dialog = this;
var cssWidth = parseInt( width, 10 ) * 0.6 - 10;
var cssHeight = parseInt( height, 10 ) * 0.7 - 20;
doc = dialog.getElement().getDocument();
doc.getById( 'fileArea' ).setHtml( '<div class="ckfinder_loader_32" style="margin: 100px auto 0 auto;text-align:center;"><p style="height:' + cssHeight + 'px;width:' + cssWidth + 'px;">' + api.lang.Fileeditor.loadingFile + '</p></div>' );
file = api.getSelectedFile();
var enableCodeMirror = regexCodeMirrorExt.test( file.ext );
this.setTitle( file.name );
if ( enableCodeMirror && typeof( window.CodeMirror ) == 'undefined' )
{
var head= doc.$.getElementsByTagName( 'head' )[0];
var script= doc.$.createElement( 'script' );
script.type= 'text/javascript';
script.src = CKFinder.getPluginPath( 'fileeditor' ) + 'codemirror/js/codemirror.js';
head.appendChild( script );
}
// If CKFinder is runninng under a different domain than baseUrl, then the following call will fail:
// CKFinder.ajax.load( file.getUrl() + '?t=' + (new Date().getTime()), function( data )...
var url = api.connector.composeUrl( 'DownloadFile', { FileName : file.name, format : 'text', t : new Date().getTime() },
file.folder.type, file.folder );
CKFinder.ajax.load( url, function( data ) {
if ( data === null || ( file.size > 0 && data === '' ) )
{
api.openMsgDialog( '', api.lang.Fileeditor.fileOpenError );
dialog.hide();
return;
}
else
fileLoaded = true;
var fileArea = doc.getById( 'fileArea' );
fileArea.setStyle('height', '100%');
fileArea.setHtml( '<textarea id="fileContent" style="height:' + cssHeight + 'px; width:' + cssWidth + 'px"></textarea>' );
doc.getById( 'fileContent' ).setText( data );
codemirror = null;
if ( enableCodeMirror && typeof( window.CodeMirror ) != 'undefined' )
{
codemirror = window.CodeMirror.fromTextArea( doc.getById('fileContent').$, {
height: "350px",
parserfile: codeMirrorParsers[ file.ext ],
stylesheet: codeMirrorCss[ file.ext ],
path : codemirrorPath + "js/"
});
// TODO get rid of ugly buttons and provide something better
var undoB = doc.createElement( "button", { attributes: { "label" : api.lang.common.undo } } );
undoB.on( 'click', function() {
codemirror.undo();
});
undoB.setHtml( api.lang.common.undo );
undoB.appendTo( doc.getById( 'fileArea' ) );
var redoB = doc.createElement( 'button', { attributes: { "label" : api.lang.common.redo } } );
redoB.on('click', function() {
codemirror.redo();
});
redoB.setHtml( api.lang.common.redo );
redoB.appendTo( doc.getById( 'fileArea' ) );
}
}
);
},
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements :
[
{
type : 'html',
id : 'htmlLoader',
html : '' +
'<style type="text/css">' +
'.CodeMirror-wrapping {background:white;}' +
'</style>' +
'<div id="fileArea"></div>'
}
]
}
],
// TODO http://dev.fckeditor.net/ticket/4750
buttons : [ saveButton, CKFinder.dialog.cancelButton ]
};
} );
api.addFileContextMenuOption( { label : api.lang.Fileeditor.contextMenuName, command : "fileEditor" } , function( api, file )
{
api.openDialog( 'fileEditor' );
},
function ( file )
{
var maxSize = 1024;
if ( typeof (CKFinder.config.fileeditorMaxSize) != 'undefined' )
maxSize = CKFinder.config.fileeditorMaxSize;
// Disable for images, binary files, large files etc.
if ( isTextFile( file ) && file.size <= maxSize )
{
if ( file.folder.acl.fileDelete )
return true;
else
return -1;
}
return false;
});
} );
| JavaScript |
CKFinder.addPlugin( 'imageresize', {
connectorInitialized : function( api, xml ) {
var node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@smallThumb' );
if ( node )
CKFinder.config.imageresize_thumbSmall = node.value;
node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@mediumThumb' );
if ( node )
CKFinder.config.imageresize_thumbMedium = node.value;
node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@largeThumb' );
if ( node )
CKFinder.config.imageresize_thumbLarge = node.value;
},
uiReady : function( api ) {
var regexExt = /^(.*)\.([^\.]+)$/,
regexFileName = /^(.*?)(?:_\d+x\d+)?\.([^\.]+)$/,
regexGetSize = /^\s*(\d+)(px)?\s*$/i,
regexGetSizeOrEmpty = /(^\s*(\d+)(px)?\s*$)|^$/i,
imageDimension = { width : 0, height : 0 },
file,
doc;
var updateFileName = function( dialog )
{
var width = dialog.getValueOf( 'tab1', 'width' ) || 0,
height = dialog.getValueOf( 'tab1', 'height' ) || 0,
e = dialog.getContentElement('tab1', 'createNewBox');
if ( width && height )
{
var matches = file.name.match( regexFileName );
dialog.setValueOf( 'tab1', 'fileName', matches[1] + "_" + width + "x" + height + "." + matches[2]);
e.getElement().show();
}
else
e.getElement().hide();
};
var onSizeChange = function()
{
var value = this.getValue(), // This = input element.
dialog = this.getDialog(),
maxWidth = api.config.imagesMaxWidth,
maxHeight = api.config.imagesMaxHeight,
aMatch = value.match( regexGetSize ),
width = imageDimension.width,
height = imageDimension.height;
if ( aMatch )
value = aMatch[1];
if ( !api.config.imageresize_allowEnlarging )
{
if ( width && width < maxWidth )
maxWidth = width;
if ( height && height < maxHeight )
maxHeight = height;
}
if ( maxHeight > 0 && this.id == 'height' && value > maxHeight )
{
value = maxHeight;
dialog.setValueOf( 'tab1', 'height', value );
}
if ( maxWidth > 0 && this.id == 'width' && value > maxWidth )
{
value = maxWidth;
dialog.setValueOf( 'tab1', 'width', value );
}
// Only if ratio is locked
if ( dialog.lockRatio && width && height )
{
if ( this.id == 'height' )
{
if ( value && value != '0' )
value = Math.round( width * ( value / height ) );
if ( !isNaN( value ) )
{
// newWidth > maxWidth
if ( maxWidth > 0 && value > maxWidth )
{
value = maxWidth;
newHeight = Math.round( height * ( value / width ) );
dialog.setValueOf( 'tab1', 'height', newHeight );
}
dialog.setValueOf( 'tab1', 'width', value );
}
}
else //this.id = txtWidth.
{
if ( value && value != '0' )
value = Math.round( height * ( value / width ) );
if ( !isNaN( value ) )
{
// newHeight > maxHeight
if ( maxHeight > 0 && value > maxHeight )
{
value = maxHeight;
newWidth = Math.round( width * ( value / height ) );
dialog.setValueOf( 'tab1', 'width', newWidth );
}
dialog.setValueOf( 'tab1', 'height', value );
}
}
}
updateFileName( dialog );
};
var resetSize = function( dialog )
{
if ( imageDimension.width && imageDimension.height )
{
dialog.setValueOf( 'tab1', 'width', imageDimension.width );
dialog.setValueOf( 'tab1', 'height', imageDimension.height );
updateFileName( dialog );
}
};
var switchLockRatio = function( dialog, value )
{
var doc = dialog.getElement().getDocument(),
ratioButton = doc.getById( 'btnLockSizes' );
if ( imageDimension.width && imageDimension.height )
{
if ( value == 'check' ) // Check image ratio and original image ratio.
{
var width = dialog.getValueOf( 'tab1', 'width' ),
height = dialog.getValueOf( 'tab1', 'height' ),
originalRatio = imageDimension.width * 1000 / imageDimension.height,
thisRatio = width * 1000 / height;
dialog.lockRatio = false; // Default: unlock ratio
if ( !width && !height )
dialog.lockRatio = true; // If someone didn't start typing, lock ratio.
else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) )
{
if ( Math.round( originalRatio ) == Math.round( thisRatio ) )
dialog.lockRatio = true;
}
}
else if ( value != undefined )
dialog.lockRatio = value;
else
dialog.lockRatio = !dialog.lockRatio;
}
else if ( value != 'check' ) // I can't lock ratio if ratio is unknown.
dialog.lockRatio = false;
if ( dialog.lockRatio )
ratioButton.removeClass( 'ckf_btn_unlocked' );
else
ratioButton.addClass( 'ckf_btn_unlocked' );
return dialog.lockRatio;
};
CKFinder.dialog.add( 'resizeDialog', function( api )
{
return {
title : api.lang.Imageresize.dialogTitle.replace( '%s', api.getSelectedFile().name ),
// TODO resizable : CKFINDER.DIALOG_RESIZE_BOTH
minWidth : 390,
minHeight : 230,
onShow : function() {
var dialog = this,
thumbSmall = CKFinder.config.imageresize_thumbSmall,
thumbMedium = CKFinder.config.imageresize_thumbMedium,
thumbLarge = CKFinder.config.imageresize_thumbLarge;
doc = dialog.getElement().getDocument();
file = api.getSelectedFile();
this.setTitle( api.lang.Imageresize.dialogTitle.replace( '%s', file.name ) );
var previewImg = doc.getById('previewImage');
var sizeSpan = doc.getById('imageSize');
previewImg.setAttribute('src', file.getThumbnailUrl( true ));
var updateImgDimension = function( width, height ) {
if ( !width || !height )
{
sizeSpan.setText( '' );
return;
}
imageDimension.width = width;
imageDimension.height = height;
sizeSpan.setText( width + " x " + height + " px" );
CKFinder.tools.setTimeout( function(){ switchLockRatio( dialog, 'check' ); }, 0, dialog );
};
api.connector.sendCommand( "ImageResizeInfo", {
fileName : file.name
},
function( xml ) {
if ( xml.checkError() )
return;
var width = xml.selectSingleNode( 'Connector/ImageInfo/@width' ),
height = xml.selectSingleNode( 'Connector/ImageInfo/@height' );
if ( width && height )
{
width = parseInt( width.value, 10 );
height = parseInt( height.value, 10 );
updateImgDimension( width, height );
var checkThumbs = function( id, size ) {
if ( !size )
return;
var reThumb = /^(\d+)x(\d+)$/;
result = reThumb.exec( size );
var el = dialog.getContentElement( 'tab1', id );
if ( 0 + result[1] > width && 0 + result[2] > height )
{
el.disable();
el.getElement().setAttribute('title', api.lang.Imageresize.imageSmall).addClass('cke_disabled');
}
else
{
el.enable();
el.getElement().setAttribute('title', '').removeClass('cke_disabled');
}
};
checkThumbs('smallThumb', thumbSmall );
checkThumbs('mediumThumb', thumbMedium );
checkThumbs('largeThumb', thumbLarge );
}
},
file.folder.type,
file.folder
);
if ( !thumbSmall )
dialog.getContentElement('tab1', 'smallThumb').getElement().hide();
if ( !thumbMedium )
dialog.getContentElement('tab1', 'mediumThumb').getElement().hide();
if ( !thumbLarge )
dialog.getContentElement('tab1', 'largeThumb').getElement().hide();
if ( !thumbSmall && !thumbMedium && !thumbLarge )
dialog.getContentElement('tab1', 'thumbsLabel').getElement().hide();
dialog.setValueOf( 'tab1', 'fileName', file.name );
dialog.getContentElement('tab1', 'width').focus();
dialog.getContentElement('tab1', 'fileName').setValue('');
dialog.getContentElement('tab1', 'createNewBox').getElement().hide();
updateImgDimension( 0,0 );
},
onOk : function() {
var dialog = this,
width = dialog.getValueOf( 'tab1', 'width' ),
height = dialog.getValueOf( 'tab1', 'height' ),
small = dialog.getValueOf( 'tab1', 'smallThumb' ),
medium = dialog.getValueOf( 'tab1', 'mediumThumb' ),
large = dialog.getValueOf( 'tab1', 'largeThumb' ),
fileName = dialog.getValueOf( 'tab1', 'fileName' ),
createNew = dialog.getValueOf( 'tab1', 'createNew' );
if ( width && !height )
{
api.openMsgDialog( '', api.lang.Imageresize.invalidHeight );
return false;
}
else if ( !width && height )
{
api.openMsgDialog( '', api.lang.Imageresize.invalidWidth );
return false;
}
if ( !api.config.imageresize_allowEnlarging && ( parseInt( width, 10 ) > imageDimension.width || parseInt( height, 10 ) > imageDimension.height ) )
{
var str = api.lang.Imageresize.sizeTooBig;
api.openMsgDialog( '', str.replace( "%size", imageDimension.width + "x" + imageDimension.height ) );
return false;
}
if ( ( width && height ) || small || medium || large )
{
if ( !createNew )
fileName = file.name;
api.connector.sendCommandPost( "ImageResize", null, {
width : width,
height : height,
fileName : file.name,
newFileName : fileName,
overwrite : createNew ? 0 : 1,
small : small ? 1 : 0,
medium : medium ? 1 : 0,
large : large ? 1 : 0
},
function( xml ) {
if ( xml.checkError() )
return;
api.openMsgDialog( '', api.lang.Imageresize.resizeSuccess );
api.refreshOpenedFolder();
},
file.folder.type,
file.folder
);
}
return undefined;
},
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements :
[
{
type : 'hbox',
widths : [ '180px', '280px' ],
children:
[
{
type : 'vbox',
children:
[
{
type : 'html',
html : '' +
'<style type="text/css">' +
'a.ckf_btn_reset' +
'{' +
'float: right;' +
'background-position: 0 -32px;' +
'background-image: url("' + CKFinder.getPluginPath('imageresize') + 'images/mini.gif");' +
'width: 16px;' +
'height: 16px;' +
'background-repeat: no-repeat;' +
'border: 1px none;' +
'font-size: 1px;' +
'}' +
'a.ckf_btn_locked,' +
'a.ckf_btn_unlocked' +
'{' +
'float: left;' +
'background-position: 0 0;' +
'background-image: url("' + CKFinder.getPluginPath('imageresize') + 'images/mini.gif");' +
'width: 16px;' +
'height: 16px;' +
'background-repeat: no-repeat;' +
'border: none 1px;' +
'font-size: 1px;' +
'}' +
'a.ckf_btn_unlocked' +
'{' +
'background-position: 0 -16px;' +
'background-image: url("' + CKFinder.getPluginPath('imageresize') + '/images/mini.gif");' +
'}' +
'.ckf_btn_over' +
'{' +
'border: outset 1px;' +
'cursor: pointer;' +
'cursor: hand;' +
'}' +
'</style>' +
'<div style="height:100px;padding:7px">' +
'<img id="previewImage" src="" style="margin-bottom:4px;" /><br />' +
'<span style="font-size:9px;" id="imageSize"></span>' +
'</div>'
},
{
type : 'html',
id : 'thumbsLabel',
html : '<strong>' + api.lang.Imageresize.thumbnailNew + '</strong>'
},
{
type : 'checkbox',
id : 'smallThumb',
checked : false,
label : api.lang.Imageresize.thumbnailSmall.replace( '%s', CKFinder.config.imageresize_thumbSmall )
},
{
type : 'checkbox',
id : 'mediumThumb',
checked : false,
label : api.lang.Imageresize.thumbnailMedium.replace( '%s', CKFinder.config.imageresize_thumbMedium )
},
{
type : 'checkbox',
id : 'largeThumb',
checked : false,
label : api.lang.Imageresize.thumbnailLarge.replace( '%s', CKFinder.config.imageresize_thumbLarge )
}
]
},
{
type : 'vbox',
children :
[
{
type : 'html',
html : '<strong>' + api.lang.Imageresize.newSize + '</strong>'
},
{
type : 'hbox',
widths : [ '80%', '20%' ],
children:
[
{
type : 'vbox',
children:
[
{
type : 'text',
labelLayout : 'horizontal',
label : api.lang.Imageresize.width,
onKeyUp : onSizeChange,
validate: function()
{
var value = this.getValue();
if ( value )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch || parseInt( aMatch[1], 10 ) < 1 )
{
api.openMsgDialog( '', api.lang.Imageresize.invalidWidth );
return false;
}
}
return true;
},
id : 'width'
},
{
type : 'text',
labelLayout : 'horizontal',
label : api.lang.Imageresize.height,
onKeyUp : onSizeChange,
validate: function()
{
var value = this.getValue();
if ( value )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch || parseInt( aMatch[1], 10 ) < 1 )
{
api.openMsgDialog( '', api.lang.Imageresize.invalidHeight );
return false;
}
}
return true;
},
id : 'height'
}
]
},
{
type : 'html',
onLoad : function()
{
var doc = this.getElement().getDocument(),
dialog = this.getDialog();
// Activate Reset button
var resetButton = doc.getById( 'btnResetSize' ),
ratioButton = doc.getById( 'btnLockSizes' );
if ( resetButton )
{
resetButton.on( 'click', function(evt)
{
resetSize( this );
evt.data.preventDefault();
}, dialog );
resetButton.on( 'mouseover', function()
{
this.addClass( 'ckf_btn_over' );
}, resetButton );
resetButton.on( 'mouseout', function()
{
this.removeClass( 'ckf_btn_over' );
}, resetButton );
}
// Activate (Un)LockRatio button
if ( ratioButton )
{
ratioButton.on( 'click', function(evt)
{
var locked = switchLockRatio( this ),
width = this.getValueOf( 'tab1', 'width' );
if ( imageDimension.width && width )
{
var height = imageDimension.height / imageDimension.width * width;
if ( !isNaN( height ) )
{
this.setValueOf( 'tab1', 'height', Math.round( height ) );
updateFileName( dialog );
}
}
evt.data.preventDefault();
}, dialog );
ratioButton.on( 'mouseover', function()
{
this.addClass( 'ckf_btn_over' );
}, ratioButton );
ratioButton.on( 'mouseout', function()
{
this.removeClass( 'ckf_btn_over' );
}, ratioButton );
}
},
html : '<div style="margin-top:4px">'+
'<a href="javascript:void(0)" tabindex="-1" title="Lock ration" class="ckf_btn_locked ckf_btn_unlocked" id="btnLockSizes"></a>' +
'<a href="javascript:void(0)" tabindex="-1" title="Reset size" class="ckf_btn_reset" id="btnResetSize"></a>'+
'</div>'
}
]
},
{
type : 'vbox',
id : 'createNewBox',
hidden : true,
children:
[
{
type : 'checkbox',
checked : true,
id : 'createNew',
label : api.lang.Imageresize.newImage,
'default' : true,
onChange : function() {
var dialog = this.getDialog();
var filenameInput = dialog.getContentElement('tab1', 'fileName');
if ( filenameInput ) {
if (!this.getValue())
filenameInput.getElement().hide();
else
filenameInput.getElement().show();
}
}
},
{
type : 'text',
label : '',
validate : function() {
var dialog = this.getDialog(),
createNew = dialog.getContentElement('tab1', 'createNew'),
value = this.getValue(),
matches = value.match( regexExt );
if ( createNew && dialog.getValueOf( 'tab1', 'width' ) && dialog.getValueOf( 'tab1', 'height' ) )
{
if ( !value || !matches ) {
api.openMsgDialog( '', api.lang.Imageresize.invalidName );
return false;
}
if ( file.ext != matches[2] ) {
api.openMsgDialog( '', api.lang.Imageresize.noExtensionChange );
return false;
}
}
return true;
},
id : 'fileName'
}
]
}
]
}
]
}
]
}
],
// TODO http://dev.fckeditor.net/ticket/4750
buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ]
};
} );
api.addFileContextMenuOption( { label : api.lang.Imageresize.contextMenuName, command : "resizeImage" } , function( api, file )
{
api.openDialog( 'resizeDialog' );
},
function ( file )
{
// Disable for files other than images.
if ( !file.isImage() || !api.getSelectedFolder().type )
return false;
if ( file.folder.acl.fileDelete && file.folder.acl.fileUpload )
return true;
else
return -1;
});
}
} );
| JavaScript |
/**
* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*
* CKFinder 2.x - sample "dummy" plugin.
*
* To enable it, add the following line to config.js:
* config.extraPlugins = 'dummy';
*/
/**
* See http://docs.cksource.com/ckfinder_2.x_api/symbols/CKFinder.html#.addPlugin
*/
CKFinder.addPlugin( 'dummy', {
lang : [ 'en', 'pl' ],
appReady : function( api ) {
CKFinder.dialog.add( 'dummydialog', function( api )
{
// CKFinder.dialog.definition
var dialogDefinition =
{
title : api.lang.dummy.title,
minWidth : 390,
minHeight : 230,
onOk : function() {
// "this" is now a CKFinder.dialog object.
var value = this.getValueOf( 'tab1', 'textareaId' );
if ( !value ) {
api.openMsgDialog( '', api.lang.dummy.typeText );
return false;
}
else {
alert( "You have entered: " + value );
}
},
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements :
[
{
type : 'html',
html : '<h3>' + api.lang.dummy.typeText + '</h3>'
},
{
type : 'textarea',
id : 'textareaId',
rows : 10,
cols : 40
}
]
}
],
buttons : [ CKFinder.dialog.cancelButton, CKFinder.dialog.okButton ]
};
return dialogDefinition;
} );
api.addFileContextMenuOption( { label : api.lang.dummy.menuItem, command : "dummycommand" } , function( api, file )
{
api.openDialog('dummydialog');
});
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKFinder.setPluginLang( 'dummy', 'pl',
{
dummy :
{
title : 'Testowe okienko',
menuItem : 'Otwórz okienko dummy',
typeText : 'Podaj jakiś tekst.'
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKFinder.setPluginLang( 'dummy', 'en',
{
dummy :
{
title : 'Dummy dialog',
menuItem : 'Open dummy dialog',
typeText : 'Please type some text.'
}
});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckfinder.com/license
*/
CKFinder.customConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.skin = 'v1';
// config.language = 'fr';
};
| JavaScript |
window.onload = function()
{
var copyP = document.createElement( 'p' ) ;
copyP.className = 'copyright' ;
copyP.innerHTML = '© 2007-2010 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . All rights reserved.<br /><br />' ;
document.body.appendChild( document.createElement( 'hr' ) ) ;
document.body.appendChild( copyP ) ;
window.top.SetActiveTopic( window.location.pathname ) ;
}
| JavaScript |
window.onload = function()
{
var copyP = document.createElement( 'p' ) ;
copyP.className = 'copyright' ;
copyP.innerHTML = '© 2007-2010 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . Todos los derechos reservados.<br /><br />' ;
document.body.appendChild( document.createElement( 'hr' ) ) ;
document.body.appendChild( copyP ) ;
window.top.SetActiveTopic( window.location.pathname ) ;
}
| JavaScript |
window.onload = function()
{
var copyP = document.createElement( 'p' ) ;
copyP.className = 'copyright' ;
copyP.innerHTML = '© 2007-2010 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . Todos los derechos reservados.<br /><br />' ;
document.body.appendChild( document.createElement( 'hr' ) ) ;
document.body.appendChild( copyP ) ;
window.top.SetActiveTopic( window.location.pathname ) ;
}
| JavaScript |
window.onload = function()
{
var copyP = document.createElement( 'p' ) ;
copyP.className = 'copyright' ;
copyP.innerHTML = '© 2007-2010 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . Wszystkie prawa zastrzeżone.<br /><br />' ;
document.body.appendChild( document.createElement( 'hr' ) ) ;
document.body.appendChild( copyP ) ;
window.top.SetActiveTopic( window.location.pathname ) ;
}
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nn'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'no',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Laster...',
FolderNew : 'Skriv inn det nye mappenavnet: ',
FolderRename : 'Skriv inn det nye mappenavnet: ',
FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?',
FolderRenaming : ' (Endrer mappenavn...)',
FolderDeleting : ' (Sletter...)',
// Files
FileRename : 'Skriv inn det nye filnavnet: ',
FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig',
FileRenaming : 'Endrer filnavn...',
FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Last opp',
UploadTip : 'Last opp en ny fil',
Refresh : 'Oppdater',
Settings : 'Innstillinger',
Help : 'Hjelp',
HelpTip : 'Hjelp finnes kun på engelsk',
// Context Menus
Select : 'Velg',
SelectThumbnail : 'Velg Miniatyr',
View : 'Vis fullversjon',
Download : 'Last ned',
NewSubFolder : 'Ny Undermappe',
Rename : 'Endre navn',
Delete : 'Slett',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Lukk',
// Upload Panel
UploadTitle : 'Last opp ny fil',
UploadSelectLbl : 'Velg filen du vil laste opp',
UploadProgressLbl : '(Laster opp filen, vennligst vent...)',
UploadBtn : 'Last opp valgt fil',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Du må velge en fil fra din datamaskin',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Innstillinger',
SetView : 'Filvisning:',
SetViewThumb : 'Miniatyrbilder',
SetViewList : 'Liste',
SetDisplay : 'Vis:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Filstørrelse',
SetSort : 'Sorter etter:',
SetSortName : 'Filnavn',
SetSortDate : 'Dato',
SetSortSize : 'Størrelse',
// Status Bar
FilesCountEmpty : '<Tom Mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)',
Errors :
{
10 : 'Ugyldig kommando.',
11 : 'Ressurstypen ble ikke spesifisert i forepørselen.',
12 : 'Ugyldig ressurstype.',
102 : 'Ugyldig fil- eller mappenavn.',
103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.',
104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig forespørsel.',
110 : 'Ukjent feil.',
115 : 'Det finnes allerede en fil eller mappe med dette navnet.',
116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.',
117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1"',
202 : 'Ugyldig fil',
203 : 'Ugyldig fil. Filen er for stor.',
204 : 'Den opplastede filen er korrupt.',
205 : 'Det finnes ingen midlertidig mappe for filopplastinger.',
206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.',
207 : 'Den opplastede filens navn har blitt endret til "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.',
501 : 'Funksjon for minityrbilder er skrudd av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet kan ikke være tomt',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Mappenavnet kan ikke være tomt',
FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nb'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'no',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Laster...',
FolderNew : 'Skriv inn det nye mappenavnet: ',
FolderRename : 'Skriv inn det nye mappenavnet: ',
FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?',
FolderRenaming : ' (Endrer mappenavn...)',
FolderDeleting : ' (Sletter...)',
// Files
FileRename : 'Skriv inn det nye filnavnet: ',
FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig',
FileRenaming : 'Endrer filnavn...',
FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Last opp',
UploadTip : 'Last opp en ny fil',
Refresh : 'Oppdater',
Settings : 'Innstillinger',
Help : 'Hjelp',
HelpTip : 'Hjelp finnes kun på engelsk',
// Context Menus
Select : 'Velg',
SelectThumbnail : 'Velg Miniatyr',
View : 'Vis fullversjon',
Download : 'Last ned',
NewSubFolder : 'Ny Undermappe',
Rename : 'Endre navn',
Delete : 'Slett',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Lukk',
// Upload Panel
UploadTitle : 'Last opp ny fil',
UploadSelectLbl : 'Velg filen du vil laste opp',
UploadProgressLbl : '(Laster opp filen, vennligst vent...)',
UploadBtn : 'Last opp valgt fil',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Du må velge en fil fra din datamaskin',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Innstillinger',
SetView : 'Filvisning:',
SetViewThumb : 'Miniatyrbilder',
SetViewList : 'Liste',
SetDisplay : 'Vis:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Filstørrelse',
SetSort : 'Sorter etter:',
SetSortName : 'Filnavn',
SetSortDate : 'Dato',
SetSortSize : 'Størrelse',
// Status Bar
FilesCountEmpty : '<Tom Mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)',
Errors :
{
10 : 'Ugyldig kommando.',
11 : 'Ressurstypen ble ikke spesifisert i forepørselen.',
12 : 'Ugyldig ressurstype.',
102 : 'Ugyldig fil- eller mappenavn.',
103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.',
104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig forespørsel.',
110 : 'Ukjent feil.',
115 : 'Det finnes allerede en fil eller mappe med dette navnet.',
116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.',
117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1"',
202 : 'Ugyldig fil',
203 : 'Ugyldig fil. Filen er for stor.',
204 : 'Den opplastede filen er korrupt.',
205 : 'Det finnes ingen midlertidig mappe for filopplastinger.',
206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.',
207 : 'Den opplastede filens navn har blitt endret til "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.',
501 : 'Funksjon for minityrbilder er skrudd av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet kan ikke være tomt',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Mappenavnet kan ikke være tomt',
FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Russian
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['ru'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, недоступно</span>',
confirmCancel : 'Внесенные вами изменения будут утеряны. Вы уверены?',
ok : 'OK',
cancel : 'Отмена',
confirmationTitle : 'Подтверждение',
messageTitle : 'Информация',
inputTitle : 'Вопрос',
undo : 'Отменить',
redo : 'Повторить',
skip : 'Пропустить',
skipAll : 'Пропустить все',
makeDecision : 'Что следует сделать?',
rememberDecision: 'Запомнить мой выбор'
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'ru',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd.mm.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Папки',
FolderLoading : 'Загрузка...',
FolderNew : 'Пожалуйста, введите новое имя папки: ',
FolderRename : 'Пожалуйста, введите новое имя папки: ',
FolderDelete : 'Вы уверены, что хотите удалить папку "%1"?',
FolderRenaming : ' (Переименовываю...)',
FolderDeleting : ' (Удаляю...)',
// Files
FileRename : 'Пожалуйста, введите новое имя файла: ',
FileRenameExt : 'Вы уверены, что хотите изменить расширение файла? Файл может стать недоступным',
FileRenaming : 'Переименовываю...',
FileDelete : 'Вы уверены, что хотите удалить файл "%1"?',
FilesLoading : 'Загрузка...',
FilesEmpty : 'Пустая папка',
FilesMoved : 'Файл %1 перемещен в %2:%3',
FilesCopied : 'Файл %1 скопирован в %2:%3',
// Basket
BasketFolder : 'Корзина',
BasketClear : 'Очистить корзину',
BasketRemove : 'Убрать из корзины',
BasketOpenFolder : 'Перейти в папку этого файла',
BasketTruncateConfirm : 'Вы точно хотите очистить корзину?',
BasketRemoveConfirm : 'Вы точно хотите убрать файл "%1" из корзины?',
BasketEmpty : 'В корзине пока нет файлов, добавьте новые с помощью драг-н-дропа (перетащите файл в корзину).',
BasketCopyFilesHere : 'Скопировать файл из корзины',
BasketMoveFilesHere : 'Переместить файл из корзины',
BasketPasteErrorOther : 'Произошла ошибка при обработке файла %s: %e',
BasketPasteMoveSuccess : 'Файлы перемещены: %s',
BasketPasteCopySuccess : 'Файлы скопированы: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Загрузка',
UploadTip : 'Загрузить новый файл',
Refresh : 'Обновить',
Settings : 'Установки',
Help : 'Помощь',
HelpTip : 'Помощь',
// Context Menus
Select : 'Выбрать',
SelectThumbnail : 'Выбрать миниатюру',
View : 'Посмотреть',
Download : 'Сохранить',
NewSubFolder : 'Новая папка',
Rename : 'Переименовать',
Delete : 'Удалить',
CopyDragDrop : 'Копировать',
MoveDragDrop : 'Переместить',
// Dialogs
RenameDlgTitle : 'Переименовать',
NewNameDlgTitle : 'Новое имя',
FileExistsDlgTitle : 'Файл уже существует',
SysErrorDlgTitle : 'Системная ошибка',
FileOverwrite : 'Заменить файл',
FileAutorename : 'Автоматически переименовывать',
// Generic
OkBtn : 'ОК',
CancelBtn : 'Отмена',
CloseBtn : 'Закрыть',
// Upload Panel
UploadTitle : 'Загрузить новый файл',
UploadSelectLbl : 'Выбрать файл для загрузки',
UploadProgressLbl : '(Загрузка в процессе, пожалуйста подождите...)',
UploadBtn : 'Загрузить выбранный файл',
UploadBtnCancel : 'Отмена',
UploadNoFileMsg : 'Пожалуйста, выберите файл на вашем компьютере',
UploadNoFolder : 'Пожалуйста, выберите папку, в которую вы хотите закачать файл.',
UploadNoPerms : 'Загрузка файлов запрещена.',
UploadUnknError : 'Ошибка при передаче файла.',
UploadExtIncorrect : 'В эту папку нельзя закачивать файлы с таким расширением.',
// Settings Panel
SetTitle : 'Установки',
SetView : 'Просмотр:',
SetViewThumb : 'Миниатюры',
SetViewList : 'Список',
SetDisplay : 'Отобразить:',
SetDisplayName : 'Имя файла',
SetDisplayDate : 'Дата',
SetDisplaySize : 'Размер файла',
SetSort : 'Сортировка:',
SetSortName : 'по имени файла',
SetSortDate : 'по дате',
SetSortSize : 'по размеру',
// Status Bar
FilesCountEmpty : '<Пустая папка>',
FilesCountOne : '1 файл',
FilesCountMany : '%1 файлов',
// Size and Speed
Kb : '%1 кБ',
KbPerSecond : '%1 кБ/с',
// Connector Error Messages.
ErrorUnknown : 'Невозможно завершить запрос. (Ошибка %1)',
Errors :
{
10 : 'Неверная команда.',
11 : 'Тип ресурса не указан в запросе.',
12 : 'Неверный запрошенный тип ресурса.',
102 : 'Неверное имя файла или папки.',
103 : 'Невозможно завершить запрос из-за ограничений авторизации.',
104 : 'Невозможно завершить запрос из-за ограничения разрешений файловой системы.',
105 : 'Неверное расширение файла.',
109 : 'Неверный запрос.',
110 : 'Неизвестная ошибка.',
115 : 'Файл или папка с таким именем уже существует.',
116 : 'Папка не найдена. Пожалуйста, обновите вид папок и попробуйте еще раз.',
117 : 'Файл не найден. Пожалуйста, обновите список файлов и попробуйте еще раз.',
118 : 'Исходное расположение файла совпадает с указанным.',
201 : 'Файл с таким именем уже существует. Загруженный файл был переименован в "%1"',
202 : 'Неверный файл',
203 : 'Неверный файл. Размер файла слишком большой.',
204 : 'Загруженный файл поврежден.',
205 : 'Недоступна временная папка для загрузки файлов на сервер.',
206 : 'Загрузка отменена из-за соображений безопасности. Файл содержит похожие на HTML данные.',
207 : 'Загруженный файл был переименован в "%1"',
300 : 'Произошла ошибка при перемещении файла(ов).',
301 : 'Произошла ошибка при копировании файла(ов).',
500 : 'Браузер файлов отключен из-за соображений безопасности. Пожалуйста, сообщите вашему системному администратру и проверьте конфигурационный файл CKFinder.',
501 : 'Поддержка миниатюр отключена.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Имя файла не может быть пустым',
FileExists : 'Файл %s уже существует',
FolderEmpty : 'Имя папки не может быть пустым',
FileInvChar : 'Имя файла не может содержать любой из перечисленных символов: \n\\ / : * ? " < > |',
FolderInvChar : 'Имя папки не может содержать любой из перечисленных символов: \n\\ / : * ? " < > |',
PopupBlockView : 'Невозможно открыть файл в новом окне. Пожалуйста, проверьте настройки браузера и отключите все блокировки всплывающих окон для этого сайта.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Изменить размеры %s',
sizeTooBig : 'Нельзя указывать размеры больше, чем у оригинального файла (%size).',
resizeSuccess : 'Размеры успешно изменены.',
thumbnailNew : 'Создать миниатюру(ы)',
thumbnailSmall : 'Маленькая (%s)',
thumbnailMedium : 'Средняя (%s)',
thumbnailLarge : 'Большая (%s)',
newSize : 'Установить новые размеры',
width : 'Ширина',
height : 'Высота',
invalidHeight : 'Высота должна быть числом больше нуля.',
invalidWidth : 'Ширина должна быть числом больше нуля.',
invalidName : 'Неверное имя файла.',
newImage : 'Сохранить как новый файл',
noExtensionChange : 'Не удалось поменять расширение файла.',
imageSmall : 'Исходная картинка слишком маленькая',
contextMenuName : 'Изменить размер'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Сохранить',
fileOpenError : 'Не удалось открыть файл.',
fileSaveSuccess : 'Файл успешно сохранен.',
contextMenuName : 'Редактировать',
loadingFile : 'Файл загружается, пожалуйста подождите...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Slovenian
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['sl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nedostopen</span>',
confirmCancel : 'Nekatere opcije so bile spremenjene. Ali res želite zapreti pogovorno okno?',
ok : 'Potrdi',
cancel : 'Prekliči',
confirmationTitle : 'Potrditev',
messageTitle : 'Informacija',
inputTitle : 'Vprašanje',
undo : 'Razveljavi',
redo : 'Obnovi',
skip : 'Preskoči',
skipAll : 'Preskoči vse',
makeDecision : 'Katera aktivnost naj se izvede?',
rememberDecision: 'Zapomni si mojo izbiro'
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'sl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd.m.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mape',
FolderLoading : 'Nalagam...',
FolderNew : 'Vnesite ime za novo mapo: ',
FolderRename : 'Vnesite ime nove mape: ',
FolderDelete : 'Ali ste prepričani, da želite zbrisati mapo "%1"?',
FolderRenaming : ' (Preimenujem...)',
FolderDeleting : ' (Brišem...)',
// Files
FileRename : 'Vnesite novo ime datoteke: ',
FileRenameExt : 'Ali ste prepričani, da želite spremeniti končnico datoteke? Možno je, da potem datoteka ne bo uporabna.',
FileRenaming : 'Preimenujem...',
FileDelete : 'Ali ste prepričani, da želite izbrisati datoteko "%1"?',
FilesLoading : 'Nalagam...',
FilesEmpty : 'Prazna mapa',
FilesMoved : 'Datoteka %1 je bila premaknjena v %2:%3',
FilesCopied : 'Datoteka %1 je bila kopirana v %2:%3',
// Basket
BasketFolder : 'Koš',
BasketClear : 'Izprazni koš',
BasketRemove : 'Odstrani iz koša',
BasketOpenFolder : 'Odpri izvorno mapo',
BasketTruncateConfirm : 'Ali res želite odstraniti vse datoteke iz koša?',
BasketRemoveConfirm : 'Ali res želite odstraniti datoteko "%1" iz koša?',
BasketEmpty : 'V košu ni datotek. Lahko jih povlečete in spustite.',
BasketCopyFilesHere : 'Kopiraj datoteke iz koša',
BasketMoveFilesHere : 'Premakni datoteke iz koša',
BasketPasteErrorOther : 'Napaka z datoteko %s: %e',
BasketPasteMoveSuccess : 'Seznam premaknjenih datotek: %s',
BasketPasteCopySuccess : 'Seznam kopiranih datotek: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Naloži na strežnik',
UploadTip : 'Naloži novo datoteko na strežnik',
Refresh : 'Osveži',
Settings : 'Nastavitve',
Help : 'Pomoč',
HelpTip : 'Pomoč',
// Context Menus
Select : 'Izberi',
SelectThumbnail : 'Izberi malo sličico (predogled)',
View : 'Predogled',
Download : 'Prenesi na svoj računalnik',
NewSubFolder : 'Nova podmapa',
Rename : 'Preimenuj',
Delete : 'Zbriši',
CopyDragDrop : 'Kopiraj datoteko',
MoveDragDrop : 'Premakni datoteko',
// Dialogs
RenameDlgTitle : 'Preimenuj',
NewNameDlgTitle : 'Novo ime',
FileExistsDlgTitle : 'Datoteka že obstaja',
SysErrorDlgTitle : 'Sistemska napaka',
FileOverwrite : 'Prepiši',
FileAutorename : 'Avtomatsko preimenuj',
// Generic
OkBtn : 'Potrdi',
CancelBtn : 'Prekliči',
CloseBtn : 'Zapri',
// Upload Panel
UploadTitle : 'Naloži novo datoteko na strežnik',
UploadSelectLbl : 'Izberi datoteko za prenos na strežnik',
UploadProgressLbl : '(Prenos na strežnik poteka, prosimo počakajte...)',
UploadBtn : 'Prenesi izbrano datoteko na strežnik',
UploadBtnCancel : 'Prekliči',
UploadNoFileMsg : 'Prosimo izberite datoteko iz svojega računalnika za prenos na strežnik',
UploadNoFolder : 'Izberite mapo v katero se bo naložilo datoteko!',
UploadNoPerms : 'Nalaganje datotek ni dovoljeno.',
UploadUnknError : 'Napaka pri pošiljanju datoteke.',
UploadExtIncorrect : 'V tej mapi ta vrsta datoteke ni dovoljena.',
// Settings Panel
SetTitle : 'Nastavitve',
SetView : 'Pogled:',
SetViewThumb : 'majhne sličice',
SetViewList : 'seznam',
SetDisplay : 'Prikaz:',
SetDisplayName : 'ime datoteke',
SetDisplayDate : 'datum',
SetDisplaySize : 'velikost datoteke',
SetSort : 'Razvrščanje:',
SetSortName : 'po imenu datoteke',
SetSortDate : 'po datumu',
SetSortSize : 'po velikosti',
// Status Bar
FilesCountEmpty : '<Prazna mapa>',
FilesCountOne : '1 datoteka',
FilesCountMany : '%1 datotek(e)',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/sek',
// Connector Error Messages.
ErrorUnknown : 'Prišlo je do napake. (Napaka %1)',
Errors :
{
10 : 'Napačen ukaz.',
11 : 'V poizvedbi ni bil jasen tip (resource type).',
12 : 'Tip datoteke ni primeren.',
102 : 'Napačno ime mape ali datoteke.',
103 : 'Vašega ukaza se ne da izvesti zaradi težav z avtorizacijo.',
104 : 'Vašega ukaza se ne da izvesti zaradi težav z nastavitvami pravic v datotečnem sistemu.',
105 : 'Napačna končnica datoteke.',
109 : 'Napačna zahteva.',
110 : 'Neznana napaka.',
115 : 'Datoteka ali mapa s tem imenom že obstaja.',
116 : 'Mapa ni najdena. Prosimo osvežite okno in poskusite znova.',
117 : 'Datoteka ni najdena. Prosimo osvežite seznam datotek in poskusite znova.',
118 : 'Začetna in končna pot je ista.',
201 : 'Datoteka z istim imenom že obstaja. Naložena datoteka je bila preimenovana v "%1"',
202 : 'Neprimerna datoteka.',
203 : 'Datoteka je prevelika in zasede preveč prostora.',
204 : 'Naložena datoteka je okvarjena.',
205 : 'Na strežniku ni na voljo začasna mapa za prenos datotek.',
206 : 'Nalaganje je bilo prekinjeno zaradi varnostnih razlogov. Datoteka vsebuje podatke, ki spominjajo na HTML kodo.',
207 : 'Naložena datoteka je bila preimenovana v "%1"',
300 : 'Premikanje datotek(e) ni uspelo.',
301 : 'Kopiranje datotek(e) ni uspelo.',
500 : 'Brskalnik je onemogočen zaradi varnostnih razlogov. Prosimo kontaktirajte upravljalca spletnih strani.',
501 : 'Ni podpore za majhne sličice (predogled).'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Ime datoteke ne more biti prazno',
FileExists : 'Datoteka %s že obstaja',
FolderEmpty : 'Mapa ne more biti prazna',
FileInvChar : 'Ime datoteke ne sme vsebovati naslednjih znakov: \n\\ / : * ? " < > |',
FolderInvChar : 'Ime mape ne sme vsebovati naslednjih znakov: \n\\ / : * ? " < > |',
PopupBlockView : 'Datoteke ni možno odpreti v novem oknu. Prosimo nastavite svoj brskalnik tako, da bo dopuščal odpiranje oken (popups) oz. izklopite filtre za blokado odpiranja oken.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Spremeni velikost slike %s',
sizeTooBig : 'Širina ali višina slike ne moreta biti večji kot je originalna velikost (%size).',
resizeSuccess : 'Velikost slike je bila uspešno spremenjena.',
thumbnailNew : 'Kreiraj novo majhno sličico',
thumbnailSmall : 'majhna (%s)',
thumbnailMedium : 'srednja (%s)',
thumbnailLarge : 'velika (%s)',
newSize : 'Določite novo velikost',
width : 'Širina',
height : 'Višina',
invalidHeight : 'Nepravilna višina.',
invalidWidth : 'Nepravilna širina.',
invalidName : 'Nepravilno ime datoteke.',
newImage : 'Kreiraj novo sliko',
noExtensionChange : 'Končnica datoteke se ne more spremeniti.',
imageSmall : 'Izvorna slika je premajhna',
contextMenuName : 'Spremeni velikost'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Shrani',
fileOpenError : 'Datoteke ni mogoče odpreti.',
fileSaveSuccess : 'Datoteka je bila shranjena.',
contextMenuName : 'Uredi',
loadingFile : 'Nalaganje datoteke, prosimo počakajte ...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the French
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['fr'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, Inaccessible</span>',
confirmCancel : 'Certaines options ont été modifiées. Êtes vous sûr de vouloir fermer cette fenêtre ?',
ok : 'OK',
cancel : 'Annuler',
confirmationTitle : 'Confirmation',
messageTitle : 'Information',
inputTitle : 'Question',
undo : 'Annuler',
redo : 'Rétablir',
skip : 'Passer',
skipAll : 'passer tout',
makeDecision : 'Quelle action choisir ?',
rememberDecision: 'Se rappeller de la décision'
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'fr',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Dossiers',
FolderLoading : 'Chargement...',
FolderNew : 'Entrez le nouveau nom du dossier: ',
FolderRename : 'Entrez le nouveau nom du dossier: ',
FolderDelete : 'Êtes-vous sûr de vouloir effacer le dossier "%1" ?',
FolderRenaming : ' (Renommage en cours...)',
FolderDeleting : ' (Suppression en cours...)',
// Files
FileRename : 'Entrez le nouveau nom du fichier: ',
FileRenameExt : 'Êtes-vous sûr de vouloir ¨changer l\'extension de ce fichier? Le fichier pourrait devenir inutilisable',
FileRenaming : 'Renommage en cours...',
FileDelete : 'Êtes-vous sûr de vouloir effacer le fichier "%1" ?',
FilesLoading : 'Chargement...',
FilesEmpty : 'Répertoire vide',
FilesMoved : 'Fichier %1 déplacé vers %2:%3',
FilesCopied : 'Fichier %1 copié vers %2:%3',
// Basket
BasketFolder : 'Corbeille',
BasketClear : 'Vider la corbeille',
BasketRemove : 'Retirer de la corbeille',
BasketOpenFolder : 'Ouvrir le répertiore parent',
BasketTruncateConfirm : 'Êtes vous sûr de vouloir supprimer tous les fichiers de la corbeille ?',
BasketRemoveConfirm : 'Êtes vous sûr de vouloir supprimer le fichier "%1" de la corbeille ?',
BasketEmpty : 'Aucun fichier dans la corbeille, déposez en queques uns.',
BasketCopyFilesHere : 'Copier des fichiers depuis la corbeille',
BasketMoveFilesHere : 'Déplacer des fichiers depuis la corbeille',
BasketPasteErrorOther : 'Fichier %s erreur: %e',
BasketPasteMoveSuccess : 'Les fichiers suivant ont été déplacés: %s',
BasketPasteCopySuccess : 'Les fichiers suivant ont été copiés: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Envoyer',
UploadTip : 'Envoyer un nouveau fichier',
Refresh : 'Rafraîchir',
Settings : 'Configuration',
Help : 'Aide',
HelpTip : 'Aide',
// Context Menus
Select : 'Choisir',
SelectThumbnail : 'Choisir une miniature',
View : 'Voir',
Download : 'Télécharger',
NewSubFolder : 'Nouveau sous-dossier',
Rename : 'Renommer',
Delete : 'Effacer',
CopyDragDrop : 'Copier les fichiers ici',
MoveDragDrop : 'Déplacer les fichiers ici',
// Dialogs
RenameDlgTitle : 'Renommer',
NewNameDlgTitle : 'Nouveau fichier',
FileExistsDlgTitle : 'Fichier déjà existant',
SysErrorDlgTitle : 'Erreur système',
FileOverwrite : 'Ré-écrire',
FileAutorename : 'Re-nommage automatique',
// Generic
OkBtn : 'OK',
CancelBtn : 'Annuler',
CloseBtn : 'Fermer',
// Upload Panel
UploadTitle : 'Envoyer un nouveau fichier',
UploadSelectLbl : 'Sélectionner le fichier à télécharger',
UploadProgressLbl : '(Envoi en cours, veuillez patienter...)',
UploadBtn : 'Envoyer le fichier sélectionné',
UploadBtnCancel : 'Annuler',
UploadNoFileMsg : 'Sélectionner un fichier sur votre ordinateur',
UploadNoFolder : 'Merci de sélectionner un répertoire avant l\'envoi.',
UploadNoPerms : 'L\'envoi de fichier n\'est pas autorisé',
UploadUnknError : 'Erreur pendant l\'envoi du fichier.',
UploadExtIncorrect : 'L\'extension du fichier n\'est pas autorisée dans ce dossier.',
// Settings Panel
SetTitle : 'Configuration',
SetView : 'Voir:',
SetViewThumb : 'Miniatures',
SetViewList : 'Liste',
SetDisplay : 'Affichage:',
SetDisplayName : 'Nom du fichier',
SetDisplayDate : 'Date',
SetDisplaySize : 'Taille du fichier',
SetSort : 'Classement:',
SetSortName : 'par Nom de Fichier',
SetSortDate : 'par Date',
SetSortSize : 'par Taille',
// Status Bar
FilesCountEmpty : '<Dossier Vide>',
FilesCountOne : '1 fichier',
FilesCountMany : '%1 fichiers',
// Size and Speed
Kb : '%1 ko',
KbPerSecond : '%1 ko/s',
// Connector Error Messages.
ErrorUnknown : 'La demande n\'a pas abouti. (Erreur %1)',
Errors :
{
10 : 'Commande invalide.',
11 : 'Le type de ressource n\'a pas été spécifié dans la commande.',
12 : 'Le type de ressource n\'est pas valide.',
102 : 'Nom de fichier ou de dossier invalide.',
103 : 'La demande n\'a pas abouti : problème d\'autorisations.',
104 : 'La demande n\'a pas abouti : problème de restrictions de permissions.',
105 : 'Extension de fichier invalide.',
109 : 'Demande invalide.',
110 : 'Erreur inconnue.',
115 : 'Un fichier ou un dossier avec ce nom existe déjà.',
116 : 'Ce dossier n\'existe pas. Veuillez rafraîchir la page et réessayer.',
117 : 'Ce fichier n\'existe pas. Veuillez rafraîchir la page et réessayer.',
118 : 'Les chemins vers la source et la cible sont les mêmes.',
201 : 'Un fichier avec ce nom existe déjà. Le fichier téléversé a été renommé en "%1"',
202 : 'Fichier invalide',
203 : 'Fichier invalide. La taille est trop grande.',
204 : 'Le fichier téléversé est corrompu.',
205 : 'Aucun dossier temporaire n\'est disponible sur le serveur.',
206 : 'Envoi interrompu pour raisons de sécurité. Le fichier contient des données de type HTML.',
207 : 'El fichero subido ha sido renombrado como "%1"',
300 : 'Le déplacement des fichiers a échoué.',
301 : 'La copie des fichiers a échoué.',
500 : 'L\'interface de gestion des fichiers est désactivé. Contactez votre administrateur et vérifier le fichier de configuration de CKFinder.',
501 : 'La fonction "miniatures" est désactivée.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Le nom du fichier ne peut être vide',
FileExists : 'Le fichier %s existes déjà',
FolderEmpty : 'Le nom du dossier ne peut être vide',
FileInvChar : 'Le nom du fichier ne peut pas contenir les charactères suivants : \n\\ / : * ? " < > |',
FolderInvChar : 'Le nom du dossier ne peut pas contenir les charactères suivants : \n\\ / : * ? " < > |',
PopupBlockView : 'Il n\'a pas été possible d\'ouvrir la nouvelle fenêtre. Désactiver votre bloqueur de fenêtres pour ce site.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionner %s',
sizeTooBig : 'Impossible de modifier la hauteur ou la largeur de cette image pour une valeur plus grande que l\'original (%size).',
resizeSuccess : 'L\'image a été redimensionné avec succès.',
thumbnailNew : 'Créer une nouvelle vignette',
thumbnailSmall : 'Petit (%s)',
thumbnailMedium : 'Moyen (%s)',
thumbnailLarge : 'Gros (%s)',
newSize : 'Déterminer les nouvelles dimensions',
width : 'Largeur',
height : 'Hauteur',
invalidHeight : 'Hauteur invalide.',
invalidWidth : 'Largeur invalide.',
invalidName : 'Nom de fichier incorrect.',
newImage : 'Créer une nouvelle image',
noExtensionChange : 'L\'extension du fichier ne peut pas être changé.',
imageSmall : 'L\'image est trop petit',
contextMenuName : 'Redimensionner'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Sauvegarder',
fileOpenError : 'Impossible d\'ouvrir le fichier',
fileSaveSuccess : 'Fichier sauvegardé avec succès.',
contextMenuName : 'Edition',
loadingFile : 'Chargement du fichier, veuillez patientez...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the English
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['he'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, לא נגיש</span>',
confirmCancel : 'חקל ממאפיינים שונו. ברצונך לסגור חלון?',
ok : 'אישור',
cancel : 'ביטול',
confirmationTitle : 'אישור',
messageTitle : 'מידע',
inputTitle : 'שאלה',
undo : 'לבטל',
redo : 'לעשות שוב',
skip : 'דלג',
skipAll : 'דלג הכל',
makeDecision : 'איזו פעולה לבצע?',
rememberDecision: 'זכור החלטתי'
},
dir : 'rtl',
HelpLang : 'en',
LangCode : 'he',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'תיקיות',
FolderLoading : 'טוען...',
FolderNew : 'הקלד שם חדש לתיקיה: ',
FolderRename : 'הקלד שם חדש לתיקיה: ',
FolderDelete : 'האם ברצונך למחוק תיקיה "%1" ?',
FolderRenaming : ' (משנה שם...)',
FolderDeleting : ' (מוחק...)',
// Files
FileRename : 'הקלש שם חדש לקובץ: ',
FileRenameExt : 'האם ברוצונך לשנות טיפוס של הקובץ',
FileRenaming : 'משנה שם...',
FileDelete : 'האם ברצונך למחוק קובץ "%1"?',
FilesLoading : 'טוען...',
FilesEmpty : 'תיקיה ריקה',
FilesMoved : 'קובץ %1 הוזז ל- %2:%3',
FilesCopied : 'קובץ %1 הועתק ל- %2:%3',
// Basket
BasketFolder : 'סל',
BasketClear : 'נקה סל',
BasketRemove : 'הורד מסל',
BasketOpenFolder : 'פתח תיקיית אב',
BasketTruncateConfirm : 'האם ברוצונך למחוק את כל הקבצים מסל?',
BasketRemoveConfirm : 'האם ברוצונך למחוק את קובץ "%1" מסל?',
BasketEmpty : 'אין קבצים בסל, גרור ושחרר משהוא.',
BasketCopyFilesHere : 'העתק קבצים מסל',
BasketMoveFilesHere : 'הזז קבצים מסל',
BasketPasteErrorOther : 'קובץ %s שגיאה: %e',
BasketPasteMoveSuccess : 'קבצים הבאים הוזזו: %s',
BasketPasteCopySuccess : 'קבצים הבאים הועתקו: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'העלאה',
UploadTip : 'לעלות קובץ חדש',
Refresh : 'רענון',
Settings : 'הגדרות',
Help : 'עזרה',
HelpTip : 'עזרה',
// Context Menus
Select : 'בחר',
SelectThumbnail : 'בחר תמונה קטנה',
View : 'צפה',
Download : 'הורד',
NewSubFolder : 'תת-תיקיה חדשה',
Rename : 'שנה שם',
Delete : 'מחק',
CopyDragDrop : 'העתק קבצים לכאן',
MoveDragDrop : 'הזז קבצים לכאן',
// Dialogs
RenameDlgTitle : 'שנה שם',
NewNameDlgTitle : 'שם חדש',
FileExistsDlgTitle : 'קובץ כבר קיים',
SysErrorDlgTitle : 'שגיעת מערכת',
FileOverwrite : 'החלף',
FileAutorename : 'אוטומטית לשנות שם',
// Generic
OkBtn : 'אישור',
CancelBtn : 'ביטול',
CloseBtn : 'סגור',
// Upload Panel
UploadTitle : 'העלאת קובץ חדש',
UploadSelectLbl : 'בחר קובץ להעלאה',
UploadProgressLbl : '(העלאה בתהליך, אנא המתן...)',
UploadBtn : 'לעלות קובץ',
UploadBtnCancel : 'ביטול',
UploadNoFileMsg : 'נא לבחור קובץ מהמחשב שלך',
UploadNoFolder : 'נא לבחור תיקיה לפני העלאה.',
UploadNoPerms : 'העלאת קובץ אסורה.',
UploadUnknError : 'שגיעה בשליחת קובץ.',
UploadExtIncorrect : 'סוג קובץ זה לא מאושר בתיקיה זאת.',
// Settings Panel
SetTitle : 'הגדרות',
SetView : 'צפה:',
SetViewThumb : 'תמונות קטנות',
SetViewList : 'רשימה',
SetDisplay : 'תצוגה:',
SetDisplayName : 'שם קובץ',
SetDisplayDate : 'תאריך',
SetDisplaySize : 'גודל קובץ',
SetSort : 'מיון:',
SetSortName : 'לפי שם',
SetSortDate : 'לפי תאריך',
SetSortSize : 'לפי גודל',
// Status Bar
FilesCountEmpty : '<תיקיה ריקה>',
FilesCountOne : 'קובץ 1',
FilesCountMany : '%1 קבצים',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'בקשה נכשלה. שגיאה. (Error %1)',
Errors :
{
10 : 'Invalid command.',
11 : 'The resource type was not specified in the request.',
12 : 'The requested resource type is not valid.',
102 : 'Invalid file or folder name.',
103 : 'It was not possible to complete the request due to authorization restrictions.',
104 : 'It was not possible to complete the request due to file system permission restrictions.',
105 : 'Invalid file extension.',
109 : 'Invalid request.',
110 : 'Unknown error.',
115 : 'A file or folder with the same name already exists.',
116 : 'Folder not found. Please refresh and try again.',
117 : 'File not found. Please refresh the files list and try again.',
118 : 'Source and target paths are equal.',
201 : 'A file with the same name is already available. The uploaded file has been renamed to "%1"',
202 : 'Invalid file',
203 : 'Invalid file. The file size is too big.',
204 : 'The uploaded file is corrupt.',
205 : 'No temporary folder is available for upload in the server.',
206 : 'Upload cancelled for security reasons. The file contains HTML like data.',
207 : 'The uploaded file has been renamed to "%1"',
300 : 'Moving file(s) failed.',
301 : 'Copying file(s) failed.',
500 : 'The file browser is disabled for security reasons. Please contact your system administrator and check the CKFinder configuration file.',
501 : 'The thumbnails support is disabled.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'שם קובץ לא יכול להיות ריק',
FileExists : 'קובץ %s already exists',
FolderEmpty : 'שם תיקיה לא יכול להיות ריק',
FileInvChar : 'שם הקובץ לא יכול לכלול תווים הבאים: \n\\ / : * ? " < > |',
FolderInvChar : 'שם התיקיה לא יכול לכלול תווים הבאים: \n\\ / : * ? " < > |',
PopupBlockView : 'בלתי אפשרי לפתוח קובץ בחלון חדש. נא לבדוק הגדרות דפדפן ולבטל כל החוסמים חלונות קופצות.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'שנה גודל %s',
sizeTooBig : 'לא יכול לקבוע גובה ורוחב של תמונה יותר גדול מדודל מקורי (%size).',
resizeSuccess : 'גודל שונה שהצלחה.',
thumbnailNew : 'ליצור תמונה קטנה)טומבנייל(',
thumbnailSmall : 'קטן (%s)',
thumbnailMedium : 'בינוני (%s)',
thumbnailLarge : 'גדול (%s)',
newSize : 'קבע גודל חדש',
width : 'רוחב',
height : 'גובה',
invalidHeight : 'גובה לא חוקי.',
invalidWidth : 'רוחב לא חוקי.',
invalidName : 'שם קובץ לא חוקי.',
newImage : 'ליצור תמונה חדשה',
noExtensionChange : 'לא ניתן לשנות סוג קובץ.',
imageSmall : 'מקור תמונה קטן מדי',
contextMenuName : 'שנה גודל'
},
// Fileeditor plugin
Fileeditor :
{
save : 'שמור',
fileOpenError : 'לא מצליח לפתוח קובץ.',
fileSaveSuccess : 'קובץ משמר בהצלחה.',
contextMenuName : 'עריכה',
loadingFile : 'טוען קובץ, אנא המתן...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Swedish
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['sv'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'en', // MISSING
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mappar',
FolderLoading : 'Laddar...',
FolderNew : 'Skriv namnet på den nya mappen: ',
FolderRename : 'Skriv det nya namnet på mappen: ',
FolderDelete : 'Är du säker på att du vill radera mappen "%1"?',
FolderRenaming : ' (Byter mappens namn...)',
FolderDeleting : ' (Raderar...)',
// Files
FileRename : 'Skriv det nya filnamnet: ',
FileRenameExt : 'Är du säker på att du fill ändra på filändelsen? Filen kan bli oanvändbar',
FileRenaming : 'Byter filnamn...',
FileDelete : 'Är du säker på att du vill radera filen "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Ladda upp',
UploadTip : 'Ladda upp en ny fil',
Refresh : 'Uppdatera',
Settings : 'Inställningar',
Help : 'Hjälp',
HelpTip : 'Hjälp',
// Context Menus
Select : 'Infoga bild',
SelectThumbnail : 'Infoga som tumnagel',
View : 'Visa',
Download : 'Ladda ner',
NewSubFolder : 'Ny Undermapp',
Rename : 'Byt namn',
Delete : 'Radera',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Stäng',
// Upload Panel
UploadTitle : 'Ladda upp en ny fil',
UploadSelectLbl : 'Välj fil att ladda upp',
UploadProgressLbl : '(Laddar upp filen, var god vänta...)',
UploadBtn : 'Ladda upp den valda filen',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Välj en fil från din dator',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Inställningar',
SetView : 'Visa:',
SetViewThumb : 'Tumnaglar',
SetViewList : 'Lista',
SetDisplay : 'Visa:',
SetDisplayName : 'Filnamn',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Filstorlek',
SetSort : 'Sortering:',
SetSortName : 'Filnamn',
SetSortDate : 'Datum',
SetSortSize : 'Storlek',
// Status Bar
FilesCountEmpty : '<Tom Mapp>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB', // MISSING
KbPerSecond : '%1 kB/s', // MISSING
// Connector Error Messages.
ErrorUnknown : 'Begäran kunde inte utföras eftersom ett fel uppstod. (Error %1)',
Errors :
{
10 : 'Ogiltig begäran.',
11 : 'Resursens typ var inte specificerad i förfrågan.',
12 : 'Den efterfrågade resurstypen är inte giltig.',
102 : 'Ogiltigt fil- eller mappnamn.',
103 : 'Begäran kunde inte utföras p.g.a. restriktioner av rättigheterna.',
104 : 'Begäran kunde inte utföras p.g.a. restriktioner av rättigheter i filsystemet.',
105 : 'Ogiltig filändelse.',
109 : 'Ogiltig begäran.',
110 : 'Okänt fel.',
115 : 'En fil eller mapp med aktuellt namn finns redan.',
116 : 'Mappen kunde inte hittas. Var god uppdatera sidan och försök igen.',
117 : 'Filen kunde inte hittas. Var god uppdatera sidan och försök igen.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'En fil med aktuellt namn fanns redan. Den uppladdade filen har döpts om till "%1"',
202 : 'Ogiltig fil',
203 : 'Ogiltig fil. Filen var för stor.',
204 : 'Den uppladdade filen var korrupt.',
205 : 'En tillfällig mapp för uppladdning är inte tillgänglig på servern.',
206 : 'Uppladdningen stoppades av säkerhetsskäl. Filen innehåller HTML-liknande data.',
207 : 'Den uppladdade filen har döpts om till "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Filhanteraren har stoppats av säkerhetsskäl. Var god kontakta administratören för att kontrollera konfigurationsfilen för CKFinder.',
501 : 'Stöd för tumnaglar har stängts av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnamnet får inte vara tomt',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Mappens namn får inte vara tomt',
FileInvChar : 'Filnamnet får inte innehålla något av följande tecken: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappens namn får inte innehålla något av följande tecken: \n\\ / : * ? " < > |',
PopupBlockView : 'Det gick inte att öppna filen i ett nytt fönster. Ändra inställningarna i din webbläsare och tillåt popupfönster för den här hemsidan.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the German
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['de'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'de',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd.m.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Verzeichnisse',
FolderLoading : 'Laden...',
FolderNew : 'Bitte geben Sie den neuen Verzeichnisnamen an: ',
FolderRename : 'Bitte geben Sie den neuen Verzeichnisnamen an: ',
FolderDelete : 'Wollen Sie wirklich den Ordner "%1" löschen?',
FolderRenaming : ' (Umbenennen...)',
FolderDeleting : ' (Löschen...)',
// Files
FileRename : 'Bitte geben Sie den neuen Dateinamen an: ',
FileRenameExt : 'Wollen Sie wirklich die Dateierweiterung ändern? Die Datei könnte unbrauchbar werden!',
FileRenaming : 'Umbennenen...',
FileDelete : 'Wollen Sie wirklich die Datei "%1" löschen?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Hochladen',
UploadTip : 'Neue Datei hochladen',
Refresh : 'Aktualisieren',
Settings : 'Einstellungen',
Help : 'Hilfe',
HelpTip : 'Hilfe',
// Context Menus
Select : 'Auswählen',
SelectThumbnail : 'Miniatur auswählen',
View : 'Ansehen',
Download : 'Herunterladen',
NewSubFolder : 'Neues Unterverzeichnis',
Rename : 'Umbenennen',
Delete : 'Löschen',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Abbrechen',
CloseBtn : 'Schließen',
// Upload Panel
UploadTitle : 'Neue Datei hochladen',
UploadSelectLbl : 'Bitte wählen Sie die Datei aus',
UploadProgressLbl : '(Die Daten werden übertragen, bitte warten...)',
UploadBtn : 'Ausgewählte Datei hochladen',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Bitte wählen Sie eine Datei auf Ihrem Computer aus',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Einstellungen',
SetView : 'Ansicht:',
SetViewThumb : 'Miniaturansicht',
SetViewList : 'Liste',
SetDisplay : 'Anzeige:',
SetDisplayName : 'Dateiname',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Dateigröße',
SetSort : 'Sortierung:',
SetSortName : 'nach Dateinamen',
SetSortDate : 'nach Datum',
SetSortSize : 'nach Größe',
// Status Bar
FilesCountEmpty : '<Leeres Verzeichnis>',
FilesCountOne : '1 Datei',
FilesCountMany : '%1 Datei',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Ihre Anfrage konnte nicht bearbeitet werden. (Fehler %1)',
Errors :
{
10 : 'Unbekannter Befehl.',
11 : 'Der Ressourcentyp wurde nicht spezifiziert.',
12 : 'Der Ressourcentyp ist nicht gültig.',
102 : 'Ungültiger Datei oder Verzeichnisname.',
103 : 'Ihre Anfrage konnte wegen Authorisierungseinschränkungen nicht durchgeführt werden.',
104 : 'Ihre Anfrage konnte wegen Dateisystemeinschränkungen nicht durchgeführt werden.',
105 : 'Invalid file extension.',
109 : 'Unbekannte Anfrage.',
110 : 'Unbekannter Fehler.',
115 : 'Es existiert bereits eine Datei oder ein Ordner mit dem gleichen Namen.',
116 : 'Verzeichnis nicht gefunden. Bitte aktualisieren Sie die Anzeige und versuchen es noch einmal.',
117 : 'Datei nicht gefunden. Bitte aktualisieren Sie die Dateiliste und versuchen es noch einmal.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Es existiert bereits eine Datei unter gleichem Namen. Die hochgeladene Datei wurde unter "%1" gespeichert.',
202 : 'Ungültige Datei',
203 : 'ungültige Datei. Die Dateigröße ist zu groß.',
204 : 'Die hochgeladene Datei ist korrupt.',
205 : 'Es existiert kein temp. Ordner für das Hochladen auf den Server.',
206 : 'Das Hochladen wurde aus Sicherheitsgründen abgebrochen. Die Datei enthält HTML-Daten.',
207 : 'Die hochgeladene Datei wurde unter "%1" gespeichert.',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Der Dateibrowser wurde aus Sicherheitsgründen deaktiviert. Bitte benachrichtigen Sie Ihren Systemadministrator und prüfen Sie die Konfigurationsdatei.',
501 : 'Die Miniaturansicht wurde deaktivert.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Der Dateinamen darf nicht leer sein',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Der Verzeichnisname darf nicht leer sein',
FileInvChar : 'Der Dateinamen darf nicht eines der folgenden Zeichen enthalten: \n\\ / : * ? " < > |',
FolderInvChar : 'Der Verzeichnisname darf nicht eines der folgenden Zeichen enthalten: \n\\ / : * ? " < > |',
PopupBlockView : 'Die Datei konnte nicht in einem neuen Fenster geöffnet werden. Bitte deaktivieren Sie in Ihrem Browser alle Popup-Blocker für diese Seite.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Latvian
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['lv'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'lv',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapes',
FolderLoading : 'Ielādē...',
FolderNew : 'Lūdzu ierakstiet mapes nosaukumu: ',
FolderRename : 'Lūdzu ierakstiet jauno mapes nosaukumu: ',
FolderDelete : 'Vai tiešām vēlaties neatgriezeniski dzēst mapi "%1"?',
FolderRenaming : ' (Pārsauc...)',
FolderDeleting : ' (Dzēš...)',
// Files
FileRename : 'Lūdzu ierakstiet jauno faila nosaukumu: ',
FileRenameExt : 'Vai tiešām vēlaties mainīt faila paplašinājumu? Fails var palikt nelietojams.',
FileRenaming : 'Pārsauc...',
FileDelete : 'Vai tiešām vēlaties neatgriezeniski dzēst failu "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Augšupielādēt',
UploadTip : 'Augšupielādēt jaunu failu',
Refresh : 'Pārlādēt',
Settings : 'Uzstādījumi',
Help : 'Palīdzība',
HelpTip : 'Palīdzība',
// Context Menus
Select : 'Izvēlēties',
SelectThumbnail : 'Izvēlēties sīkbildi',
View : 'Skatīt',
Download : 'Lejupielādēt',
NewSubFolder : 'Jauna apakšmape',
Rename : 'Pārsaukt',
Delete : 'Dzēst',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'Labi',
CancelBtn : 'Atcelt',
CloseBtn : 'Aizvērt',
// Upload Panel
UploadTitle : 'Jauna faila augšupielādēšana',
UploadSelectLbl : 'Izvēlaties failu, ko augšupielādēt',
UploadProgressLbl : '(Augšupielādē, lūdzu uzgaidiet...)',
UploadBtn : 'Augšupielādēt izvēlēto failu',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Lūdzu izvēlaties failu no sava datora',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Uzstādījumi',
SetView : 'Attēlot:',
SetViewThumb : 'Sīkbildes',
SetViewList : 'Failu Sarakstu',
SetDisplay : 'Rādīt:',
SetDisplayName : 'Faila Nosaukumu',
SetDisplayDate : 'Datumu',
SetDisplaySize : 'Faila Izmēru',
SetSort : 'Kārtot:',
SetSortName : 'pēc Faila Nosaukuma',
SetSortDate : 'pēc Datuma',
SetSortSize : 'pēc Izmēra',
// Status Bar
FilesCountEmpty : '<Tukša mape>',
FilesCountOne : '1 fails',
FilesCountMany : '%1 faili',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Nebija iespējams pabeigt pieprasījumu. (Kļūda %1)',
Errors :
{
10 : 'Nederīga komanda.',
11 : 'Resursa veids netika norādīts pieprasījumā.',
12 : 'Pieprasītais resursa veids nav derīgs.',
102 : 'Nederīgs faila vai mapes nosaukums.',
103 : 'Nav iespējams pabeigt pieprasījumu, autorizācijas aizliegumu dēļ.',
104 : 'Nav iespējams pabeigt pieprasījumu, failu sistēmas atļauju ierobežojumu dēļ.',
105 : 'Neatļauts faila paplašinājums.',
109 : 'Nederīgs pieprasījums.',
110 : 'Nezināma kļūda.',
115 : 'Fails vai mape ar šādu nosaukumu jau pastāv.',
116 : 'Mape nav atrasta. Lūdzu pārlādējiet šo logu un mēģiniet vēlreiz.',
117 : 'Fails nav atrasts. Lūdzu pārlādējiet failu sarakstu un mēģiniet vēlreiz.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Fails ar šādu nosaukumu jau eksistē. Augšupielādētais fails tika pārsaukts par "%1"',
202 : 'Nederīgs fails',
203 : 'Nederīgs fails. Faila izmērs pārsniedz pieļaujamo.',
204 : 'Augšupielādētais fails ir bojāts.',
205 : 'Neviena pagaidu mape nav pieejama priekš augšupielādēšanas uz servera.',
206 : 'Augšupielāde atcelta drošības apsvērumu dēļ. Fails satur HTML veida datus.',
207 : 'Augšupielādētais fails tika pārsaukts par "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Failu pārlūks ir atslēgts drošības apsvērumu dēļ. Lūdzu sazinieties ar šīs sistēmas tehnisko administratoru vai pārbaudiet CKFinder konfigurācijas failu.',
501 : 'Sīkbilžu atbalsts ir atslēgts.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Faila nosaukumā nevar būt tukšums',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Mapes nosaukumā nevar būt tukšums',
FileInvChar : 'Faila nosaukums nedrīkst saturēt nevienu no sekojošajām zīmēm: \n\\ / : * ? " < > |',
FolderInvChar : 'Mapes nosaukums nedrīkst saturēt nevienu no sekojošajām zīmēm: \n\\ / : * ? " < > |',
PopupBlockView : 'Nav iespējams failu atvērt jaunā logā. Lūdzu veiciet izmaiņas uzstādījumos savai interneta pārlūkprogrammai un izslēdziet visus uznirstošo logu bloķētājus šai adresei.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['no'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'no',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Laster...',
FolderNew : 'Skriv inn det nye mappenavnet: ',
FolderRename : 'Skriv inn det nye mappenavnet: ',
FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?',
FolderRenaming : ' (Endrer mappenavn...)',
FolderDeleting : ' (Sletter...)',
// Files
FileRename : 'Skriv inn det nye filnavnet: ',
FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig',
FileRenaming : 'Endrer filnavn...',
FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Last opp',
UploadTip : 'Last opp en ny fil',
Refresh : 'Oppdater',
Settings : 'Innstillinger',
Help : 'Hjelp',
HelpTip : 'Hjelp finnes kun på engelsk',
// Context Menus
Select : 'Velg',
SelectThumbnail : 'Velg Miniatyr',
View : 'Vis fullversjon',
Download : 'Last ned',
NewSubFolder : 'Ny Undermappe',
Rename : 'Endre navn',
Delete : 'Slett',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Lukk',
// Upload Panel
UploadTitle : 'Last opp ny fil',
UploadSelectLbl : 'Velg filen du vil laste opp',
UploadProgressLbl : '(Laster opp filen, vennligst vent...)',
UploadBtn : 'Last opp valgt fil',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Du må velge en fil fra din datamaskin',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Innstillinger',
SetView : 'Filvisning:',
SetViewThumb : 'Miniatyrbilder',
SetViewList : 'Liste',
SetDisplay : 'Vis:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Filstørrelse',
SetSort : 'Sorter etter:',
SetSortName : 'Filnavn',
SetSortDate : 'Dato',
SetSortSize : 'Størrelse',
// Status Bar
FilesCountEmpty : '<Tom Mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)',
Errors :
{
10 : 'Ugyldig kommando.',
11 : 'Ressurstypen ble ikke spesifisert i forepørselen.',
12 : 'Ugyldig ressurstype.',
102 : 'Ugyldig fil- eller mappenavn.',
103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.',
104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig forespørsel.',
110 : 'Ukjent feil.',
115 : 'Det finnes allerede en fil eller mappe med dette navnet.',
116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.',
117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1"',
202 : 'Ugyldig fil',
203 : 'Ugyldig fil. Filen er for stor.',
204 : 'Den opplastede filen er korrupt.',
205 : 'Det finnes ingen midlertidig mappe for filopplastinger.',
206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.',
207 : 'Den opplastede filens navn har blitt endret til "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.',
501 : 'Funksjon for minityrbilder er skrudd av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet kan ikke være tomt',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Mappenavnet kan ikke være tomt',
FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['el'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'el',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['ΜΜ', 'ΠΜ'],
// Folders
FoldersTitle : 'Φάκελοι',
FolderLoading : 'Φόρτωση...',
FolderNew : 'Παρακαλούμε πληκτρολογήστε την ονομασία του νέου φακέλου: ',
FolderRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του φακέλου: ',
FolderDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το φάκελο "%1";',
FolderRenaming : ' (Μετονομασία...)',
FolderDeleting : ' (Διαγραφή...)',
// Files
FileRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του αρχείου: ',
FileRenameExt : 'Είστε σίγουροι ότι θέλετε να αλλάξετε την επέκταση του αρχείου; Μετά από αυτή την ενέργεια το αρχείο μπορεί να μην μπορεί να χρησιμοποιηθεί',
FileRenaming : 'Μετονομασία...',
FileDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το αρχείο "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Μεταφόρτωση',
UploadTip : 'Μεταφόρτωση Νέου Αρχείου',
Refresh : 'Ανανέωση',
Settings : 'Ρυθμίσεις',
Help : 'Βοήθεια',
HelpTip : 'Βοήθεια',
// Context Menus
Select : 'Επιλογή',
SelectThumbnail : 'Επιλογή Μικρογραφίας',
View : 'Προβολή',
Download : 'Λήψη Αρχείου',
NewSubFolder : 'Νέος Υποφάκελος',
Rename : 'Μετονομασία',
Delete : 'Διαγραφή',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Ακύρωση',
CloseBtn : 'Κλείσιμο',
// Upload Panel
UploadTitle : 'Μεταφόρτωση Νέου Αρχείου',
UploadSelectLbl : 'επιλέξτε το αρχείο που θέλετε να μεταφερθεί κάνοντας κλίκ στο κουμπί',
UploadProgressLbl : '(Η μεταφόρτωση εκτελείται, παρακαλούμε περιμένετε...)',
UploadBtn : 'Μεταφόρτωση Επιλεγμένου Αρχείου',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Παρακαλούμε επιλέξτε ένα αρχείο από τον υπολογιστή σας',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Ρυθμίσεις',
SetView : 'Προβολή:',
SetViewThumb : 'Μικρογραφίες',
SetViewList : 'Λίστα',
SetDisplay : 'Εμφάνιση:',
SetDisplayName : 'Όνομα Αρχείου',
SetDisplayDate : 'Ημερομηνία',
SetDisplaySize : 'Μέγεθος Αρχείου',
SetSort : 'Ταξινόμηση:',
SetSortName : 'βάσει Όνοματος Αρχείου',
SetSortDate : 'βάσει Ημερομήνιας',
SetSortSize : 'βάσει Μεγέθους',
// Status Bar
FilesCountEmpty : '<Κενός Φάκελος>',
FilesCountOne : '1 αρχείο',
FilesCountMany : '%1 αρχεία',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Η ενέργεια δεν ήταν δυνατόν να εκτελεστεί. (Σφάλμα %1)',
Errors :
{
10 : 'Λανθασμένη Εντολή.',
11 : 'Το resource type δεν ήταν δυνατόν να προσδιορίστεί.',
12 : 'Το resource type δεν είναι έγκυρο.',
102 : 'Το όνομα αρχείου ή φακέλου δεν είναι έγκυρο.',
103 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω έλλειψης δικαιωμάτων ασφαλείας.',
104 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω περιορισμών του συστήματος αρχείων.',
105 : 'Λανθασμένη Επέκταση Αρχείου.',
109 : 'Λανθασμένη Ενέργεια.',
110 : 'Άγνωστο Λάθος.',
115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.',
116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
202 : 'Λανθασμένο Αρχείο',
203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.',
204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.',
205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για τις μεταφορτώσεις των αρχείων.',
206 : 'Η μεταφόρτωση ακυρώθηκε για λόγους ασφαλείας. Το αρχείο περιέχει δεδομένα μορφής HTML.',
207 : 'Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Ο πλοηγός αρχείων έχει απενεργοποιηθεί για λόγους ασφαλείας. Παρακαλούμε επικοινωνήστε με τον διαχειριστή της ιστοσελίδας και ελέγξτε το αρχείο ρυθμίσεων του πλοηγού (CKFinder).',
501 : 'Η υποστήριξη των μικρογραφιών έχει απενεργοποιηθεί.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Η ονομασία του αρχείου δεν μπορεί να είναι κενή',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Η ονομασία του φακέλου δεν μπορεί να είναι κενή',
FileInvChar : 'Η ονομασία του αρχείου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
FolderInvChar : 'Η ονομασία του φακέλου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
PopupBlockView : 'Δεν ήταν εφικτό να ανοίξει το αρχείο σε νέο παράθυρο. Παρακαλώ, ελέγξτε τις ρυθμίσεις τους πλοηγού σας και απενεργοποιήστε όλους τους popup blockers για αυτή την ιστοσελίδα.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Latin American Spanish
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['es-mx'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, no disponible</span>',
confirmCancel : 'Algunas opciones se han cambiado\r\n¿Está seguro de querer cerrar el diálogo?',
ok : 'Aceptar',
cancel : 'Cancelar',
confirmationTitle : 'Confirmación',
messageTitle : 'Información',
inputTitle : 'Pregunta',
undo : 'Deshacer',
redo : 'Rehacer',
skip : 'Omitir',
skipAll : 'Omitir todos',
makeDecision : '¿Qué acción debe realizarse?',
rememberDecision: 'Recordar mi decisión'
},
dir : 'ltr',
HelpLang : 'es-mx',
LangCode : 'es-mx',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Carpetas',
FolderLoading : 'Cargando...',
FolderNew : 'Por favor, escriba el nombre para la nueva carpeta: ',
FolderRename : 'Por favor, escriba el nuevo nombre para la carpeta: ',
FolderDelete : '¿Está seguro de que quiere borrar la carpeta "%1"?',
FolderRenaming : ' (Renombrando...)',
FolderDeleting : ' (Borrando...)',
// Files
FileRename : 'Por favor, escriba el nuevo nombre del archivo: ',
FileRenameExt : '¿Está seguro de querer cambiar la extensión del archivo? El archivo puede dejar de ser usable',
FileRenaming : 'Renombrando...',
FileDelete : '¿Está seguro de que quiere borrar el archivo "%1"?',
FilesLoading : 'Cargando...',
FilesEmpty : 'Carpeta vacía',
FilesMoved : 'Archivo %1 movido a %2:%3',
FilesCopied : 'Archivo %1 copiado a %2:%3',
// Basket
BasketFolder : 'Cesta',
BasketClear : 'Vaciar cesta',
BasketRemove : 'Quitar de la cesta',
BasketOpenFolder : 'Abrir carpeta padre',
BasketTruncateConfirm : '¿Está seguro de querer quitar todos los archivos de la cesta?',
BasketRemoveConfirm : '¿Está seguro de querer quitar el archivo "%1" de la cesta?',
BasketEmpty : 'No hay archivos en la cesta, arrastra y suelta algunos.',
BasketCopyFilesHere : 'Copiar archivos de la cesta',
BasketMoveFilesHere : 'Mover archivos de la cesta',
BasketPasteErrorOther : 'Fichero %s error: %e',
BasketPasteMoveSuccess : 'Los siguientes ficheros han sido movidos: %s',
BasketPasteCopySuccess : 'Los siguientes ficheros han sido copiados: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Añadir',
UploadTip : 'Añadir nuevo archivo',
Refresh : 'Actualizar',
Settings : 'Configuración',
Help : 'Ayuda',
HelpTip : 'Ayuda',
// Context Menus
Select : 'Seleccionar',
SelectThumbnail : 'Seleccionar el icono',
View : 'Ver',
Download : 'Descargar',
NewSubFolder : 'Nueva Subcarpeta',
Rename : 'Renombrar',
Delete : 'Borrar',
CopyDragDrop : 'Copiar archivo aquí',
MoveDragDrop : 'Mover archivo aquí',
// Dialogs
RenameDlgTitle : 'Renombrar',
NewNameDlgTitle : 'Nuevo nombre',
FileExistsDlgTitle : 'Archivo existente',
SysErrorDlgTitle : 'Error de sistema',
FileOverwrite : 'Sobreescribir',
FileAutorename : 'Auto-renombrar',
// Generic
OkBtn : 'Aceptar',
CancelBtn : 'Cancelar',
CloseBtn : 'Cerrar',
// Upload Panel
UploadTitle : 'Añadir nuevo archivo',
UploadSelectLbl : 'Elija el archivo a subir',
UploadProgressLbl : '(Subida en progreso, por favor espere...)',
UploadBtn : 'Subir el archivo elegido',
UploadBtnCancel : 'Cancelar',
UploadNoFileMsg : 'Por favor, elija un archivo de su computadora',
UploadNoFolder : 'Por favor, escoja la carpeta antes de iniciar la subida.',
UploadNoPerms : 'No puede subir archivos.',
UploadUnknError : 'Error enviando el archivo.',
UploadExtIncorrect : 'La extensión del archivo no está permitida en esta carpeta.',
// Settings Panel
SetTitle : 'Configuración',
SetView : 'Vista:',
SetViewThumb : 'Iconos',
SetViewList : 'Lista',
SetDisplay : 'Mostrar:',
SetDisplayName : 'Nombre de archivo',
SetDisplayDate : 'Fecha',
SetDisplaySize : 'Tamaño del archivo',
SetSort : 'Ordenar:',
SetSortName : 'por Nombre',
SetSortDate : 'por Fecha',
SetSortSize : 'por Tamaño',
// Status Bar
FilesCountEmpty : '<Carpeta vacía>',
FilesCountOne : '1 archivo',
FilesCountMany : '%1 archivos',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'No ha sido posible completar la solicitud. (Error %1)',
Errors :
{
10 : 'Comando incorrecto.',
11 : 'El tipo de recurso no ha sido especificado en la solicitud.',
12 : 'El tipo de recurso solicitado no es válido.',
102 : 'Nombre de archivo o carpeta no válido.',
103 : 'No se ha podido completar la solicitud debido a las restricciones de autorización.',
104 : 'No ha sido posible completar la solicitud debido a restricciones en el sistema de archivos.',
105 : 'La extensión del archivo no es válida.',
109 : 'Petición inválida.',
110 : 'Error desconocido.',
115 : 'Ya existe un archivo o carpeta con ese nombre.',
116 : 'No se ha encontrado la carpeta. Por favor, actualice y pruebe de nuevo.',
117 : 'No se ha encontrado el archivo. Por favor, actualice la lista de archivos y pruebe de nuevo.',
118 : 'Las rutas origen y destino son iguales.',
201 : 'Ya existía un archivo con ese nombre. El archivo subido ha sido renombrado como "%1"',
202 : 'Archivo inválido',
203 : 'Archivo inválido. El tamaño es demasiado grande.',
204 : 'El archivo subido está corrupto.',
205 : 'La carpeta temporal no está disponible en el servidor para las subidas.',
206 : 'La subida se ha cancelado por razones de seguridad. El archivo contenía código HTML.',
207 : 'El archivo subido ha sido renombrado como "%1"',
300 : 'Ha fallado el mover el(los) archivo(s).',
301 : 'Ha fallado el copiar el(los) archivo(s).',
500 : 'El navegador de archivos está deshabilitado por razones de seguridad. Por favor, contacte con el administrador de su sistema y compruebe el archivo de configuración de CKFinder.',
501 : 'El soporte para iconos está deshabilitado.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'El nombre del archivo no puede estar vacío',
FileExists : 'El archivo %s ya existe',
FolderEmpty : 'El nombre de la carpeta no puede estar vacío',
FileInvChar : 'El nombre del archivo no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |',
FolderInvChar : 'El nombre de la carpeta no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |',
PopupBlockView : 'No ha sido posible abrir el archivo en una nueva ventana. Por favor, configure su navegador y desactive todos los bloqueadores de ventanas para esta página.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionar %s',
sizeTooBig : 'No se puede poner la altura o anchura de la imagen mayor que las dimensiones originales (%size).',
resizeSuccess : 'Imagen redimensionada correctamente.',
thumbnailNew : 'Crear nueva minuatura',
thumbnailSmall : 'Pequeña (%s)',
thumbnailMedium : 'Mediana (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Establecer nuevo tamaño',
width : 'Ancho',
height : 'Alto',
invalidHeight : 'Altura inválida.',
invalidWidth : 'Anchura inválida.',
invalidName : 'Nombre no válido.',
newImage : 'Crear nueva imagen',
noExtensionChange : 'La extensión no se puede cambiar.',
imageSmall : 'La imagen original es demasiado pequeña',
contextMenuName : 'Redimensionar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Guardar',
fileOpenError : 'No se puede abrir el archivo.',
fileSaveSuccess : 'Archivo guardado correctamente.',
contextMenuName : 'Editar',
loadingFile : 'Cargando archivo, por favor espere...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Italian
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['it'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK',
cancel : 'Annulla',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Annulla',
redo : 'Ripristina',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'it',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Cartelle',
FolderLoading : 'Caricando...',
FolderNew : 'Nome della cartella: ',
FolderRename : 'Nuovo nome della cartella: ',
FolderDelete : 'Se sicuro di voler eliminare la cartella "%1"?',
FolderRenaming : ' (Rinominando...)',
FolderDeleting : ' (Eliminando...)',
// Files
FileRename : 'Nuovo nome del file: ',
FileRenameExt : 'Sei sicure di voler cambiare la estensione del file? Il file può risultare inusabile',
FileRenaming : 'Rinominando...',
FileDelete : 'Sei sicuro di voler eliminare il file "%1"?',
FilesLoading : 'Caricamento in corso...',
FilesEmpty : 'Cartella vuota',
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Carica Nuovo File',
Refresh : 'Aggiorna',
Settings : 'Configurazioni',
Help : 'Aiuto',
HelpTip : 'Aiuto (Inglese)',
// Context Menus
Select : 'Seleziona',
SelectThumbnail : 'Seleziona la miniatura',
View : 'Vedi',
Download : 'Scarica',
NewSubFolder : 'Nuova Sottocartella',
Rename : 'Rinomina',
Delete : 'Elimina',
CopyDragDrop : 'Copia file qui',
MoveDragDrop : 'Muove file qui',
// Dialogs
RenameDlgTitle : 'Rinomina',
NewNameDlgTitle : 'Nuovo nome',
FileExistsDlgTitle : 'Il file già esiste',
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Sovrascrivere',
FileAutorename : 'Rinomina automaticamente',
// Generic
OkBtn : 'OK',
CancelBtn : 'Anulla',
CloseBtn : 'Chiudi',
// Upload Panel
UploadTitle : 'Carica Nuovo File',
UploadSelectLbl : 'Seleziona il file',
UploadProgressLbl : '(Caricamento in corso, attendere prego...)',
UploadBtn : 'Carica File',
UploadBtnCancel : 'Annulla',
UploadNoFileMsg : 'Seleziona il file da caricare',
UploadNoFolder : 'Seleziona il file prima di caricare.',
UploadNoPerms : 'Non è permesso il caricamento di file.',
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'In questa cartella non sono permessi file con questa estensione.',
// Settings Panel
SetTitle : 'Configurazioni',
SetView : 'Vedi:',
SetViewThumb : 'Anteprima',
SetViewList : 'Lista',
SetDisplay : 'Informazioni:',
SetDisplayName : 'Nome del File',
SetDisplayDate : 'Data',
SetDisplaySize : 'Dimensione',
SetSort : 'Ordina:',
SetSortName : 'per Nome',
SetSortDate : 'per Data',
SetSortSize : 'per Dimensione',
// Status Bar
FilesCountEmpty : '<Nessun file>',
FilesCountOne : '1 file',
FilesCountMany : '%1 file',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Impossibile completare la richiesta. (Errore %1)',
Errors :
{
10 : 'Commando non valido.',
11 : 'Il tipo di risorsa non è stato specificato nella richiesta.',
12 : 'Il tipo di risorsa richiesto non è valido.',
102 : 'Nome di file o cartella non valido.',
103 : 'Non è stato possibile completare la richiesta a causa di restrizioni di autorizazione.',
104 : 'Non è stato possibile completare la richiesta a causa di restrizioni nei permessi del file system.',
105 : 'L\'estensione del file non è valida.',
109 : 'Richiesta invalida.',
110 : 'Errore sconosciuto.',
115 : 'Un file o cartella con lo stesso nome è già esistente.',
116 : 'Cartella non trovata. Prego aggiornare e riprovare.',
117 : 'File non trovato. Prego aggirnare la lista dei file e riprovare.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Un file con lo stesso nome è già disponibile. Il file caricato è stato rinominato in "%1".',
202 : 'File invalido',
203 : 'File invalido. La dimensione del file eccede i limiti del sistema.',
204 : 'Il file caricato è corrotto.',
205 : 'Il folder temporario non è disponibile new server.',
206 : 'Upload annullato per motivi di sicurezza. Il file contiene dati in formatto HTML.',
207 : 'El fichero subido ha sido renombrado como "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Questo programma è disabilitato per motivi di sicurezza. Prego contattare l\'amministratore del sistema e verificare le configurazioni di CKFinder.',
501 : 'Il supporto alle anteprime non è attivo.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Il nome del file non può essere vuoto',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Il nome della cartella non può essere vuoto',
FileInvChar : 'I seguenti caratteri non possono essere usati per comporre il nome del file: \n\\ / : * ? " < > |',
FolderInvChar : 'I seguenti caratteri non possono essere usati per comporre il nome della cartella: \n\\ / : * ? " < > |',
PopupBlockView : 'Non è stato possile aprire il file in una nuova finestra. Prego configurare il browser e disabilitare i blocchi delle popup.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Ridimensiona %s',
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Piccolo (%s)',
thumbnailMedium : 'Medio (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Nuove dimensioni',
width : 'Larghezza',
height : 'Altezza',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Crea nuova immagine',
noExtensionChange : 'L\'estensione del file non può essere cambiata.',
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Ridimensiona'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Salva',
fileOpenError : 'Non è stato possibile aprire il file.',
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Modifica',
loadingFile : 'Attendere prego. Caricamento del file in corso...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Slovak
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['sk'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'sk',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'mm/dd/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Adresáre',
FolderLoading : 'Nahrávam...',
FolderNew : 'Zadajte prosím meno nového adresára: ',
FolderRename : 'Zadajte prosím meno nového adresára: ',
FolderDelete : 'Skutočne zmazať adresár "%1" ?',
FolderRenaming : ' (Prebieha premenovanie adresára...)',
FolderDeleting : ' (Prebieha zmazanie adresára...)',
// Files
FileRename : 'Zadajte prosím meno nového súboru: ',
FileRenameExt : 'Skutočne chcete zmeniť príponu súboru? Upozornenie: zmenou prípony sa súbor môže stať nepoužiteľným, pokiaľ prípona nie je podporovaná.',
FileRenaming : 'Prebieha premenovanie súboru...',
FileDelete : 'Skutočne chcete odstrániť súbor "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Prekopírovať na server (Upload)',
UploadTip : 'Prekopírovať nový súbor',
Refresh : 'Znovunačítať (Refresh)',
Settings : 'Nastavenia',
Help : 'Pomoc',
HelpTip : 'Pomoc',
// Context Menus
Select : 'Vybrať',
SelectThumbnail : 'Select Thumbnail', // MISSING
View : 'Náhľad',
Download : 'Stiahnuť',
NewSubFolder : 'Nový podadresár',
Rename : 'Premenovať',
Delete : 'Zmazať',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Zrušiť',
CloseBtn : 'Zatvoriť',
// Upload Panel
UploadTitle : 'Nahrať nový súbor',
UploadSelectLbl : 'Vyberte súbor, ktorý chcete prekopírovať na server',
UploadProgressLbl : '(Prebieha kopírovanie, čakajte prosím...)',
UploadBtn : 'Prekopírovať vybratý súbor',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Vyberte prosím súbor na Vašom počítači!',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Nastavenia',
SetView : 'Náhľad:',
SetViewThumb : 'Miniobrázky',
SetViewList : 'Zoznam',
SetDisplay : 'Zobraziť:',
SetDisplayName : 'Názov súboru',
SetDisplayDate : 'Dátum',
SetDisplaySize : 'Veľkosť súboru',
SetSort : 'Zoradenie:',
SetSortName : 'podľa názvu súboru',
SetSortDate : 'podľa dátumu',
SetSortSize : 'podľa veľkosti',
// Status Bar
FilesCountEmpty : '<Prázdny adresár>',
FilesCountOne : '1 súbor',
FilesCountMany : '%1 súborov',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Server nemohol dokončiť spracovanie požiadavky. (Chyba %1)',
Errors :
{
10 : 'Neplatný príkaz.',
11 : 'V požiadavke nebol špecifikovaný typ súboru.',
12 : 'Nepodporovaný typ súboru.',
102 : 'Neplatný názov súboru alebo adresára.',
103 : 'Nebolo možné dokončiť spracovanie požiadavky kvôli nepostačujúcej úrovni oprávnení.',
104 : 'Nebolo možné dokončiť spracovanie požiadavky kvôli obmedzeniam v prístupových právach ku súborom.',
105 : 'Neplatná prípona súboru.',
109 : 'Neplatná požiadavka.',
110 : 'Neidentifikovaná chyba.',
115 : 'Zadaný súbor alebo adresár už existuje.',
116 : 'Adresár nebol nájdený. Aktualizujte obsah adresára (Znovunačítať) a skúste znovu.',
117 : 'Súbor nebol nájdený. Aktualizujte obsah adresára (Znovunačítať) a skúste znovu.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Súbor so zadaným názvom už existuje. Prekopírovaný súbor bol premenovaný na "%1"',
202 : 'Neplatný súbor',
203 : 'Neplatný súbor - súbor presahuje maximálnu povolenú veľkosť.',
204 : 'Kopírovaný súbor je poškodený.',
205 : 'Server nemá špecifikovaný dočasný adresár pre kopírované súbory.',
206 : 'Kopírovanie prerušené kvôli nedostatočnému zabezpečeniu. Súbor obsahuje HTML data.',
207 : 'Prekopírovaný súbor bol premenovaný na "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Prehliadanie súborov je zakázané kvôli bezpečnosti. Kontaktujte prosím administrátora a overte nastavenia v konfiguračnom súbore pre CKFinder.',
501 : 'Momentálne nie je zapnutá podpora pre generáciu miniobrázkov.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Názov súbor nesmie prázdny',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Názov adresára nesmie byť prázdny',
FileInvChar : 'Súbor nesmie obsahovať žiadny z nasledujúcich znakov: \n\\ / : * ? " < > |',
FolderInvChar : 'Adresár nesmie obsahovať žiadny z nasledujúcich znakov: \n\\ / : * ? " < > |',
PopupBlockView : 'Nebolo možné otvoriť súbor v novom okne. Overte nastavenia Vášho prehliadača a zakážte všetky blokovače popup okien pre túto webstránku.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nl'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'nl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mappen',
FolderLoading : 'Laden...',
FolderNew : 'Vul de mapnaam in: ',
FolderRename : 'Vul de nieuwe mapnaam in: ',
FolderDelete : 'Weet je het zeker dat je de map "%1" wilt verwijderen?',
FolderRenaming : ' (Aanpassen...)',
FolderDeleting : ' (Verwijderen...)',
// Files
FileRename : 'Vul de nieuwe bestandsnaam in: ',
FileRenameExt : 'Weet je zeker dat je de extensie wilt veranderen? Het bestand kan onbruikbaar worden.',
FileRenaming : 'Aanpassen...',
FileDelete : 'Weet je zeker dat je het bestand "%1" wilt verwijderen?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Uploaden',
UploadTip : 'Nieuw bestand uploaden',
Refresh : 'Vernieuwen',
Settings : 'Instellingen',
Help : 'Help',
HelpTip : 'Help',
// Context Menus
Select : 'Selecteer',
SelectThumbnail : 'Selecteer miniatuur afbeelding',
View : 'Weergave',
Download : 'Downloaden',
NewSubFolder : 'Nieuwe subfolder',
Rename : 'Hernoemen',
Delete : 'Verwijderen',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Annuleren',
CloseBtn : 'Sluiten',
// Upload Panel
UploadTitle : 'Nieuw bestand uploaden',
UploadSelectLbl : 'Selecteer het bestand om te uploaden',
UploadProgressLbl : '(Bezig met uploaden, even geduld...)',
UploadBtn : 'Upload geselecteerde bestand',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Kies een bestand van je computer.',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Instellingen',
SetView : 'Bekijken:',
SetViewThumb : 'Miniatuur afbeelding',
SetViewList : 'Lijst',
SetDisplay : 'Weergeef:',
SetDisplayName : 'Bestandsnaam',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Bestandsgrootte',
SetSort : 'Sorteren op:',
SetSortName : 'Op bestandsnaam',
SetSortDate : 'Op datum',
SetSortSize : 'Op grootte',
// Status Bar
FilesCountEmpty : '<Lege map>',
FilesCountOne : '1 bestand',
FilesCountMany : '%1 bestanden',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Het was niet mogelijk om deze actie uit te voeren. (Fout %1)',
Errors :
{
10 : 'Ongeldige commando.',
11 : 'De bestandstype komt niet voor in de aanvraag.',
12 : 'De gevraagde brontype is niet geldig.',
102 : 'Ongeldig bestands- of mapnaam.',
103 : 'Het verzoek kon niet worden voltooid vanwege autorisatie beperkingen.',
104 : 'Het verzoek kon niet worden voltooid door beperkingen in de permissies van het bestandssysteem.',
105 : 'Ongeldige bestandsextensie.',
109 : 'Ongeldige aanvraag.',
110 : 'Onbekende fout.',
115 : 'Er bestaat al een bestand of map met deze naam.',
116 : 'Map niet gevonden, vernieuw de mappenlijst of kies een andere map.',
117 : 'Bestand niet gevonden, vernieuw de mappenlijst of kies een andere folder.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Er bestaat al een bestand met dezelfde naam. Het geüploade bestand is hernoemd naar: "%1"',
202 : 'Ongeldige bestand',
203 : 'Ongeldige bestand. Het bestand is te groot.',
204 : 'De geüploade file is kapot.',
205 : 'Er is geen hoofdmap gevonden.',
206 : 'Het uploaden van het bestand is om veiligheidsredenen afgebroken. Er is HTML in het bestand aangetroffen.',
207 : 'Het geuploade bestand is hernoemd naar: "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Het uploaden van een bestand is momenteel niet mogelijk. Contacteer de beheerder en controleer het CKFinder configuratiebestand..',
501 : 'De ondersteuning voor miniatuur afbeeldingen is uitgeschakeld.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'De bestandsnaam mag niet leeg zijn.',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'De mapnaam mag niet leeg zijn.',
FileInvChar : 'De bestandsnaam mag niet de volgende tekens bevatten: \n\\ / : * ? " < > |',
FolderInvChar : 'De folder mag niet de volgende tekens bevatten: \n\\ / : * ? " < > |',
PopupBlockView : 'Het was niet mogelijk om dit bestand in een nieuw venster te openen. Configureer de browser zo dat het de popups van deze website niet blokkeert.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Danish
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['da'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, ikke tilgængelig</span>',
confirmCancel : 'Nogle af indstillingerne er blevet ændret. Er du sikker på at lukke dialogen?',
ok : 'OK',
cancel : 'Annuller',
confirmationTitle : 'Bekræftelse',
messageTitle : 'Information',
inputTitle : 'Spørgsmål',
undo : 'Fortryd',
redo : 'Annuller fortryd',
skip : 'Skip',
skipAll : 'Skip alle',
makeDecision : 'Hvad skal der foretages?',
rememberDecision: 'Husk denne indstilling'
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'da',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd-mm-yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Indlæser...',
FolderNew : 'Skriv navnet på den nye mappe: ',
FolderRename : 'Skriv det nye navn på mappen: ',
FolderDelete : 'Er du sikker på, at du vil slette mappen "%1" ?',
FolderRenaming : ' (Omdøber...)',
FolderDeleting : ' (Sletter...)',
// Files
FileRename : 'Skriv navnet på den nye fil: ',
FileRenameExt : 'Er du sikker på, at du vil ændre filtypen? Filen kan muligvis ikke bruges bagefter.',
FileRenaming : '(Omdøber...)',
FileDelete : 'Er du sikker på, at du vil slette filen "%1" ?',
FilesLoading : 'Indlæser...',
FilesEmpty : 'Tom mappe',
FilesMoved : 'Filen %1 flyttet til %2:%3',
FilesCopied : 'Filen %1 kopieret til %2:%3',
// Basket
BasketFolder : 'Kurv',
BasketClear : 'Tøm kurv',
BasketRemove : 'Fjern fra kurv',
BasketOpenFolder : 'Åben overordnet mappe',
BasketTruncateConfirm : 'Er du sikker på at du vil tømme kurven?',
BasketRemoveConfirm : 'Er du sikker på at du vil slette filen "%1" fra kurven?',
BasketEmpty : 'Ingen filer i kurven, brug musen til at trække filer til kurven.',
BasketCopyFilesHere : 'Kopier Filer fra kurven',
BasketMoveFilesHere : 'Flyt Filer fra kurven',
BasketPasteErrorOther : 'Fil fejl: %e',
BasketPasteMoveSuccess : 'Følgende filer blev flyttet: %s',
BasketPasteCopySuccess : 'Følgende filer blev kopieret: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Upload ny fil',
Refresh : 'Opdatér',
Settings : 'Indstillinger',
Help : 'Hjælp',
HelpTip : 'Hjælp',
// Context Menus
Select : 'Vælg',
SelectThumbnail : 'Vælg thumbnail',
View : 'Vis',
Download : 'Download',
NewSubFolder : 'Ny undermappe',
Rename : 'Omdøb',
Delete : 'Slet',
CopyDragDrop : 'Kopier hertil',
MoveDragDrop : 'Flyt hertil',
// Dialogs
RenameDlgTitle : 'Omdøb',
NewNameDlgTitle : 'Nyt navn',
FileExistsDlgTitle : 'Filen eksisterer allerede',
SysErrorDlgTitle : 'System fejl',
FileOverwrite : 'Overskriv',
FileAutorename : 'Auto-omdøb',
// Generic
OkBtn : 'OK',
CancelBtn : 'Annullér',
CloseBtn : 'Luk',
// Upload Panel
UploadTitle : 'Upload ny fil',
UploadSelectLbl : 'Vælg den fil, som du vil uploade',
UploadProgressLbl : '(Uploader, vent venligst...)',
UploadBtn : 'Upload filen',
UploadBtnCancel : 'Annuller',
UploadNoFileMsg : 'Vælg en fil på din computer',
UploadNoFolder : 'Venligst vælg en mappe før upload startes.',
UploadNoPerms : 'Upload er ikke tilladt.',
UploadUnknError : 'Fejl ved upload.',
UploadExtIncorrect : 'Denne filtype er ikke tilladt i denne mappe.',
// Settings Panel
SetTitle : 'Indstillinger',
SetView : 'Vis:',
SetViewThumb : 'Thumbnails',
SetViewList : 'Liste',
SetDisplay : 'Thumbnails:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Størrelse',
SetSort : 'Sortering:',
SetSortName : 'efter filnavn',
SetSortDate : 'efter dato',
SetSortSize : 'efter størrelse',
// Status Bar
FilesCountEmpty : '<tom mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke muligt at fuldføre handlingen. (Fejl: %1)',
Errors :
{
10 : 'Ugyldig handling.',
11 : 'Ressourcetypen blev ikke angivet i anmodningen.',
12 : 'Ressourcetypen er ikke gyldig.',
102 : 'Ugyldig fil eller mappenavn.',
103 : 'Det var ikke muligt at fuldføre handlingen på grund af en begrænsning i rettigheder.',
104 : 'Det var ikke muligt at fuldføre handlingen på grund af en begrænsning i filsystem rettigheder.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig anmodning.',
110 : 'Ukendt fejl.',
115 : 'En fil eller mappe med det samme navn eksisterer allerede.',
116 : 'Mappen blev ikke fundet. Opdatér listen eller prøv igen.',
117 : 'Filen blev ikke fundet. Opdatér listen eller prøv igen.',
118 : 'Originalplacering og destination er ens',
201 : 'En fil med det samme filnavn eksisterer allerede. Den uploadede fil er blevet omdøbt til "%1"',
202 : 'Ugyldig fil.',
203 : 'Ugyldig fil. Filstørrelsen er for stor.',
204 : 'Den uploadede fil er korrupt.',
205 : 'Der er ikke en midlertidig mappe til upload til rådighed på serveren.',
206 : 'Upload annulleret af sikkerhedsmæssige årsager. Filen indeholder HTML-lignende data.',
207 : 'Den uploadede fil er blevet omdøbt til "%1"',
300 : 'Flytning af fil(er) fejlede.',
301 : 'Kopiering af fil(er) fejlede.',
500 : 'Filbrowseren er deaktiveret af sikkerhedsmæssige årsager. Kontakt systemadministratoren eller kontrollér CKFinders konfigurationsfil.',
501 : 'Understøttelse af thumbnails er deaktiveret.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet må ikke være tomt',
FileExists : 'Fil %erne eksisterer allerede',
FolderEmpty : 'Mappenavnet må ikke være tomt',
FileInvChar : 'Filnavnet må ikke indeholde et af følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet må ikke indeholde et af følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Det var ikke muligt at åbne filen i et nyt vindue. Kontrollér konfigurationen i din browser, og deaktivér eventuelle popup-blokkere for denne hjemmeside.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Rediger størrelse %s',
sizeTooBig : 'Kan ikke ændre billedets højde eller bredde til en værdi større end dets originale størrelse (%size).',
resizeSuccess : 'Størrelsen er nu ændret.',
thumbnailNew : 'Opret ny thumbnail',
thumbnailSmall : 'Lille (%s)',
thumbnailMedium : 'Mellem (%s)',
thumbnailLarge : 'Stor (%s)',
newSize : 'Rediger størrelse',
width : 'Bredde',
height : 'Højde',
invalidHeight : 'Ugyldig højde.',
invalidWidth : 'Ugyldig bredde.',
invalidName : 'Ugyldigt filenavn.',
newImage : 'Opret nyt billede.',
noExtensionChange : 'Filtypen kan ikke ændres.',
imageSmall : 'Originalfilen er for lille',
contextMenuName : 'Rediger størrelse'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Gem',
fileOpenError : 'Filen kan ikke åbnes.',
fileSaveSuccess : 'Filen er nu gemt.',
contextMenuName : 'Rediger',
loadingFile : 'Henter fil, vent venligst...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Spanish
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['es'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, no disponible</span>',
confirmCancel : 'Algunas opciones se han cambiado\r\n¿Está seguro de querer cerrar el diálogo?',
ok : 'Aceptar',
cancel : 'Cancelar',
confirmationTitle : 'Confirmación',
messageTitle : 'Información',
inputTitle : 'Pregunta',
undo : 'Deshacer',
redo : 'Rehacer',
skip : 'Omitir',
skipAll : 'Omitir todos',
makeDecision : '¿Qué acción debe realizarse?',
rememberDecision: 'Recordar mi decisión'
},
dir : 'ltr',
HelpLang : 'es',
LangCode : 'es',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Carpetas',
FolderLoading : 'Cargando...',
FolderNew : 'Por favor, escriba el nombre para la nueva carpeta: ',
FolderRename : 'Por favor, escriba el nuevo nombre para la carpeta: ',
FolderDelete : '¿Está seguro de que quiere borrar la carpeta "%1"?',
FolderRenaming : ' (Renombrando...)',
FolderDeleting : ' (Borrando...)',
// Files
FileRename : 'Por favor, escriba el nuevo nombre del fichero: ',
FileRenameExt : '¿Está seguro de querer cambiar la extensión del fichero? El fichero puede dejar de ser usable',
FileRenaming : 'Renombrando...',
FileDelete : '¿Está seguro de que quiere borrar el fichero "%1"?',
FilesLoading : 'Cargando...',
FilesEmpty : 'Carpeta vacía',
FilesMoved : 'Fichero %1 movido a %2:%3',
FilesCopied : 'Fichero %1 copiado a %2:%3',
// Basket
BasketFolder : 'Cesta',
BasketClear : 'Vaciar cesta',
BasketRemove : 'Quitar de la cesta',
BasketOpenFolder : 'Abrir carpeta padre',
BasketTruncateConfirm : '¿Está seguro de querer quitar todos los ficheros de la cesta?',
BasketRemoveConfirm : '¿Está seguro de querer quitar el fichero "%1" de la cesta?',
BasketEmpty : 'No hay ficheros en la cesta, arrastra y suelta algunos.',
BasketCopyFilesHere : 'Copiar ficheros de la cesta',
BasketMoveFilesHere : 'Mover ficheros de la cesta',
BasketPasteErrorOther : 'Fichero %s error: %e',
BasketPasteMoveSuccess : 'Los siguientes ficheros han sido movidos: %s',
BasketPasteCopySuccess : 'Los siguientes ficheros han sido copiados: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Añadir',
UploadTip : 'Añadir nuevo fichero',
Refresh : 'Actualizar',
Settings : 'Configuración',
Help : 'Ayuda',
HelpTip : 'Ayuda',
// Context Menus
Select : 'Seleccionar',
SelectThumbnail : 'Seleccionar el icono',
View : 'Ver',
Download : 'Descargar',
NewSubFolder : 'Nueva Subcarpeta',
Rename : 'Renombrar',
Delete : 'Borrar',
CopyDragDrop : 'Copiar fichero aquí',
MoveDragDrop : 'Mover fichero aquí',
// Dialogs
RenameDlgTitle : 'Renombrar',
NewNameDlgTitle : 'Nuevo nombre',
FileExistsDlgTitle : 'Fichero existente',
SysErrorDlgTitle : 'Error de sistema',
FileOverwrite : 'Sobreescribir',
FileAutorename : 'Auto-renombrar',
// Generic
OkBtn : 'Aceptar',
CancelBtn : 'Cancelar',
CloseBtn : 'Cerrar',
// Upload Panel
UploadTitle : 'Añadir nuevo fichero',
UploadSelectLbl : 'Elija el fichero a subir',
UploadProgressLbl : '(Subida en progreso, por favor espere...)',
UploadBtn : 'Subir el fichero elegido',
UploadBtnCancel : 'Cancelar',
UploadNoFileMsg : 'Por favor, elija un fichero de su ordenador',
UploadNoFolder : 'Por favor, escoja la carpeta antes de iniciar la subida.',
UploadNoPerms : 'No puede subir ficheros.',
UploadUnknError : 'Error enviando el fichero.',
UploadExtIncorrect : 'La extensión del fichero no está permitida en esta carpeta.',
// Settings Panel
SetTitle : 'Configuración',
SetView : 'Vista:',
SetViewThumb : 'Iconos',
SetViewList : 'Lista',
SetDisplay : 'Mostrar:',
SetDisplayName : 'Nombre de fichero',
SetDisplayDate : 'Fecha',
SetDisplaySize : 'Peso del fichero',
SetSort : 'Ordenar:',
SetSortName : 'por Nombre',
SetSortDate : 'por Fecha',
SetSortSize : 'por Peso',
// Status Bar
FilesCountEmpty : '<Carpeta vacía>',
FilesCountOne : '1 fichero',
FilesCountMany : '%1 ficheros',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'No ha sido posible completar la solicitud. (Error %1)',
Errors :
{
10 : 'Comando incorrecto.',
11 : 'El tipo de recurso no ha sido especificado en la solicitud.',
12 : 'El tipo de recurso solicitado no es válido.',
102 : 'Nombre de fichero o carpeta no válido.',
103 : 'No se ha podido completar la solicitud debido a las restricciones de autorización.',
104 : 'No ha sido posible completar la solicitud debido a restricciones en el sistema de ficheros.',
105 : 'La extensión del archivo no es válida.',
109 : 'Petición inválida.',
110 : 'Error desconocido.',
115 : 'Ya existe un fichero o carpeta con ese nombre.',
116 : 'No se ha encontrado la carpeta. Por favor, actualice y pruebe de nuevo.',
117 : 'No se ha encontrado el fichero. Por favor, actualice la lista de ficheros y pruebe de nuevo.',
118 : 'Las rutas origen y destino son iguales.',
201 : 'Ya existía un fichero con ese nombre. El fichero subido ha sido renombrado como "%1"',
202 : 'Fichero inválido',
203 : 'Fichero inválido. El peso es demasiado grande.',
204 : 'El fichero subido está corrupto.',
205 : 'La carpeta temporal no está disponible en el servidor para las subidas.',
206 : 'La subida se ha cancelado por razones de seguridad. El fichero contenía código HTML.',
207 : 'El fichero subido ha sido renombrado como "%1"',
300 : 'Ha fallado el mover el(los) fichero(s).',
301 : 'Ha fallado el copiar el(los) fichero(s).',
500 : 'El navegador de archivos está deshabilitado por razones de seguridad. Por favor, contacte con el administrador de su sistema y compruebe el fichero de configuración de CKFinder.',
501 : 'El soporte para iconos está deshabilitado.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'El nombre del fichero no puede estar vacío',
FileExists : 'El fichero %s ya existe',
FolderEmpty : 'El nombre de la carpeta no puede estar vacío',
FileInvChar : 'El nombre del fichero no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |',
FolderInvChar : 'El nombre de la carpeta no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |',
PopupBlockView : 'No ha sido posible abrir el fichero en una nueva ventana. Por favor, configure su navegador y desactive todos los bloqueadores de ventanas para esta página.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionar %s',
sizeTooBig : 'No se puede poner la altura o anchura de la imagen mayor que las dimensiones originales (%size).',
resizeSuccess : 'Imagen redimensionada correctamente.',
thumbnailNew : 'Crear nueva minuatura',
thumbnailSmall : 'Pequeña (%s)',
thumbnailMedium : 'Mediana (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Establecer nuevo tamaño',
width : 'Ancho',
height : 'Alto',
invalidHeight : 'Altura inválida.',
invalidWidth : 'Anchura inválida.',
invalidName : 'Nombre no válido.',
newImage : 'Crear nueva imagen',
noExtensionChange : 'La extensión no se puede cambiar.',
imageSmall : 'La imagen original es demasiado pequeña',
contextMenuName : 'Redimensionar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Guardar',
fileOpenError : 'No se puede abrir el fichero.',
fileSaveSuccess : 'Fichero guardado correctamente.',
contextMenuName : 'Editar',
loadingFile : 'Cargando fichero, por favor espere...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Portuguese (Brazilian)
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['pt-br'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Algumas opções foram modificadas. Deseja fechar a janela realmente?',
ok : 'OK',
cancel : 'Cancelar',
confirmationTitle : 'Confirmação',
messageTitle : 'Informação',
inputTitle : 'Pergunta',
undo : 'Desfazer',
redo : 'Refazer',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'pt-br',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Pastas',
FolderLoading : 'Carregando...',
FolderNew : 'Favor informar o nome da nova pasta: ',
FolderRename : 'Favor informar o nome da nova pasta: ',
FolderDelete : 'Você tem certeza que deseja apagar a pasta "%1"?',
FolderRenaming : ' (Renomeando...)',
FolderDeleting : ' (Apagando...)',
// Files
FileRename : 'Favor informar o nome do novo arquivo: ',
FileRenameExt : 'Você tem certeza que deseja alterar a extensão do arquivo? O arquivo pode ser danificado',
FileRenaming : 'Renomeando...',
FileDelete : 'Você tem certeza que deseja apagar o arquivo "%1"?',
FilesLoading : 'Carregando...',
FilesEmpty : 'Pasta vazia',
FilesMoved : 'Arquivo %1 movido para %2:%3',
FilesCopied : 'Arquivo %1 copiado em %2:%3',
// Basket
BasketFolder : 'Cesta',
BasketClear : 'Limpa Cesta',
BasketRemove : 'Remove da cesta',
BasketOpenFolder : 'Abre a pasta original',
BasketTruncateConfirm : 'Remover todos os arquivas da cesta?',
BasketRemoveConfirm : 'Remover o arquivo "%1" da cesta?',
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copia Arquivos da Cesta',
BasketMoveFilesHere : 'Move os Arquivos da Cesta',
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'Os seguintes arquivos foram movidos: %s',
BasketPasteCopySuccess : 'Os sequintes arquivos foram copiados: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Enviar arquivo',
UploadTip : 'Enviar novo arquivo',
Refresh : 'Atualizar',
Settings : 'Configurações',
Help : 'Ajuda',
HelpTip : 'Ajuda',
// Context Menus
Select : 'Selecionar',
SelectThumbnail : 'Selecionar miniatura',
View : 'Visualizar',
Download : 'Download',
NewSubFolder : 'Nova sub-pasta',
Rename : 'Renomear',
Delete : 'Apagar',
CopyDragDrop : 'Copia arquivo aqui',
MoveDragDrop : 'Move arquivo aqui',
// Dialogs
RenameDlgTitle : 'Renomeia',
NewNameDlgTitle : 'Novo nome',
FileExistsDlgTitle : 'O arquivo já existe',
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Sobrescrever',
FileAutorename : 'Renomeia automaticamente',
// Generic
OkBtn : 'OK',
CancelBtn : 'Cancelar',
CloseBtn : 'Fechar',
// Upload Panel
UploadTitle : 'Enviar novo arquivo',
UploadSelectLbl : 'Selecione o arquivo para enviar',
UploadProgressLbl : '(Enviado arquivo, favor aguardar...)',
UploadBtn : 'Enviar arquivo selecionado',
UploadBtnCancel : 'Cancelar',
UploadNoFileMsg : 'Favor selecionar o arquivo no seu computador',
UploadNoFolder : 'Favor selecionar a pasta antes the enviar o arquivo.',
UploadNoPerms : 'Não é permitido o envio de arquivos.',
UploadUnknError : 'Erro no envio do arquivo.',
UploadExtIncorrect : 'A extensão deste arquivo não é permitida nesat pasta.',
// Settings Panel
SetTitle : 'Configurações',
SetView : 'Visualizar:',
SetViewThumb : 'Miniaturas',
SetViewList : 'Lista',
SetDisplay : 'Exibir:',
SetDisplayName : 'Arquivo',
SetDisplayDate : 'Data',
SetDisplaySize : 'Tamanho',
SetSort : 'Ordenar:',
SetSortName : 'por Nome do arquivo',
SetSortDate : 'por Data',
SetSortSize : 'por Tamanho',
// Status Bar
FilesCountEmpty : '<Pasta vazia>',
FilesCountOne : '1 arquivo',
FilesCountMany : '%1 arquivos',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Não foi possível completer o seu pedido. (Erro %1)',
Errors :
{
10 : 'Comando inválido.',
11 : 'O tipo de recurso não foi especificado na solicitação.',
12 : 'O recurso solicitado não é válido.',
102 : 'Nome do arquivo ou pasta inválido.',
103 : 'Não foi possível completar a solicitação por restrições de acesso.',
104 : 'Não foi possível completar a solicitação por restrições de acesso do sistema de arquivos.',
105 : 'Extensão de arquivo inválida.',
109 : 'Solicitação inválida.',
110 : 'Erro desconhecido.',
115 : 'Uma arquivo ou pasta já existe com esse nome.',
116 : 'Pasta não encontrada. Atualize e tente novamente.',
117 : 'Arquivo não encontrado. Atualize a lista de arquivos e tente novamente.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Um arquivo com o mesmo nome já está disponível. O arquivo enviado foi renomeado para "%1"',
202 : 'Arquivo inválido',
203 : 'Arquivo inválido. O tamanho é muito grande.',
204 : 'O arquivo enviado está corrompido.',
205 : 'Nenhuma pasta temporária para envio está disponível no servidor.',
206 : 'Transmissão cancelada por razões de segurança. O arquivo contem dados HTML.',
207 : 'O arquivo enviado foi renomeado para "%1"',
300 : 'Não foi possível mover o(s) arquivo(s).',
301 : 'Não foi possível copiar o(s) arquivos(s).',
500 : 'A navegação de arquivos está desativada por razões de segurança. Contacte o administrador do sistema.',
501 : 'O suporte a miniaturas está desabilitado.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'O nome do arquivo não pode ser vazio',
FileExists : 'O nome %s já é em uso',
FolderEmpty : 'O nome da pasta não pode ser vazio',
FileInvChar : 'O nome do arquivo não pode conter nenhum desses caracteres: \n\\ / : * ? " < > |',
FolderInvChar : 'O nome da pasta não pode conter nenhum desses caracteres: \n\\ / : * ? " < > |',
PopupBlockView : 'Não foi possível abrir o arquivo em outra janela. Configure seu navegador e desabilite o bloqueio a popups para esse site.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionar %s',
sizeTooBig : 'Não possível usar dimensões maiores do que as originais (%size).',
resizeSuccess : 'Imagem redimensionada corretamente.',
thumbnailNew : 'Cria nova anteprima',
thumbnailSmall : 'Pequeno (%s)',
thumbnailMedium : 'Médio (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Novas dimensões',
width : 'Largura',
height : 'Altura',
invalidHeight : 'Altura incorreta.',
invalidWidth : 'Largura incorreta.',
invalidName : 'O nome do arquivo não é válido.',
newImage : 'Cria nova imagem',
noExtensionChange : 'A extensão do arquivo não pode ser modificada.',
imageSmall : 'A imagem original é muito pequena',
contextMenuName : 'Redimensionar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Salva',
fileOpenError : 'Não é possível abrir o arquivo.',
fileSaveSuccess : 'Arquivo salvado corretamente.',
contextMenuName : 'Modificar',
loadingFile : 'Carregando arquivo. Por favor aguarde...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Chinese (Taiwan)
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['zh-tw'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'zh-tw',
LangCode : 'zh-tw',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'mm/dd/yyyy HH:MM',
DateAmPm : ['上午', '下午'],
// Folders
FoldersTitle : '目錄',
FolderLoading : '載入中...',
FolderNew : '請輸入新目錄名稱: ',
FolderRename : '請輸入新目錄名稱: ',
FolderDelete : '確定刪除 "%1" 這個目錄嗎?',
FolderRenaming : ' (修改目錄...)',
FolderDeleting : ' (刪除目錄...)',
// Files
FileRename : '請輸入新檔案名稱: ',
FileRenameExt : '確定變更這個檔案的副檔名嗎? 變更後 , 此檔案可能會無法使用 !',
FileRenaming : '修改檔案名稱...',
FileDelete : '確定要刪除這個檔案 "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : '上傳檔案',
UploadTip : '上傳一個新檔案',
Refresh : '重新整理',
Settings : '偏好設定',
Help : '說明',
HelpTip : '說明',
// Context Menus
Select : '選擇',
SelectThumbnail : 'Select Thumbnail', // MISSING
View : '瀏覽',
Download : '下載',
NewSubFolder : '建立新子目錄',
Rename : '重新命名',
Delete : '刪除',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : '確定',
CancelBtn : '取消',
CloseBtn : '關閉',
// Upload Panel
UploadTitle : '上傳新檔案',
UploadSelectLbl : '請選擇要上傳的檔案',
UploadProgressLbl : '(檔案上傳中 , 請稍候...)',
UploadBtn : '將檔案上傳到伺服器',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : '請從你的電腦選擇一個檔案',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : '設定',
SetView : '瀏覽方式:',
SetViewThumb : '縮圖預覽',
SetViewList : '清單列表',
SetDisplay : '顯示欄位:',
SetDisplayName : '檔案名稱',
SetDisplayDate : '檔案日期',
SetDisplaySize : '檔案大小',
SetSort : '排序方式:',
SetSortName : '依 檔案名稱',
SetSortDate : '依 檔案日期',
SetSortSize : '依 檔案大小',
// Status Bar
FilesCountEmpty : '<此目錄沒有任何檔案>',
FilesCountOne : '1 個檔案',
FilesCountMany : '%1 個檔案',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : '無法連接到伺服器 ! (錯誤代碼 %1)',
Errors :
{
10 : '不合法的指令.',
11 : '連接過程中 , 未指定資源形態 !',
12 : '連接過程中出現不合法的資源形態 !',
102 : '不合法的檔案或目錄名稱 !',
103 : '無法連接:可能是使用者權限設定錯誤 !',
104 : '無法連接:可能是伺服器檔案權限設定錯誤 !',
105 : '無法上傳:不合法的副檔名 !',
109 : '不合法的請求 !',
110 : '不明錯誤 !',
115 : '檔案或目錄名稱重複 !',
116 : '找不到目錄 ! 請先重新整理 , 然後再試一次 !',
117 : '找不到檔案 ! 請先重新整理 , 然後再試一次 !',
118 : 'Source and target paths are equal.', // MISSING
201 : '伺服器上已有相同的檔案名稱 ! 您上傳的檔案名稱將會自動更改為 "%1"',
202 : '不合法的檔案 !',
203 : '不合法的檔案 ! 檔案大小超過預設值 !',
204 : '您上傳的檔案已經損毀 !',
205 : '伺服器上沒有預設的暫存目錄 !',
206 : '檔案上傳程序因為安全因素已被系統自動取消 ! 可能是上傳的檔案內容包含 HTML 碼 !',
207 : '您上傳的檔案名稱將會自動更改為 "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : '因為安全因素 , 檔案瀏覽器已被停用 ! 請聯絡您的系統管理者並檢查 CKFinder 的設定檔 config.php !',
501 : '縮圖預覽功能已被停用 !'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : '檔案名稱不能空白 !',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : '目錄名稱不能空白 !',
FileInvChar : '檔案名稱不能包含以下字元: \n\\ / : * ? " < > |',
FolderInvChar : '目錄名稱不能包含以下字元: \n\\ / : * ? " < > |',
PopupBlockView : '無法在新視窗開啟檔案 ! 請檢查瀏覽器的設定並且針對這個網站 關閉 <封鎖彈跳視窗> 這個功能 !'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Polish
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['pl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, wyłączone</span>',
confirmCancel : 'Pewne opcje zostały zmienione. Czy na pewno zamknąć okno dialogowe?',
ok : 'OK',
cancel : 'Anuluj',
confirmationTitle : 'Potwierdzenie',
messageTitle : 'Informacja',
inputTitle : 'Pytanie',
undo : 'Cofnij',
redo : 'Ponów',
skip : 'Pomiń',
skipAll : 'Pomiń wszystkie',
makeDecision : 'Wybierz jedną z opcji:',
rememberDecision: 'Zapamiętaj mój wybór'
},
dir : 'ltr',
HelpLang : 'pl',
LangCode : 'pl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Katalogi',
FolderLoading : 'Ładowanie...',
FolderNew : 'Podaj nazwę nowego katalogu: ',
FolderRename : 'Podaj nową nazwę katalogu: ',
FolderDelete : 'Czy na pewno chcesz usunąć katalog "%1"?',
FolderRenaming : ' (Zmieniam nazwę...)',
FolderDeleting : ' (Kasowanie...)',
// Files
FileRename : 'Podaj nową nazwę pliku: ',
FileRenameExt : 'Czy na pewno chcesz zmienić rozszerzenie pliku? Może to spowodować problemy z otwieraniem pliku przez innych użytkowników',
FileRenaming : 'Zmieniam nazwę...',
FileDelete : 'Czy na pewno chcesz usunąć plik "%1"?',
FilesLoading : 'Ładowanie...',
FilesEmpty : 'Katalog jest pusty',
FilesMoved : 'Plik %1 został przeniesiony do %2:%3',
FilesCopied : 'Plik %1 został skopiowany do %2:%3',
// Basket
BasketFolder : 'Koszyk',
BasketClear : 'Wyczyść koszyk',
BasketRemove : 'Usuń z koszyka',
BasketOpenFolder : 'Otwórz katalog z plikiem',
BasketTruncateConfirm : 'Czy naprawdę chcesz usunąć wszystkie pliki z koszyka?',
BasketRemoveConfirm : 'Czy naprawdę chcesz usunąć plik "%1" z koszyka?',
BasketEmpty : 'Brak plików w koszyku, aby dodać plik, przeciągnij i upuść (drag\'n\'drop) dowolny plik do koszyka.',
BasketCopyFilesHere : 'Skopiuj pliki z koszyka',
BasketMoveFilesHere : 'Przenieś pliki z koszyka',
BasketPasteErrorOther : 'Plik: %s błąd: %e',
BasketPasteMoveSuccess : 'Następujące pliki zostały przeniesione: %s',
BasketPasteCopySuccess : 'Następujące pliki zostały skopiowane: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Wyślij',
UploadTip : 'Wyślij plik',
Refresh : 'Odśwież',
Settings : 'Ustawienia',
Help : 'Pomoc',
HelpTip : 'Wskazówka',
// Context Menus
Select : 'Wybierz',
SelectThumbnail : 'Wybierz miniaturkę',
View : 'Zobacz',
Download : 'Pobierz',
NewSubFolder : 'Nowy podkatalog',
Rename : 'Zmień nazwę',
Delete : 'Usuń',
CopyDragDrop : 'Skopiuj tutaj plik',
MoveDragDrop : 'Przenieś tutaj plik',
// Dialogs
RenameDlgTitle : 'Zmiana nazwy',
NewNameDlgTitle : 'Nowa nazwa',
FileExistsDlgTitle : 'Plik już istnieje',
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Nadpisz',
FileAutorename : 'Zmień automatycznie nazwę',
// Generic
OkBtn : 'OK',
CancelBtn : 'Anuluj',
CloseBtn : 'Zamknij',
// Upload Panel
UploadTitle : 'Wyślij plik',
UploadSelectLbl : 'Wybierz plik',
UploadProgressLbl : '(Trwa wysyłanie pliku, proszę czekać...)',
UploadBtn : 'Wyślij wybrany plik',
UploadBtnCancel : 'Anuluj',
UploadNoFileMsg : 'Wybierz plik ze swojego komputera',
UploadNoFolder : 'Wybierz katalog przed wysłaniem pliku.',
UploadNoPerms : 'Wysyłanie plików nie jest dozwolone.',
UploadUnknError : 'Błąd podczas wysyłania pliku.',
UploadExtIncorrect : 'Rozszerzenie pliku nie jest dozwolone w tym katalogu.',
// Settings Panel
SetTitle : 'Ustawienia',
SetView : 'Widok:',
SetViewThumb : 'Miniaturki',
SetViewList : 'Lista',
SetDisplay : 'Wyświetlanie:',
SetDisplayName : 'Nazwa pliku',
SetDisplayDate : 'Data',
SetDisplaySize : 'Rozmiar pliku',
SetSort : 'Sortowanie:',
SetSortName : 'wg nazwy pliku',
SetSortDate : 'wg daty',
SetSortSize : 'wg rozmiaru',
// Status Bar
FilesCountEmpty : '<Pusty katalog>',
FilesCountOne : '1 plik',
FilesCountMany : 'Ilość plików: %1',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Wykonanie operacji zakończyło się niepowodzeniem. (Błąd %1)',
Errors :
{
10 : 'Nieprawidłowe polecenie (command).',
11 : 'Brak wymaganego parametru: źródło danych (type).',
12 : 'Nieprawidłowe źródło danych (type).',
102 : 'Nieprawidłowa nazwa pliku lub katalogu.',
103 : 'Wykonanie operacji nie jest możliwe: brak autoryzacji.',
104 : 'Wykonanie operacji nie powiodło się z powodu niewystarczających uprawnień do systemu plików.',
105 : 'Nieprawidłowe rozszerzenie.',
109 : 'Nieprawiłowe polecenie.',
110 : 'Niezidentyfikowany błąd.',
115 : 'Plik lub katalog o podanej nazwie już istnieje.',
116 : 'Nie znaleziono ktalogu. Odśwież panel i spróbuj ponownie.',
117 : 'Nie znaleziono pliku. Odśwież listę plików i spróbuj ponownie.',
118 : 'Ścieżki źródłowa i docelowa są jednakowe.',
201 : 'Plik o podanej nazwie już istnieje. Nazwa przesłanego pliku została zmieniona na "%1"',
202 : 'Nieprawidłowy plik.',
203 : 'Nieprawidłowy plik. Plik przekroczył dozwolony rozmiar.',
204 : 'Przesłany plik jest uszkodzony.',
205 : 'Brak folderu tymczasowego na serwerze do przesyłania plików.',
206 : 'Przesyłanie pliku zakończyło się niepowodzeniem z powodów bezpieczeństwa. Plik zawiera dane przypominające HTML.',
207 : 'Nazwa przesłanego pliku została zmieniona na "%1"',
300 : 'Przenoszenie nie powiodło się.',
301 : 'Kopiowanie nie powiodo się.',
500 : 'Menedżer plików jest wyłączony z powodów bezpieczeństwa. Skontaktuj się z administratorem oraz sprawdź plik konfiguracyjny CKFindera.',
501 : 'Tworzenie miniaturek jest wyłączone.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Nazwa pliku nie może być pusta',
FileExists : 'Plik %s już istnieje',
FolderEmpty : 'Nazwa katalogu nie może być pusta',
FileInvChar : 'Nazwa pliku nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
FolderInvChar : 'Nazwa katalogu nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
PopupBlockView : 'Otwarcie pliku w nowym oknie nie powiodło się. Proszę zmienić konfigurację przeglądarki i wyłączyć wszelkie blokady okienek popup dla tej strony.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Zmiana rozmiaru %s',
sizeTooBig : 'Nie możesz zmienić wysokości lub szerokości na wartośc wyższą niż oryginalny rozmiar (%size).',
resizeSuccess : 'Obrazek został pomyślnie przeskalowany.',
thumbnailNew : 'Utwórz nową miniaturkę',
thumbnailSmall : 'Mały (%s)',
thumbnailMedium : 'Średni (%s)',
thumbnailLarge : 'Duży (%s)',
newSize : 'Podaj nowe wymiary',
width : 'Szerokość',
height : 'Wysokość',
invalidHeight : 'Nieprawidłowa wysokość.',
invalidWidth : 'Nieprawidłowa szerokość.',
invalidName : 'Nieprawidłowa nazwa pliku.',
newImage : 'Utwórz nowy obrazek',
noExtensionChange : 'Rozszerzenie pliku nie może zostac zmienione.',
imageSmall : 'Plik źródłowy jest zbyt mały',
contextMenuName : 'Zmień rozmiar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Zapisz',
fileOpenError : 'Nie udało się otworzyć pliku.',
fileSaveSuccess : 'Plik został zapisany pomyślnie.',
contextMenuName : 'Edytuj',
loadingFile : 'Trwa ładowanie pliku, proszę czekać...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['cs'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'cs',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Složky',
FolderLoading : 'Načítání...',
FolderNew : 'Zadejte jméno nové složky: ',
FolderRename : 'Zadejte nové jméno složky: ',
FolderDelete : 'Opravdu chcete smazat složku "%1" ?',
FolderRenaming : ' (Přejmenovávám...)',
FolderDeleting : ' (Mažu...)',
// Files
FileRename : 'Zadejte jméno novéhho souboru: ',
FileRenameExt : 'Opravdu chcete změnit příponu souboru, může se stát nečitelným',
FileRenaming : 'Přejmenovávám...',
FileDelete : 'Opravdu chcete smazat soubor "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Nahrát',
UploadTip : 'Nahrát nový soubor',
Refresh : 'Načíst znova',
Settings : 'Nastavení',
Help : 'Pomoc',
HelpTip : 'Pomoc',
// Context Menus
Select : 'Vybrat',
SelectThumbnail : 'Vybrat náhled',
View : 'Zobrazit',
Download : 'Uložit jako',
NewSubFolder : 'Nová podsložka',
Rename : 'Přejmenovat',
Delete : 'Smazat',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Zrušit',
CloseBtn : 'Zavřít',
// Upload Panel
UploadTitle : 'Nahrát nový soubor',
UploadSelectLbl : 'Zvolit soubor k nahrání',
UploadProgressLbl : '(Nahrávám, čekejte...)',
UploadBtn : 'Nahrát zvolený soubor',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Vyberte prosím soubor',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Nastavení',
SetView : 'Zobrazení:',
SetViewThumb : 'Náhledy',
SetViewList : 'Seznam',
SetDisplay : 'Informace:',
SetDisplayName : 'Název',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Velikost',
SetSort : 'Seřazení:',
SetSortName : 'Podle jména',
SetSortDate : 'Podle data',
SetSortSize : 'Podle velikosti',
// Status Bar
FilesCountEmpty : '<Prázdná složka>',
FilesCountOne : '1 soubor',
FilesCountMany : '%1 soubor',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Nebylo možno dokončit příkaz. (Error %1)',
Errors :
{
10 : 'Neplatný příkaz.',
11 : 'Požadovaný typ prostředku nebyl specifikován v dotazu.',
12 : 'Požadovaný typ prostředku není validní.',
102 : 'Šatné jméno souboru, nebo složky.',
103 : 'Nebylo možné dokončit příkaz kvůli autorizačním omezením.',
104 : 'Nebylo možné dokončit příkaz kvůli omezeným přístupovým právům k souborům.',
105 : 'Špatná přípona souboru.',
109 : 'Neplatný příkaz.',
110 : 'Neznámá chyba.',
115 : 'Již existuje soubor nebo složka se stejným jménem.',
116 : 'Složka nenalezena, prosím obnovte stránku.',
117 : 'Soubor nenalezen, prosím obnovte stránku.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Již existoval soubor se stejným jménem, nahraný soubor byl přejmenován na "%1"',
202 : 'Špatný soubor',
203 : 'Špatný soubor. Příliš velký.',
204 : 'Nahraný soubor je poškozen.',
205 : 'Na serveru není dostupná dočasná složka.',
206 : 'Nahrávání zrušeno z bezpečnostních důvodů. Soubor obsahuje data podobná HTML.',
207 : 'Nahraný soubor byl přejmenován na "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Nahrávání zrušeno z bezpečnostních důvodů. Zdělte to prosím administrátorovi a zkontrolujte nastavení CKFinderu.',
501 : 'Podpora náhledů je vypnuta.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Název souboru nemůže být prázdný',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Název složky nemůže být prázdný',
FileInvChar : 'Název souboru nesmí obsahovat následující znaky: \n\\ / : * ? " < > |',
FolderInvChar : 'Název složky nesmí obsahovat následující znaky: \n\\ / : * ? " < > |',
PopupBlockView : 'Nebylo možné otevřít soubor do nového okna. Prosím nastavte si prohlížeč aby neblokoval vyskakovací okna.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Chinese-Simplified
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['zh-cn'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : '部分内容尚未保存,确定关闭对话框么?',
ok : '确定',
cancel : '取消',
confirmationTitle : '确认',
messageTitle : '提示',
inputTitle : '询问',
undo : '撤销',
redo : '重做',
skip : '跳过',
skipAll : '全部跳过',
makeDecision : '应采取何样措施?',
rememberDecision: '下次不再询问'
},
dir : '自左向右',
HelpLang : 'en',
LangCode : 'zh-cn',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy年m月d日 h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : '文件夹',
FolderLoading : '正在加载文件夹...',
FolderNew : '请输入新文件夹名称: ',
FolderRename : '请输入新文件夹名称: ',
FolderDelete : '您确定要删除文件夹 "%1" 吗?',
FolderRenaming : ' (正在重命名...)',
FolderDeleting : ' (正在删除...)',
// Files
FileRename : '请输入新文件名: ',
FileRenameExt : '如果改变文件扩展名,可能会导致文件不可用。\r\n确定要更改吗?',
FileRenaming : '正在重命名...',
FileDelete : '您确定要删除文件 "%1" 吗?',
FilesLoading : '加载中...',
FilesEmpty : '空文件夹',
FilesMoved : '文件 %1 已移动至 %2:%3',
FilesCopied : '文件 %1 已拷贝至 %2:%3',
// Basket
BasketFolder : '临时文件夹',
BasketClear : '清空临时文件夹',
BasketRemove : '从临时文件夹移除',
BasketOpenFolder : '打开临时文件夹',
BasketTruncateConfirm : '确认清空临时文件夹?',
BasketRemoveConfirm : '确认从临时文件夹中移除文件 "%1" ?',
BasketEmpty : '临时文件夹为空, 可拖放文件至其中.',
BasketCopyFilesHere : '从临时文件夹复制至此',
BasketMoveFilesHere : '从临时文件夹移动至此',
BasketPasteErrorOther : '文件 %s 出错: %e',
BasketPasteMoveSuccess : '已移动以下文件: %s',
BasketPasteCopySuccess : '已拷贝以下文件: %s',
// Toolbar Buttons (some used elsewhere)
Upload : '上传',
UploadTip : '上传文件',
Refresh : '刷新',
Settings : '设置',
Help : '帮助',
HelpTip : '查看在线帮助',
// Context Menus
Select : '选择',
SelectThumbnail : '选中缩略图',
View : '查看',
Download : '下载',
NewSubFolder : '创建子文件夹',
Rename : '重命名',
Delete : '删除',
CopyDragDrop : '将文件复制至此',
MoveDragDrop : '将文件移动至此',
// Dialogs
RenameDlgTitle : '重命名',
NewNameDlgTitle : '文件名',
FileExistsDlgTitle : '文件已存在',
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : '自动覆盖重名',
FileAutorename : '自动重命名重名',
// Generic
OkBtn : '确定',
CancelBtn : '取消',
CloseBtn : '关闭',
// Upload Panel
UploadTitle : '上传文件',
UploadSelectLbl : '选定要上传的文件',
UploadProgressLbl : '(正在上传文件,请稍候...)',
UploadBtn : '上传选定的文件',
UploadBtnCancel : '取消',
UploadNoFileMsg : '请选择一个要上传的文件',
UploadNoFolder : '需先选择一个文件.',
UploadNoPerms : '无文件上传权限.',
UploadUnknError : '上传文件出错.',
UploadExtIncorrect : '此文件后缀在当前文件夹中不可用.',
// Settings Panel
SetTitle : '设置',
SetView : '查看:',
SetViewThumb : '缩略图',
SetViewList : '列表',
SetDisplay : '显示:',
SetDisplayName : '文件名',
SetDisplayDate : '日期',
SetDisplaySize : '大小',
SetSort : '排列顺序:',
SetSortName : '按文件名',
SetSortDate : '按日期',
SetSortSize : '按大小',
// Status Bar
FilesCountEmpty : '<空文件夹>',
FilesCountOne : '1 个文件',
FilesCountMany : '%1 个文件',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : '请求的操作未能完成. (错误 %1)',
Errors :
{
10 : '无效的指令.',
11 : '文件类型不在许可范围之内.',
12 : '文件类型无效.',
102 : '无效的文件名或文件夹名称.',
103 : '由于作者限制,该请求不能完成.',
104 : '由于文件系统的限制,该请求不能完成.',
105 : '无效的扩展名.',
109 : '无效请求.',
110 : '未知错误.',
115 : '存在重名的文件或文件夹.',
116 : '文件夹不存在. 请刷新后再试.',
117 : '文件不存在. 请刷新列表后再试.',
118 : '目标位置与当前位置相同.',
201 : '文件与现有的重名. 新上传的文件改名为 "%1"',
202 : '无效的文件',
203 : '无效的文件. 文件尺寸太大.',
204 : '上传文件已损失.',
205 : '服务器中的上传临时文件夹无效.',
206 : '因为安全原因,上传中断. 上传文件包含不能 HTML 类型数据.',
207 : '新上传的文件改名为 "%1"',
300 : '移动文件失败.',
301 : '复制文件失败.',
500 : '因为安全原因,文件不可浏览. 请联系系统管理员并检查CKFinder配置文件.',
501 : '不支持缩略图方式.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : '文件名不能为空',
FileExists : '文件 %s 已存在.',
FolderEmpty : '文件夹名称不能为空',
FileInvChar : '文件名不能包含以下字符: \n\\ / : * ? " < > |',
FolderInvChar : '文件夹名称不能包含以下字符: \n\\ / : * ? " < > |',
PopupBlockView : '未能在新窗口中打开文件. 请修改浏览器配置解除对本站点的锁定.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : '改变尺寸 %s',
sizeTooBig : '无法大于原图尺寸 (%size).',
resizeSuccess : '图像尺寸已修改.',
thumbnailNew : '创建缩略图',
thumbnailSmall : '小 (%s)',
thumbnailMedium : '中 (%s)',
thumbnailLarge : '大 (%s)',
newSize : '设置新尺寸',
width : '宽度',
height : '高度',
invalidHeight : '无效高度.',
invalidWidth : '无效宽度.',
invalidName : '文件名无效.',
newImage : '创建图像',
noExtensionChange : '无法改变文件后缀.',
imageSmall : '原文件尺寸过小',
contextMenuName : '改变尺寸'
},
// Fileeditor plugin
Fileeditor :
{
save : '保存',
fileOpenError : '无法打开文件.',
fileSaveSuccess : '成功保存文件.',
contextMenuName : '编辑',
loadingFile : '加载文件中...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the English
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['ja'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, は利用できません。</span>',
confirmCancel : '変更された項目があります。ウィンドウを閉じてもいいですか?',
ok : '適用',
cancel : 'キャンセル',
confirmationTitle : '確認',
messageTitle : 'インフォメーション',
inputTitle : '質問',
undo : '元に戻す',
redo : 'やり直す',
skip : 'スキップ',
skipAll : 'すべてスキップ',
makeDecision : 'どうしますか?',
rememberDecision: '注意:'
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'ja',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Folders',
FolderLoading : '読み込み中...',
FolderNew : '新しいフォルダ名を入力してください: ',
FolderRename : '新しいフォルダ名を入力してください: ',
FolderDelete : '本当にフォルダ「"%1"」を削除してもよろしいですか?',
FolderRenaming : ' (リネーム中...)',
FolderDeleting : ' (削除中...)',
// Files
FileRename : '新しいファイル名を入力してください: ',
FileRenameExt : 'ファイルが使えなくなる可能性がありますが、本当に拡張子を変更してもよろしいですか?',
FileRenaming : 'リネーム中...',
FileDelete : '本当に「"%1"」を削除してもよろしいですか?',
FilesLoading : '読み込み中...',
FilesEmpty : 'ファイルがありません',
FilesMoved : ' %1 は %2:%3 に移動されました',
FilesCopied : ' %1 cは %2:%3 にコピーされました',
// Basket
BasketFolder : 'Basket',
BasketClear : 'バスケットを空にする',
BasketRemove : 'バスケットから削除',
BasketOpenFolder : '親フォルダを開く',
BasketTruncateConfirm : '本当にバスケットの中身を空にしますか?',
BasketRemoveConfirm : '本当に「"%1"」をバスケットから削除しますか?',
BasketEmpty : 'バスケットの中にファイルがありません。このエリアにドラッグ&ドロップして追加することができます。',
BasketCopyFilesHere : 'バスケットからファイルをコピー',
BasketMoveFilesHere : 'バスケットからファイルを移動',
BasketPasteErrorOther : 'ファイル %s のエラー: %e',
BasketPasteMoveSuccess : '以下のファイルが移動されました: %s',
BasketPasteCopySuccess : '以下のファイルがコピーされました: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'アップロード',
UploadTip : '新しいファイルのアップロード',
Refresh : '表示の更新',
Settings : 'カスタマイズ',
Help : 'ヘルプ',
HelpTip : 'ヘルプ',
// Context Menus
Select : 'この画像を選択',
SelectThumbnail : 'この画像のサムネイルを選択',
View : '画像だけを表示',
Download : 'ダウンロード',
NewSubFolder : '新しいフォルダに入れる',
Rename : 'ファイル名の変更',
Delete : '削除',
CopyDragDrop : 'コピーするファイルをここにドロップしてください',
MoveDragDrop : '移動するファイルをここにドロップしてください',
// Dialogs
RenameDlgTitle : 'リネーム',
NewNameDlgTitle : '新しい名前',
FileExistsDlgTitle : 'ファイルはすでに存在します。',
SysErrorDlgTitle : 'システムエラー',
FileOverwrite : '上書き',
FileAutorename : 'A自動でリネーム',
// Generic
OkBtn : 'OK',
CancelBtn : 'キャンセル',
CloseBtn : '閉じる',
// Upload Panel
UploadTitle : 'ファイルのアップロード',
UploadSelectLbl : 'アップロードするファイルを選択してください',
UploadProgressLbl : '(ファイルのアップロード中...)',
UploadBtn : 'アップロード',
UploadBtnCancel : 'キャンセル',
UploadNoFileMsg : 'ファイルを選んでください。',
UploadNoFolder : 'アップロードの前にフォルダを選択してください。',
UploadNoPerms : 'ファイルのアップロード権限がありません。',
UploadUnknError : 'ファイルの送信に失敗しました。',
UploadExtIncorrect : '選択されたファイルの拡張子は許可されていません。',
// Settings Panel
SetTitle : '表示のカスタマイズ',
SetView : '表示方法:',
SetViewThumb : 'サムネイル',
SetViewList : '表示形式',
SetDisplay : '表示する項目:',
SetDisplayName : 'ファイル名',
SetDisplayDate : '日時',
SetDisplaySize : 'ファイルサイズ',
SetSort : '表示の順番:',
SetSortName : 'ファイル名',
SetSortDate : '日付',
SetSortSize : 'サイズ',
// Status Bar
FilesCountEmpty : '<フォルダ内にファイルがありません>',
FilesCountOne : '1つのファイル',
FilesCountMany : '%1個のファイル',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'リクエストの処理に失敗しました。 (Error %1)',
Errors :
{
10 : '不正なコマンドです。',
11 : 'リソースタイプが特定できませんでした。',
12 : '要求されたリソースのタイプが正しくありません。',
102 : 'ファイル名/フォルダ名が正しくありません。',
103 : 'リクエストを完了できませんでした。認証エラーです。',
104 : 'リクエストを完了できませんでした。ファイルのパーミッションが許可されていません。',
105 : '拡張子が正しくありません。',
109 : '不正なリクエストです。',
110 : '不明なエラーが発生しました。',
115 : '同じ名前のファイル/フォルダがすでに存在しています。',
116 : 'フォルダが見つかりませんでした。ページを更新して再度お試し下さい。',
117 : 'ファイルが見つかりませんでした。ページを更新して再度お試し下さい。',
118 : '対象が移動元と同じ場所を指定されています。',
201 : '同じ名前のファイルがすでに存在しています。"%1" にリネームして保存されました。',
202 : '不正なファイルです。',
203 : 'ファイルのサイズが大きすぎます。',
204 : 'アップロードされたファイルは壊れています。',
205 : 'サーバ内の一時作業フォルダが利用できません。',
206 : 'セキュリティ上の理由からアップロードが取り消されました。このファイルにはHTMLに似たデータが含まれています。',
207 : 'ファイルは "%1" にリネームして保存されました。',
300 : 'ファイルの移動に失敗しました。',
301 : 'ファイルのコピーに失敗しました。',
500 : 'ファイルブラウザはセキュリティ上の制限から無効になっています。システム担当者に連絡をして、CKFinderの設定をご確認下さい。',
501 : 'サムネイル機能は無効になっています。'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'ファイル名を入力してください',
FileExists : ' %s はすでに存在しています。別の名前を入力してください。',
FolderEmpty : 'フォルダ名を入力してください',
FileInvChar : 'ファイルに以下の文字は使えません: \n\\ / : * ? " < > |',
FolderInvChar : 'フォルダに以下の文字は使えません: \n\\ / : * ? " < > |',
PopupBlockView : 'ファイルを新しいウィンドウで開くことに失敗しました。 お使いのブラウザの設定でポップアップをブロックする設定を解除してください。'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'リサイズ: %s',
sizeTooBig : 'オリジナルの画像よりも大きいサイズは指定できません。 (%size).',
resizeSuccess : '画像のリサイズに成功しました',
thumbnailNew : 'サムネイルをつくる',
thumbnailSmall : '小 (%s)',
thumbnailMedium : '中 (%s)',
thumbnailLarge : '大 (%s)',
newSize : 'Set new size',
width : '幅',
height : '高さ',
invalidHeight : '高さの値が不正です。',
invalidWidth : '幅の値が不正です。',
invalidName : 'ファイル名が不正です。',
newImage : '新しい画像を作成',
noExtensionChange : '拡張子は変更できません。',
imageSmall : '元画像が小さすぎます。',
contextMenuName : 'リサイズ'
},
// Fileeditor plugin
Fileeditor :
{
save : '保存',
fileOpenError : 'ファイルを開けませんでした。',
fileSaveSuccess : 'ファイルの保存が完了しました。',
contextMenuName : '編集',
loadingFile : 'ファイルの読み込み中...'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['hu'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'hu',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy. m. d. HH:MM',
DateAmPm : ['de.', 'du.'],
// Folders
FoldersTitle : 'Mappák',
FolderLoading : 'Betöltés...',
FolderNew : 'Kérjük adja meg a mappa nevét: ',
FolderRename : 'Kérjük adja meg a mappa új nevét: ',
FolderDelete : 'Biztosan törölni szeretné a következő mappát: "%1"?',
FolderRenaming : ' (átnevezés...)',
FolderDeleting : ' (törlés...)',
// Files
FileRename : 'Kérjük adja meg a fájl új nevét: ',
FileRenameExt : 'Biztosan szeretné módosítani a fájl kiterjesztését? A fájl esetleg használhatatlan lesz.',
FileRenaming : 'Átnevezés...',
FileDelete : 'Biztosan törölni szeretné a következő fájlt: "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Feltöltés',
UploadTip : 'Új fájl feltöltése',
Refresh : 'Frissítés',
Settings : 'Beállítások',
Help : 'Súgó',
HelpTip : 'Súgó (angolul)',
// Context Menus
Select : 'Kiválaszt',
SelectThumbnail : 'Bélyegkép kiválasztása',
View : 'Megtekintés',
Download : 'Letöltés',
NewSubFolder : 'Új almappa',
Rename : 'Átnevezés',
Delete : 'Törlés',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Mégsem',
CloseBtn : 'Bezárás',
// Upload Panel
UploadTitle : 'Új fájl feltöltése',
UploadSelectLbl : 'Válassza ki a feltölteni kívánt fájlt',
UploadProgressLbl : '(A feltöltés folyamatban, kérjük várjon...)',
UploadBtn : 'A kiválasztott fájl feltöltése',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Kérjük válassza ki a fájlt a számítógépéről',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Beállítások',
SetView : 'Nézet:',
SetViewThumb : 'bélyegképes',
SetViewList : 'listás',
SetDisplay : 'Megjelenik:',
SetDisplayName : 'fájl neve',
SetDisplayDate : 'dátum',
SetDisplaySize : 'fájlméret',
SetSort : 'Rendezés:',
SetSortName : 'fájlnév',
SetSortDate : 'dátum',
SetSortSize : 'méret',
// Status Bar
FilesCountEmpty : '<üres mappa>',
FilesCountOne : '1 fájl',
FilesCountMany : '%1 fájl',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'A parancsot nem sikerült végrehajtani. (Hiba: %1)',
Errors :
{
10 : 'Érvénytelen parancs.',
11 : 'A fájl típusa nem lett a kérés során beállítva.',
12 : 'A kívánt fájl típus érvénytelen.',
102 : 'Érvénytelen fájl vagy könyvtárnév.',
103 : 'Hitelesítési problémák miatt nem sikerült a kérést teljesíteni.',
104 : 'Jogosultsági problémák miatt nem sikerült a kérést teljesíteni.',
105 : 'Érvénytelen fájl kiterjesztés.',
109 : 'Érvénytelen kérés.',
110 : 'Ismeretlen hiba.',
115 : 'A fálj vagy mappa már létezik ezen a néven.',
116 : 'Mappa nem található. Kérjük frissítsen és próbálja újra.',
117 : 'Fájl nem található. Kérjük frissítsen és próbálja újra.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Ilyen nevű fájl már létezett. A feltöltött fájl a következőre lett átnevezve: "%1"',
202 : 'Érvénytelen fájl',
203 : 'Érvénytelen fájl. A fájl mérete túl nagy.',
204 : 'A feltöltött fájl hibás.',
205 : 'A szerveren nem található a feltöltéshez ideiglenes mappa.',
206 : 'A feltöltés biztonsági okok miatt meg lett szakítva. The file contains HTML like data.',
207 : 'El fichero subido ha sido renombrado como "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'A fájl-tallózó biztonsági okok miatt nincs engedélyezve. Kérjük vegye fel a kapcsolatot a rendszer üzemeltetőjével és ellenőrizze a CKFinder konfigurációs fájlt.',
501 : 'A bélyegkép támogatás nincs engedélyezve.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'A fájl neve nem lehet üres',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'A mappa neve nem lehet üres',
FileInvChar : 'A fájl neve nem tartalmazhatja a következő karaktereket: \n\\ / : * ? " < > |',
FolderInvChar : 'A mappa neve nem tartalmazhatja a következő karaktereket: \n\\ / : * ? " < > |',
PopupBlockView : 'A felugró ablak megnyitása nem sikerült. Kérjük ellenőrizze a böngészője beállításait és tiltsa le a felugró ablakokat blokkoló alkalmazásait erre a honlapra.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2010, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the English
* language. This is the base file for all translations.
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['en'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>',
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?',
ok : 'OK',
cancel : 'Cancel',
confirmationTitle : 'Confirmation',
messageTitle : 'Information',
inputTitle : 'Question',
undo : 'Undo',
redo : 'Redo',
skip : 'Skip',
skipAll : 'Skip all',
makeDecision : 'What action should be taken?',
rememberDecision: 'Remember my decision'
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'en',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM','PM'],
// Folders
FoldersTitle : 'Folders',
FolderLoading : 'Loading...',
FolderNew : 'Please type the new folder name: ',
FolderRename : 'Please type the new folder name: ',
FolderDelete : 'Are you sure you want to delete the "%1" folder?',
FolderRenaming : ' (Renaming...)',
FolderDeleting : ' (Deleting...)',
// Files
FileRename : 'Please type the new file name: ',
FileRenameExt : 'Are you sure you want to change the file name extension? The file may become unusable',
FileRenaming : 'Renaming...',
FileDelete : 'Are you sure you want to delete the file "%1"?',
FilesLoading : 'Loading...',
FilesEmpty : 'Empty folder',
FilesMoved : 'File %1 moved into %2:%3',
FilesCopied : 'File %1 copied into %2:%3',
// Basket
BasketFolder : 'Basket',
BasketClear : 'Clear Basket',
BasketRemove : 'Remove from basket',
BasketOpenFolder : 'Open parent folder',
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?',
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?',
BasketEmpty : 'No files in the basket, drag\'n\'drop some.',
BasketCopyFilesHere : 'Copy Files from Basket',
BasketMoveFilesHere : 'Move Files from Basket',
BasketPasteErrorOther : 'File %s error: %e',
BasketPasteMoveSuccess : 'The following files were moved: %s',
BasketPasteCopySuccess : 'The following files were copied: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Upload New File',
Refresh : 'Refresh',
Settings : 'Settings',
Help : 'Help',
HelpTip : 'Help',
// Context Menus
Select : 'Select',
SelectThumbnail : 'Select Thumbnail',
View : 'View',
Download : 'Download',
NewSubFolder : 'New Subfolder',
Rename : 'Rename',
Delete : 'Delete',
CopyDragDrop : 'Copy file here',
MoveDragDrop : 'Move file here',
// Dialogs
RenameDlgTitle : 'Rename',
NewNameDlgTitle : 'New name',
FileExistsDlgTitle : 'File already exists',
SysErrorDlgTitle : 'System error',
FileOverwrite : 'Overwrite',
FileAutorename : 'Auto-rename',
// Generic
OkBtn : 'OK',
CancelBtn : 'Cancel',
CloseBtn : 'Close',
// Upload Panel
UploadTitle : 'Upload New File',
UploadSelectLbl : 'Select the file to upload',
UploadProgressLbl : '(Upload in progress, please wait...)',
UploadBtn : 'Upload Selected File',
UploadBtnCancel : 'Cancel',
UploadNoFileMsg : 'Please select a file from your computer',
UploadNoFolder : 'Please select folder before uploading.',
UploadNoPerms : 'File upload not allowed.',
UploadUnknError : 'Error sending the file.',
UploadExtIncorrect : 'File extension not allowed in this folder.',
// Settings Panel
SetTitle : 'Settings',
SetView : 'View:',
SetViewThumb : 'Thumbnails',
SetViewList : 'List',
SetDisplay : 'Display:',
SetDisplayName : 'File Name',
SetDisplayDate : 'Date',
SetDisplaySize : 'File Size',
SetSort : 'Sorting:',
SetSortName : 'by File Name',
SetSortDate : 'by Date',
SetSortSize : 'by Size',
// Status Bar
FilesCountEmpty : '<Empty Folder>',
FilesCountOne : '1 file',
FilesCountMany : '%1 files',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'It was not possible to complete the request. (Error %1)',
Errors :
{
10 : 'Invalid command.',
11 : 'The resource type was not specified in the request.',
12 : 'The requested resource type is not valid.',
102 : 'Invalid file or folder name.',
103 : 'It was not possible to complete the request due to authorization restrictions.',
104 : 'It was not possible to complete the request due to file system permission restrictions.',
105 : 'Invalid file extension.',
109 : 'Invalid request.',
110 : 'Unknown error.',
115 : 'A file or folder with the same name already exists.',
116 : 'Folder not found. Please refresh and try again.',
117 : 'File not found. Please refresh the files list and try again.',
118 : 'Source and target paths are equal.',
201 : 'A file with the same name is already available. The uploaded file has been renamed to "%1"',
202 : 'Invalid file',
203 : 'Invalid file. The file size is too big.',
204 : 'The uploaded file is corrupt.',
205 : 'No temporary folder is available for upload in the server.',
206 : 'Upload cancelled for security reasons. The file contains HTML like data.',
207 : 'The uploaded file has been renamed to "%1"',
300 : 'Moving file(s) failed.',
301 : 'Copying file(s) failed.',
500 : 'The file browser is disabled for security reasons. Please contact your system administrator and check the CKFinder configuration file.',
501 : 'The thumbnails support is disabled.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'The file name cannot be empty',
FileExists : 'File %s already exists',
FolderEmpty : 'The folder name cannot be empty',
FileInvChar : 'The file name cannot contain any of the following characters: \n\\ / : * ? " < > |',
FolderInvChar : 'The folder name cannot contain any of the following characters: \n\\ / : * ? " < > |',
PopupBlockView : 'It was not possible to open the file in a new window. Please configure your browser and disable all popup blockers for this site.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s',
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).',
resizeSuccess : 'Image resized successfully.',
thumbnailNew : 'Create new thumbnail',
thumbnailSmall : 'Small (%s)',
thumbnailMedium : 'Medium (%s)',
thumbnailLarge : 'Large (%s)',
newSize : 'Set new size',
width : 'Width',
height : 'Height',
invalidHeight : 'Invalid height.',
invalidWidth : 'Invalid width.',
invalidName : 'Invalid file name.',
newImage : 'Create new image',
noExtensionChange : 'The file extension cannot be changed.',
imageSmall : 'Source image is too small',
contextMenuName : 'Resize'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save',
fileOpenError : 'Unable to open file.',
fileSaveSuccess : 'File saved successfully.',
contextMenuName : 'Edit',
loadingFile : 'Loading file, please wait...'
}
};
| JavaScript |
/* http://keith-wood.name/countdown.html
Countdown for jQuery v1.5.11.
Written by Keith Wood (kbwood{at}iinet.com.au) January 2008.
Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
Please attribute the author if you use it. */
/* Display a countdown timer.
Attach it with options like:
$('div selector').countdown(
{until: new Date(2009, 1 - 1, 1, 0, 0, 0), onExpiry: happyNewYear}); */
(function($) { // Hide scope, no $ conflict
/* Countdown manager. */
function Countdown() {
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
// The display texts for the counters
labels: ['Năm', 'Tháng', 'Tuần', 'Ngày', 'Giờ', 'Phút', 'Giây'],
// The display texts for the counters if only one
labels1: ['Năm', 'Tháng', 'Tuần', 'Ngày', 'Giờ', 'Phút', 'Giây'],
compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
whichLabels: null, // Function to determine which labels to use
timeSeparator: ':', // Separator for time periods
isRTL: false // True for right-to-left languages, false for left-to-right
};
this._defaults = {
until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
// or numeric for seconds offset, or string for unit offset(s):
// 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from
// or numeric for seconds offset, or string for unit offset(s):
// 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
timezone: null, // The timezone (hours or minutes from GMT) for the target times,
// or null for client local
serverSync: null, // A function to retrieve the current server time for synchronisation
format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
// 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
layout: '', // Build your own layout for the countdown
compact: false, // True to display in a compact format, false for an expanded one
significant: 0, // The number of periods with values to show, zero for all
description: '', // The description displayed for the countdown
expiryUrl: '', // A URL to load upon expiry, replacing the current page
expiryText: '', // Text to display upon expiry, replacing the countdown
alwaysExpire: false, // True to trigger onExpiry even if never counted down
onExpiry: null, // Callback when the countdown expires -
// receives no parameters and 'this' is the containing division
onTick: null, // Callback when the countdown is updated -
// receives int[7] being the breakdown by period (based on format)
// and 'this' is the containing division
tickInterval: 1 // Interval (seconds) between onTick callbacks
};
$.extend(this._defaults, this.regional['']);
this._serverSyncs = [];
// Shared timer for all countdowns
function timerCallBack(timestamp) {
var drawStart = (timestamp || new Date().getTime());
if (drawStart - animationStartTime >= 1000) {
$.countdown._updateTargets();
animationStartTime = drawStart;
}
requestAnimationFrame(timerCallBack);
}
var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.oRequestAnimationFrame ||
window.msRequestAnimationFrame || null; // this is when we expect a fall-back to setInterval as it's much more fluid
var animationStartTime = 0;
if (!requestAnimationFrame) {
setInterval(function() { $.countdown._updateTargets(); }, 980); // Fall back to good old setInterval
}
else {
animationStartTime = window.mozAnimationStartTime || new Date().getTime();
requestAnimationFrame(timerCallBack);
}
}
var PROP_NAME = 'countdown';
var Y = 0; // Years
var O = 1; // Months
var W = 2; // Weeks
var D = 3; // Days
var H = 4; // Hours
var M = 5; // Minutes
var S = 6; // Seconds
$.extend(Countdown.prototype, {
/* Class name added to elements to indicate already configured with countdown. */
markerClassName: 'hasCountdown',
/* List of currently active countdown targets. */
_timerTargets: [],
/* Override the default settings for all instances of the countdown widget.
@param options (object) the new settings to use as defaults */
setDefaults: function(options) {
this._resetExtraLabels(this._defaults, options);
extendRemove(this._defaults, options || {});
},
/* Convert a date/time to UTC.
@param tz (number) the hour or minute offset from GMT, e.g. +9, -360
@param year (Date) the date/time in that timezone or
(number) the year in that timezone
@param month (number, optional) the month (0 - 11) (omit if year is a Date)
@param day (number, optional) the day (omit if year is a Date)
@param hours (number, optional) the hour (omit if year is a Date)
@param mins (number, optional) the minute (omit if year is a Date)
@param secs (number, optional) the second (omit if year is a Date)
@param ms (number, optional) the millisecond (omit if year is a Date)
@return (Date) the equivalent UTC date/time */
UTCDate: function(tz, year, month, day, hours, mins, secs, ms) {
if (typeof year == 'object' && year.constructor == Date) {
ms = year.getMilliseconds();
secs = year.getSeconds();
mins = year.getMinutes();
hours = year.getHours();
day = year.getDate();
month = year.getMonth();
year = year.getFullYear();
}
var d = new Date();
d.setUTCFullYear(year);
d.setUTCDate(1);
d.setUTCMonth(month || 0);
d.setUTCDate(day || 1);
d.setUTCHours(hours || 0);
d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz));
d.setUTCSeconds(secs || 0);
d.setUTCMilliseconds(ms || 0);
return d;
},
/* Convert a set of periods into seconds.
Averaged for months and years.
@param periods (number[7]) the periods per year/month/week/day/hour/minute/second
@return (number) the corresponding number of seconds */
periodsToSeconds: function(periods) {
return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 +
periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6];
},
/* Retrieve one or more settings values.
@param name (string, optional) the name of the setting to retrieve
or 'all' for all instance settings or omit for all default settings
@return (any) the requested setting(s) */
_settingsCountdown: function(target, name) {
if (!name) {
return $.countdown._defaults;
}
var inst = $.data(target, PROP_NAME);
return (name == 'all' ? inst.options : inst.options[name]);
},
/* Attach the countdown widget to a div.
@param target (element) the containing division
@param options (object) the initial settings for the countdown */
_attachCountdown: function(target, options) {
var $target = $(target);
if ($target.hasClass(this.markerClassName)) {
return;
}
$target.addClass(this.markerClassName);
var inst = {options: $.extend({}, options),
_periods: [0, 0, 0, 0, 0, 0, 0]};
$.data(target, PROP_NAME, inst);
this._changeCountdown(target);
},
/* Add a target to the list of active ones.
@param target (element) the countdown target */
_addTarget: function(target) {
if (!this._hasTarget(target)) {
this._timerTargets.push(target);
}
},
/* See if a target is in the list of active ones.
@param target (element) the countdown target
@return (boolean) true if present, false if not */
_hasTarget: function(target) {
return ($.inArray(target, this._timerTargets) > -1);
},
/* Remove a target from the list of active ones.
@param target (element) the countdown target */
_removeTarget: function(target) {
this._timerTargets = $.map(this._timerTargets,
function(value) { return (value == target ? null : value); }); // delete entry
},
/* Update each active timer target. */
_updateTargets: function() {
for (var i = this._timerTargets.length - 1; i >= 0; i--) {
this._updateCountdown(this._timerTargets[i]);
}
},
/* Redisplay the countdown with an updated display.
@param target (jQuery) the containing division
@param inst (object) the current settings for this instance */
_updateCountdown: function(target, inst) {
var $target = $(target);
inst = inst || $.data(target, PROP_NAME);
if (!inst) {
return;
}
$target.html(this._generateHTML(inst));
$target[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('countdown_rtl');
var onTick = this._get(inst, 'onTick');
if (onTick) {
var periods = inst._hold != 'lap' ? inst._periods :
this._calculatePeriods(inst, inst._show, this._get(inst, 'significant'), new Date());
var tickInterval = this._get(inst, 'tickInterval');
if (tickInterval == 1 || this.periodsToSeconds(periods) % tickInterval == 0) {
onTick.apply(target, [periods]);
}
}
var expired = inst._hold != 'pause' &&
(inst._since ? inst._now.getTime() < inst._since.getTime() :
inst._now.getTime() >= inst._until.getTime());
if (expired && !inst._expiring) {
inst._expiring = true;
if (this._hasTarget(target) || this._get(inst, 'alwaysExpire')) {
this._removeTarget(target);
var onExpiry = this._get(inst, 'onExpiry');
if (onExpiry) {
onExpiry.apply(target, []);
}
var expiryText = this._get(inst, 'expiryText');
if (expiryText) {
var layout = this._get(inst, 'layout');
inst.options.layout = expiryText;
this._updateCountdown(target, inst);
inst.options.layout = layout;
}
var expiryUrl = this._get(inst, 'expiryUrl');
if (expiryUrl) {
window.location = expiryUrl;
}
}
inst._expiring = false;
}
else if (inst._hold == 'pause') {
this._removeTarget(target);
}
$.data(target, PROP_NAME, inst);
},
/* Reconfigure the settings for a countdown div.
@param target (element) the containing division
@param options (object) the new settings for the countdown or
(string) an individual property name
@param value (any) the individual property value
(omit if options is an object) */
_changeCountdown: function(target, options, value) {
options = options || {};
if (typeof options == 'string') {
var name = options;
options = {};
options[name] = value;
}
var inst = $.data(target, PROP_NAME);
if (inst) {
this._resetExtraLabels(inst.options, options);
extendRemove(inst.options, options);
this._adjustSettings(target, inst);
$.data(target, PROP_NAME, inst);
var now = new Date();
if ((inst._since && inst._since < now) ||
(inst._until && inst._until > now)) {
this._addTarget(target);
}
this._updateCountdown(target, inst);
}
},
/* Reset any extra labelsn and compactLabelsn entries if changing labels.
@param base (object) the options to be updated
@param options (object) the new option values */
_resetExtraLabels: function(base, options) {
var changingLabels = false;
for (var n in options) {
if (n != 'whichLabels' && n.match(/[Ll]abels/)) {
changingLabels = true;
break;
}
}
if (changingLabels) {
for (var n in base) { // Remove custom numbered labels
if (n.match(/[Ll]abels[0-9]/)) {
base[n] = null;
}
}
}
},
/* Calculate interal settings for an instance.
@param target (element) the containing division
@param inst (object) the current settings for this instance */
_adjustSettings: function(target, inst) {
var now;
var serverSync = this._get(inst, 'serverSync');
var serverOffset = 0;
var serverEntry = null;
for (var i = 0; i < this._serverSyncs.length; i++) {
if (this._serverSyncs[i][0] == serverSync) {
serverEntry = this._serverSyncs[i][1];
break;
}
}
if (serverEntry != null) {
serverOffset = (serverSync ? serverEntry : 0);
now = new Date();
}
else {
var serverResult = (serverSync ? serverSync.apply(target, []) : null);
now = new Date();
serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0);
this._serverSyncs.push([serverSync, serverOffset]);
}
var timezone = this._get(inst, 'timezone');
timezone = (timezone == null ? -now.getTimezoneOffset() : timezone);
inst._since = this._get(inst, 'since');
if (inst._since != null) {
inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null));
if (inst._since && serverOffset) {
inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset);
}
}
inst._until = this.UTCDate(timezone, this._determineTime(this._get(inst, 'until'), now));
if (serverOffset) {
inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset);
}
inst._show = this._determineShow(inst);
},
/* Remove the countdown widget from a div.
@param target (element) the containing division */
_destroyCountdown: function(target) {
var $target = $(target);
if (!$target.hasClass(this.markerClassName)) {
return;
}
this._removeTarget(target);
$target.removeClass(this.markerClassName).empty();
$.removeData(target, PROP_NAME);
},
/* Pause a countdown widget at the current time.
Stop it running but remember and display the current time.
@param target (element) the containing division */
_pauseCountdown: function(target) {
this._hold(target, 'pause');
},
/* Pause a countdown widget at the current time.
Stop the display but keep the countdown running.
@param target (element) the containing division */
_lapCountdown: function(target) {
this._hold(target, 'lap');
},
/* Resume a paused countdown widget.
@param target (element) the containing division */
_resumeCountdown: function(target) {
this._hold(target, null);
},
/* Pause or resume a countdown widget.
@param target (element) the containing division
@param hold (string) the new hold setting */
_hold: function(target, hold) {
var inst = $.data(target, PROP_NAME);
if (inst) {
if (inst._hold == 'pause' && !hold) {
inst._periods = inst._savePeriods;
var sign = (inst._since ? '-' : '+');
inst[inst._since ? '_since' : '_until'] =
this._determineTime(sign + inst._periods[0] + 'y' +
sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' +
sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' +
sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's');
this._addTarget(target);
}
inst._hold = hold;
inst._savePeriods = (hold == 'pause' ? inst._periods : null);
$.data(target, PROP_NAME, inst);
this._updateCountdown(target, inst);
}
},
/* Return the current time periods.
@param target (element) the containing division
@return (number[7]) the current periods for the countdown */
_getTimesCountdown: function(target) {
var inst = $.data(target, PROP_NAME);
return (!inst ? null : (!inst._hold ? inst._periods :
this._calculatePeriods(inst, inst._show, this._get(inst, 'significant'), new Date())));
},
/* Get a setting value, defaulting if necessary.
@param inst (object) the current settings for this instance
@param name (string) the name of the required setting
@return (any) the setting's value or a default if not overridden */
_get: function(inst, name) {
return (inst.options[name] != null ?
inst.options[name] : $.countdown._defaults[name]);
},
/* A time may be specified as an exact value or a relative one.
@param setting (string or number or Date) - the date/time value
as a relative or absolute value
@param defaultTime (Date) the date/time to use if no other is supplied
@return (Date) the corresponding date/time */
_determineTime: function(setting, defaultTime) {
var offsetNumeric = function(offset) { // e.g. +300, -2
var time = new Date();
time.setTime(time.getTime() + offset * 1000);
return time;
};
var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m'
offset = offset.toLowerCase();
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth();
var day = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g;
var matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || 's') {
case 's': second += parseInt(matches[1], 10); break;
case 'm': minute += parseInt(matches[1], 10); break;
case 'h': hour += parseInt(matches[1], 10); break;
case 'd': day += parseInt(matches[1], 10); break;
case 'w': day += parseInt(matches[1], 10) * 7; break;
case 'o':
month += parseInt(matches[1], 10);
day = Math.min(day, $.countdown._getDaysInMonth(year, month));
break;
case 'y':
year += parseInt(matches[1], 10);
day = Math.min(day, $.countdown._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day, hour, minute, second, 0);
};
var time = (setting == null ? defaultTime :
(typeof setting == 'string' ? offsetString(setting) :
(typeof setting == 'number' ? offsetNumeric(setting) : setting)));
if (time) time.setMilliseconds(0);
return time;
},
/* Determine the number of days in a month.
@param year (number) the year
@param month (number) the month
@return (number) the days in that month */
_getDaysInMonth: function(year, month) {
return 32 - new Date(year, month, 32).getDate();
},
/* Determine which set of labels should be used for an amount.
@param num (number) the amount to be displayed
@return (number) the set of labels to be used for this amount */
_normalLabels: function(num) {
return num;
},
/* Generate the HTML to display the countdown widget.
@param inst (object) the current settings for this instance
@return (string) the new HTML for the countdown display */
_generateHTML: function(inst) {
// Determine what to show
var significant = this._get(inst, 'significant');
inst._periods = (inst._hold ? inst._periods :
this._calculatePeriods(inst, inst._show, significant, new Date()));
// Show all 'asNeeded' after first non-zero value
var shownNonZero = false;
var showCount = 0;
var sigCount = significant;
var show = $.extend({}, inst._show);
for (var period = Y; period <= S; period++) {
shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0);
show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]);
showCount += (show[period] ? 1 : 0);
sigCount -= (inst._periods[period] > 0 ? 1 : 0);
}
var showSignificant = [false, false, false, false, false, false, false];
for (var period = S; period >= Y; period--) { // Determine significant periods
if (inst._show[period]) {
if (inst._periods[period]) {
showSignificant[period] = true;
}
else {
showSignificant[period] = sigCount > 0;
sigCount--;
}
}
}
var compact = this._get(inst, 'compact');
var layout = this._get(inst, 'layout');
var labels = (compact ? this._get(inst, 'compactLabels') : this._get(inst, 'labels'));
var whichLabels = this._get(inst, 'whichLabels') || this._normalLabels;
var timeSeparator = this._get(inst, 'timeSeparator');
var description = this._get(inst, 'description') || '';
var showCompact = function(period) {
var labelsNum = $.countdown._get(inst,
'compactLabels' + whichLabels(inst._periods[period]));
return (show[period] ? inst._periods[period] +
(labelsNum ? labelsNum[period] : labels[period]) + ' ' : '');
};
var showFull = function(period) {
var labelsNum = $.countdown._get(inst, 'labels' + whichLabels(inst._periods[period]));
return ((!significant && show[period]) || (significant && showSignificant[period]) ?
'<span class="countdown_section"><span class="countdown_amount">' +
inst._periods[period] + '</span><br/>' +
(labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
};
return (layout ? this._buildLayout(inst, show, layout, compact, significant, showSignificant) :
((compact ? // Compact version
'<span class="countdown_row countdown_amount' +
(inst._hold ? ' countdown_holding' : '') + '">' +
showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) +
(show[H] ? this._minDigits(inst._periods[H], 2) : '') +
(show[M] ? (show[H] ? timeSeparator : '') +
this._minDigits(inst._periods[M], 2) : '') +
(show[S] ? (show[H] || show[M] ? timeSeparator : '') +
this._minDigits(inst._periods[S], 2) : '') :
// Full version
'<span class="countdown_row countdown_show' + (significant || showCount) +
(inst._hold ? ' countdown_holding' : '') + '">' +
showFull(Y) + showFull(O) + showFull(W) + showFull(D) +
showFull(H) + showFull(M) + showFull(S)) + '</span>' +
(description ? '<span class="countdown_row countdown_descr">' + description + '</span>' : '')));
},
/* Construct a custom layout.
@param inst (object) the current settings for this instance
@param show (string[7]) flags indicating which periods are requested
@param layout (string) the customised layout
@param compact (boolean) true if using compact labels
@param significant (number) the number of periods with values to show, zero for all
@param showSignificant (boolean[7]) other periods to show for significance
@return (string) the custom HTML */
_buildLayout: function(inst, show, layout, compact, significant, showSignificant) {
var labels = this._get(inst, (compact ? 'compactLabels' : 'labels'));
var whichLabels = this._get(inst, 'whichLabels') || this._normalLabels;
var labelFor = function(index) {
return ($.countdown._get(inst,
(compact ? 'compactLabels' : 'labels') + whichLabels(inst._periods[index])) ||
labels)[index];
};
var digit = function(value, position) {
return Math.floor(value / position) % 10;
};
var subs = {desc: this._get(inst, 'description'), sep: this._get(inst, 'timeSeparator'),
yl: labelFor(Y), yn: inst._periods[Y], ynn: this._minDigits(inst._periods[Y], 2),
ynnn: this._minDigits(inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100),
y1000: digit(inst._periods[Y], 1000),
ol: labelFor(O), on: inst._periods[O], onn: this._minDigits(inst._periods[O], 2),
onnn: this._minDigits(inst._periods[O], 3), o1: digit(inst._periods[O], 1),
o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100),
o1000: digit(inst._periods[O], 1000),
wl: labelFor(W), wn: inst._periods[W], wnn: this._minDigits(inst._periods[W], 2),
wnnn: this._minDigits(inst._periods[W], 3), w1: digit(inst._periods[W], 1),
w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100),
w1000: digit(inst._periods[W], 1000),
dl: labelFor(D), dn: inst._periods[D], dnn: this._minDigits(inst._periods[D], 2),
dnnn: this._minDigits(inst._periods[D], 3), d1: digit(inst._periods[D], 1),
d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100),
d1000: digit(inst._periods[D], 1000),
hl: labelFor(H), hn: inst._periods[H], hnn: this._minDigits(inst._periods[H], 2),
hnnn: this._minDigits(inst._periods[H], 3), h1: digit(inst._periods[H], 1),
h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100),
h1000: digit(inst._periods[H], 1000),
ml: labelFor(M), mn: inst._periods[M], mnn: this._minDigits(inst._periods[M], 2),
mnnn: this._minDigits(inst._periods[M], 3), m1: digit(inst._periods[M], 1),
m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100),
m1000: digit(inst._periods[M], 1000),
sl: labelFor(S), sn: inst._periods[S], snn: this._minDigits(inst._periods[S], 2),
snnn: this._minDigits(inst._periods[S], 3), s1: digit(inst._periods[S], 1),
s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100),
s1000: digit(inst._periods[S], 1000)};
var html = layout;
// Replace period containers: {p<}...{p>}
for (var i = Y; i <= S; i++) {
var period = 'yowdhms'.charAt(i);
var re = new RegExp('\\{' + period + '<\\}(.*)\\{' + period + '>\\}', 'g');
html = html.replace(re, ((!significant && show[i]) ||
(significant && showSignificant[i]) ? '$1' : ''));
}
// Replace period values: {pn}
$.each(subs, function(n, v) {
var re = new RegExp('\\{' + n + '\\}', 'g');
html = html.replace(re, v);
});
return html;
},
/* Ensure a numeric value has at least n digits for display.
@param value (number) the value to display
@param len (number) the minimum length
@return (string) the display text */
_minDigits: function(value, len) {
value = '' + value;
if (value.length >= len) {
return value;
}
value = '0000000000' + value;
return value.substr(value.length - len);
},
/* Translate the format into flags for each period.
@param inst (object) the current settings for this instance
@return (string[7]) flags indicating which periods are requested (?) or
required (!) by year, month, week, day, hour, minute, second */
_determineShow: function(inst) {
var format = this._get(inst, 'format');
var show = [];
show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null));
show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null));
show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null));
show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null));
show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null));
show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null));
show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null));
return show;
},
/* Calculate the requested periods between now and the target time.
@param inst (object) the current settings for this instance
@param show (string[7]) flags indicating which periods are requested/required
@param significant (number) the number of periods with values to show, zero for all
@param now (Date) the current date and time
@return (number[7]) the current time periods (always positive)
by year, month, week, day, hour, minute, second */
_calculatePeriods: function(inst, show, significant, now) {
// Find endpoints
inst._now = now;
inst._now.setMilliseconds(0);
var until = new Date(inst._now.getTime());
if (inst._since) {
if (now.getTime() < inst._since.getTime()) {
inst._now = now = until;
}
else {
now = inst._since;
}
}
else {
until.setTime(inst._until.getTime());
if (now.getTime() > inst._until.getTime()) {
inst._now = now = until;
}
}
// Calculate differences by period
var periods = [0, 0, 0, 0, 0, 0, 0];
if (show[Y] || show[O]) {
// Treat end of months as the same
var lastNow = $.countdown._getDaysInMonth(now.getFullYear(), now.getMonth());
var lastUntil = $.countdown._getDaysInMonth(until.getFullYear(), until.getMonth());
var sameDay = (until.getDate() == now.getDate() ||
(until.getDate() >= Math.min(lastNow, lastUntil) &&
now.getDate() >= Math.min(lastNow, lastUntil)));
var getSecs = function(date) {
return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds();
};
var months = Math.max(0,
(until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() +
((until.getDate() < now.getDate() && !sameDay) ||
(sameDay && getSecs(until) < getSecs(now)) ? -1 : 0));
periods[Y] = (show[Y] ? Math.floor(months / 12) : 0);
periods[O] = (show[O] ? months - periods[Y] * 12 : 0);
// Adjust for months difference and end of month if necessary
now = new Date(now.getTime());
var wasLastDay = (now.getDate() == lastNow);
var lastDay = $.countdown._getDaysInMonth(now.getFullYear() + periods[Y],
now.getMonth() + periods[O]);
if (now.getDate() > lastDay) {
now.setDate(lastDay);
}
now.setFullYear(now.getFullYear() + periods[Y]);
now.setMonth(now.getMonth() + periods[O]);
if (wasLastDay) {
now.setDate(lastDay);
}
}
var diff = Math.floor((until.getTime() - now.getTime()) / 1000);
var extractPeriod = function(period, numSecs) {
periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0);
diff -= periods[period] * numSecs;
};
extractPeriod(W, 604800);
extractPeriod(D, 86400);
extractPeriod(H, 3600);
extractPeriod(M, 60);
extractPeriod(S, 1);
if (diff > 0 && !inst._since) { // Round up if left overs
var multiplier = [1, 12, 4.3482, 7, 24, 60, 60];
var lastShown = S;
var max = 1;
for (var period = S; period >= Y; period--) {
if (show[period]) {
if (periods[lastShown] >= max) {
periods[lastShown] = 0;
diff = 1;
}
if (diff > 0) {
periods[period]++;
diff = 0;
lastShown = period;
max = 1;
}
}
max *= multiplier[period];
}
}
if (significant) { // Zero out insignificant periods
for (var period = Y; period <= S; period++) {
if (significant && periods[period]) {
significant--;
}
else if (!significant) {
periods[period] = 0;
}
}
}
return periods;
}
});
/* jQuery extend now ignores nulls!
@param target (object) the object to update
@param props (object) the new settings
@return (object) the updated object */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = null;
}
}
return target;
}
/* Process the countdown functionality for a jQuery selection.
@param command (string) the command to run (optional, default 'attach')
@param options (object) the new settings to use for these countdown instances
@return (jQuery) for chaining further calls */
$.fn.countdown = function(options) {
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (options == 'getTimes' || options == 'settings') {
return $.countdown['_' + options + 'Countdown'].
apply($.countdown, [this[0]].concat(otherArgs));
}
return this.each(function() {
if (typeof options == 'string') {
$.countdown['_' + options + 'Countdown'].apply($.countdown, [this].concat(otherArgs));
}
else {
$.countdown._attachCountdown(this, options);
}
});
};
/* Initialise the countdown functionality. */
$.countdown = new Countdown(); // singleton instance
})(jQuery);
| JavaScript |
/*!
* jQuery corner plugin: simple corner rounding
* Examples and documentation at: http://jquery.malsup.com/corner/
* version 2.12 (23-MAY-2011)
* Requires jQuery v1.3.2 or later
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Authors: Dave Methvin and Mike Alsup
*/
/**
* corner() takes a single string argument: $('#myDiv').corner("effect corners width")
*
* effect: name of the effect to apply, such as round, bevel, notch, bite, etc (default is round).
* corners: one or more of: top, bottom, tr, tl, br, or bl. (default is all corners)
* width: width of the effect; in the case of rounded corners this is the radius.
* specify this value using the px suffix such as 10px (yes, it must be pixels).
*/
;(function($) {
var style = document.createElement('div').style,
moz = style['MozBorderRadius'] !== undefined,
webkit = style['WebkitBorderRadius'] !== undefined,
radius = style['borderRadius'] !== undefined || style['BorderRadius'] !== undefined,
mode = document.documentMode || 0,
noBottomFold = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8),
expr = $.browser.msie && (function() {
var div = document.createElement('div');
try { div.style.setExpression('width','0+0'); div.style.removeExpression('width'); }
catch(e) { return false; }
return true;
})();
$.support = $.support || {};
$.support.borderRadius = moz || webkit || radius; // so you can do: if (!$.support.borderRadius) $('#myDiv').corner();
function sz(el, p) {
return parseInt($.css(el,p))||0;
};
function hex2(s) {
s = parseInt(s).toString(16);
return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
while(node) {
var v = $.css(node,'backgroundColor'), rgb;
if (v && v != 'transparent' && v != 'rgba(0, 0, 0, 0)') {
if (v.indexOf('rgb') >= 0) {
rgb = v.match(/\d+/g);
return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
}
return v;
}
if (node.nodeName.toLowerCase() == 'html')
break;
node = node.parentNode; // keep walking if transparent
}
return '#ffffff';
};
function getWidth(fx, i, width) {
switch(fx) {
case 'round': return Math.round(width*(1-Math.cos(Math.asin(i/width))));
case 'cool': return Math.round(width*(1+Math.cos(Math.asin(i/width))));
case 'sharp': return width-i;
case 'bite': return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
case 'slide': return Math.round(width*(Math.atan2(i,width/i)));
case 'jut': return Math.round(width*(Math.atan2(width,(width-i-1))));
case 'curl': return Math.round(width*(Math.atan(i)));
case 'tear': return Math.round(width*(Math.cos(i)));
case 'wicked': return Math.round(width*(Math.tan(i)));
case 'long': return Math.round(width*(Math.sqrt(i)));
case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
case 'dogfold':
case 'dog': return (i&1) ? (i+1) : width;
case 'dog2': return (i&2) ? (i+1) : width;
case 'dog3': return (i&3) ? (i+1) : width;
case 'fray': return (i%2)*width;
case 'notch': return width;
case 'bevelfold':
case 'bevel': return i+1;
case 'steep': return i/2 + 1;
case 'invsteep':return (width-i)/2+1;
}
};
$.fn.corner = function(options) {
// in 1.3+ we can fix mistakes with the ready state
if (this.length == 0) {
if (!$.isReady && this.selector) {
var s = this.selector, c = this.context;
$(function() {
$(s,c).corner(options);
});
}
return this;
}
return this.each(function(index){
var $this = $(this),
// meta values override options
o = [$this.attr($.fn.corner.defaults.metaAttr) || '', options || ''].join(' ').toLowerCase(),
keep = /keep/.test(o), // keep borders?
cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]), // corner color
sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]), // strip color
width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10, // corner width
re = /round|bevelfold|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dogfold|dog|invsteep|steep/,
fx = ((o.match(re)||['round'])[0]),
fold = /dogfold|bevelfold/.test(o),
edges = { T:0, B:1 },
opts = {
TL: /top|tl|left/.test(o), TR: /top|tr|right/.test(o),
BL: /bottom|bl|left/.test(o), BR: /bottom|br|right/.test(o)
},
// vars used in func later
strip, pad, cssHeight, j, bot, d, ds, bw, i, w, e, c, common, $horz;
if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
opts = { TL:1, TR:1, BL:1, BR:1 };
// support native rounding
if ($.fn.corner.defaults.useNative && fx == 'round' && (radius || moz || webkit) && !cc && !sc) {
if (opts.TL)
$this.css(radius ? 'border-top-left-radius' : moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
if (opts.TR)
$this.css(radius ? 'border-top-right-radius' : moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
if (opts.BL)
$this.css(radius ? 'border-bottom-left-radius' : moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
if (opts.BR)
$this.css(radius ? 'border-bottom-right-radius' : moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
return;
}
strip = document.createElement('div');
$(strip).css({
overflow: 'hidden',
height: '1px',
minHeight: '1px',
fontSize: '1px',
backgroundColor: sc || 'transparent',
borderStyle: 'solid'
});
pad = {
T: parseInt($.css(this,'paddingTop'))||0, R: parseInt($.css(this,'paddingRight'))||0,
B: parseInt($.css(this,'paddingBottom'))||0, L: parseInt($.css(this,'paddingLeft'))||0
};
if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
if (!keep) this.style.border = 'none';
strip.style.borderColor = cc || gpc(this.parentNode);
cssHeight = $(this).outerHeight();
for (j in edges) {
bot = edges[j];
// only add stips if needed
if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
//strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
d = document.createElement('div');
$(d).addClass('jquery-corner');
ds = d.style;
try {
bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);
}
catch(e) { /* do nothing */ }
if (bot && cssHeight != 'auto') {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
ds.position = 'absolute';
ds.bottom = ds.left = ds.padding = ds.margin = '0';
if (expr)
ds.setExpression('width', 'this.parentNode.offsetWidth');
else
ds.width = '100%';
}
else if (!bot && $.browser.msie) {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
ds.position = 'absolute';
ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
// fix ie6 problem when blocked element has a border width
if (expr) {
bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
}
else
ds.width = '100%';
}
else {
ds.position = 'relative';
ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' :
(pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';
}
for (i=0; i < width; i++) {
w = Math.max(0,getWidth(fx,i, width));
e = strip.cloneNode(false);
e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
}
if (fold && $.support.boxModel) {
if (bot && noBottomFold) continue;
for (c in opts) {
if (!opts[c]) continue;
if (bot && (c == 'TL' || c == 'TR')) continue;
if (!bot && (c == 'BL' || c == 'BR')) continue;
common = { position: 'absolute', border: 'none', margin: 0, padding: 0, overflow: 'hidden', backgroundColor: strip.style.borderColor };
$horz = $('<div/>').css(common).css({ width: width + 'px', height: '1px' });
switch(c) {
case 'TL': $horz.css({ bottom: 0, left: 0 }); break;
case 'TR': $horz.css({ bottom: 0, right: 0 }); break;
case 'BL': $horz.css({ top: 0, left: 0 }); break;
case 'BR': $horz.css({ top: 0, right: 0 }); break;
}
d.appendChild($horz[0]);
var $vert = $('<div/>').css(common).css({ top: 0, bottom: 0, width: '1px', height: width + 'px' });
switch(c) {
case 'TL': $vert.css({ left: width }); break;
case 'TR': $vert.css({ right: width }); break;
case 'BL': $vert.css({ left: width }); break;
case 'BR': $vert.css({ right: width }); break;
}
d.appendChild($vert[0]);
}
}
}
}
});
};
$.fn.uncorner = function() {
if (radius || moz || webkit)
this.css(radius ? 'border-radius' : moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
$('div.jquery-corner', this).remove();
return this;
};
// expose options
$.fn.corner.defaults = {
useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
metaAttr: 'data-corner' // name of meta attribute to use for options
};
})(jQuery);
| JavaScript |
/*
* jPlayerInspector Plugin for jPlayer Plugin for jQuery JavaScript Library
* http://www.jplayer.org
*
* Copyright (c) 2009 - 2013 Happyworm Ltd
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
*
* Author: Mark J Panaghiston
* Version: 1.0.4
* Date: 29th January 2013
*
* For use with jPlayer Version: 2.2.19+
*
* Note: Declare inspector instances after jPlayer instances. ie., Otherwise the jPlayer instance is nonsense.
*/
(function($, undefined) {
$.jPlayerInspector = {};
$.jPlayerInspector.i = 0;
$.jPlayerInspector.defaults = {
jPlayer: undefined, // The jQuery selector of the jPlayer instance to inspect.
idPrefix: "jplayer_inspector_",
visible: false
};
var methods = {
init: function(options) {
var self = this;
var $this = $(this);
var config = $.extend({}, $.jPlayerInspector.defaults, options);
$(this).data("jPlayerInspector", config);
config.id = $(this).attr("id");
config.jPlayerId = config.jPlayer.attr("id");
config.windowId = config.idPrefix + "window_" + $.jPlayerInspector.i;
config.statusId = config.idPrefix + "status_" + $.jPlayerInspector.i;
config.configId = config.idPrefix + "config_" + $.jPlayerInspector.i;
config.toggleId = config.idPrefix + "toggle_" + $.jPlayerInspector.i;
config.eventResetId = config.idPrefix + "event_reset_" + $.jPlayerInspector.i;
config.updateId = config.idPrefix + "update_" + $.jPlayerInspector.i;
config.eventWindowId = config.idPrefix + "event_window_" + $.jPlayerInspector.i;
config.eventId = {};
config.eventJq = {};
config.eventTimeout = {};
config.eventOccurrence = {};
$.each($.jPlayer.event, function(eventName,eventType) {
config.eventId[eventType] = config.idPrefix + "event_" + eventName + "_" + $.jPlayerInspector.i;
config.eventOccurrence[eventType] = 0;
});
var structure =
'<p><a href="#" id="' + config.toggleId + '">' + (config.visible ? "Hide" : "Show") + '</a> jPlayer Inspector</p>'
+ '<div id="' + config.windowId + '">'
+ '<div id="' + config.statusId + '"></div>'
+ '<div id="' + config.eventWindowId + '" style="padding:5px 5px 0 5px;background-color:#eee;border:1px dotted #000;">'
+ '<p style="margin:0 0 10px 0;"><strong>jPlayer events that have occurred over the past 1 second:</strong>'
+ '<br />(Backgrounds: <span style="padding:0 5px;background-color:#eee;border:1px dotted #000;">Never occurred</span> <span style="padding:0 5px;background-color:#fff;border:1px dotted #000;">Occurred before</span> <span style="padding:0 5px;background-color:#9f9;border:1px dotted #000;">Occurred</span> <span style="padding:0 5px;background-color:#ff9;border:1px dotted #000;">Multiple occurrences</span> <a href="#" id="' + config.eventResetId + '">reset</a>)</p>';
// MJP: Would use the next 3 lines for ease, but the events are just slapped on the page.
// $.each($.jPlayer.event, function(eventName,eventType) {
// structure += '<div id="' + config.eventId[eventType] + '" style="float:left;">' + eventName + '</div>';
// });
var eventStyle = "float:left;margin:0 5px 5px 0;padding:0 5px;border:1px dotted #000;";
// MJP: Doing it longhand so order and layout easier to control.
structure +=
'<div id="' + config.eventId[$.jPlayer.event.ready] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.flashreset] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.resize] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.repeat] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.click] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.error] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.warning] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.loadstart] + '" style="clear:left;' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.progress] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.timeupdate] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.volumechange] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.play] + '" style="clear:left;' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.pause] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.waiting] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.playing] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.seeking] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.seeked] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.ended] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.loadeddata] + '" style="clear:left;' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.loadedmetadata] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.canplay] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.canplaythrough] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.suspend] + '" style="clear:left;' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.abort] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.emptied] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.stalled] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.ratechange] + '" style="' + eventStyle + '"></div>'
+ '<div id="' + config.eventId[$.jPlayer.event.durationchange] + '" style="' + eventStyle + '"></div>'
+ '<div style="clear:both"></div>';
// MJP: Would like a check here in case we missed an event.
// MJP: Check fails, since it is not on the page yet.
/* $.each($.jPlayer.event, function(eventName,eventType) {
if($("#" + config.eventId[eventType])[0] === undefined) {
structure += '<div id="' + config.eventId[eventType] + '" style="clear:left;' + eventStyle + '">' + eventName + '</div>';
}
});
*/
structure +=
'</div>'
+ '<p><a href="#" id="' + config.updateId + '">Update</a> jPlayer Inspector</p>'
+ '<div id="' + config.configId + '"></div>'
+ '</div>';
$(this).html(structure);
config.windowJq = $("#" + config.windowId);
config.statusJq = $("#" + config.statusId);
config.configJq = $("#" + config.configId);
config.toggleJq = $("#" + config.toggleId);
config.eventResetJq = $("#" + config.eventResetId);
config.updateJq = $("#" + config.updateId);
$.each($.jPlayer.event, function(eventName,eventType) {
config.eventJq[eventType] = $("#" + config.eventId[eventType]);
config.eventJq[eventType].text(eventName + " (" + config.eventOccurrence[eventType] + ")"); // Sets the text to the event name and (0);
config.jPlayer.bind(eventType + ".jPlayerInspector", function(e) {
config.eventOccurrence[e.type]++;
if(config.eventOccurrence[e.type] > 1) {
config.eventJq[e.type].css("background-color","#ff9");
} else {
config.eventJq[e.type].css("background-color","#9f9");
}
config.eventJq[e.type].text(eventName + " (" + config.eventOccurrence[e.type] + ")");
// The timer to handle the color
clearTimeout(config.eventTimeout[e.type]);
config.eventTimeout[e.type] = setTimeout(function() {
config.eventJq[e.type].css("background-color","#fff");
}, 1000);
// The timer to handle the occurences.
setTimeout(function() {
config.eventOccurrence[e.type]--;
config.eventJq[e.type].text(eventName + " (" + config.eventOccurrence[e.type] + ")");
}, 1000);
if(config.visible) { // Update the status, if inspector open.
$this.jPlayerInspector("updateStatus");
}
});
});
config.jPlayer.bind($.jPlayer.event.ready + ".jPlayerInspector", function(e) {
$this.jPlayerInspector("updateConfig");
});
config.toggleJq.click(function() {
if(config.visible) {
$(this).text("Show");
config.windowJq.hide();
config.statusJq.empty();
config.configJq.empty();
} else {
$(this).text("Hide");
config.windowJq.show();
config.updateJq.click();
}
config.visible = !config.visible;
$(this).blur();
return false;
});
config.eventResetJq.click(function() {
$.each($.jPlayer.event, function(eventName,eventType) {
config.eventJq[eventType].css("background-color","#eee");
});
$(this).blur();
return false;
});
config.updateJq.click(function() {
$this.jPlayerInspector("updateStatus");
$this.jPlayerInspector("updateConfig");
return false;
});
if(!config.visible) {
config.windowJq.hide();
} else {
// config.updateJq.click();
}
$.jPlayerInspector.i++;
return this;
},
destroy: function() {
$(this).data("jPlayerInspector") && $(this).data("jPlayerInspector").jPlayer.unbind(".jPlayerInspector");
$(this).empty();
},
updateConfig: function() { // This displays information about jPlayer's configuration in inspector
var jPlayerInfo = "<p>This jPlayer instance is running in your browser where:<br />"
for(i = 0; i < $(this).data("jPlayerInspector").jPlayer.data("jPlayer").solutions.length; i++) {
var solution = $(this).data("jPlayerInspector").jPlayer.data("jPlayer").solutions[i];
jPlayerInfo += " jPlayer's <strong>" + solution + "</strong> solution is";
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer")[solution].used) {
jPlayerInfo += " being <strong>used</strong> and will support:<strong>";
for(format in $(this).data("jPlayerInspector").jPlayer.data("jPlayer")[solution].support) {
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer")[solution].support[format]) {
jPlayerInfo += " " + format;
}
}
jPlayerInfo += "</strong><br />";
} else {
jPlayerInfo += " <strong>not required</strong><br />";
}
}
jPlayerInfo += "</p>";
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer").html.active) {
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer").flash.active) {
jPlayerInfo += "<strong>Problem with jPlayer since both HTML5 and Flash are active.</strong>";
} else {
jPlayerInfo += "The <strong>HTML5 is active</strong>.";
}
} else {
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer").flash.active) {
jPlayerInfo += "The <strong>Flash is active</strong>.";
} else {
jPlayerInfo += "No solution is currently active. jPlayer needs a setMedia().";
}
}
jPlayerInfo += "</p>";
var formatType = $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.formatType;
jPlayerInfo += "<p><code>status.formatType = '" + formatType + "'</code><br />";
if(formatType) {
jPlayerInfo += "<code>Browser canPlay('" + $.jPlayer.prototype.format[formatType].codec + "')</code>";
} else {
jPlayerInfo += "</p>";
}
jPlayerInfo += "<p><code>status.src = '" + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.src + "'</code></p>";
jPlayerInfo += "<p><code>status.media = {<br />";
for(prop in $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.media) {
jPlayerInfo += " " + prop + ": " + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.media[prop] + "<br />"; // Some are strings
}
jPlayerInfo += "};</code></p>"
jPlayerInfo += "<p>";
jPlayerInfo += "<code>status.videoWidth = '" + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.videoWidth + "'</code>";
jPlayerInfo += " | <code>status.videoHeight = '" + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.videoHeight + "'</code>";
jPlayerInfo += "<br /><code>status.width = '" + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.width + "'</code>";
jPlayerInfo += " | <code>status.height = '" + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.height + "'</code>";
jPlayerInfo += "</p>";
+ "<p>Raw browser test for HTML5 support. Should equal a function if HTML5 is available.<br />";
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer").html.audio.available) {
jPlayerInfo += "<code>htmlElement.audio.canPlayType = " + (typeof $(this).data("jPlayerInspector").jPlayer.data("jPlayer").htmlElement.audio.canPlayType) +"</code><br />"
}
if($(this).data("jPlayerInspector").jPlayer.data("jPlayer").html.video.available) {
jPlayerInfo += "<code>htmlElement.video.canPlayType = " + (typeof $(this).data("jPlayerInspector").jPlayer.data("jPlayer").htmlElement.video.canPlayType) +"</code>";
}
jPlayerInfo += "</p>";
jPlayerInfo += "<p>This instance is using the constructor options:<br />"
+ "<code>$('#" + $(this).data("jPlayerInspector").jPlayer.data("jPlayer").internal.self.id + "').jPlayer({<br />"
+ " swfPath: '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "swfPath") + "',<br />"
+ " solution: '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "solution") + "',<br />"
+ " supplied: '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "supplied") + "',<br />"
+ " preload: '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "preload") + "',<br />"
+ " volume: " + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "volume") + ",<br />"
+ " muted: " + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "muted") + ",<br />"
+ " backgroundColor: '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "backgroundColor") + "',<br />"
+ " cssSelectorAncestor: '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "cssSelectorAncestor") + "',<br />"
+ " cssSelector: {";
var cssSelector = $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "cssSelector");
for(prop in cssSelector) {
// jPlayerInfo += "<br /> " + prop + ": '" + cssSelector[prop] + "'," // This works too of course, but want to use option method for deep keys.
jPlayerInfo += "<br /> " + prop + ": '" + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "cssSelector." + prop) + "',"
}
jPlayerInfo = jPlayerInfo.slice(0, -1); // Because the sloppy comma was bugging me.
jPlayerInfo += "<br /> },<br />"
+ " errorAlerts: " + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "errorAlerts") + ",<br />"
+ " warningAlerts: " + $(this).data("jPlayerInspector").jPlayer.jPlayer("option", "warningAlerts") + "<br />"
+ "});</code></p>";
$(this).data("jPlayerInspector").configJq.html(jPlayerInfo);
return this;
},
updateStatus: function() { // This displays information about jPlayer's status in the inspector
$(this).data("jPlayerInspector").statusJq.html(
"<p>jPlayer is " +
($(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.paused ? "paused" : "playing") +
" at time: " + Math.floor($(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.currentTime*10)/10 + "s." +
" (d: " + Math.floor($(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.duration*10)/10 + "s" +
", sp: " + Math.floor($(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.seekPercent) + "%" +
", cpr: " + Math.floor($(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.currentPercentRelative) + "%" +
", cpa: " + Math.floor($(this).data("jPlayerInspector").jPlayer.data("jPlayer").status.currentPercentAbsolute) + "%)</p>"
);
return this;
}
};
$.fn.jPlayerInspector = function( method ) {
// Method calling logic
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.jPlayerInspector' );
}
};
})(jQuery);
| JavaScript |
document.write('<script src="http://connect.facebook.net/en_US/all.js"></script>');
var FB_LoginUrl= 'http://www.facebook.com/dialog/oauth?client_id=579561022109158&redirect_uri=http://www.c2life.com.vn/smart_phone/OpenId&response_type=token&display=popup&scope=email,manage_pages,photo_upload,publish_actions,publish_stream,read_friendlists,status_update,user_birthday,user_photos,user_status,video_upload';
var windowInvite;
function FB_LOGIN(){
window.location = FB_LoginUrl;
}
function check_info()
{
var url = root + 'smart_phone/view_check_login';
$.post(url,{
},
function(data){
if(data == "false")
{
FB_LOGIN();
}
else
{
checkFirstTime();
}
});
return false;
}
function checkFirstTime(){
var url = root + 'smart_phone/view_check_first_time';
$.post(url,{
},
function(data){
if(data == "true")
{
getInfo();
}
if(data == "false")
{
nex_page(1);
}
});
return false;
}
function getInfo()
{
var url = root + 'smart_phone/view_get_info';
$.post(url,{
},
function(data){
if(data)
{
$(".tab-register").html(data);
nex_page(2);
}
});
return false;
}
function select_link()
{
var url = root + 'smart_phone/view_code';
var type =$(".check_value").val();
$.post(url,{ type:type
},
function(data){
if(data)
{
$(".tab-noti").html(data);
nex_page(0);
}
});
return false;
}
function update_info()
{
var fullname =$(".fullname").val();
var phone =$(".phone").val();
var email =$(".email").val();
var url = root + 'smart_phone/view_update_info';
$.post(url,{ fullname:fullname,phone:phone
},
function(data){
if(data == "true")
{
nex_page(1);
}
});
return false;
}
// global properties
var stage;
var currentTick = 0;
var arrayImages = new Array();
var loadedImgNumber = 0;
// for welcome screen
var loadingC2Img;
var loadingTextImg;
var loadingMusicImg;
// for other screen
var stageSprite;
var topLightImgs;
var logoSprite;
var welcomeCha;
var tvcCha;
// for character lap
var welcomeLapSpite;
var tvcStartSpite;
var tvcLapSpite;
var tickTVC = -1;
// audio
var myCirclePlayer;
var myOtherOne;
/**
* Init handler
*/
$(document).ready(function () {
log("Width: " + window.innerWidth + " - Height: " + window.innerHeight + "- Ratio: " + window.devicePixelRatio);
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode(
"@-ms-viewport{width:auto!important}"
)
);
document.getElementsByTagName("head")[0].
appendChild(msViewportStyle);
}
initLoadingScreen();
$("#btnHome").click(welcomeVideoStart);
$("#btnVideo").click(tvcVideoStart);
$("#btnMusic").click(fullsongVideoStart);
$("#btnShare").click(showshareStart);
$('#page-mp3').html('<img src="'+ root +'static/images/mobile/videotrangmp3_07504.gif" alt="" width="430" height="450" />').hide();
$("#sound-welcom").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", {
m4a: root + "static/images/mobile/Welcome.m4a",
oga: root + "static/images/mobile/Welcome.ogg"
});
},
swfPath: "js",
supplied: "m4a, oga",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true,
nativeSupport: true,
oggSupport: false,
loop: true,
customCssIds: true
});
$("#sound-mp3").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", {
m4a: root + "static/images/mobile/videotrangmp3.mp3",
oga: root + "static/images/mobile/videotrangmp3.ogg"
});
},
swfPath: "js",
supplied: "m4a, oga",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true,
nativeSupport: true,
oggSupport: false,
loop: true,
customCssIds: true
});
$("#btnNext").click(function () {
$(".buttonNext").hide();
startMainScreen();
$("#sound-welcom").jPlayer("play");
$('#welcom').html('<img src="'+ root +'static/images/mobile/Welcome.gif" alt="" width="306" height="500" />');
});
$('.btn-video').on('click',function(){
$(this).removeClass('unactive').addClass('active');
$('.btn-zing').removeClass('active').addClass('unactive');
$(".check_value").val("1");
});
$('.btn-zing').on('click',function(){
$(this).removeClass('unactive').addClass('active');
$('.btn-video').removeClass('active').addClass('unactive');
$(".check_value").val("2");
});
$(window).load(function(){
// var myScroll = new iScroll('iscroll-giaithuong');
// myScroll_1 = new iScroll('iscroll-week-1');
// myScroll_2 = new iScroll('iscroll-week-2');
// myScroll_3 = new iScroll('iscroll-week-3');
// myScroll_4 = new iScroll('iscroll-week-4');
});
$('.btn-week').on('click',function(){
if($(this).hasClass('disable') || $(this).hasClass('active')){
return false;
}
$('.btn-week').removeClass('active');
$(this).addClass('active');
var index = $('.btn-week').index(this) + 1;
$('.iscroll-week').hide();
$('#iscroll-week-'+index).show();
return false;
});
});
var ischeck = true;
var ischeck1 = true;
function nex_page(id){
$('.content-share > div').hide();
$('.content-share > div').eq(id).show();
if(!$('.tab-giaithuong').is(':hidden') && ischeck){
var myScroll = new iScroll('iscroll-giaithuong');
ischeck = false;
}
}
/**
* Init welcome handler
*/
function initLoadingScreen() {
arrayImages[0] = new Image();
arrayImages[0].onload = handleLoadingImageLoad;
arrayImages[0].onerror = handleImageError;
arrayImages[0].src = root + "static/images/mobile/Chai_C2.png";
arrayImages[1] = new Image();
arrayImages[1].onload = handleLoadingImageLoad;
arrayImages[1].onerror = handleImageError;
arrayImages[1].src = root + "static/images/mobile/music.png";
arrayImages[2] = new Image();
arrayImages[2].onload = handleLoadingImageLoad;
arrayImages[2].onerror = handleImageError;
arrayImages[2].src = root + "static/images/mobile/loading.png";
}
/**
* Handle loading image for welcome
*/
function handleLoadingImageLoad(e) {
loadedImgNumber++;
if (loadedImgNumber == 3) {
startWelcomeScreen();
}
}
/**
* Handle loading error
*/
function handleImageError(e) {
log("Error Loading Image : " + e.target.src);
}
/**
* Initilale Welcome Screen
*/
function startWelcomeScreen() {
$(".buttons").show();
$(".loading").hide();
var canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
loadingC2Img = new createjs.Bitmap(arrayImages[0]);
loadingC2Img.regX = 85;
loadingC2Img.regY = 460;
loadingC2Img.x = 320;
loadingC2Img.y = 650;
stage.addChild(loadingC2Img);
loadingMusicImg = new createjs.Bitmap(arrayImages[1]);
loadingMusicImg.regX = 85;
loadingMusicImg.regY = 217;
loadingMusicImg.x = 320;
loadingMusicImg.y = 150;
stage.addChild(loadingMusicImg);
loadingTextImg = new createjs.Bitmap(arrayImages[2]);
loadingTextImg.regX = 87;
loadingTextImg.regY = 30;
loadingTextImg.x = 320;
loadingTextImg.y = 150;
stage.addChild(loadingTextImg);
createjs.Ticker.setFPS(12);
createjs.Ticker.addEventListener("tick", tickLoading);
initMainScreen();
}
/**
* Tick Handler
*/
var angle = 5;
function tickLoading() {
currentTick += 1;
loadingC2Img.rotation += angle;
if (loadingC2Img.rotation == 10)
angle = -5;
else if (loadingC2Img.rotation == -10)
angle = 5;
if (loadingMusicImg.y > 0)
loadingMusicImg.y -= 13;
else {
if (currentTick == 1) {
loadingMusicImg.y = 150;
}
}
if (currentTick > 12)
currentTick = 0;
stage.update();
}
/**
* Handle loading image for main stage
*/
function initMainScreen() {
arrayImages[3] = new Image();
arrayImages[3].onload = handleImageLoad;
arrayImages[3].onerror = handleImageError;
arrayImages[3].src = root + "static/images/mobile/light.png";
arrayImages[4] = new Image();
arrayImages[4].onload = handleImageLoad;
arrayImages[4].onerror = handleImageError;
arrayImages[4].src = root + "static/images/mobile/logo.png";
arrayImages[5] = new Image();
arrayImages[5].onload = handleImageLoad;
arrayImages[5].onerror = handleImageError;
arrayImages[5].src = root + "static/images/mobile/stage.png";
arrayImages[6] = new Image();
arrayImages[6].onload = handleImageLoad;
arrayImages[6].onerror = handleImageError;
arrayImages[6].src = root + "static/images/mobile/welcome_lap_SH.png";
arrayImages[7] = new Image();
arrayImages[7].onload = handleImageLoad;
arrayImages[7].onerror = handleImageError;
arrayImages[7].src = root + "static/images/mobile/startTvc_S.png";
arrayImages[8] = new Image();
arrayImages[8].onload = handleImageLoad;
arrayImages[8].onerror = handleImageError;
arrayImages[8].src = root + "static/images/mobile/tvclap.png";
arrayImages[9] = new Image();
arrayImages[9].onload = handleImageLoad;
arrayImages[9].onerror = handleImageError;
arrayImages[9].src = root + "static/images/mobile/Welcome.gif";
arrayImages[10] = new Image();
arrayImages[10].onload = handleImageLoad;
arrayImages[10].onerror = handleImageError;
arrayImages[10].src = root + "static/images/mobile/videotrangmp3_07504.gif";
tvcSound =new mProton.Sound(root + "static/images/mobile/tvc.mp3", 0, handleImageLoad);
}
/**
* Handle loading image for main stage
*/
function handleImageLoad(e) {
loadedImgNumber++;
if (loadedImgNumber == 11) {
reset();
$(".buttonNext").show();
}
}
/**
* Initilale Main Screen
*/
function startMainScreen() {
reset();
stage = new createjs.Stage(canvas);
log("Start main stage");
log("Add stage");
var stageSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[5]],
//width, height & registration point of each sprite
frames: [
[0, 1, 1020, 120],
[0, 1, 1020, 120],
[0, 1, 1020, 120],
[0, 121, 1020, 120],
[0, 121, 1020, 120],
[0, 121, 1020, 120],
[0, 241, 1020, 120],
[0, 241, 1020, 120],
[0, 241, 1020, 120],
[0, 361, 1020, 120],
[0, 361, 1020, 120],
[0, 361, 1020, 120]
],
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
stageanimation: [0, 11, "stageanimation"]
}
});
stageSprite = new createjs.BitmapAnimation(stageSpriteSheet);
stageSprite.x = -194;
stageSprite.y = 607;
stageSprite.gotoAndPlay("stageanimation");
stage.addChild(stageSprite);
log("Add light");
topLightImgs = new Array();
var positionLeft = 110;
for (var i = 0; i < 3; i++) {
topLightImgs[i] = new createjs.Bitmap(arrayImages[3]);
topLightImgs[i].regX = 225;
topLightImgs[i].regY = 13;
topLightImgs[i].x = positionLeft;
topLightImgs[i].y = -80;
topLightImgs[i].scaleX = 1.3;
topLightImgs[i].scaleY = 1.3;
positionLeft += 210;
stage.addChild(topLightImgs[i]);
}
log("Add logo");
var logoSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[4]],
//width, height & registration point of each sprite
frames: [
[0, 0, 227, 386],
[227, 0, 227, 386],
[454, 0, 227, 386],
[681, 0, 227, 386],
[908, 0, 227, 386],
[1135, 0, 227, 386],
[1362, 0, 227, 386],
[1599, 0, 227, 386]
],
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
stay: {
frames: [0],
next: "run",
frequency: 2
},
run: {
frames: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6]
}
}
});
logoSprite = new createjs.BitmapAnimation(logoSpriteSheet);
logoSprite.x = 18;
logoSprite.y = 18;
logoSprite.gotoAndPlay("run");
stage.addChild(logoSprite);
log("Add Welcome lap character");
var welcomeLapSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[6]],
//width, height & registration point of each sprite
frames: { width: 139, height: 250, regX: 0, regY: 0, count: 110 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
lap: [0, 110, "lap"]
}
});
welcomeLapSpite = new createjs.BitmapAnimation(welcomeLapSpriteSheet);
welcomeLapSpite.x = 220;
welcomeLapSpite.y = 290;
welcomeLapSpite.scaleX = 1.5;
welcomeLapSpite.scaleY = 1.5;
welcomeLapSpite.gotoAndStop("lap");
welcomeLapSpite.visible = false;
stage.addChild(welcomeLapSpite);
log("Add tvc Start character");
var tvcStartSpriteSheet = new createjs.SpriteSheet({
images: [arrayImages[7]],
frames: { width: 233, height: 250.5, regX: 0, regY: 0, count: 64 },
animations: {
walk: [0, 64]
}
});
tvcStartSpite = new createjs.BitmapAnimation(tvcStartSpriteSheet);
tvcStartSpite.x = 250;
tvcStartSpite.y = 240;
tvcStartSpite.scaleX = 1.8;
tvcStartSpite.scaleY = 1.8;
tvcStartSpite.gotoAndStop("walk");
tvcStartSpite.visible = false;
stage.addChild(tvcStartSpite);
var tvcLapSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[8]],
//width, height & registration point of each sprite
frames: { width: 66, height: 250, regX: 0, regY: 0, count: 117 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
lap: [0, 115]
}
});
tvcLapSpite = new createjs.BitmapAnimation(tvcLapSpriteSheet);
tvcLapSpite.x = 530;
tvcLapSpite.y = 290;
tvcLapSpite.scaleX = 1.5;
tvcLapSpite.scaleY = 1.5;
tvcLapSpite.gotoAndStop("lap");
tvcLapSpite.visible = false;
stage.addChild(tvcLapSpite);
createjs.Ticker.setFPS(8);
createjs.Ticker.addEventListener("tick", tickHandle);
setActiveTab($("#btnHome"));
//var introVideo = document.getElementById("welcomeVideo");
//var bitmap = new createjs.Bitmap(introVideo);
//bitmap.x = 0;
//bitmap.y = 300;
//bitmap.scaleX = 0.5;
//bitmap.scaleY = 0.5;
//stage.addChild(bitmap);
// welcomeVideoStart();
}
/**
* Tick Handler
*/
var lightAngle = 2;
function tickHandle() {
console.log('111');
currentTick += 1;
topLightImgs[0].rotation += lightAngle;
topLightImgs[1].rotation -= lightAngle / 2;
topLightImgs[2].rotation -= lightAngle;
if (topLightImgs[0].rotation == 10)
lightAngle = -2;
else if (topLightImgs[0].rotation == -10)
lightAngle = 2;
if (currentTick > 8)
currentTick = 0;
if (tickTVC > -1) {
tickTVC += 1;
if (tickTVC == 54) {
}
else if (tickTVC == 60) {
logoSprite.visible = false;
showVideo("tvcVideo", tvcVideoEnd);
}
else if (tickTVC == 64) {
tvcStartSpite.visible = false;
tvcStartSpite.stop();
tickTVC = -1;
document.getElementById("tvcVideo").play();
}
}
stage.update();
}
/**
* Set tab active
*/
function setActiveTab(button) {
$(".buttons button").removeClass("active");
$(button).addClass("active");
}
/**
* Reset
*/
function reset() {
stage.removeAllChildren();
createjs.Ticker.removeAllListeners();
stage.update();
}
/**
* log message
*/
function log(message) {
console.log(message);
$("#message").html(message);
}
function showwelcom() {
logoSprite.visible = true;
$('#welcom').show();
$("video").removeClass("videoActive");
$("#sound-welcom").jPlayer("play");
$('#welcom img').attr('src',root + 'static/images/mobile/Welcome.gif');
}
function showmp3() {
logoSprite.visible = true;
$('#page-mp3').show();
$("video").removeClass("videoActive");
$("#sound-mp3").jPlayer("play");
$('#page-mp3 img').attr('src',root + 'static/images/mobile/videotrangmp3_07504.gif');
}
function showVideo(videoid, nextFunction) {
$("video").removeClass("videoActive");
var video = document.getElementById(videoid);
$(video).addClass("videoActive");
droidfix.init(video);
video.addEventListener("abort", nextFunction);
droidfix.addEndListener(nextFunction);
}
function showshare(){
logoSprite.visible = false;
$('#tvcVideo').removeClass('videoActive');
$('.content-share').show();
}
function welcomeVideoStart() {
pauseVideos();
showwelcom();
setActiveTab($("#btnHome"));
}
function showshareStart(){
pauseVideos();
setActiveTab($("#btnShare"));
showshare();
if(!$('.tab-rules').is(':hidden') && ischeck1){
var myScroll_1 = new iScroll('iscroll_rules');
ischeck1 = false;
}
}
function tvcVideoStart() {
pauseVideos();
setActiveTab($("#btnVideo"));
$("video").removeClass("videoActive");
tvcStartSpite.visible = true;
tvcStartSpite.play();
tickTVC = 0;
tvcSound.play();
}
function fullsongVideoStart() {
pauseVideos();
setActiveTab($("#btnMusic"));
showmp3();
}
function welcomeVideoEnd() {
log("Welcome video end");
$("#welcomeVideo").removeClass("videoActive");
welcomeLapSpite.visible = true;
welcomeLapSpite.play();
}
function tvcVideoEnd() {
log("TVC video end");
}
function fullsongVideoEnd() {
log("Fullsong video end");
}
function pauseVideos() {
$("#sound-welcom").jPlayer("stop");
$('#welcom img').attr('src',root + 'static/images/mobile/blank.gif');
$("#sound-mp3").jPlayer("stop");
$('#page-mp3 img').attr('src',root + 'static/images/mobile/blank.gif');
document.getElementById("tvcVideo").pause();
tvcStartSpite.visible = false;
tvcStartSpite.stop();
tickTVC = -1;
tvcSound.stop();
$('.content-share').hide();
} | JavaScript |
// global properties
var stage;
var currentTick = 0;
var arrayImages = new Array();
var loadedImgNumber = 0;
// for welcome screen
var loadingC2Img;
var loadingTextImg;
var loadingMusicImg;
// for other screen
var stageSprite;
var topLightImgs;
var logoSprite;
var welcomeCha;
var tvcCha;
// for character lap
var welcomeLapSpite;
var tvcStartSpite;
var tvcLapSpite;
var tickTVC = -1;
/**
* Init handler
*/
$(document).ready(function () {
log("Width: " + window.innerWidth + " - Height: " + window.innerHeight + "- Ratio: " + window.devicePixelRatio);
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode(
"@-ms-viewport{width:auto!important}"
)
);
document.getElementsByTagName("head")[0].
appendChild(msViewportStyle);
}
initLoadingScreen();
$("#btnHome").click(welcomeVideoStart);
$("#btnVideo").click(tvcVideoStart);
$("#btnMusic").click(fullsongVideoStart);
});
/**
* Init welcome handler
*/
function initLoadingScreen() {
arrayImages[0] = new Image();
arrayImages[0].onload = handleLoadingImageLoad;
arrayImages[0].onerror = handleImageError;
arrayImages[0].src = "index_files/Chai_C2.png";
arrayImages[1] = new Image();
arrayImages[1].onload = handleLoadingImageLoad;
arrayImages[1].onerror = handleImageError;
arrayImages[1].src = "index_files/music.png";
arrayImages[2] = new Image();
arrayImages[2].onload = handleLoadingImageLoad;
arrayImages[2].onerror = handleImageError;
arrayImages[2].src = "index_files/loading.png";
}
/**
* Handle loading image for welcome
*/
function handleLoadingImageLoad(e) {
loadedImgNumber++;
if (loadedImgNumber == 3) {
startWelcomeScreen();
}
}
/**
* Handle loading error
*/
function handleImageError(e) {
log("Error Loading Image : " + e.target.src);
}
/**
* Initilale Welcome Screen
*/
function startWelcomeScreen() {
$(".loading").hide();
var canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
loadingC2Img = new createjs.Bitmap(arrayImages[0]);
loadingC2Img.regX = 85;
loadingC2Img.regY = 460;
loadingC2Img.x = 512;
loadingC2Img.y = 570;
loadingC2Img.scaleX = 0.8;
loadingC2Img.scaleY = 0.8;
stage.addChild(loadingC2Img);
loadingMusicImg = new createjs.Bitmap(arrayImages[1]);
loadingMusicImg.regX = 85;
loadingMusicImg.regY = 217;
loadingMusicImg.x = 512;
loadingMusicImg.y = 150;
stage.addChild(loadingMusicImg);
loadingTextImg = new createjs.Bitmap(arrayImages[2]);
loadingTextImg.regX = 87;
loadingTextImg.regY = 30;
loadingTextImg.x = 512;
loadingTextImg.y = 150;
stage.addChild(loadingTextImg);
createjs.Ticker.setFPS(12);
createjs.Ticker.addEventListener("tick", tickLoading);
initMainScreen();
}
/**
* Tick Handler
*/
var angle = 5;
function tickLoading() {
console.log(angle);
currentTick += 1;
loadingC2Img.rotation += angle;
if (loadingC2Img.rotation == 10)
angle = -5;
else if (loadingC2Img.rotation == -10)
angle = 5;
if (loadingMusicImg.y > 0)
loadingMusicImg.y -= 13;
else {
if (currentTick == 1) {
loadingMusicImg.y = 150;
}
}
if (currentTick > 12)
currentTick = 0;
stage.update();
}
/**
* Handle loading image for main stage
*/
function initMainScreen() {
$(".buttons").show();
arrayImages[3] = new Image();
arrayImages[3].onload = handleImageLoad;
arrayImages[3].onerror = handleImageError;
arrayImages[3].src = "index_files/light.png";
arrayImages[4] = new Image();
arrayImages[4].onload = handleImageLoad;
arrayImages[4].onerror = handleImageError;
arrayImages[4].src = "index_files/logo.png";
arrayImages[5] = new Image();
arrayImages[5].onload = handleImageLoad;
arrayImages[5].onerror = handleImageError;
arrayImages[5].src = "index_files/stage_tablet.png";
arrayImages[6] = new Image();
arrayImages[6].onload = handleImageLoad;
arrayImages[6].onerror = handleImageError;
arrayImages[6].src = "index_files/welcome_lap_SH.png";
arrayImages[7] = new Image();
arrayImages[7].onload = handleImageLoad;
arrayImages[7].onerror = handleImageError;
arrayImages[7].src = "index_files/startTvc_S.png";
}
/**
* Handle loading image for main stage
*/
function handleImageLoad(e) {
loadedImgNumber++;
if (loadedImgNumber == 8) {
startMainScreen();
}
}
/**
* Initilale Main Screen
*/
function startMainScreen() {
reset();
stage = new createjs.Stage(canvas);
log("Start main stage");
log("Add stage");
var stageSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[5]],
//width, height & registration point of each sprite
frames: [
[0, 1, 867, 90],
[0, 1, 867, 90],
[0, 1, 867, 90],
[0, 103, 867, 90],
[0, 103, 867, 90],
[0, 103, 867, 90],
[0, 205, 867, 90],
[0, 205, 867, 90],
[0, 205, 867, 90],
[0, 307, 867, 90],
[0, 307, 867, 90],
[0, 307, 867, 90]
],
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
stageanimation: [0, 11, "stageanimation"]
}
});
stageSprite = new createjs.BitmapAnimation(stageSpriteSheet);
stageSprite.x = 77;
stageSprite.y = 534;
stageSprite.gotoAndPlay("stageanimation");
stage.addChild(stageSprite);
log("Add light");
topLightImgs = new Array();
var positionLeft = 110;
for (var i = 0; i < 3; i++) {
topLightImgs[i] = new createjs.Bitmap(arrayImages[3]);
topLightImgs[i].regX = 225;
topLightImgs[i].regY = 13;
topLightImgs[i].x = positionLeft;
topLightImgs[i].y = -100;
positionLeft += 400;
topLightImgs[i].scaleX = 1.2;
topLightImgs[i].scaleY = 1.2;
stage.addChild(topLightImgs[i]);
}
log("Add logo");
var logoSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[4]],
//width, height & registration point of each sprite
frames: [
[0, 0, 227, 386],
[227, 0, 227, 386],
[454, 0, 227, 386],
[681, 0, 227, 386],
[908, 0, 227, 386],
[1135, 0, 227, 386],
[1362, 0, 227, 386],
[1599, 0, 227, 386]
],
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
stay: {
frames: [0],
next: "run",
frequency: 2
},
run: {
frames: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6]
}
}
});
logoSprite = new createjs.BitmapAnimation(logoSpriteSheet);
logoSprite.x = 146;
logoSprite.y = 18;
logoSprite.gotoAndPlay("run");
stage.addChild(logoSprite);
log("Add Welcome lap character");
var welcomeLapSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[6]],
//width, height & registration point of each sprite
frames: { width: 139, height: 250, regX: 0, regY: 0, count: 110 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
lap: [0, 110, "lap"]
}
});
welcomeLapSpite = new createjs.BitmapAnimation(welcomeLapSpriteSheet);
welcomeLapSpite.x = 410;
welcomeLapSpite.y = 200;
welcomeLapSpite.scaleX = 1.5;
welcomeLapSpite.scaleY = 1.5;
welcomeLapSpite.gotoAndStop("lap");
welcomeLapSpite.visible = false;
stage.addChild(welcomeLapSpite);
log("Add tvc Start character");
var tvcStartSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[7]],
//width, height & registration point of each sprite
frames: { width: 233, height: 250.5, regX: 0, regY: 0, count: 64 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
walk: [0, 64]
}
});
tvcStartSpite = new createjs.BitmapAnimation(tvcStartSpriteSheet);
tvcStartSpite.x = 520;
tvcStartSpite.y = 200;
tvcStartSpite.scaleX = 1.5;
tvcStartSpite.scaleY = 1.5;
tvcStartSpite.gotoAndStop("walk");
tvcStartSpite.visible = false;
stage.addChild(tvcStartSpite);
createjs.Ticker.setFPS(8);
createjs.Ticker.addEventListener("tick", tickHandle);
setActiveTab($("#btnHome"));
//var introVideo = document.getElementById("welcomeVideo");
//var bitmap = new createjs.Bitmap(introVideo);
//bitmap.x = 0;
//bitmap.y = 300;
//bitmap.scaleX = 0.5;
//bitmap.scaleY = 0.5;
//stage.addChild(bitmap);
// welcomeVideoStart();
$('#welcom').html('<img src="index_files/Welcome.gif" alt="" width="306" height="500" />');
var myAudio = document.getElementById('sound-welcom').play();
// myAudio.addEventListener('canplaythrough', function() {
// this.currentTime = 12;
// this.play();
// });
}
/**
* Tick Handler
*/
var lightAngle = 2;
function tickHandle() {
currentTick += 1;
topLightImgs[0].rotation += lightAngle;
topLightImgs[1].rotation -= lightAngle / 2;
topLightImgs[2].rotation -= lightAngle;
if (topLightImgs[0].rotation == 10)
lightAngle = -2;
else if (topLightImgs[0].rotation == -10)
lightAngle = 2;
if (currentTick > 8)
currentTick = 0;
if (tickTVC > -1) {
if (tickTVC == 54) {
showVideo("tvcVideo", tvcVideoEnd);
}
else
if (tickTVC == 64) {
tvcStartSpite.visible = false;
tvcStartSpite.stop();
tickTVC = -1;
document.getElementById("tvcVideo").play();
}
tickTVC += 1;
}
stage.update();
}
/**
* Set tab active
*/
function setActiveTab(button) {
$(".buttons button").removeClass("active");
$(button).addClass("active");
}
/**
* Reset
*/
function reset() {
stage.removeAllChildren();
createjs.Ticker.removeAllListeners();
stage.update();
}
/**
* log message
*/
function log(message) {
console.log(message);
$("#message").html(message);
}
function showVideo(videoid, nextFunction) {
$("video").removeClass("videoActive");
var video = document.getElementById(videoid);
$(video).addClass("videoActive");
droidfix.init(video);
video.addEventListener("abort", nextFunction);
droidfix.addEndListener(nextFunction);
}
function welcomeVideoStart() {
pauseVideos();
setActiveTab($("#btnHome"));
showVideo("welcomeVideo", welcomeVideoEnd);
document.getElementById("welcomeVideo").play();
}
function tvcVideoStart() {
pauseVideos();
setActiveTab($("#btnVideo"));
$("video").removeClass("videoActive");
//document.getElementById("tvcVideo").play();
tvcStartSpite.visible = true;
tvcStartSpite.play();
tickTVC = 0;
}
function fullsongVideoStart() {
pauseVideos();
setActiveTab($("#btnMusic"));
showVideo("fullsongVideo", fullsongVideoEnd);
document.getElementById("fullsongVideo").play();
}
function welcomeVideoEnd() {
log("Welcome video end");
$("#welcomeVideo").removeClass("videoActive");
welcomeLapSpite.visible = true;
welcomeLapSpite.play();
}
function tvcVideoEnd() {
log("TVC video end");
}
function fullsongVideoEnd() {
log("Fullsong video end");
}
function pauseVideos() {
document.getElementById("welcomeVideo").pause();
document.getElementById("tvcVideo").pause();
document.getElementById("fullsongVideo").pause();
welcomeLapSpite.visible = false;
welcomeLapSpite.stop();
tvcStartSpite.visible = false;
tvcStartSpite.stop();
tickTVC = -1;
} | JavaScript |
/*
* transform: A jQuery cssHooks adding cross-browser 2d transform capabilities to $.fn.css() and $.fn.animate()
*
* limitations:
* - requires jQuery 1.4.3+
* - Should you use the *translate* property, then your elements need to be absolutely positionned in a relatively positionned wrapper **or it will fail in IE678**.
* - transformOrigin is not accessible
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.transform.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*
* This saved you an hour of work?
* Send me music http://www.amazon.co.uk/wishlist/HNTU0468LQON
*
*/
(function( $, window, document, Math, undefined ) {
/*
* Feature tests and global variables
*/
var div = document.createElement("div"),
divStyle = div.style,
suffix = "Transform",
testProperties = [
"O" + suffix,
"ms" + suffix,
"Webkit" + suffix,
"Moz" + suffix
],
i = testProperties.length,
supportProperty,
supportMatrixFilter,
supportFloat32Array = "Float32Array" in window,
propertyHook,
propertyGet,
rMatrix = /Matrix([^)]*)/,
rAffine = /^\s*matrix\(\s*1\s*,\s*0\s*,\s*0\s*,\s*1\s*(?:,\s*0(?:px)?\s*){2}\)\s*$/,
_transform = "transform",
_transformOrigin = "transformOrigin",
_translate = "translate",
_rotate = "rotate",
_scale = "scale",
_skew = "skew",
_matrix = "matrix";
// test different vendor prefixes of these properties
while ( i-- ) {
if ( testProperties[i] in divStyle ) {
$.support[_transform] = supportProperty = testProperties[i];
$.support[_transformOrigin] = supportProperty + "Origin";
continue;
}
}
// IE678 alternative
if ( !supportProperty ) {
$.support.matrixFilter = supportMatrixFilter = divStyle.filter === "";
}
// px isn't the default unit of these properties
$.cssNumber[_transform] = $.cssNumber[_transformOrigin] = true;
/*
* fn.css() hooks
*/
if ( supportProperty && supportProperty != _transform ) {
// Modern browsers can use jQuery.cssProps as a basic hook
$.cssProps[_transform] = supportProperty;
$.cssProps[_transformOrigin] = supportProperty + "Origin";
// Firefox needs a complete hook because it stuffs matrix with "px"
if ( supportProperty == "Moz" + suffix ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
// remove "px" from the computed matrix
$.css( elem, supportProperty ).split("px").join(""):
elem.style[supportProperty]
);
},
set: function( elem, value ) {
// add "px" to matrices
elem.style[supportProperty] = /matrix\([^)p]*\)/.test(value) ?
value.replace(/matrix((?:[^,]*,){4})([^,]*),([^)]*)/, _matrix+"$1$2px,$3px"):
value;
}
};
/* Fix two jQuery bugs still present in 1.5.1
* - rupper is incompatible with IE9, see http://jqbug.com/8346
* - jQuery.css is not really jQuery.cssProps aware, see http://jqbug.com/8402
*/
} else if ( /^1\.[0-5](?:\.|$)/.test($.fn.jquery) ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
$.css( elem, supportProperty.replace(/^ms/, "Ms") ):
elem.style[supportProperty]
);
}
};
}
/* TODO: leverage hardware acceleration of 3d transform in Webkit only
else if ( supportProperty == "Webkit" + suffix && support3dTransform ) {
propertyHook = {
set: function( elem, value ) {
elem.style[supportProperty] =
value.replace();
}
}
}*/
} else if ( supportMatrixFilter ) {
propertyHook = {
get: function( elem, computed, asArray ) {
var elemStyle = ( computed && elem.currentStyle ? elem.currentStyle : elem.style ),
matrix, data;
if ( elemStyle && rMatrix.test( elemStyle.filter ) ) {
matrix = RegExp.$1.split(",");
matrix = [
matrix[0].split("=")[1],
matrix[2].split("=")[1],
matrix[1].split("=")[1],
matrix[3].split("=")[1]
];
} else {
matrix = [1,0,0,1];
}
if ( ! $.cssHooks[_transformOrigin] ) {
matrix[4] = elemStyle ? parseInt(elemStyle.left, 10) || 0 : 0;
matrix[5] = elemStyle ? parseInt(elemStyle.top, 10) || 0 : 0;
} else {
data = $._data( elem, "transformTranslate", undefined );
matrix[4] = data ? data[0] : 0;
matrix[5] = data ? data[1] : 0;
}
return asArray ? matrix : _matrix+"(" + matrix + ")";
},
set: function( elem, value, animate ) {
var elemStyle = elem.style,
currentStyle,
Matrix,
filter,
centerOrigin;
if ( !animate ) {
elemStyle.zoom = 1;
}
value = matrix(value);
// rotate, scale and skew
Matrix = [
"Matrix("+
"M11="+value[0],
"M12="+value[2],
"M21="+value[1],
"M22="+value[3],
"SizingMethod='auto expand'"
].join();
filter = ( currentStyle = elem.currentStyle ) && currentStyle.filter || elemStyle.filter || "";
elemStyle.filter = rMatrix.test(filter) ?
filter.replace(rMatrix, Matrix) :
filter + " progid:DXImageTransform.Microsoft." + Matrix + ")";
if ( ! $.cssHooks[_transformOrigin] ) {
// center the transform origin, from pbakaus's Transformie http://github.com/pbakaus/transformie
if ( (centerOrigin = $.transform.centerOrigin) ) {
elemStyle[centerOrigin == "margin" ? "marginLeft" : "left"] = -(elem.offsetWidth/2) + (elem.clientWidth/2) + "px";
elemStyle[centerOrigin == "margin" ? "marginTop" : "top"] = -(elem.offsetHeight/2) + (elem.clientHeight/2) + "px";
}
// translate
// We assume that the elements are absolute positionned inside a relative positionned wrapper
elemStyle.left = value[4] + "px";
elemStyle.top = value[5] + "px";
} else {
$.cssHooks[_transformOrigin].set( elem, value );
}
}
};
}
// populate jQuery.cssHooks with the appropriate hook if necessary
if ( propertyHook ) {
$.cssHooks[_transform] = propertyHook;
}
// we need a unique setter for the animation logic
propertyGet = propertyHook && propertyHook.get || $.css;
/*
* fn.animate() hooks
*/
$.fx.step.transform = function( fx ) {
var elem = fx.elem,
start = fx.start,
end = fx.end,
pos = fx.pos,
transform = "",
precision = 1E5,
i, startVal, endVal, unit;
// fx.end and fx.start need to be converted to interpolation lists
if ( !start || typeof start === "string" ) {
// the following block can be commented out with jQuery 1.5.1+, see #7912
if ( !start ) {
start = propertyGet( elem, supportProperty );
}
// force layout only once per animation
if ( supportMatrixFilter ) {
elem.style.zoom = 1;
}
// replace "+=" in relative animations (-= is meaningless with transforms)
end = end.split("+=").join(start);
// parse both transform to generate interpolation list of same length
$.extend( fx, interpolationList( start, end ) );
start = fx.start;
end = fx.end;
}
i = start.length;
// interpolate functions of the list one by one
while ( i-- ) {
startVal = start[i];
endVal = end[i];
unit = +false;
switch ( startVal[0] ) {
case _translate:
unit = "px";
case _scale:
unit || ( unit = "");
transform = startVal[0] + "(" +
Math.round( (startVal[1][0] + (endVal[1][0] - startVal[1][0]) * pos) * precision ) / precision + unit +","+
Math.round( (startVal[1][1] + (endVal[1][1] - startVal[1][1]) * pos) * precision ) / precision + unit + ")"+
transform;
break;
case _skew + "X":
case _skew + "Y":
case _rotate:
transform = startVal[0] + "(" +
Math.round( (startVal[1] + (endVal[1] - startVal[1]) * pos) * precision ) / precision +"rad)"+
transform;
break;
}
}
fx.origin && ( transform = fx.origin + transform );
propertyHook && propertyHook.set ?
propertyHook.set( elem, transform, +true ):
elem.style[supportProperty] = transform;
};
/*
* Utility functions
*/
// turns a transform string into its "matrix(A,B,C,D,X,Y)" form (as an array, though)
function matrix( transform ) {
transform = transform.split(")");
var
trim = $.trim
, i = -1
// last element of the array is an empty string, get rid of it
, l = transform.length -1
, split, prop, val
, prev = supportFloat32Array ? new Float32Array(6) : []
, curr = supportFloat32Array ? new Float32Array(6) : []
, rslt = supportFloat32Array ? new Float32Array(6) : [1,0,0,1,0,0]
;
prev[0] = prev[3] = rslt[0] = rslt[3] = 1;
prev[1] = prev[2] = prev[4] = prev[5] = 0;
// Loop through the transform properties, parse and multiply them
while ( ++i < l ) {
split = transform[i].split("(");
prop = trim(split[0]);
val = split[1];
curr[0] = curr[3] = 1;
curr[1] = curr[2] = curr[4] = curr[5] = 0;
switch (prop) {
case _translate+"X":
curr[4] = parseInt(val, 10);
break;
case _translate+"Y":
curr[5] = parseInt(val, 10);
break;
case _translate:
val = val.split(",");
curr[4] = parseInt(val[0], 10);
curr[5] = parseInt(val[1] || 0, 10);
break;
case _rotate:
val = toRadian(val);
curr[0] = Math.cos(val);
curr[1] = Math.sin(val);
curr[2] = -Math.sin(val);
curr[3] = Math.cos(val);
break;
case _scale+"X":
curr[0] = +val;
break;
case _scale+"Y":
curr[3] = val;
break;
case _scale:
val = val.split(",");
curr[0] = val[0];
curr[3] = val.length>1 ? val[1] : val[0];
break;
case _skew+"X":
curr[2] = Math.tan(toRadian(val));
break;
case _skew+"Y":
curr[1] = Math.tan(toRadian(val));
break;
case _matrix:
val = val.split(",");
curr[0] = val[0];
curr[1] = val[1];
curr[2] = val[2];
curr[3] = val[3];
curr[4] = parseInt(val[4], 10);
curr[5] = parseInt(val[5], 10);
break;
}
// Matrix product (array in column-major order)
rslt[0] = prev[0] * curr[0] + prev[2] * curr[1];
rslt[1] = prev[1] * curr[0] + prev[3] * curr[1];
rslt[2] = prev[0] * curr[2] + prev[2] * curr[3];
rslt[3] = prev[1] * curr[2] + prev[3] * curr[3];
rslt[4] = prev[0] * curr[4] + prev[2] * curr[5] + prev[4];
rslt[5] = prev[1] * curr[4] + prev[3] * curr[5] + prev[5];
prev = [rslt[0],rslt[1],rslt[2],rslt[3],rslt[4],rslt[5]];
}
return rslt;
}
// turns a matrix into its rotate, scale and skew components
// algorithm from http://hg.mozilla.org/mozilla-central/file/7cb3e9795d04/layout/style/nsStyleAnimation.cpp
function unmatrix(matrix) {
var
scaleX
, scaleY
, skew
, A = matrix[0]
, B = matrix[1]
, C = matrix[2]
, D = matrix[3]
;
// Make sure matrix is not singular
if ( A * D - B * C ) {
// step (3)
scaleX = Math.sqrt( A * A + B * B );
A /= scaleX;
B /= scaleX;
// step (4)
skew = A * C + B * D;
C -= A * skew;
D -= B * skew;
// step (5)
scaleY = Math.sqrt( C * C + D * D );
C /= scaleY;
D /= scaleY;
skew /= scaleY;
// step (6)
if ( A * D < B * C ) {
A = -A;
B = -B;
skew = -skew;
scaleX = -scaleX;
}
// matrix is singular and cannot be interpolated
} else {
// In this case the elem shouldn't be rendered, hence scale == 0
scaleX = scaleY = skew = 0;
}
// The recomposition order is very important
// see http://hg.mozilla.org/mozilla-central/file/7cb3e9795d04/layout/style/nsStyleAnimation.cpp#l971
return [
[_translate, [+matrix[4], +matrix[5]]],
[_rotate, Math.atan2(B, A)],
[_skew + "X", Math.atan(skew)],
[_scale, [scaleX, scaleY]]
];
}
// build the list of transform functions to interpolate
// use the algorithm described at http://dev.w3.org/csswg/css3-2d-transforms/#animation
function interpolationList( start, end ) {
var list = {
start: [],
end: []
},
i = -1, l,
currStart, currEnd, currType;
// get rid of affine transform matrix
( start == "none" || isAffine( start ) ) && ( start = "" );
( end == "none" || isAffine( end ) ) && ( end = "" );
// if end starts with the current computed style, this is a relative animation
// store computed style as the origin, remove it from start and end
if ( start && end && !end.indexOf("matrix") && toArray( start ).join() == toArray( end.split(")")[0] ).join() ) {
list.origin = start;
start = "";
end = end.slice( end.indexOf(")") +1 );
}
if ( !start && !end ) { return; }
// start or end are affine, or list of transform functions are identical
// => functions will be interpolated individually
if ( !start || !end || functionList(start) == functionList(end) ) {
start && ( start = start.split(")") ) && ( l = start.length );
end && ( end = end.split(")") ) && ( l = end.length );
while ( ++i < l-1 ) {
start[i] && ( currStart = start[i].split("(") );
end[i] && ( currEnd = end[i].split("(") );
currType = $.trim( ( currStart || currEnd )[0] );
append( list.start, parseFunction( currType, currStart ? currStart[1] : 0 ) );
append( list.end, parseFunction( currType, currEnd ? currEnd[1] : 0 ) );
}
// otherwise, functions will be composed to a single matrix
} else {
list.start = unmatrix(matrix(start));
list.end = unmatrix(matrix(end))
}
return list;
}
function parseFunction( type, value ) {
var
// default value is 1 for scale, 0 otherwise
defaultValue = +(!type.indexOf(_scale)),
scaleX,
// remove X/Y from scaleX/Y & translateX/Y, not from skew
cat = type.replace( /e[XY]/, "e" );
switch ( type ) {
case _translate+"Y":
case _scale+"Y":
value = [
defaultValue,
value ?
parseFloat( value ):
defaultValue
];
break;
case _translate+"X":
case _translate:
case _scale+"X":
scaleX = 1;
case _scale:
value = value ?
( value = value.split(",") ) && [
parseFloat( value[0] ),
parseFloat( value.length>1 ? value[1] : type == _scale ? scaleX || value[0] : defaultValue+"" )
]:
[defaultValue, defaultValue];
break;
case _skew+"X":
case _skew+"Y":
case _rotate:
value = value ? toRadian( value ) : 0;
break;
case _matrix:
return unmatrix( value ? toArray(value) : [1,0,0,1,0,0] );
break;
}
return [[ cat, value ]];
}
function isAffine( matrix ) {
return rAffine.test(matrix);
}
function functionList( transform ) {
return transform.replace(/(?:\([^)]*\))|\s/g, "");
}
function append( arr1, arr2, value ) {
while ( value = arr2.shift() ) {
arr1.push( value );
}
}
// converts an angle string in any unit to a radian Float
function toRadian(value) {
return ~value.indexOf("deg") ?
parseInt(value,10) * (Math.PI * 2 / 360):
~value.indexOf("grad") ?
parseInt(value,10) * (Math.PI/200):
parseFloat(value);
}
// Converts "matrix(A,B,C,D,X,Y)" to [A,B,C,D,X,Y]
function toArray(matrix) {
// remove the unit of X and Y for Firefox
matrix = /([^,]*),([^,]*),([^,]*),([^,]*),([^,p]*)(?:px)?,([^)p]*)(?:px)?/.exec(matrix);
return [matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]];
}
$.transform = {
centerOrigin: "margin"
};
})( jQuery, window, document, Math );
| JavaScript |
// create a namespace for the application
this.mProton = this.mProton || {};
// this is a function closure
(function () {
// the application
function Sound(source, loop, onLoadCompleted) {
this.src = source;
this.loop = loop;
this.onLoadCompleted = onLoadCompleted;
this.init();
}
Sound.prototype = {
src: null, // the audio src we are trying to play
soundInstance: null, // the soundInstance returned by Sound when we create or play a src
displayStatus: null, // the HTML element we use to display messages to the user
loadProxy: null,
loop: 1,
onLoadCompleted: function () { },
init: function (source) {
if (!createjs.Sound.initializeDefaultPlugins()) {
return;
}
this.loadProxy = createjs.proxy(this.loadCompleted, this);
createjs.Sound.addEventListener("fileload", this.loadProxy); // add event listener for when load is completed.
createjs.Sound.registerSound(this.src); // register sound, which preloads by default
return this;
},
loadCompleted: function () {
createjs.Sound.removeEventListener("fileload", this.loadProxy); // we only load 1 sound, so remove the listener
this.onLoadCompleted();
},
pause: function () {
if (this.soundInstance != null)
this.soundInstance.pause();
},
play: function () {
this.soundInstance = createjs.Sound.play(this.src, "none", 0, 0, this.loop, 1, 0); // start playback and store the soundInstance we are currently play
},
resume: function () {
if (this.soundInstance != null)
this.soundInstance.resume();
},
playOrResume:function() {
if (this.soundInstance != null)
this.soundInstance.resume();
else
this.soundInstance = createjs.Sound.play(this.src, "none", 0, 0, this.loop, 1, 0); // start playback and store the soundInstance we are currently play
},
stop: function () {
if (this.soundInstance != null)
this.soundInstance.stop();
},
setVolumn: function (volumn) {
if (this.soundInstance != null)
this.soundInstance.volume(volumn);
}
};
// add Sound to mProton
mProton.Sound = Sound;
}()); | JavaScript |
/*
* CirclePlayer for the jPlayer Plugin (jQuery)
* http://www.jplayer.org
*
* Copyright (c) 2009 - 2012 Happyworm Ltd
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
*
* Version: 1.0.1 (jPlayer 2.1.0+)
* Date: 30th May 2011
*
* Author: Mark J Panaghiston @thepag
*
* CirclePlayer prototype developed by:
* Mark Boas @maboa
* Silvia Benvenuti @aulentina
* Jussi Kalliokoski @quinirill
*
* Inspired by :
* Neway @imneway http://imneway.net/ http://forrst.com/posts/Untitled-CPt
* and
* Liam McKay @liammckay http://dribbble.com/shots/50882-Purple-Play-Pause
*
* Standing on the shoulders of :
* John Resig @jresig
* Mark Panaghiston @thepag
* Louis-Rémi Babé @Louis_Remi
*/
var CirclePlayer = function(jPlayerSelector, media, options) {
var self = this,
defaults = {
// solution: "flash, html", // For testing Flash with CSS3
supplied: "m4a, oga",
// Android 2.3 corrupts media element if preload:"none" is used.
// preload: "none", // No point preloading metadata since no times are displayed. It helps keep the buffer state correct too.
cssSelectorAncestor: "#cp_container_1",
cssSelector: {
play: ".cp-play",
pause: ".cp-pause"
}
},
cssSelector = {
bufferHolder: ".cp-buffer-holder",
buffer1: ".cp-buffer-1",
buffer2: ".cp-buffer-2",
progressHolder: ".cp-progress-holder",
progress1: ".cp-progress-1",
progress2: ".cp-progress-2",
circleControl: ".cp-circle-control"
};
this.cssClass = {
gt50: "cp-gt50",
fallback: "cp-fallback"
};
this.spritePitch = 104;
this.spriteRatio = 0.24; // Number of steps / 100
this.player = $(jPlayerSelector);
this.media = $.extend({}, media);
this.options = $.extend(true, {}, defaults, options); // Deep copy
this.cssTransforms = Modernizr.csstransforms;
this.audio = {};
this.dragging = false; // Indicates if the progressbar is being 'dragged'.
this.eventNamespace = ".CirclePlayer"; // So the events can easily be removed in destroy.
this.jq = {};
$.each(cssSelector, function(entity, cssSel) {
self.jq[entity] = $(self.options.cssSelectorAncestor + " " + cssSel);
});
this._initSolution();
this._initPlayer();
};
CirclePlayer.prototype = {
_createHtml: function() {
},
_initPlayer: function() {
var self = this;
this.player.jPlayer(this.options);
this.player.bind($.jPlayer.event.ready + this.eventNamespace, function(event) {
if(event.jPlayer.html.used && event.jPlayer.html.audio.available) {
self.audio = $(this).data("jPlayer").htmlElement.audio;
}
$(this).jPlayer("setMedia", self.media);
self._initCircleControl();
});
this.player.bind($.jPlayer.event.play + this.eventNamespace, function(event) {
$(this).jPlayer("pauseOthers");
});
// This event fired as play time increments
this.player.bind($.jPlayer.event.timeupdate + this.eventNamespace, function(event) {
if (!self.dragging) {
self._timeupdate(event.jPlayer.status.currentPercentAbsolute);
}
});
// This event fired as buffered time increments
this.player.bind($.jPlayer.event.progress + this.eventNamespace, function(event) {
var percent = 0;
if((typeof self.audio.buffered === "object") && (self.audio.buffered.length > 0)) {
if(self.audio.duration > 0) {
var bufferTime = 0;
for(var i = 0; i < self.audio.buffered.length; i++) {
bufferTime += self.audio.buffered.end(i) - self.audio.buffered.start(i);
// console.log(i + " | start = " + self.audio.buffered.start(i) + " | end = " + self.audio.buffered.end(i) + " | bufferTime = " + bufferTime + " | duration = " + self.audio.duration);
}
percent = 100 * bufferTime / self.audio.duration;
} // else the Metadata has not been read yet.
// console.log("percent = " + percent);
} else { // Fallback if buffered not supported
// percent = event.jPlayer.status.seekPercent;
percent = 0; // Cleans up the inital conditions on all browsers, since seekPercent defaults to 100 when object is undefined.
}
self._progress(percent); // Problem here at initial condition. Due to the Opera clause above of buffered.length > 0 above... Removing it means Opera's white buffer ring never shows like with polyfill.
// Firefox 4 does not always give the final progress event when buffered = 100%
});
this.player.bind($.jPlayer.event.ended + this.eventNamespace, function(event) {
self._resetSolution();
});
},
_initSolution: function() {
if (this.cssTransforms) {
this.jq.progressHolder.show();
this.jq.bufferHolder.show();
}
else {
this.jq.progressHolder.addClass(this.cssClass.gt50).show();
this.jq.progress1.addClass(this.cssClass.fallback);
this.jq.progress2.hide();
this.jq.bufferHolder.hide();
}
this._resetSolution();
},
_resetSolution: function() {
if (this.cssTransforms) {
this.jq.progressHolder.removeClass(this.cssClass.gt50);
this.jq.progress1.css({'transform': 'rotate(0deg)'});
this.jq.progress2.css({'transform': 'rotate(0deg)'}).hide();
}
else {
this.jq.progress1.css('background-position', '0 ' + this.spritePitch + 'px');
}
},
_initCircleControl: function() {
var self = this;
this.jq.circleControl.grab({
onstart: function(){
self.dragging = true;
}, onmove: function(event){
var pc = self._getArcPercent(event.position.x, event.position.y);
self.player.jPlayer("playHead", pc).jPlayer("play");
self._timeupdate(pc);
}, onfinish: function(event){
self.dragging = false;
var pc = self._getArcPercent(event.position.x, event.position.y);
self.player.jPlayer("playHead", pc).jPlayer("play");
}
});
},
_timeupdate: function(percent) {
var degs = percent * 3.6+"deg";
var spriteOffset = (Math.floor((Math.round(percent))*this.spriteRatio)-1)*-this.spritePitch;
if (percent <= 50) {
if (this.cssTransforms) {
this.jq.progressHolder.removeClass(this.cssClass.gt50);
this.jq.progress1.css({'transform': 'rotate(' + degs + ')'});
this.jq.progress2.hide();
} else { // fall back
this.jq.progress1.css('background-position', '0 '+spriteOffset+'px');
}
} else if (percent <= 100) {
if (this.cssTransforms) {
this.jq.progressHolder.addClass(this.cssClass.gt50);
this.jq.progress1.css({'transform': 'rotate(180deg)'});
this.jq.progress2.css({'transform': 'rotate(' + degs + ')'});
this.jq.progress2.show();
} else { // fall back
this.jq.progress1.css('background-position', '0 '+spriteOffset+'px');
}
}
},
_progress: function(percent) {
var degs = percent * 3.6+"deg";
if (this.cssTransforms) {
if (percent <= 50) {
this.jq.bufferHolder.removeClass(this.cssClass.gt50);
this.jq.buffer1.css({'transform': 'rotate(' + degs + ')'});
this.jq.buffer2.hide();
} else if (percent <= 100) {
this.jq.bufferHolder.addClass(this.cssClass.gt50);
this.jq.buffer1.css({'transform': 'rotate(180deg)'});
this.jq.buffer2.show();
this.jq.buffer2.css({'transform': 'rotate(' + degs + ')'});
}
}
},
_getArcPercent: function(pageX, pageY) {
var offset = this.jq.circleControl.offset(),
x = pageX - offset.left - this.jq.circleControl.width()/2,
y = pageY - offset.top - this.jq.circleControl.height()/2,
theta = Math.atan2(y,x);
if (theta > -1 * Math.PI && theta < -0.5 * Math.PI) {
theta = 2 * Math.PI + theta;
}
// theta is now value between -0.5PI and 1.5PI
// ready to be normalized and applied
return (theta + Math.PI / 2) / 2 * Math.PI * 10;
},
setMedia: function(media) {
this.media = $.extend({}, media);
this.player.jPlayer("setMedia", this.media);
},
play: function(time) {
this.player.jPlayer("play", time);
},
pause: function(time) {
this.player.jPlayer("pause", time);
},
destroy: function() {
this.player.unbind(this.eventNamespace);
this.player.jPlayer("destroy");
}
};
| JavaScript |
/*!
* iScroll v4.2.5 ~ Copyright (c) 2012 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
(function(window, doc){
var m = Math,
dummyStyle = doc.createElement('div').style,
vendor = (function () {
var vendors = 't,webkitT,MozT,msT,OT'.split(','),
t,
i = 0,
l = vendors.length;
for ( ; i < l; i++ ) {
t = vendors[i] + 'ransform';
if ( t in dummyStyle ) {
return vendors[i].substr(0, vendors[i].length - 1);
}
}
return false;
})(),
cssVendor = vendor ? '-' + vendor.toLowerCase() + '-' : '',
// Style properties
transform = prefixStyle('transform'),
transitionProperty = prefixStyle('transitionProperty'),
transitionDuration = prefixStyle('transitionDuration'),
transformOrigin = prefixStyle('transformOrigin'),
transitionTimingFunction = prefixStyle('transitionTimingFunction'),
transitionDelay = prefixStyle('transitionDelay'),
// Browser capabilities
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isTouchPad = (/hp-tablet/gi).test(navigator.appVersion),
has3d = prefixStyle('perspective') in dummyStyle,
hasTouch = 'ontouchstart' in window && !isTouchPad,
hasTransform = vendor !== false,
hasTransitionEnd = prefixStyle('transition') in dummyStyle,
RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
START_EV = hasTouch ? 'touchstart' : 'mousedown',
MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
END_EV = hasTouch ? 'touchend' : 'mouseup',
CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
TRNEND_EV = (function () {
if ( vendor === false ) return false;
var transitionEnd = {
'' : 'transitionend',
'webkit' : 'webkitTransitionEnd',
'Moz' : 'transitionend',
'O' : 'otransitionend',
'ms' : 'MSTransitionEnd'
};
return transitionEnd[vendor];
})(),
nextFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { return setTimeout(callback, 1); };
})(),
cancelFrame = (function () {
return window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout;
})(),
// Helpers
translateZ = has3d ? ' translateZ(0)' : '',
// Constructor
iScroll = function (el, options) {
var that = this,
i;
that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
that.wrapper.style.overflow = 'hidden';
that.scroller = that.wrapper.children[0];
// Default options
that.options = {
hScroll: true,
vScroll: true,
x: 0,
y: 0,
bounce: true,
bounceLock: false,
momentum: true,
lockDirection: true,
useTransform: true,
useTransition: false,
topOffset: 0,
checkDOMChanges: false, // Experimental
handleClick: true,
// Scrollbar
hScrollbar: true,
vScrollbar: true,
fixedScrollbar: isAndroid,
hideScrollbar: isIDevice,
fadeScrollbar: isIDevice && has3d,
scrollbarClass: '',
// Zoom
zoom: false,
zoomMin: 1,
zoomMax: 4,
doubleTapZoom: 2,
wheelAction: 'scroll',
// Snap
snap: false,
snapThreshold: 1,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: null,
onZoomStart: null,
onZoom: null,
onZoomEnd: null
};
// User defined options
for (i in options) that.options[i] = options[i];
// Set starting position
that.x = that.options.x;
that.y = that.options.y;
// Normalize options
that.options.useTransform = hasTransform && that.options.useTransform;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.zoom = that.options.useTransform && that.options.zoom;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Helpers FIX ANDROID BUG!
// translate3d and scale doesn't work together!
// Ignoring 3d ONLY WHEN YOU SET that.options.zoom
if ( that.options.zoom && isAndroid ){
translateZ = '';
}
// Set some default styles
that.scroller.style[transitionProperty] = that.options.useTransform ? cssVendor + 'transform' : 'top left';
that.scroller.style[transitionDuration] = '0';
that.scroller.style[transformOrigin] = '0 0';
if (that.options.useTransition) that.scroller.style[transitionTimingFunction] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px)' + translateZ;
else that.scroller.style.cssText += ';position:absolute;top:' + that.y + 'px;left:' + that.x + 'px';
if (that.options.useTransition) that.options.fixedScrollbar = true;
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) {
if (that.options.wheelAction != 'none') {
that._bind('DOMMouseScroll');
that._bind('mousewheel');
}
}
if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
that._checkDOMChanges();
}, 500);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
currPageX: 0, currPageY: 0,
pagesX: [], pagesY: [],
aniTime: null,
wheelZoomCount: 0,
handleEvent: function (e) {
var that = this;
switch(e.type) {
case START_EV:
if (!hasTouch && e.button !== 0) return;
that._start(e);
break;
case MOVE_EV: that._move(e); break;
case END_EV:
case CANCEL_EV: that._end(e); break;
case RESIZE_EV: that._resize(); break;
case 'DOMMouseScroll': case 'mousewheel': that._wheel(e); break;
case TRNEND_EV: that._transitionEnd(e); break;
}
},
_checkDOMChanges: function () {
if (this.moved || this.zoomed || this.animating ||
(this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
this.refresh();
},
_scrollbar: function (dir) {
var that = this,
bar;
if (!that[dir + 'Scrollbar']) {
if (that[dir + 'ScrollbarWrapper']) {
if (hasTransform) that[dir + 'ScrollbarIndicator'].style[transform] = '';
that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
that[dir + 'ScrollbarWrapper'] = null;
that[dir + 'ScrollbarIndicator'] = null;
}
return;
}
if (!that[dir + 'ScrollbarWrapper']) {
// Create the scrollbar wrapper
bar = doc.createElement('div');
if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
bar.style.cssText += ';pointer-events:none;' + cssVendor + 'transition-property:opacity;' + cssVendor + 'transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
that.wrapper.appendChild(bar);
that[dir + 'ScrollbarWrapper'] = bar;
// Create the scrollbar indicator
bar = doc.createElement('div');
if (!that.options.scrollbarClass) {
bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);' + cssVendor + 'background-clip:padding-box;' + cssVendor + 'box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';' + cssVendor + 'border-radius:3px;border-radius:3px';
}
bar.style.cssText += ';pointer-events:none;' + cssVendor + 'transition-property:' + cssVendor + 'transform;' + cssVendor + 'transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);' + cssVendor + 'transition-duration:0;' + cssVendor + 'transform: translate(0,0)' + translateZ;
if (that.options.useTransition) bar.style.cssText += ';' + cssVendor + 'transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)';
that[dir + 'ScrollbarWrapper'].appendChild(bar);
that[dir + 'ScrollbarIndicator'] = bar;
}
if (dir == 'h') {
that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
that.hScrollbarIndicatorSize = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
that.hScrollbarIndicator.style.width = that.hScrollbarIndicatorSize + 'px';
that.hScrollbarMaxScroll = that.hScrollbarSize - that.hScrollbarIndicatorSize;
that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
} else {
that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
that.vScrollbarIndicatorSize = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
that.vScrollbarIndicator.style.height = that.vScrollbarIndicatorSize + 'px';
that.vScrollbarMaxScroll = that.vScrollbarSize - that.vScrollbarIndicatorSize;
that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
}
// Reset position
that._scrollbarPos(dir, true);
},
_resize: function () {
var that = this;
setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
},
_pos: function (x, y) {
if (this.zoomed) return;
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[transform] = 'translate(' + x + 'px,' + y + 'px) scale(' + this.scale + ')' + translateZ;
} else {
x = m.round(x);
y = m.round(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
this._scrollbarPos('h');
this._scrollbarPos('v');
},
_scrollbarPos: function (dir, hidden) {
var that = this,
pos = dir == 'h' ? that.x : that.y,
size;
if (!that[dir + 'Scrollbar']) return;
pos = that[dir + 'ScrollbarProp'] * pos;
if (pos < 0) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] + m.round(pos * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
}
pos = 0;
} else if (pos > that[dir + 'ScrollbarMaxScroll']) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + 'ScrollbarIndicatorSize'] - size);
} else {
pos = that[dir + 'ScrollbarMaxScroll'];
}
}
that[dir + 'ScrollbarWrapper'].style[transitionDelay] = '0';
that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
that[dir + 'ScrollbarIndicator'].style[transform] = 'translate(' + (dir == 'h' ? pos + 'px,0)' : '0,' + pos + 'px)') + translateZ;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y,
c1, c2;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
that.moved = false;
that.animating = false;
that.zoomed = false;
that.distX = 0;
that.distY = 0;
that.absDistX = 0;
that.absDistY = 0;
that.dirX = 0;
that.dirY = 0;
// Gesture start
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
}
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[transform].replace(/[^0-9\-.,]/g, '').split(',');
x = +(matrix[12] || matrix[4]);
y = +(matrix[13] || matrix[5]);
} else {
x = +getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '');
y = +getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '');
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind(TRNEND_EV);
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, y);
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that);
}
}
that.absStartX = that.x; // Needed by snap threshold
that.absStartY = that.y;
that.startX = that.x;
that.startY = that.y;
that.pointX = point.pageX;
that.pointY = point.pageY;
that.startTime = e.timeStamp || Date.now();
if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
that._bind(MOVE_EV, window);
that._bind(END_EV, window);
that._bind(CANCEL_EV, window);
},
_move: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
deltaX = point.pageX - that.pointX,
deltaY = point.pageY - that.pointY,
newX = that.x + deltaX,
newY = that.y + deltaY,
c1, c2, scale,
timestamp = e.timeStamp || Date.now();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
// Zoom
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
that.touchesDist = m.sqrt(c1*c1+c2*c2);
that.zoomed = true;
scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
that.lastScale = scale / this.scale;
newX = this.originX - this.originX * that.lastScale + this.x;
newY = this.originY - this.originY * that.lastScale + this.y;
this.scroller.style[transform] = 'translate(' + newX + 'px,' + newY + 'px) scale(' + scale + ')' + translateZ;
if (that.options.onZoom) that.options.onZoom.call(that, e);
return;
}
that.pointX = point.pageX;
that.pointY = point.pageY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
}
if (newY > that.minScrollY || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
}
that.distX += deltaX;
that.distY += deltaY;
that.absDistX = m.abs(that.distX);
that.absDistY = m.abs(that.distY);
if (that.absDistX < 6 && that.absDistY < 6) {
return;
}
// Lock direction
if (that.options.lockDirection) {
if (that.absDistX > that.absDistY + 5) {
newY = that.y;
deltaY = 0;
} else if (that.absDistY > that.absDistX + 5) {
newX = that.x;
deltaX = 0;
}
}
that.moved = true;
that._pos(newX, newY);
that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (timestamp - that.startTime > 300) {
that.startTime = timestamp;
that.startX = that.x;
that.startY = that.y;
}
if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
},
_end: function (e) {
if (hasTouch && e.touches.length !== 0) return;
var that = this,
point = hasTouch ? e.changedTouches[0] : e,
target, ev,
momentumX = { dist:0, time:0 },
momentumY = { dist:0, time:0 },
duration = (e.timeStamp || Date.now()) - that.startTime,
newPosX = that.x,
newPosY = that.y,
distX, distY,
newDuration,
snap,
scale;
that._unbind(MOVE_EV, window);
that._unbind(END_EV, window);
that._unbind(CANCEL_EV, window);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (that.zoomed) {
scale = that.scale * that.lastScale;
scale = Math.max(that.options.zoomMin, scale);
scale = Math.min(that.options.zoomMax, scale);
that.lastScale = scale / that.scale;
that.scale = scale;
that.x = that.originX - that.originX * that.lastScale + that.x;
that.y = that.originY - that.originY * that.lastScale + that.y;
that.scroller.style[transitionDuration] = '200ms';
that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px) scale(' + that.scale + ')' + translateZ;
that.zoomed = false;
that.refresh();
if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
return;
}
if (!that.moved) {
if (hasTouch) {
if (that.doubleTapTimer && that.options.zoom) {
// Double tapped
clearTimeout(that.doubleTapTimer);
that.doubleTapTimer = null;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
if (that.options.onZoomEnd) {
setTimeout(function() {
that.options.onZoomEnd.call(that, e);
}, 200); // 200 is default zoom duration
}
} else if (this.options.handleClick) {
that.doubleTapTimer = setTimeout(function () {
that.doubleTapTimer = null;
// Find the last touched element
target = point.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = doc.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
point.screenX, point.screenY, point.clientX, point.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._fake = true;
target.dispatchEvent(ev);
}
}, that.options.zoom ? 250 : 0);
}
}
that._resetPos(400);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
if (duration < 300 && that.options.momentum) {
momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
newPosX = that.x + momentumX.dist;
newPosY = that.y + momentumY.dist;
if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
}
if (momentumX.dist || momentumY.dist) {
newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
else {
snap = that._snap(newPosX, newPosY);
newPosX = snap.x;
newPosY = snap.y;
newDuration = m.max(snap.time, newDuration);
}
}
that.scrollTo(m.round(newPosX), m.round(newPosY), newDuration);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
else {
snap = that._snap(that.x, that.y);
if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
}
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
},
_resetPos: function (time) {
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
that.moved = false;
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
}
if (that.hScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.hScrollbarWrapper.style[transitionDelay] = '300ms';
that.hScrollbarWrapper.style.opacity = '0';
}
if (that.vScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.vScrollbarWrapper.style[transitionDelay] = '300ms';
that.vScrollbarWrapper.style.opacity = '0';
}
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_wheel: function (e) {
var that = this,
wheelDeltaX, wheelDeltaY,
deltaX, deltaY,
deltaScale;
if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 12;
wheelDeltaY = e.wheelDeltaY / 12;
} else if('wheelDelta' in e) {
wheelDeltaX = wheelDeltaY = e.wheelDelta / 12;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail * 3;
} else {
return;
}
if (that.options.wheelAction == 'zoom') {
deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
if (deltaScale != that.scale) {
if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.wheelZoomCount++;
that.zoom(e.pageX, e.pageY, deltaScale, 400);
setTimeout(function() {
that.wheelZoomCount--;
if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
}, 400);
}
return;
}
deltaX = that.x + wheelDeltaX;
deltaY = that.y + wheelDeltaY;
if (deltaX > 0) deltaX = 0;
else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
if (deltaY > that.minScrollY) deltaY = that.minScrollY;
else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
if (that.maxScrollY < 0) {
that.scrollTo(deltaX, deltaY, 0);
}
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind(TRNEND_EV);
that._startAni();
},
/**
*
* Utilities
*
*/
_startAni: function () {
var that = this,
startX = that.x, startY = that.y,
startTime = Date.now(),
step, easeOut,
animate;
if (that.animating) return;
if (!that.steps.length) {
that._resetPos(400);
return;
}
step = that.steps.shift();
if (step.x == startX && step.y == startY) step.time = 0;
that.animating = true;
that.moved = true;
if (that.options.useTransition) {
that._transitionTime(step.time);
that._pos(step.x, step.y);
that.animating = false;
if (step.time) that._bind(TRNEND_EV);
else that._resetPos(0);
return;
}
animate = function () {
var now = Date.now(),
newX, newY;
if (now >= startTime + step.time) {
that._pos(step.x, step.y);
that.animating = false;
if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
that._startAni();
return;
}
now = (now - startTime) / step.time - 1;
easeOut = m.sqrt(1 - now * now);
newX = (step.x - startX) * easeOut + startX;
newY = (step.y - startY) * easeOut + startY;
that._pos(newX, newY);
if (that.animating) that.aniTime = nextFrame(animate);
};
animate();
},
_transitionTime: function (time) {
time += 'ms';
this.scroller.style[transitionDuration] = time;
if (this.hScrollbar) this.hScrollbarIndicator.style[transitionDuration] = time;
if (this.vScrollbar) this.vScrollbarIndicator.style[transitionDuration] = time;
},
_momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
var deceleration = 0.0006,
speed = m.abs(dist) / time,
newDist = (speed * speed) / (2 * deceleration),
newTime = 0, outsideDist = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistUpper = maxDistUpper + outsideDist;
speed = speed * maxDistUpper / newDist;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistLower = maxDistLower + outsideDist;
speed = speed * maxDistLower / newDist;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: newDist, time: m.round(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
if (el != this.wrapper) {
left *= this.scale;
top *= this.scale;
}
return { left: left, top: top };
},
_snap: function (x, y) {
var that = this,
i, l,
page, time,
sizeX, sizeY;
// Check page X
page = that.pagesX.length - 1;
for (i=0, l=that.pagesX.length; i<l; i++) {
if (x >= that.pagesX[i]) {
page = i;
break;
}
}
if (page == that.currPageX && page > 0 && that.dirX < 0) page--;
x = that.pagesX[page];
sizeX = m.abs(x - that.pagesX[that.currPageX]);
sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
that.currPageX = page;
// Check page Y
page = that.pagesY.length-1;
for (i=0; i<page; i++) {
if (y >= that.pagesY[i]) {
page = i;
break;
}
}
if (page == that.currPageY && page > 0 && that.dirY < 0) page--;
y = that.pagesY[page];
sizeY = m.abs(y - that.pagesY[that.currPageY]);
sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
that.currPageY = page;
// Snap with constant speed (proportional duration)
time = m.round(m.max(sizeX, sizeY)) || 200;
return { x: x, y: y, time: time };
},
_bind: function (type, el, bubble) {
(el || this.scroller).addEventListener(type, this, !!bubble);
},
_unbind: function (type, el, bubble) {
(el || this.scroller).removeEventListener(type, this, !!bubble);
},
/**
*
* Public methods
*
*/
destroy: function () {
var that = this;
that.scroller.style[transform] = '';
// Remove the scrollbars
that.hScrollbar = false;
that.vScrollbar = false;
that._scrollbar('h');
that._scrollbar('v');
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV, window);
that._unbind(END_EV, window);
that._unbind(CANCEL_EV, window);
if (!that.options.hasTouch) {
that._unbind('DOMMouseScroll');
that._unbind('mousewheel');
}
if (that.options.useTransition) that._unbind(TRNEND_EV);
if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset,
i, l,
els,
pos = 0,
page = 0;
if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
that.wrapperW = that.wrapper.clientWidth || 1;
that.wrapperH = that.wrapper.clientHeight || 1;
that.minScrollY = -that.options.topOffset || 0;
that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
that.dirX = 0;
that.dirY = 0;
if (that.options.onRefresh) that.options.onRefresh.call(that);
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
that.hScrollbar = that.hScroll && that.options.hScrollbar;
that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
// Prepare snap
if (typeof that.options.snap == 'string') {
that.pagesX = [];
that.pagesY = [];
els = that.scroller.querySelectorAll(that.options.snap);
for (i=0, l=els.length; i<l; i++) {
pos = that._offset(els[i]);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
}
} else if (that.options.snap) {
that.pagesX = [];
while (pos >= that.maxScrollX) {
that.pagesX[page] = pos;
pos = pos - that.wrapperW;
page++;
}
if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
pos = 0;
page = 0;
that.pagesY = [];
while (pos >= that.maxScrollY) {
that.pagesY[page] = pos;
pos = pos - that.wrapperH;
page++;
}
if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
}
// Prepare the scrollbars
that._scrollbar('h');
that._scrollbar('v');
if (!that.zoomed) {
that.scroller.style[transitionDuration] = '0';
that._resetPos(400);
}
},
scrollTo: function (x, y, time, relative) {
var that = this,
step = x,
i, l;
that.stop();
if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
for (i=0, l=step.length; i<l; i++) {
if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
}
that._startAni();
},
scrollToElement: function (el, time) {
var that = this, pos;
el = el.nodeType ? el : that.scroller.querySelector(el);
if (!el) return;
pos = that._offset(el);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
that.scrollTo(pos.left, pos.top, time);
},
scrollToPage: function (pageX, pageY, time) {
var that = this, x, y;
time = time === undefined ? 400 : time;
if (that.options.onScrollStart) that.options.onScrollStart.call(that);
if (that.options.snap) {
pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
that.currPageX = pageX;
that.currPageY = pageY;
x = that.pagesX[pageX];
y = that.pagesY[pageY];
} else {
x = -that.wrapperW * pageX;
y = -that.wrapperH * pageY;
if (x < that.maxScrollX) x = that.maxScrollX;
if (y < that.maxScrollY) y = that.maxScrollY;
}
that.scrollTo(x, y, time);
},
disable: function () {
this.stop();
this._resetPos(0);
this.enabled = false;
// If disabled after touchstart we make sure that there are no left over events
this._unbind(MOVE_EV, window);
this._unbind(END_EV, window);
this._unbind(CANCEL_EV, window);
},
enable: function () {
this.enabled = true;
},
stop: function () {
if (this.options.useTransition) this._unbind(TRNEND_EV);
else cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
},
zoom: function (x, y, scale, time) {
var that = this,
relScale = scale / that.scale;
if (!that.options.useTransform) return;
that.zoomed = true;
time = time === undefined ? 200 : time;
x = x - that.wrapperOffsetLeft - that.x;
y = y - that.wrapperOffsetTop - that.y;
that.x = x - x * relScale + that.x;
that.y = y - y * relScale + that.y;
that.scale = scale;
that.refresh();
that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
that.scroller.style[transitionDuration] = time + 'ms';
that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px) scale(' + scale + ')' + translateZ;
that.zoomed = false;
},
isReady: function () {
return !this.moved && !this.zoomed && !this.animating;
}
};
function prefixStyle (style) {
if ( vendor === '' ) return style;
style = style.charAt(0).toUpperCase() + style.substr(1);
return vendor + style;
}
dummyStyle = null; // for the sake of it
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})(window, document);
| JavaScript |
var droidfix = (function () {
var el,
ALLOWED_GAP = 2,
lastTime = ALLOWED_GAP + 1,
callbacks = [];
function init(element) {
el = (typeof element === "string") ? document.getElementById(element) : element;
if (!el) return false;
addEventListeners();
}
function addEventListeners() {
el.addEventListener("timeupdate", timeUpdate, false);
el.addEventListener("ended", ended, false);
}
function timeUpdate(e) {
lastTime = Math.max(lastTime, el.currentTime);
}
function checkAndroidEnd() {
return ((el.duration - lastTime) < ALLOWED_GAP) && (el.currentTime === 0);
}
function ended(e) {
var complete = (el.currentTime === el.duration);
if (complete || checkAndroidEnd()) {
executeEndCallbacks(e);
} else {
triggerPause();
}
}
function addEndListener(fn) {
if (typeof fn === "function") {
callbacks.push(fn);
}
}
function executeEndCallbacks(e) {
for (var fn in callbacks) {
callbacks[fn](e);
}
}
function triggerPause() {
var e = document.createEvent("Events");
e.initEvent("pause", true, true);
el.dispatchEvent(e);
}
return {
init: init,
addEndListener: addEndListener
}
})(); | JavaScript |
/*
jQuery grab
https://github.com/jussi-kalliokoski/jQuery.grab
Ported from Jin.js::gestures
https://github.com/jussi-kalliokoski/jin.js/
Created by Jussi Kalliokoski
Licensed under MIT License.
Includes fix for IE
*/
(function($){
var extend = $.extend,
mousedown = 'mousedown',
mousemove = 'mousemove',
mouseup = 'mouseup',
touchstart = 'touchstart',
touchmove = 'touchmove',
touchend = 'touchend',
touchcancel = 'touchcancel';
function unbind(elem, type, func){
if (type.substr(0,5) !== 'touch'){ // A temporary fix for IE8 data passing problem in Jin.
return $(elem).unbind(type, func);
}
var fnc, i;
for (i=0; i<bind._binds.length; i++){
if (bind._binds[i].elem === elem && bind._binds[i].type === type && bind._binds[i].func === func){
if (document.addEventListener){
elem.removeEventListener(type, bind._binds[i].fnc, false);
} else {
elem.detachEvent('on'+type, bind._binds[i].fnc);
}
bind._binds.splice(i--, 1);
}
}
}
function bind(elem, type, func, pass){
if (type.substr(0,5) !== 'touch'){ // A temporary fix for IE8 data passing problem in Jin.
return $(elem).bind(type, pass, func);
}
var fnc, i;
if (bind[type]){
return bind[type].bind(elem, type, func, pass);
}
fnc = function(e){
if (!e){ // Fix some ie bugs...
e = window.event;
}
if (!e.stopPropagation){
e.stopPropagation = function(){ this.cancelBubble = true; };
}
e.data = pass;
func.call(elem, e);
};
if (document.addEventListener){
elem.addEventListener(type, fnc, false);
} else {
elem.attachEvent('on' + type, fnc);
}
bind._binds.push({elem: elem, type: type, func: func, fnc: fnc});
}
function grab(elem, options)
{
var data = {
move: {x: 0, y: 0},
offset: {x: 0, y: 0},
position: {x: 0, y: 0},
start: {x: 0, y: 0},
affects: document.documentElement,
stopPropagation: false,
preventDefault: true,
touch: true // Implementation unfinished, and doesn't support multitouch
};
extend(data, options);
data.element = elem;
bind(elem, mousedown, mouseDown, data);
if (data.touch){
bind(elem, touchstart, touchStart, data);
}
}
function ungrab(elem){
unbind(elem, mousedown, mousedown);
}
function mouseDown(e){
e.data.position.x = e.pageX;
e.data.position.y = e.pageY;
e.data.start.x = e.pageX;
e.data.start.y = e.pageY;
e.data.event = e;
if (e.data.onstart && e.data.onstart.call(e.data.element, e.data)){
return;
}
if (e.preventDefault && e.data.preventDefault){
e.preventDefault();
}
if (e.stopPropagation && e.data.stopPropagation){
e.stopPropagation();
}
bind(e.data.affects, mousemove, mouseMove, e.data);
bind(e.data.affects, mouseup, mouseUp, e.data);
}
function mouseMove(e){
if (e.preventDefault && e.data.preventDefault){
e.preventDefault();
}
if (e.stopPropagation && e.data.preventDefault){
e.stopPropagation();
}
e.data.move.x = e.pageX - e.data.position.x;
e.data.move.y = e.pageY - e.data.position.y;
e.data.position.x = e.pageX;
e.data.position.y = e.pageY;
e.data.offset.x = e.pageX - e.data.start.x;
e.data.offset.y = e.pageY - e.data.start.y;
e.data.event = e;
if (e.data.onmove){
e.data.onmove.call(e.data.element, e.data);
}
}
function mouseUp(e){
if (e.preventDefault && e.data.preventDefault){
e.preventDefault();
}
if (e.stopPropagation && e.data.stopPropagation){
e.stopPropagation();
}
unbind(e.data.affects, mousemove, mouseMove);
unbind(e.data.affects, mouseup, mouseUp);
e.data.event = e;
if (e.data.onfinish){
e.data.onfinish.call(e.data.element, e.data);
}
}
function touchStart(e){
e.data.position.x = e.touches[0].pageX;
e.data.position.y = e.touches[0].pageY;
e.data.start.x = e.touches[0].pageX;
e.data.start.y = e.touches[0].pageY;
e.data.event = e;
if (e.data.onstart && e.data.onstart.call(e.data.element, e.data)){
return;
}
if (e.preventDefault && e.data.preventDefault){
e.preventDefault();
}
if (e.stopPropagation && e.data.stopPropagation){
e.stopPropagation();
}
bind(e.data.affects, touchmove, touchMove, e.data);
bind(e.data.affects, touchend, touchEnd, e.data);
}
function touchMove(e){
if (e.preventDefault && e.data.preventDefault){
e.preventDefault();
}
if (e.stopPropagation && e.data.stopPropagation){
e.stopPropagation();
}
e.data.move.x = e.touches[0].pageX - e.data.position.x;
e.data.move.y = e.touches[0].pageY - e.data.position.y;
e.data.position.x = e.touches[0].pageX;
e.data.position.y = e.touches[0].pageY;
e.data.offset.x = e.touches[0].pageX - e.data.start.x;
e.data.offset.y = e.touches[0].pageY - e.data.start.y;
e.data.event = e;
if (e.data.onmove){
e.data.onmove.call(e.data.elem, e.data);
}
}
function touchEnd(e){
if (e.preventDefault && e.data.preventDefault){
e.preventDefault();
}
if (e.stopPropagation && e.data.stopPropagation){
e.stopPropagation();
}
unbind(e.data.affects, touchmove, touchMove);
unbind(e.data.affects, touchend, touchEnd);
e.data.event = e;
if (e.data.onfinish){
e.data.onfinish.call(e.data.element, e.data);
}
}
bind._binds = [];
$.fn.grab = function(a, b){
return this.each(function(){
return grab(this, a, b);
});
};
$.fn.ungrab = function(a){
return this.each(function(){
return ungrab(this, a);
});
};
})(jQuery); | JavaScript |
document.write('<script src="http://connect.facebook.net/en_US/all.js"></script>');
var FB_LoginUrl= 'http://www.facebook.com/dialog/oauth?client_id=663137273709858&redirect_uri=http://www.c2life.com.vn/ipad/OpenId&response_type=token&display=popup&scope=email,manage_pages,photo_upload,publish_actions,publish_stream,read_friendlists,status_update,user_birthday,user_photos,user_status,video_upload';
var windowInvite;
function FB_LOGIN(){
window.location = FB_LoginUrl;
}
function check_info()
{
var url = root + 'ipad/view_check_login';
$.post(url,{
},
function(data){
if(data == "false")
{
FB_LOGIN();
}
else
{
checkFirstTime();
}
});
return false;
}
function checkFirstTime(){
var url = root + 'ipad/view_check_first_time';
$.post(url,{
},
function(data){
if(data == "true")
{
getInfo();
}
if(data == "false")
{
nex_page(4);
}
});
return false;
}
function getInfo()
{
var url = root + 'ipad/view_get_info';
$.post(url,{
},
function(data){
if(data)
{
$(".tab-register").html(data);
nex_page(2);
}
});
return false;
}
function select_link()
{
var url = root + 'ipad/view_code';
var type =$("#type_check_1").val();
$.post(url,{ type:type
},
function(data){
if(data)
{
$(".tab-noti").html(data);
nex_page(3);
}
});
return false;
}
function update_info()
{
var fullname =$(".fullname").val();
var phone =$(".phone").val();
var email =$(".email").val();
var type =$("#type_check").val();
var url = root + 'ipad/view_update_info';
if ($('.phone').val() == '') {
$('.phone').focus();
return false;
}
if ($('.phone').val().length < 10) {
$('.phone').focus();
}
var remember = $('#check').is(":checked");
if(remember == false)
{
return false;
}
$.post(url,{ fullname:fullname,phone:phone,type:type
},
function(data){
$(".tab-noti").html(data);
nex_page(3);
});
return false;
}
// global properties
var stage;
var currentTick = 0;
var arrayImages = new Array();
var loadedImgNumber = 0;
// for welcome screen
var loadingC2Img;
var loadingTextImg;
var loadingMusicImg;
// for other screen
var stageSprite;
var topLightImgs;
var logoSprite;
var welcomeCha;
var tvcCha;
// for character lap
var welcomeLapSpite;
var tvcStartSpite;
var tvcLapSpite;
// sound
var backgroundSound;
var tvcSound;
var tickTVC = -1;
/**
* Init handler
*/
$(document).ready(function () {
log("Width: " + window.innerWidth + " - Height: " + window.innerHeight + "- Ratio: " + window.devicePixelRatio);
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode(
"@-ms-viewport{width:auto!important}"
)
);
document.getElementsByTagName("head")[0].
appendChild(msViewportStyle);
}
initLoadingScreen();
$("#btnHome").click(welcomeVideoStart);
$("#btnVideo").click(tvcVideoStart);
$("#btnMusic").click(fullsongVideoStart);
$("#btnShare").click(showshareStart);
$('#page-mp3').html('<img src="'+ root +'static/images/mobile/videotrangmp3_07504.gif" alt="" width="400" height="419" />').hide();
$("#sound-welcom").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", {
m4a: root + "static/images/mobile/Welcome.m4a",
oga: root + "static/images/mobile/Welcome.ogg"
});
},
swfPath: "js",
supplied: "m4a, oga",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true,
nativeSupport: true,
oggSupport: false,
loop: true,
customCssIds: true
});
$("#sound-mp3").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", {
m4a: root + "static/images/mobile/videotrangmp3.mp3",
oga: root + "static/images/mobile/videotrangmp3.ogg"
});
},
swfPath: "js",
supplied: "m4a, oga",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true,
nativeSupport: true,
oggSupport: false,
loop: true,
customCssIds: true
});
$("#btnNext").click(function () {
$(".buttonNext").hide();
startMainScreen();
$("#sound-welcom").jPlayer("play");
$('#welcom').html('<img src="'+ root +'static/images/mobile/Welcome.gif" alt="" width="276" height="451" />');
});
$('.tab-register .icon').click(function(){
$('.tab-register .icon').removeClass('active');
$(this).addClass('active');
});
$('.icon-cuatui').on('click',function(){
$(this).removeClass('unactive').addClass('active');
$('.icon-zing').removeClass('active').addClass('unactive');
$("#type_check_1").val("1");
});
$('.icon-zing').on('click',function(){
$(this).removeClass('unactive').addClass('active');
$('.icon-cuatui').removeClass('active').addClass('unactive');
$("#type_check_1").val("2");
});
});
var ischeck = true;
var ischeck1 = true;
function nex_page(id){
$('.content-share > div').hide();
$('.content-share > div').eq(id).show();
if(!$('.tab-giaithuong').is(':hidden') && ischeck){
var myScroll = new iScroll('iscroll_giaithuong');
ischeck = false;
}
}
/**
* Init welcome handler
*/
function initLoadingScreen() {
arrayImages[0] = new Image();
arrayImages[0].onload = handleLoadingImageLoad;
arrayImages[0].onerror = handleImageError;
arrayImages[0].src = root + "static/images/mobile/Chai_C2.png";
arrayImages[1] = new Image();
arrayImages[1].onload = handleLoadingImageLoad;
arrayImages[1].onerror = handleImageError;
arrayImages[1].src = root + "static/images/mobile/music.png";
arrayImages[2] = new Image();
arrayImages[2].onload = handleLoadingImageLoad;
arrayImages[2].onerror = handleImageError;
arrayImages[2].src = root + "static/images/mobile/loading.png";
}
/**
* Handle loading image for welcome
*/
function handleLoadingImageLoad(e) {
loadedImgNumber++;
if (loadedImgNumber == 3) {
startWelcomeScreen();
}
}
/**
* Handle loading error
*/
function handleImageError(e) {
log("Error Loading Image : " + e.target.src);
}
/**
* Initilale Welcome Screen
*/
function startWelcomeScreen() {
$(".loading").hide();
var canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
loadingC2Img = new createjs.Bitmap(arrayImages[0]);
loadingC2Img.regX = 85;
loadingC2Img.regY = 460;
loadingC2Img.x = 512;
loadingC2Img.y = 570;
loadingC2Img.scaleX = 0.8;
loadingC2Img.scaleY = 0.8;
stage.addChild(loadingC2Img);
loadingMusicImg = new createjs.Bitmap(arrayImages[1]);
loadingMusicImg.regX = 85;
loadingMusicImg.regY = 217;
loadingMusicImg.x = 512;
loadingMusicImg.y = 150;
stage.addChild(loadingMusicImg);
loadingTextImg = new createjs.Bitmap(arrayImages[2]);
loadingTextImg.regX = 87;
loadingTextImg.regY = 30;
loadingTextImg.x = 512;
loadingTextImg.y = 150;
stage.addChild(loadingTextImg);
createjs.Ticker.setFPS(12);
createjs.Ticker.addEventListener("tick", tickLoading);
initMainScreen();
}
/**
* Tick Handler
*/
var angle = 5;
function tickLoading() {
currentTick += 1;
loadingC2Img.rotation += angle;
if (loadingC2Img.rotation == 10)
angle = -5;
else if (loadingC2Img.rotation == -10)
angle = 5;
if (loadingMusicImg.y > 0)
loadingMusicImg.y -= 13;
else {
if (currentTick == 1) {
loadingMusicImg.y = 150;
}
}
if (currentTick > 12)
currentTick = 0;
stage.update();
}
/**
* Handle loading image for main stage
*/
function initMainScreen() {
arrayImages[3] = new Image();
arrayImages[3].onload = handleImageLoad;
arrayImages[3].onerror = handleImageError;
arrayImages[3].src = root + "static/images/mobile/light.png";
arrayImages[4] = new Image();
arrayImages[4].onload = handleImageLoad;
arrayImages[4].onerror = handleImageError;
arrayImages[4].src = root + "static/images/mobile/logo.png";
arrayImages[5] = new Image();
arrayImages[5].onload = handleImageLoad;
arrayImages[5].onerror = handleImageError;
arrayImages[5].src = root + "static/images/mobile/stage_tablet.png";
arrayImages[6] = new Image();
arrayImages[6].onload = handleImageLoad;
arrayImages[6].onerror = handleImageError;
arrayImages[6].src = root + "static/images/mobile/welcome_lap_SH.png";
arrayImages[7] = new Image();
arrayImages[7].onload = handleImageLoad;
arrayImages[7].onerror = handleImageError;
arrayImages[7].src = root + "static/images/mobile/startTvc_S.png";
arrayImages[8] = new Image();
arrayImages[8].onload = handleImageLoad;
arrayImages[8].onerror = handleImageError;
arrayImages[8].src = root + "static/images/mobile/tvclap.png";
tvcSound =new mProton.Sound(root + "static/images/mobile/tvc.mp3", 0, handleImageLoad);
}
/**
* Handle loading image for main stage
*/
function handleImageLoad(e) {
loadedImgNumber++;
if (loadedImgNumber == 10) {
reset();
$(".buttonNext").show();
}
}
/**
* Initilale Main Screen
*/
function startMainScreen() {
$(".buttons").show();
stage = new createjs.Stage(canvas);
log("Start main stage");
log("Add stage");
var stageSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[5]],
//width, height & registration point of each sprite
frames: [
[0, 1, 867, 90],
[0, 1, 867, 90],
[0, 1, 867, 90],
[0, 103, 867, 90],
[0, 103, 867, 90],
[0, 103, 867, 90],
[0, 205, 867, 90],
[0, 205, 867, 90],
[0, 205, 867, 90],
[0, 307, 867, 90],
[0, 307, 867, 90],
[0, 307, 867, 90]
],
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
stageanimation: [0, 11, "stageanimation"]
}
});
stageSprite = new createjs.BitmapAnimation(stageSpriteSheet);
stageSprite.x = 77;
stageSprite.y = 534;
stageSprite.gotoAndPlay("stageanimation");
stage.addChild(stageSprite);
log("Add light");
topLightImgs = new Array();
var positionLeft = 110;
for (var i = 0; i < 3; i++) {
topLightImgs[i] = new createjs.Bitmap(arrayImages[3]);
topLightImgs[i].regX = 225;
topLightImgs[i].regY = 13;
topLightImgs[i].x = positionLeft;
topLightImgs[i].y = -100;
positionLeft += 400;
topLightImgs[i].scaleX = 1.2;
topLightImgs[i].scaleY = 1.2;
stage.addChild(topLightImgs[i]);
}
log("Add logo");
var logoSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[4]],
//width, height & registration point of each sprite
frames: [
[0, 0, 227, 386],
[227, 0, 227, 386],
[454, 0, 227, 386],
[681, 0, 227, 386],
[908, 0, 227, 386],
[1135, 0, 227, 386],
[1362, 0, 227, 386],
[1599, 0, 227, 386]
],
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
stay: {
frames: [0],
next: "run",
frequency: 2
},
run: {
frames: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6]
}
}
});
logoSprite = new createjs.BitmapAnimation(logoSpriteSheet);
logoSprite.x = 146;
logoSprite.y = 18;
logoSprite.gotoAndPlay("run");
stage.addChild(logoSprite);
log("Add Welcome lap character");
var welcomeLapSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[6]],
//width, height & registration point of each sprite
frames: { width: 139, height: 250, regX: 0, regY: 0, count: 110 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
lap: [0, 108]
}
});
welcomeLapSpite = new createjs.BitmapAnimation(welcomeLapSpriteSheet);
welcomeLapSpite.x = 410;
welcomeLapSpite.y = 210;
welcomeLapSpite.scaleX = 1.5;
welcomeLapSpite.scaleY = 1.5;
welcomeLapSpite.gotoAndStop("lap");
welcomeLapSpite.visible = false;
stage.addChild(welcomeLapSpite);
log("Add tvc Start character");
var tvcStartSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[7]],
//width, height & registration point of each sprite
frames: { width: 233, height: 250.5, regX: 0, regY: 0, count: 64 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
walk: [0, 64]
}
});
tvcStartSpite = new createjs.BitmapAnimation(tvcStartSpriteSheet);
tvcStartSpite.x = 450;
tvcStartSpite.y = 160;
tvcStartSpite.scaleX = 1.8;
tvcStartSpite.scaleY = 1.8;
tvcStartSpite.gotoAndStop("walk");
tvcStartSpite.visible = false;
stage.addChild(tvcStartSpite);
var tvcLapSpriteSheet = new createjs.SpriteSheet({
//image to use
images: [arrayImages[8]],
//width, height & registration point of each sprite
frames: { width: 66, height: 250, regX: 0, regY: 0, count: 117 },
// To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
animations: {
lap: [0, 115]
}
});
tvcLapSpite = new createjs.BitmapAnimation(tvcLapSpriteSheet);
tvcLapSpite.x = 750;
tvcLapSpite.y = 160;
tvcLapSpite.scaleX = 1.8;
tvcLapSpite.scaleY = 1.8;
tvcLapSpite.gotoAndStop("lap");
tvcLapSpite.visible = false;
stage.addChild(tvcLapSpite);
createjs.Ticker.setFPS(8);
createjs.Ticker.addEventListener("tick", tickHandle);
setActiveTab($("#btnHome"));
//var introVideo = document.getElementById("welcomeVideo");
//var bitmap = new createjs.Bitmap(introVideo);
//bitmap.x = 0;
//bitmap.y = 300;
//bitmap.scaleX = 0.5;
//bitmap.scaleY = 0.5;
//stage.addChild(bitmap);
// welcomeVideoStart();
}
/**
* Tick Handler
*/
var lightAngle = 2;
function tickHandle() {
currentTick += 1;
topLightImgs[0].rotation += lightAngle;
topLightImgs[1].rotation -= lightAngle / 2;
topLightImgs[2].rotation -= lightAngle;
if (topLightImgs[0].rotation == 10)
lightAngle = -2;
else if (topLightImgs[0].rotation == -10)
lightAngle = 2;
if (currentTick > 8)
currentTick = 0;
if (tickTVC > -1) {
tickTVC += 1;
if (tickTVC == 54) {
}
else if (tickTVC == 60) {
//logoSprite.visible = false;
showVideo("tvcVideo", tvcVideoEnd);
$('.bg-tvc').show();
}
else if (tickTVC == 64) {
tvcLapSpite.visible = true;
tvcLapSpite.play();
tvcStartSpite.visible = false;
tvcStartSpite.stop();
tickTVC = -1;
document.getElementById("tvcVideo").play();
}
}
stage.update();
}
/**
* Set tab active
*/
function setActiveTab(button) {
$(".buttons button").removeClass("active");
$(button).addClass("active");
}
/**
* Reset
*/
function reset() {
stage.removeAllChildren();
createjs.Ticker.removeAllListeners();
stage.update();
}
/**
* log message
*/
function log(message) {
console.log(message);
$("#message").html(message);
}
function welcomeVideoStart() {
pauseVideos();
showwelcom();
setActiveTab($("#btnHome"));
//showVideo();
// document.getElementById("welcomeVideo").play();
}
function showwelcom() {
logoSprite.visible = true;
$('#welcom').show();
$("video").removeClass("videoActive");
$("#sound-welcom").jPlayer("play");
$('#welcom').show();
$('#welcom img').attr('src',root + 'static/images/mobile/Welcome.gif');
}
function tvcVideoStart() {
pauseVideos();
setActiveTab($("#btnVideo"));
$("video").removeClass("videoActive");
tvcStartSpite.visible = true;
tvcStartSpite.play();
tickTVC = 0;
tvcSound.play();
}
function showVideo(videoid, nextFunction) {
$("video").removeClass("videoActive");
var video = document.getElementById(videoid);
$(video).addClass("videoActive");
droidfix.init(video);
video.addEventListener("abort", nextFunction);
droidfix.addEndListener(nextFunction);
}
function fullsongVideoStart() {
pauseVideos();
setActiveTab($("#btnMusic"));
showmp3();
}
function showmp3() {
logoSprite.visible = true;
$('#page-mp3').show();
$("video").removeClass("videoActive");
$("#sound-mp3").jPlayer("play");
$('.img-baihat').show();
$('#page-mp3').show();
$('#page-mp3 img').attr('src',root + 'static/images/mobile/videotrangmp3_07504.gif');
}
function showshareStart(){
pauseVideos();
setActiveTab($("#btnShare"));
showshare();
if(!$('.tab-rules').is(':hidden') && ischeck1){
var myScroll_1 = new iScroll('iscroll_rules');
ischeck1 = false;
}
}
function showshare(){
logoSprite.visible = true;
$('#tvcVideo').removeClass('videoActive');
$('.content-share').show();
}
function welcomeVideoEnd() {
log("Welcome video end");
$("#welcomeVideo").removeClass("videoActive");
welcomeLapSpite.visible = true;
welcomeLapSpite.play();
backgroundSound.playOrResume();
}
function tvcVideoEnd() {
log("TVC video end");
backgroundSound.playOrResume();
}
function fullsongVideoEnd() {
log("Fullsong video end");
backgroundSound.playOrResume();
}
function pauseVideos() {
$("#sound-welcom").jPlayer("stop");
$('#welcom img').attr('src',root + 'static/images/mobile/blank.gif');
$("#sound-mp3").jPlayer("stop");
$('#page-mp3 img').attr('src',root + 'static/images/mobile/blank.gif');
document.getElementById("tvcVideo").pause();
tvcStartSpite.visible = false;
tvcStartSpite.stop();
tvcLapSpite.visible = false;
tvcLapSpite.stop();
tickTVC = -1;
tvcSound.stop();
$('.content-share').hide();
$('#welcom').hide();
$('#page-mp3').hide();
$('.bg-tvc').hide();
$('.img-baihat').hide();
} | JavaScript |
/*
* jPlayer Plugin for jQuery JavaScript Library
* http://www.jplayer.org
*
* Copyright (c) 2009 - 2012 Happyworm Ltd
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
*
* Author: Mark J Panaghiston
* Version: 2.2.0
* Date: 13th September 2012
*/
/* Code verified using http://www.jshint.com/ */
/*jshint asi:false, bitwise:false, boss:false, browser:true, curly:true, debug:false, eqeqeq:true, eqnull:false, evil:false, forin:false, immed:false, jquery:true, laxbreak:false, newcap:true, noarg:true, noempty:true, nonew:true, onevar:false, passfail:false, plusplus:false, regexp:false, undef:true, sub:false, strict:false, white:false smarttabs:true */
/*global jQuery:false, ActiveXObject:false, alert:false */
(function($, undefined) {
// Adapted from jquery.ui.widget.js (1.8.7): $.widget.bridge
$.fn.jPlayer = function( options ) {
var name = "jPlayer";
var isMethodCall = typeof options === "string",
args = Array.prototype.slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.extend.apply( null, [ true, options ].concat(args) ) :
options;
// prevent calls to internal methods
if ( isMethodCall && options.charAt( 0 ) === "_" ) {
return returnValue;
}
if ( isMethodCall ) {
this.each(function() {
var instance = $.data( this, name ),
methodValue = instance && $.isFunction( instance[options] ) ?
instance[ options ].apply( instance, args ) :
instance;
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
// instance.option( options || {} )._init(); // Orig jquery.ui.widget.js code: Not recommend for jPlayer. ie., Applying new options to an existing instance (via the jPlayer constructor) and performing the _init(). The _init() is what concerns me. It would leave a lot of event handlers acting on jPlayer instance and the interface.
instance.option( options || {} ); // The new constructor only changes the options. Changing options only has basic support atm.
} else {
$.data( this, name, new $.jPlayer( options, this ) );
}
});
}
return returnValue;
};
$.jPlayer = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this.element = $(element);
this.options = $.extend(true, {},
this.options,
options
);
var self = this;
this.element.bind( "remove.jPlayer", function() {
self.destroy();
});
this._init();
}
};
// End of: (Adapted from jquery.ui.widget.js (1.8.7))
// Emulated HTML5 methods and properties
$.jPlayer.emulateMethods = "load play pause";
$.jPlayer.emulateStatus = "src readyState networkState currentTime duration paused ended playbackRate";
$.jPlayer.emulateOptions = "muted volume";
// Reserved event names generated by jPlayer that are not part of the HTML5 Media element spec
$.jPlayer.reservedEvent = "ready flashreset resize repeat error warning";
// Events generated by jPlayer
$.jPlayer.event = {
ready: "jPlayer_ready",
flashreset: "jPlayer_flashreset", // Similar to the ready event if the Flash solution is set to display:none and then shown again or if it's reloaded for another reason by the browser. For example, using CSS position:fixed on Firefox for the full screen feature.
resize: "jPlayer_resize", // Occurs when the size changes through a full/restore screen operation or if the size/sizeFull options are changed.
repeat: "jPlayer_repeat", // Occurs when the repeat status changes. Usually through clicks on the repeat button of the interface.
click: "jPlayer_click", // Occurs when the user clicks on one of the following: poster image, html video, flash video.
error: "jPlayer_error", // Event error code in event.jPlayer.error.type. See $.jPlayer.error
warning: "jPlayer_warning", // Event warning code in event.jPlayer.warning.type. See $.jPlayer.warning
// Other events match HTML5 spec.
loadstart: "jPlayer_loadstart",
progress: "jPlayer_progress",
suspend: "jPlayer_suspend",
abort: "jPlayer_abort",
emptied: "jPlayer_emptied",
stalled: "jPlayer_stalled",
play: "jPlayer_play",
pause: "jPlayer_pause",
loadedmetadata: "jPlayer_loadedmetadata",
loadeddata: "jPlayer_loadeddata",
waiting: "jPlayer_waiting",
playing: "jPlayer_playing",
canplay: "jPlayer_canplay",
canplaythrough: "jPlayer_canplaythrough",
seeking: "jPlayer_seeking",
seeked: "jPlayer_seeked",
timeupdate: "jPlayer_timeupdate",
ended: "jPlayer_ended",
ratechange: "jPlayer_ratechange",
durationchange: "jPlayer_durationchange",
volumechange: "jPlayer_volumechange"
};
$.jPlayer.htmlEvent = [ // These HTML events are bubbled through to the jPlayer event, without any internal action.
"loadstart",
// "progress", // jPlayer uses internally before bubbling.
// "suspend", // jPlayer uses internally before bubbling.
"abort",
// "error", // jPlayer uses internally before bubbling.
"emptied",
"stalled",
// "play", // jPlayer uses internally before bubbling.
// "pause", // jPlayer uses internally before bubbling.
"loadedmetadata",
"loadeddata",
// "waiting", // jPlayer uses internally before bubbling.
// "playing", // jPlayer uses internally before bubbling.
"canplay",
"canplaythrough",
// "seeking", // jPlayer uses internally before bubbling.
// "seeked", // jPlayer uses internally before bubbling.
// "timeupdate", // jPlayer uses internally before bubbling.
// "ended", // jPlayer uses internally before bubbling.
"ratechange"
// "durationchange" // jPlayer uses internally before bubbling.
// "volumechange" // jPlayer uses internally before bubbling.
];
$.jPlayer.pause = function() {
$.each($.jPlayer.prototype.instances, function(i, element) {
if(element.data("jPlayer").status.srcSet) { // Check that media is set otherwise would cause error event.
element.jPlayer("pause");
}
});
};
$.jPlayer.timeFormat = {
showHour: false,
showMin: true,
showSec: true,
padHour: false,
padMin: true,
padSec: true,
sepHour: ":",
sepMin: ":",
sepSec: ""
};
$.jPlayer.convertTime = function(s) {
var myTime = new Date(s * 1000);
var hour = myTime.getUTCHours();
var min = myTime.getUTCMinutes();
var sec = myTime.getUTCSeconds();
var strHour = ($.jPlayer.timeFormat.padHour && hour < 10) ? "0" + hour : hour;
var strMin = ($.jPlayer.timeFormat.padMin && min < 10) ? "0" + min : min;
var strSec = ($.jPlayer.timeFormat.padSec && sec < 10) ? "0" + sec : sec;
return (($.jPlayer.timeFormat.showHour) ? strHour + $.jPlayer.timeFormat.sepHour : "") + (($.jPlayer.timeFormat.showMin) ? strMin + $.jPlayer.timeFormat.sepMin : "") + (($.jPlayer.timeFormat.showSec) ? strSec + $.jPlayer.timeFormat.sepSec : "");
};
// Adapting jQuery 1.4.4 code for jQuery.browser. Required since jQuery 1.3.2 does not detect Chrome as webkit.
$.jPlayer.uaBrowser = function( userAgent ) {
var ua = userAgent.toLowerCase();
// Useragent RegExp
var rwebkit = /(webkit)[ \/]([\w.]+)/;
var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/;
var rmsie = /(msie) ([\w.]+)/;
var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
};
// Platform sniffer for detecting mobile devices
$.jPlayer.uaPlatform = function( userAgent ) {
var ua = userAgent.toLowerCase();
// Useragent RegExp
var rplatform = /(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/;
var rtablet = /(ipad|playbook)/;
var randroid = /(android)/;
var rmobile = /(mobile)/;
var platform = rplatform.exec( ua ) || [];
var tablet = rtablet.exec( ua ) ||
!rmobile.exec( ua ) && randroid.exec( ua ) ||
[];
if(platform[1]) {
platform[1] = platform[1].replace(/\s/g, "_"); // Change whitespace to underscore. Enables dot notation.
}
return { platform: platform[1] || "", tablet: tablet[1] || "" };
};
$.jPlayer.browser = {
};
$.jPlayer.platform = {
};
var browserMatch = $.jPlayer.uaBrowser(navigator.userAgent);
if ( browserMatch.browser ) {
$.jPlayer.browser[ browserMatch.browser ] = true;
$.jPlayer.browser.version = browserMatch.version;
}
var platformMatch = $.jPlayer.uaPlatform(navigator.userAgent);
if ( platformMatch.platform ) {
$.jPlayer.platform[ platformMatch.platform ] = true;
$.jPlayer.platform.mobile = !platformMatch.tablet;
$.jPlayer.platform.tablet = !!platformMatch.tablet;
}
$.jPlayer.prototype = {
count: 0, // Static Variable: Change it via prototype.
version: { // Static Object
script: "2.2.0",
needFlash: "2.2.0",
flash: "unknown"
},
options: { // Instanced in $.jPlayer() constructor
swfPath: "js", // Path to Jplayer.swf. Can be relative, absolute or server root relative.
solution: "html, flash", // Valid solutions: html, flash. Order defines priority. 1st is highest,
supplied: "mp3", // Defines which formats jPlayer will try and support and the priority by the order. 1st is highest,
preload: 'metadata', // HTML5 Spec values: none, metadata, auto.
volume: 0.8, // The volume. Number 0 to 1.
muted: false,
wmode: "opaque", // Valid wmode: window, transparent, opaque, direct, gpu.
backgroundColor: "#000000", // To define the jPlayer div and Flash background color.
cssSelectorAncestor: "#jp_container_1",
cssSelector: { // * denotes properties that should only be required when video media type required. _cssSelector() would require changes to enable splitting these into Audio and Video defaults.
videoPlay: ".jp-video-play", // *
play: ".jp-play",
pause: ".jp-pause",
stop: ".jp-stop",
seekBar: ".jp-seek-bar",
playBar: ".jp-play-bar",
mute: ".jp-mute",
unmute: ".jp-unmute",
volumeBar: ".jp-volume-bar",
volumeBarValue: ".jp-volume-bar-value",
volumeMax: ".jp-volume-max",
currentTime: ".jp-current-time",
duration: ".jp-duration",
fullScreen: ".jp-full-screen", // *
restoreScreen: ".jp-restore-screen", // *
repeat: ".jp-repeat",
repeatOff: ".jp-repeat-off",
gui: ".jp-gui", // The interface used with autohide feature.
noSolution: ".jp-no-solution" // For error feedback when jPlayer cannot find a solution.
},
fullScreen: false,
autohide: {
restored: false, // Controls the interface autohide feature.
full: true, // Controls the interface autohide feature.
fadeIn: 200, // Milliseconds. The period of the fadeIn anim.
fadeOut: 600, // Milliseconds. The period of the fadeOut anim.
hold: 1000 // Milliseconds. The period of the pause before autohide beings.
},
loop: false,
repeat: function(event) { // The default jPlayer repeat event handler
if(event.jPlayer.options.loop) {
$(this).unbind(".jPlayerRepeat").bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function() {
$(this).jPlayer("play");
});
} else {
$(this).unbind(".jPlayerRepeat");
}
},
nativeVideoControls: {
// Works well on standard browsers.
// Phone and tablet browsers can have problems with the controls disappearing.
},
noFullScreen: {
msie: /msie [0-6]/,
ipad: /ipad.*?os [0-4]/,
iphone: /iphone/,
ipod: /ipod/,
android_pad: /android [0-3](?!.*?mobile)/,
android_phone: /android.*?mobile/,
blackberry: /blackberry/,
windows_ce: /windows ce/,
webos: /webos/
},
noVolume: {
ipad: /ipad/,
iphone: /iphone/,
ipod: /ipod/,
android_pad: /android(?!.*?mobile)/,
android_phone: /android.*?mobile/,
blackberry: /blackberry/,
windows_ce: /windows ce/,
webos: /webos/,
playbook: /playbook/
},
verticalVolume: false, // Calculate volume from the bottom of the volume bar. Default is from the left. Also volume affects either width or height.
// globalVolume: false, // Not implemented: Set to make volume changes affect all jPlayer instances
// globalMute: false, // Not implemented: Set to make mute changes affect all jPlayer instances
idPrefix: "jp", // Prefix for the ids of html elements created by jPlayer. For flash, this must not include characters: . - + * / \
noConflict: "jQuery",
emulateHtml: false, // Emulates the HTML5 Media element on the jPlayer element.
errorAlerts: false,
warningAlerts: false
},
optionsAudio: {
size: {
width: "0px",
height: "0px",
cssClass: ""
},
sizeFull: {
width: "0px",
height: "0px",
cssClass: ""
}
},
optionsVideo: {
size: {
width: "480px",
height: "270px",
cssClass: "jp-video-270p"
},
sizeFull: {
width: "100%",
height: "100%",
cssClass: "jp-video-full"
}
},
instances: {}, // Static Object
status: { // Instanced in _init()
src: "",
media: {},
paused: true,
format: {},
formatType: "",
waitForPlay: true, // Same as waitForLoad except in case where preloading.
waitForLoad: true,
srcSet: false,
video: false, // True if playing a video
seekPercent: 0,
currentPercentRelative: 0,
currentPercentAbsolute: 0,
currentTime: 0,
duration: 0,
readyState: 0,
networkState: 0,
playbackRate: 1,
ended: 0
/* Persistant status properties created dynamically at _init():
width
height
cssClass
nativeVideoControls
noFullScreen
noVolume
*/
},
internal: { // Instanced in _init()
ready: false
// instance: undefined
// domNode: undefined
// htmlDlyCmdId: undefined
// autohideId: undefined
},
solution: { // Static Object: Defines the solutions built in jPlayer.
html: true,
flash: true
},
// 'MPEG-4 support' : canPlayType('video/mp4; codecs="mp4v.20.8"')
format: { // Static Object
mp3: {
codec: 'audio/mpeg; codecs="mp3"',
flashCanPlay: true,
media: 'audio'
},
m4a: { // AAC / MP4
codec: 'audio/mp4; codecs="mp4a.40.2"',
flashCanPlay: true,
media: 'audio'
},
oga: { // OGG
codec: 'audio/ogg; codecs="vorbis"',
flashCanPlay: false,
media: 'audio'
},
wav: { // PCM
codec: 'audio/wav; codecs="1"',
flashCanPlay: false,
media: 'audio'
},
webma: { // WEBM
codec: 'audio/webm; codecs="vorbis"',
flashCanPlay: false,
media: 'audio'
},
fla: { // FLV / F4A
codec: 'audio/x-flv',
flashCanPlay: true,
media: 'audio'
},
rtmpa: { // RTMP AUDIO
codec: 'audio/rtmp; codecs="rtmp"',
flashCanPlay: true,
media: 'audio'
},
m4v: { // H.264 / MP4
codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
flashCanPlay: true,
media: 'video'
},
ogv: { // OGG
codec: 'video/ogg; codecs="theora, vorbis"',
flashCanPlay: false,
media: 'video'
},
webmv: { // WEBM
codec: 'video/webm; codecs="vorbis, vp8"',
flashCanPlay: false,
media: 'video'
},
flv: { // FLV / F4V
codec: 'video/x-flv',
flashCanPlay: true,
media: 'video'
},
rtmpv: { // RTMP VIDEO
codec: 'video/rtmp; codecs="rtmp"',
flashCanPlay: true,
media: 'video'
}
},
_init: function() {
var self = this;
this.element.empty();
this.status = $.extend({}, this.status); // Copy static to unique instance.
this.internal = $.extend({}, this.internal); // Copy static to unique instance.
this.internal.domNode = this.element.get(0);
this.formats = []; // Array based on supplied string option. Order defines priority.
this.solutions = []; // Array based on solution string option. Order defines priority.
this.require = {}; // Which media types are required: video, audio.
this.htmlElement = {}; // DOM elements created by jPlayer
this.html = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array.
this.html.audio = {};
this.html.video = {};
this.flash = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array.
this.css = {};
this.css.cs = {}; // Holds the css selector strings
this.css.jq = {}; // Holds jQuery selectors. ie., $(css.cs.method)
this.ancestorJq = []; // Holds jQuery selector of cssSelectorAncestor. Init would use $() instead of [], but it is only 1.4+
this.options.volume = this._limitValue(this.options.volume, 0, 1); // Limit volume value's bounds.
// Create the formats array, with prority based on the order of the supplied formats string
$.each(this.options.supplied.toLowerCase().split(","), function(index1, value1) {
var format = value1.replace(/^\s+|\s+$/g, ""); //trim
if(self.format[format]) { // Check format is valid.
var dupFound = false;
$.each(self.formats, function(index2, value2) { // Check for duplicates
if(format === value2) {
dupFound = true;
return false;
}
});
if(!dupFound) {
self.formats.push(format);
}
}
});
// Create the solutions array, with prority based on the order of the solution string
$.each(this.options.solution.toLowerCase().split(","), function(index1, value1) {
var solution = value1.replace(/^\s+|\s+$/g, ""); //trim
if(self.solution[solution]) { // Check solution is valid.
var dupFound = false;
$.each(self.solutions, function(index2, value2) { // Check for duplicates
if(solution === value2) {
dupFound = true;
return false;
}
});
if(!dupFound) {
self.solutions.push(solution);
}
}
});
this.internal.instance = "jp_" + this.count;
this.instances[this.internal.instance] = this.element;
// Check the jPlayer div has an id and create one if required. Important for Flash to know the unique id for comms.
if(!this.element.attr("id")) {
this.element.attr("id", this.options.idPrefix + "_jplayer_" + this.count);
}
this.internal.self = $.extend({}, {
id: this.element.attr("id"),
jq: this.element
});
this.internal.audio = $.extend({}, {
id: this.options.idPrefix + "_audio_" + this.count,
jq: undefined
});
this.internal.video = $.extend({}, {
id: this.options.idPrefix + "_video_" + this.count,
jq: undefined
});
this.internal.flash = $.extend({}, {
id: this.options.idPrefix + "_flash_" + this.count,
jq: undefined,
swf: this.options.swfPath + (this.options.swfPath.toLowerCase().slice(-4) !== ".swf" ? (this.options.swfPath && this.options.swfPath.slice(-1) !== "/" ? "/" : "") + "Jplayer.swf" : "")
});
this.internal.poster = $.extend({}, {
id: this.options.idPrefix + "_poster_" + this.count,
jq: undefined
});
// Register listeners defined in the constructor
$.each($.jPlayer.event, function(eventName,eventType) {
if(self.options[eventName] !== undefined) {
self.element.bind(eventType + ".jPlayer", self.options[eventName]); // With .jPlayer namespace.
self.options[eventName] = undefined; // Destroy the handler pointer copy on the options. Reason, events can be added/removed in other ways so this could be obsolete and misleading.
}
});
// Determine if we require solutions for audio, video or both media types.
this.require.audio = false;
this.require.video = false;
$.each(this.formats, function(priority, format) {
self.require[self.format[format].media] = true;
});
// Now required types are known, finish the options default settings.
if(this.require.video) {
this.options = $.extend(true, {},
this.optionsVideo,
this.options
);
} else {
this.options = $.extend(true, {},
this.optionsAudio,
this.options
);
}
this._setSize(); // update status and jPlayer element size
// Determine the status for Blocklisted options.
this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls);
this.status.noFullScreen = this._uaBlocklist(this.options.noFullScreen);
this.status.noVolume = this._uaBlocklist(this.options.noVolume);
// The native controls are only for video and are disabled when audio is also used.
this._restrictNativeVideoControls();
// Create the poster image.
this.htmlElement.poster = document.createElement('img');
this.htmlElement.poster.id = this.internal.poster.id;
this.htmlElement.poster.onload = function() { // Note that this did not work on Firefox 3.6: poster.addEventListener("onload", function() {}, false); Did not investigate x-browser.
if(!self.status.video || self.status.waitForPlay) {
self.internal.poster.jq.show();
}
};
this.element.append(this.htmlElement.poster);
this.internal.poster.jq = $("#" + this.internal.poster.id);
this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height});
this.internal.poster.jq.hide();
this.internal.poster.jq.bind("click.jPlayer", function() {
self._trigger($.jPlayer.event.click);
});
// Generate the required media elements
this.html.audio.available = false;
if(this.require.audio) { // If a supplied format is audio
this.htmlElement.audio = document.createElement('audio');
this.htmlElement.audio.id = this.internal.audio.id;
this.html.audio.available = !!this.htmlElement.audio.canPlayType && this._testCanPlayType(this.htmlElement.audio); // Test is for IE9 on Win Server 2008.
}
this.html.video.available = false;
if(this.require.video) { // If a supplied format is video
this.htmlElement.video = document.createElement('video');
this.htmlElement.video.id = this.internal.video.id;
this.html.video.available = !!this.htmlElement.video.canPlayType && this._testCanPlayType(this.htmlElement.video); // Test is for IE9 on Win Server 2008.
}
this.flash.available = this._checkForFlash(10);
this.html.canPlay = {};
this.flash.canPlay = {};
$.each(this.formats, function(priority, format) {
self.html.canPlay[format] = self.html[self.format[format].media].available && "" !== self.htmlElement[self.format[format].media].canPlayType(self.format[format].codec);
self.flash.canPlay[format] = self.format[format].flashCanPlay && self.flash.available;
});
this.html.desired = false;
this.flash.desired = false;
$.each(this.solutions, function(solutionPriority, solution) {
if(solutionPriority === 0) {
self[solution].desired = true;
} else {
var audioCanPlay = false;
var videoCanPlay = false;
$.each(self.formats, function(formatPriority, format) {
if(self[self.solutions[0]].canPlay[format]) { // The other solution can play
if(self.format[format].media === 'video') {
videoCanPlay = true;
} else {
audioCanPlay = true;
}
}
});
self[solution].desired = (self.require.audio && !audioCanPlay) || (self.require.video && !videoCanPlay);
}
});
// This is what jPlayer will support, based on solution and supplied.
this.html.support = {};
this.flash.support = {};
$.each(this.formats, function(priority, format) {
self.html.support[format] = self.html.canPlay[format] && self.html.desired;
self.flash.support[format] = self.flash.canPlay[format] && self.flash.desired;
});
// If jPlayer is supporting any format in a solution, then the solution is used.
this.html.used = false;
this.flash.used = false;
$.each(this.solutions, function(solutionPriority, solution) {
$.each(self.formats, function(formatPriority, format) {
if(self[solution].support[format]) {
self[solution].used = true;
return false;
}
});
});
// Init solution active state and the event gates to false.
this._resetActive();
this._resetGate();
// Set up the css selectors for the control and feedback entities.
this._cssSelectorAncestor(this.options.cssSelectorAncestor);
// If neither html nor flash are being used by this browser, then media playback is not possible. Trigger an error event.
if(!(this.html.used || this.flash.used)) {
this._error( {
type: $.jPlayer.error.NO_SOLUTION,
context: "{solution:'" + this.options.solution + "', supplied:'" + this.options.supplied + "'}",
message: $.jPlayer.errorMsg.NO_SOLUTION,
hint: $.jPlayer.errorHint.NO_SOLUTION
});
if(this.css.jq.noSolution.length) {
this.css.jq.noSolution.show();
}
} else {
if(this.css.jq.noSolution.length) {
this.css.jq.noSolution.hide();
}
}
// Add the flash solution if it is being used.
if(this.flash.used) {
var htmlObj,
flashVars = 'jQuery=' + encodeURI(this.options.noConflict) + '&id=' + encodeURI(this.internal.self.id) + '&vol=' + this.options.volume + '&muted=' + this.options.muted;
// Code influenced by SWFObject 2.2: http://code.google.com/p/swfobject/
// Non IE browsers have an initial Flash size of 1 by 1 otherwise the wmode affected the Flash ready event.
if($.jPlayer.browser.msie && Number($.jPlayer.browser.version) <= 8) {
var objStr = '<object id="' + this.internal.flash.id + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0"></object>';
var paramStr = [
'<param name="movie" value="' + this.internal.flash.swf + '" />',
'<param name="FlashVars" value="' + flashVars + '" />',
'<param name="allowScriptAccess" value="always" />',
'<param name="bgcolor" value="' + this.options.backgroundColor + '" />',
'<param name="wmode" value="' + this.options.wmode + '" />'
];
htmlObj = document.createElement(objStr);
for(var i=0; i < paramStr.length; i++) {
htmlObj.appendChild(document.createElement(paramStr[i]));
}
} else {
var createParam = function(el, n, v) {
var p = document.createElement("param");
p.setAttribute("name", n);
p.setAttribute("value", v);
el.appendChild(p);
};
htmlObj = document.createElement("object");
htmlObj.setAttribute("id", this.internal.flash.id);
htmlObj.setAttribute("data", this.internal.flash.swf);
htmlObj.setAttribute("type", "application/x-shockwave-flash");
htmlObj.setAttribute("width", "1"); // Non-zero
htmlObj.setAttribute("height", "1"); // Non-zero
createParam(htmlObj, "flashvars", flashVars);
createParam(htmlObj, "allowscriptaccess", "always");
createParam(htmlObj, "bgcolor", this.options.backgroundColor);
createParam(htmlObj, "wmode", this.options.wmode);
}
this.element.append(htmlObj);
this.internal.flash.jq = $(htmlObj);
}
// Add the HTML solution if being used.
if(this.html.used) {
// The HTML Audio handlers
if(this.html.audio.available) {
this._addHtmlEventListeners(this.htmlElement.audio, this.html.audio);
this.element.append(this.htmlElement.audio);
this.internal.audio.jq = $("#" + this.internal.audio.id);
}
// The HTML Video handlers
if(this.html.video.available) {
this._addHtmlEventListeners(this.htmlElement.video, this.html.video);
this.element.append(this.htmlElement.video);
this.internal.video.jq = $("#" + this.internal.video.id);
if(this.status.nativeVideoControls) {
this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height});
} else {
this.internal.video.jq.css({'width':'0px', 'height':'0px'}); // Using size 0x0 since a .hide() causes issues in iOS
}
this.internal.video.jq.bind("click.jPlayer", function() {
self._trigger($.jPlayer.event.click);
});
}
}
// Create the bridge that emulates the HTML Media element on the jPlayer DIV
if( this.options.emulateHtml ) {
this._emulateHtmlBridge();
}
if(this.html.used && !this.flash.used) { // If only HTML, then emulate flash ready() call after 100ms.
setTimeout( function() {
self.internal.ready = true;
self.version.flash = "n/a";
self._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option.
self._trigger($.jPlayer.event.ready);
}, 100);
}
// Initialize the interface components with the options.
this._updateNativeVideoControls(); // Must do this first, otherwise there is a bizarre bug in iOS 4.3.2, where the native controls are not shown. Fails in iOS if called after _updateButtons() below. Works if called later in setMedia too, so it odd.
this._updateInterface();
this._updateButtons(false);
this._updateAutohide();
this._updateVolume(this.options.volume);
this._updateMute(this.options.muted);
if(this.css.jq.videoPlay.length) {
this.css.jq.videoPlay.hide();
}
$.jPlayer.prototype.count++; // Change static variable via prototype.
},
destroy: function() {
// MJP: The background change remains. Would need to store the original to restore it correctly.
// MJP: The jPlayer element's size change remains.
// Clear the media to reset the GUI and stop any downloads. Streams on some browsers had persited. (Chrome)
this.clearMedia();
// Remove the size/sizeFull cssClass from the cssSelectorAncestor
this._removeUiClass();
// Remove the times from the GUI
if(this.css.jq.currentTime.length) {
this.css.jq.currentTime.text("");
}
if(this.css.jq.duration.length) {
this.css.jq.duration.text("");
}
// Remove any bindings from the interface controls.
$.each(this.css.jq, function(fn, jq) {
// Check selector is valid before trying to execute method.
if(jq.length) {
jq.unbind(".jPlayer");
}
});
// Remove the click handlers for $.jPlayer.event.click
this.internal.poster.jq.unbind(".jPlayer");
if(this.internal.video.jq) {
this.internal.video.jq.unbind(".jPlayer");
}
// Destroy the HTML bridge.
if(this.options.emulateHtml) {
this._destroyHtmlBridge();
}
this.element.removeData("jPlayer"); // Remove jPlayer data
this.element.unbind(".jPlayer"); // Remove all event handlers created by the jPlayer constructor
this.element.empty(); // Remove the inserted child elements
delete this.instances[this.internal.instance]; // Clear the instance on the static instance object
},
enable: function() { // Plan to implement
// options.disabled = false
},
disable: function () { // Plan to implement
// options.disabled = true
},
_testCanPlayType: function(elem) {
// IE9 on Win Server 2008 did not implement canPlayType(), but it has the property.
try {
elem.canPlayType(this.format.mp3.codec); // The type is irrelevant.
return true;
} catch(err) {
return false;
}
},
_uaBlocklist: function(list) {
// list : object with properties that are all regular expressions. Property names are irrelevant.
// Returns true if the user agent is matched in list.
var ua = navigator.userAgent.toLowerCase(),
block = false;
$.each(list, function(p, re) {
if(re && re.test(ua)) {
block = true;
return false; // exit $.each.
}
});
return block;
},
_restrictNativeVideoControls: function() {
// Fallback to noFullScreen when nativeVideoControls is true and audio media is being used. Affects when both media types are used.
if(this.require.audio) {
if(this.status.nativeVideoControls) {
this.status.nativeVideoControls = false;
this.status.noFullScreen = true;
}
}
},
_updateNativeVideoControls: function() {
if(this.html.video.available && this.html.used) {
// Turn the HTML Video controls on/off
this.htmlElement.video.controls = this.status.nativeVideoControls;
// Show/hide the jPlayer GUI.
this._updateAutohide();
// For when option changed. The poster image is not updated, as it is dealt with in setMedia(). Acceptable degradation since seriously doubt these options will change on the fly. Can again review later.
if(this.status.nativeVideoControls && this.require.video) {
this.internal.poster.jq.hide();
this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height});
} else if(this.status.waitForPlay && this.status.video) {
this.internal.poster.jq.show();
this.internal.video.jq.css({'width': '0px', 'height': '0px'});
}
}
},
_addHtmlEventListeners: function(mediaElement, entity) {
var self = this;
mediaElement.preload = this.options.preload;
mediaElement.muted = this.options.muted;
mediaElement.volume = this.options.volume;
// Create the event listeners
// Only want the active entity to affect jPlayer and bubble events.
// Using entity.gate so that object is referenced and gate property always current
mediaElement.addEventListener("progress", function() {
if(entity.gate) {
self._getHtmlStatus(mediaElement);
self._updateInterface();
self._trigger($.jPlayer.event.progress);
}
}, false);
mediaElement.addEventListener("timeupdate", function() {
if(entity.gate) {
self._getHtmlStatus(mediaElement);
self._updateInterface();
self._trigger($.jPlayer.event.timeupdate);
}
}, false);
mediaElement.addEventListener("durationchange", function() {
if(entity.gate) {
self._getHtmlStatus(mediaElement);
self._updateInterface();
self._trigger($.jPlayer.event.durationchange);
}
}, false);
mediaElement.addEventListener("play", function() {
if(entity.gate) {
self._updateButtons(true);
self._html_checkWaitForPlay(); // So the native controls update this variable and puts the hidden interface in the correct state. Affects toggling native controls.
self._trigger($.jPlayer.event.play);
}
}, false);
mediaElement.addEventListener("playing", function() {
if(entity.gate) {
self._updateButtons(true);
self._seeked();
self._trigger($.jPlayer.event.playing);
}
}, false);
mediaElement.addEventListener("pause", function() {
if(entity.gate) {
self._updateButtons(false);
self._trigger($.jPlayer.event.pause);
}
}, false);
mediaElement.addEventListener("waiting", function() {
if(entity.gate) {
self._seeking();
self._trigger($.jPlayer.event.waiting);
}
}, false);
mediaElement.addEventListener("seeking", function() {
if(entity.gate) {
self._seeking();
self._trigger($.jPlayer.event.seeking);
}
}, false);
mediaElement.addEventListener("seeked", function() {
if(entity.gate) {
self._seeked();
self._trigger($.jPlayer.event.seeked);
}
}, false);
mediaElement.addEventListener("volumechange", function() {
if(entity.gate) {
// Read the values back from the element as the Blackberry PlayBook shares the volume with the physical buttons master volume control.
// However, when tested 6th July 2011, those buttons do not generate an event. The physical play/pause button does though.
self.options.volume = mediaElement.volume;
self.options.muted = mediaElement.muted;
self._updateMute();
self._updateVolume();
self._trigger($.jPlayer.event.volumechange);
}
}, false);
mediaElement.addEventListener("suspend", function() { // Seems to be the only way of capturing that the iOS4 browser did not actually play the media from the page code. ie., It needs a user gesture.
if(entity.gate) {
self._seeked();
self._trigger($.jPlayer.event.suspend);
}
}, false);
mediaElement.addEventListener("ended", function() {
if(entity.gate) {
// Order of the next few commands are important. Change the time and then pause.
// Solves a bug in Firefox, where issuing pause 1st causes the media to play from the start. ie., The pause is ignored.
if(!$.jPlayer.browser.webkit) { // Chrome crashes if you do this in conjunction with a setMedia command in an ended event handler. ie., The playlist demo.
self.htmlElement.media.currentTime = 0; // Safari does not care about this command. ie., It works with or without this line. (Both Safari and Chrome are Webkit.)
}
self.htmlElement.media.pause(); // Pause otherwise a click on the progress bar will play from that point, when it shouldn't, since it stopped playback.
self._updateButtons(false);
self._getHtmlStatus(mediaElement, true); // With override true. Otherwise Chrome leaves progress at full.
self._updateInterface();
self._trigger($.jPlayer.event.ended);
}
}, false);
mediaElement.addEventListener("error", function() {
if(entity.gate) {
self._updateButtons(false);
self._seeked();
if(self.status.srcSet) { // Deals with case of clearMedia() causing an error event.
clearTimeout(self.internal.htmlDlyCmdId); // Clears any delayed commands used in the HTML solution.
self.status.waitForLoad = true; // Allows the load operation to try again.
self.status.waitForPlay = true; // Reset since a play was captured.
if(self.status.video && !self.status.nativeVideoControls) {
self.internal.video.jq.css({'width':'0px', 'height':'0px'});
}
if(self._validString(self.status.media.poster) && !self.status.nativeVideoControls) {
self.internal.poster.jq.show();
}
if(self.css.jq.videoPlay.length) {
self.css.jq.videoPlay.show();
}
self._error( {
type: $.jPlayer.error.URL,
context: self.status.src, // this.src shows absolute urls. Want context to show the url given.
message: $.jPlayer.errorMsg.URL,
hint: $.jPlayer.errorHint.URL
});
}
}
}, false);
// Create all the other event listeners that bubble up to a jPlayer event from html, without being used by jPlayer.
$.each($.jPlayer.htmlEvent, function(i, eventType) {
mediaElement.addEventListener(this, function() {
if(entity.gate) {
self._trigger($.jPlayer.event[eventType]);
}
}, false);
});
},
_getHtmlStatus: function(media, override) {
var ct = 0, cpa = 0, sp = 0, cpr = 0;
// Fixes the duration bug in iOS, where the durationchange event occurs when media.duration is not always correct.
// Fixes the initial duration bug in BB OS7, where the media.duration is infinity and displays as NaN:NaN due to Date() using inifity.
if(isFinite(media.duration)) {
this.status.duration = media.duration;
}
ct = media.currentTime;
cpa = (this.status.duration > 0) ? 100 * ct / this.status.duration : 0;
if((typeof media.seekable === "object") && (media.seekable.length > 0)) {
sp = (this.status.duration > 0) ? 100 * media.seekable.end(media.seekable.length-1) / this.status.duration : 100;
cpr = (this.status.duration > 0) ? 100 * media.currentTime / media.seekable.end(media.seekable.length-1) : 0; // Duration conditional for iOS duration bug. ie., seekable.end is a NaN in that case.
} else {
sp = 100;
cpr = cpa;
}
if(override) {
ct = 0;
cpr = 0;
cpa = 0;
}
this.status.seekPercent = sp;
this.status.currentPercentRelative = cpr;
this.status.currentPercentAbsolute = cpa;
this.status.currentTime = ct;
this.status.readyState = media.readyState;
this.status.networkState = media.networkState;
this.status.playbackRate = media.playbackRate;
this.status.ended = media.ended;
},
_resetStatus: function() {
this.status = $.extend({}, this.status, $.jPlayer.prototype.status); // Maintains the status properties that persist through a reset.
},
_trigger: function(eventType, error, warning) { // eventType always valid as called using $.jPlayer.event.eventType
var event = $.Event(eventType);
event.jPlayer = {};
event.jPlayer.version = $.extend({}, this.version);
event.jPlayer.options = $.extend(true, {}, this.options); // Deep copy
event.jPlayer.status = $.extend(true, {}, this.status); // Deep copy
event.jPlayer.html = $.extend(true, {}, this.html); // Deep copy
event.jPlayer.flash = $.extend(true, {}, this.flash); // Deep copy
if(error) {
event.jPlayer.error = $.extend({}, error);
}
if(warning) {
event.jPlayer.warning = $.extend({}, warning);
}
this.element.trigger(event);
},
jPlayerFlashEvent: function(eventType, status) { // Called from Flash
if(eventType === $.jPlayer.event.ready) {
if(!this.internal.ready) {
this.internal.ready = true;
this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); // Once Flash generates the ready event, minimise to zero as it is not affected by wmode anymore.
this.version.flash = status.version;
if(this.version.needFlash !== this.version.flash) {
this._error( {
type: $.jPlayer.error.VERSION,
context: this.version.flash,
message: $.jPlayer.errorMsg.VERSION + this.version.flash,
hint: $.jPlayer.errorHint.VERSION
});
}
this._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option.
this._trigger(eventType);
} else {
// This condition occurs if the Flash is hidden and then shown again.
// Firefox also reloads the Flash if the CSS position changes. position:fixed is used for full screen.
// Only do this if the Flash is the solution being used at the moment. Affects Media players where both solution may be being used.
if(this.flash.gate) {
// Send the current status to the Flash now that it is ready (available) again.
if(this.status.srcSet) {
// Need to read original status before issuing the setMedia command.
var currentTime = this.status.currentTime,
paused = this.status.paused;
this.setMedia(this.status.media);
if(currentTime > 0) {
if(paused) {
this.pause(currentTime);
} else {
this.play(currentTime);
}
}
}
this._trigger($.jPlayer.event.flashreset);
}
}
}
if(this.flash.gate) {
switch(eventType) {
case $.jPlayer.event.progress:
this._getFlashStatus(status);
this._updateInterface();
this._trigger(eventType);
break;
case $.jPlayer.event.timeupdate:
this._getFlashStatus(status);
this._updateInterface();
this._trigger(eventType);
break;
case $.jPlayer.event.play:
this._seeked();
this._updateButtons(true);
this._trigger(eventType);
break;
case $.jPlayer.event.pause:
this._updateButtons(false);
this._trigger(eventType);
break;
case $.jPlayer.event.ended:
this._updateButtons(false);
this._trigger(eventType);
break;
case $.jPlayer.event.click:
this._trigger(eventType); // This could be dealt with by the default
break;
case $.jPlayer.event.error:
this.status.waitForLoad = true; // Allows the load operation to try again.
this.status.waitForPlay = true; // Reset since a play was captured.
if(this.status.video) {
this.internal.flash.jq.css({'width':'0px', 'height':'0px'});
}
if(this._validString(this.status.media.poster)) {
this.internal.poster.jq.show();
}
if(this.css.jq.videoPlay.length && this.status.video) {
this.css.jq.videoPlay.show();
}
if(this.status.video) { // Set up for another try. Execute before error event.
this._flash_setVideo(this.status.media);
} else {
this._flash_setAudio(this.status.media);
}
this._updateButtons(false);
this._error( {
type: $.jPlayer.error.URL,
context:status.src,
message: $.jPlayer.errorMsg.URL,
hint: $.jPlayer.errorHint.URL
});
break;
case $.jPlayer.event.seeking:
this._seeking();
this._trigger(eventType);
break;
case $.jPlayer.event.seeked:
this._seeked();
this._trigger(eventType);
break;
case $.jPlayer.event.ready:
// The ready event is handled outside the switch statement.
// Captured here otherwise 2 ready events would be generated if the ready event handler used setMedia.
break;
default:
this._trigger(eventType);
}
}
return false;
},
_getFlashStatus: function(status) {
this.status.seekPercent = status.seekPercent;
this.status.currentPercentRelative = status.currentPercentRelative;
this.status.currentPercentAbsolute = status.currentPercentAbsolute;
this.status.currentTime = status.currentTime;
this.status.duration = status.duration;
// The Flash does not generate this information in this release
this.status.readyState = 4; // status.readyState;
this.status.networkState = 0; // status.networkState;
this.status.playbackRate = 1; // status.playbackRate;
this.status.ended = false; // status.ended;
},
_updateButtons: function(playing) {
if(playing !== undefined) {
this.status.paused = !playing;
if(this.css.jq.play.length && this.css.jq.pause.length) {
if(playing) {
this.css.jq.play.hide();
this.css.jq.pause.show();
} else {
this.css.jq.play.show();
this.css.jq.pause.hide();
}
}
}
if(this.css.jq.restoreScreen.length && this.css.jq.fullScreen.length) {
if(this.status.noFullScreen) {
this.css.jq.fullScreen.hide();
this.css.jq.restoreScreen.hide();
} else if(this.options.fullScreen) {
this.css.jq.fullScreen.hide();
this.css.jq.restoreScreen.show();
} else {
this.css.jq.fullScreen.show();
this.css.jq.restoreScreen.hide();
}
}
if(this.css.jq.repeat.length && this.css.jq.repeatOff.length) {
if(this.options.loop) {
this.css.jq.repeat.hide();
this.css.jq.repeatOff.show();
} else {
this.css.jq.repeat.show();
this.css.jq.repeatOff.hide();
}
}
},
_updateInterface: function() {
if(this.css.jq.seekBar.length) {
this.css.jq.seekBar.width(this.status.seekPercent+"%");
}
if(this.css.jq.playBar.length) {
this.css.jq.playBar.width(this.status.currentPercentRelative+"%");
}
if(this.css.jq.currentTime.length) {
this.css.jq.currentTime.text($.jPlayer.convertTime(this.status.currentTime));
}
if(this.css.jq.duration.length) {
this.css.jq.duration.text($.jPlayer.convertTime(this.status.duration));
}
},
_seeking: function() {
if(this.css.jq.seekBar.length) {
this.css.jq.seekBar.addClass("jp-seeking-bg");
}
},
_seeked: function() {
if(this.css.jq.seekBar.length) {
this.css.jq.seekBar.removeClass("jp-seeking-bg");
}
},
_resetGate: function() {
this.html.audio.gate = false;
this.html.video.gate = false;
this.flash.gate = false;
},
_resetActive: function() {
this.html.active = false;
this.flash.active = false;
},
setMedia: function(media) {
/* media[format] = String: URL of format. Must contain all of the supplied option's video or audio formats.
* media.poster = String: Video poster URL.
* media.subtitles = String: * NOT IMPLEMENTED * URL of subtitles SRT file
* media.chapters = String: * NOT IMPLEMENTED * URL of chapters SRT file
* media.stream = Boolean: * NOT IMPLEMENTED * Designating actual media streams. ie., "false/undefined" for files. Plan to refresh the flash every so often.
*/
var self = this,
supported = false,
posterChanged = this.status.media.poster !== media.poster; // Compare before reset. Important for OSX Safari as this.htmlElement.poster.src is absolute, even if original poster URL was relative.
this._resetMedia();
this._resetGate();
this._resetActive();
$.each(this.formats, function(formatPriority, format) {
var isVideo = self.format[format].media === 'video';
$.each(self.solutions, function(solutionPriority, solution) {
if(self[solution].support[format] && self._validString(media[format])) { // Format supported in solution and url given for format.
var isHtml = solution === 'html';
if(isVideo) {
if(isHtml) {
self.html.video.gate = true;
self._html_setVideo(media);
self.html.active = true;
} else {
self.flash.gate = true;
self._flash_setVideo(media);
self.flash.active = true;
}
if(self.css.jq.videoPlay.length) {
self.css.jq.videoPlay.show();
}
self.status.video = true;
} else {
if(isHtml) {
self.html.audio.gate = true;
self._html_setAudio(media);
self.html.active = true;
} else {
self.flash.gate = true;
self._flash_setAudio(media);
self.flash.active = true;
}
if(self.css.jq.videoPlay.length) {
self.css.jq.videoPlay.hide();
}
self.status.video = false;
}
supported = true;
return false; // Exit $.each
}
});
if(supported) {
return false; // Exit $.each
}
});
if(supported) {
if(!(this.status.nativeVideoControls && this.html.video.gate)) {
// Set poster IMG if native video controls are not being used
// Note: With IE the IMG onload event occurs immediately when cached.
// Note: Poster hidden by default in _resetMedia()
if(this._validString(media.poster)) {
if(posterChanged) { // Since some browsers do not generate img onload event.
this.htmlElement.poster.src = media.poster;
} else {
this.internal.poster.jq.show();
}
}
}
this.status.srcSet = true;
this.status.media = $.extend({}, media);
this._updateButtons(false);
this._updateInterface();
} else { // jPlayer cannot support any formats provided in this browser
// Send an error event
this._error( {
type: $.jPlayer.error.NO_SUPPORT,
context: "{supplied:'" + this.options.supplied + "'}",
message: $.jPlayer.errorMsg.NO_SUPPORT,
hint: $.jPlayer.errorHint.NO_SUPPORT
});
}
},
_resetMedia: function() {
this._resetStatus();
this._updateButtons(false);
this._updateInterface();
this._seeked();
this.internal.poster.jq.hide();
clearTimeout(this.internal.htmlDlyCmdId);
if(this.html.active) {
this._html_resetMedia();
} else if(this.flash.active) {
this._flash_resetMedia();
}
},
clearMedia: function() {
this._resetMedia();
if(this.html.active) {
this._html_clearMedia();
} else if(this.flash.active) {
this._flash_clearMedia();
}
this._resetGate();
this._resetActive();
},
load: function() {
if(this.status.srcSet) {
if(this.html.active) {
this._html_load();
} else if(this.flash.active) {
this._flash_load();
}
} else {
this._urlNotSetError("load");
}
},
play: function(time) {
time = (typeof time === "number") ? time : NaN; // Remove jQuery event from click handler
if(this.status.srcSet) {
if(this.html.active) {
this._html_play(time);
} else if(this.flash.active) {
this._flash_play(time);
}
} else {
this._urlNotSetError("play");
}
},
videoPlay: function() { // Handles clicks on the play button over the video poster
this.play();
},
pause: function(time) {
time = (typeof time === "number") ? time : NaN; // Remove jQuery event from click handler
if(this.status.srcSet) {
if(this.html.active) {
this._html_pause(time);
} else if(this.flash.active) {
this._flash_pause(time);
}
} else {
this._urlNotSetError("pause");
}
},
pauseOthers: function() {
var self = this;
$.each(this.instances, function(i, element) {
if(self.element !== element) { // Do not this instance.
if(element.data("jPlayer").status.srcSet) { // Check that media is set otherwise would cause error event.
element.jPlayer("pause");
}
}
});
},
stop: function() {
if(this.status.srcSet) {
if(this.html.active) {
this._html_pause(0);
} else if(this.flash.active) {
this._flash_pause(0);
}
} else {
this._urlNotSetError("stop");
}
},
playHead: function(p) {
p = this._limitValue(p, 0, 100);
if(this.status.srcSet) {
if(this.html.active) {
this._html_playHead(p);
} else if(this.flash.active) {
this._flash_playHead(p);
}
} else {
this._urlNotSetError("playHead");
}
},
_muted: function(muted) {
this.options.muted = muted;
if(this.html.used) {
this._html_mute(muted);
}
if(this.flash.used) {
this._flash_mute(muted);
}
// The HTML solution generates this event from the media element itself.
if(!this.html.video.gate && !this.html.audio.gate) {
this._updateMute(muted);
this._updateVolume(this.options.volume);
this._trigger($.jPlayer.event.volumechange);
}
},
mute: function(mute) { // mute is either: undefined (true), an event object (true) or a boolean (muted).
mute = mute === undefined ? true : !!mute;
this._muted(mute);
},
unmute: function(unmute) { // unmute is either: undefined (true), an event object (true) or a boolean (!muted).
unmute = unmute === undefined ? true : !!unmute;
this._muted(!unmute);
},
_updateMute: function(mute) {
if(mute === undefined) {
mute = this.options.muted;
}
if(this.css.jq.mute.length && this.css.jq.unmute.length) {
if(this.status.noVolume) {
this.css.jq.mute.hide();
this.css.jq.unmute.hide();
} else if(mute) {
this.css.jq.mute.hide();
this.css.jq.unmute.show();
} else {
this.css.jq.mute.show();
this.css.jq.unmute.hide();
}
}
},
volume: function(v) {
v = this._limitValue(v, 0, 1);
this.options.volume = v;
if(this.html.used) {
this._html_volume(v);
}
if(this.flash.used) {
this._flash_volume(v);
}
// The HTML solution generates this event from the media element itself.
if(!this.html.video.gate && !this.html.audio.gate) {
this._updateVolume(v);
this._trigger($.jPlayer.event.volumechange);
}
},
volumeBar: function(e) { // Handles clicks on the volumeBar
if(this.css.jq.volumeBar.length) {
var offset = this.css.jq.volumeBar.offset(),
x = e.pageX - offset.left,
w = this.css.jq.volumeBar.width(),
y = this.css.jq.volumeBar.height() - e.pageY + offset.top,
h = this.css.jq.volumeBar.height();
if(this.options.verticalVolume) {
this.volume(y/h);
} else {
this.volume(x/w);
}
}
if(this.options.muted) {
this._muted(false);
}
},
volumeBarValue: function(e) { // Handles clicks on the volumeBarValue
this.volumeBar(e);
},
_updateVolume: function(v) {
if(v === undefined) {
v = this.options.volume;
}
v = this.options.muted ? 0 : v;
if(this.status.noVolume) {
if(this.css.jq.volumeBar.length) {
this.css.jq.volumeBar.hide();
}
if(this.css.jq.volumeBarValue.length) {
this.css.jq.volumeBarValue.hide();
}
if(this.css.jq.volumeMax.length) {
this.css.jq.volumeMax.hide();
}
} else {
if(this.css.jq.volumeBar.length) {
this.css.jq.volumeBar.show();
}
if(this.css.jq.volumeBarValue.length) {
this.css.jq.volumeBarValue.show();
this.css.jq.volumeBarValue[this.options.verticalVolume ? "height" : "width"]((v*100)+"%");
}
if(this.css.jq.volumeMax.length) {
this.css.jq.volumeMax.show();
}
}
},
volumeMax: function() { // Handles clicks on the volume max
this.volume(1);
if(this.options.muted) {
this._muted(false);
}
},
_cssSelectorAncestor: function(ancestor) {
var self = this;
this.options.cssSelectorAncestor = ancestor;
this._removeUiClass();
this.ancestorJq = ancestor ? $(ancestor) : []; // Would use $() instead of [], but it is only 1.4+
if(ancestor && this.ancestorJq.length !== 1) { // So empty strings do not generate the warning.
this._warning( {
type: $.jPlayer.warning.CSS_SELECTOR_COUNT,
context: ancestor,
message: $.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.ancestorJq.length + " found for cssSelectorAncestor.",
hint: $.jPlayer.warningHint.CSS_SELECTOR_COUNT
});
}
this._addUiClass();
$.each(this.options.cssSelector, function(fn, cssSel) {
self._cssSelector(fn, cssSel);
});
},
_cssSelector: function(fn, cssSel) {
var self = this;
if(typeof cssSel === 'string') {
if($.jPlayer.prototype.options.cssSelector[fn]) {
if(this.css.jq[fn] && this.css.jq[fn].length) {
this.css.jq[fn].unbind(".jPlayer");
}
this.options.cssSelector[fn] = cssSel;
this.css.cs[fn] = this.options.cssSelectorAncestor + " " + cssSel;
if(cssSel) { // Checks for empty string
this.css.jq[fn] = $(this.css.cs[fn]);
} else {
this.css.jq[fn] = []; // To comply with the css.jq[fn].length check before its use. As of jQuery 1.4 could have used $() for an empty set.
}
if(this.css.jq[fn].length) {
var handler = function(e) {
self[fn](e);
$(this).blur();
return false;
};
this.css.jq[fn].bind("click.jPlayer", handler); // Using jPlayer namespace
}
if(cssSel && this.css.jq[fn].length !== 1) { // So empty strings do not generate the warning. ie., they just remove the old one.
this._warning( {
type: $.jPlayer.warning.CSS_SELECTOR_COUNT,
context: this.css.cs[fn],
message: $.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.css.jq[fn].length + " found for " + fn + " method.",
hint: $.jPlayer.warningHint.CSS_SELECTOR_COUNT
});
}
} else {
this._warning( {
type: $.jPlayer.warning.CSS_SELECTOR_METHOD,
context: fn,
message: $.jPlayer.warningMsg.CSS_SELECTOR_METHOD,
hint: $.jPlayer.warningHint.CSS_SELECTOR_METHOD
});
}
} else {
this._warning( {
type: $.jPlayer.warning.CSS_SELECTOR_STRING,
context: cssSel,
message: $.jPlayer.warningMsg.CSS_SELECTOR_STRING,
hint: $.jPlayer.warningHint.CSS_SELECTOR_STRING
});
}
},
seekBar: function(e) { // Handles clicks on the seekBar
if(this.css.jq.seekBar) {
var offset = this.css.jq.seekBar.offset();
var x = e.pageX - offset.left;
var w = this.css.jq.seekBar.width();
var p = 100*x/w;
this.playHead(p);
}
},
playBar: function(e) { // Handles clicks on the playBar
this.seekBar(e);
},
repeat: function() { // Handle clicks on the repeat button
this._loop(true);
},
repeatOff: function() { // Handle clicks on the repeatOff button
this._loop(false);
},
_loop: function(loop) {
if(this.options.loop !== loop) {
this.options.loop = loop;
this._updateButtons();
this._trigger($.jPlayer.event.repeat);
}
},
// Plan to review the cssSelector method to cope with missing associated functions accordingly.
currentTime: function() { // Handles clicks on the text
// Added to avoid errors using cssSelector system for the text
},
duration: function() { // Handles clicks on the text
// Added to avoid errors using cssSelector system for the text
},
gui: function() { // Handles clicks on the gui
// Added to avoid errors using cssSelector system for the gui
},
noSolution: function() { // Handles clicks on the error message
// Added to avoid errors using cssSelector system for no-solution
},
// Options code adapted from ui.widget.js (1.8.7). Made changes so the key can use dot notation. To match previous getData solution in jPlayer 1.
option: function(key, value) {
var options = key;
// Enables use: options(). Returns a copy of options object
if ( arguments.length === 0 ) {
return $.extend( true, {}, this.options );
}
if(typeof key === "string") {
var keys = key.split(".");
// Enables use: options("someOption") Returns a copy of the option. Supports dot notation.
if(value === undefined) {
var opt = $.extend(true, {}, this.options);
for(var i = 0; i < keys.length; i++) {
if(opt[keys[i]] !== undefined) {
opt = opt[keys[i]];
} else {
this._warning( {
type: $.jPlayer.warning.OPTION_KEY,
context: key,
message: $.jPlayer.warningMsg.OPTION_KEY,
hint: $.jPlayer.warningHint.OPTION_KEY
});
return undefined;
}
}
return opt;
}
// Enables use: options("someOptionObject", someObject}). Creates: {someOptionObject:someObject}
// Enables use: options("someOption", someValue). Creates: {someOption:someValue}
// Enables use: options("someOptionObject.someOption", someValue). Creates: {someOptionObject:{someOption:someValue}}
options = {};
var opts = options;
for(var j = 0; j < keys.length; j++) {
if(j < keys.length - 1) {
opts[keys[j]] = {};
opts = opts[keys[j]];
} else {
opts[keys[j]] = value;
}
}
}
// Otherwise enables use: options(optionObject). Uses original object (the key)
this._setOptions(options);
return this;
},
_setOptions: function(options) {
var self = this;
$.each(options, function(key, value) { // This supports the 2 level depth that the options of jPlayer has. Would review if we ever need more depth.
self._setOption(key, value);
});
return this;
},
_setOption: function(key, value) {
var self = this;
// The ability to set options is limited at this time.
switch(key) {
case "volume" :
this.volume(value);
break;
case "muted" :
this._muted(value);
break;
case "cssSelectorAncestor" :
this._cssSelectorAncestor(value); // Set and refresh all associations for the new ancestor.
break;
case "cssSelector" :
$.each(value, function(fn, cssSel) {
self._cssSelector(fn, cssSel); // NB: The option is set inside this function, after further validity checks.
});
break;
case "fullScreen" :
if(this.options[key] !== value) { // if changed
this._removeUiClass();
this.options[key] = value;
this._refreshSize();
}
break;
case "size" :
if(!this.options.fullScreen && this.options[key].cssClass !== value.cssClass) {
this._removeUiClass();
}
this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed.
this._refreshSize();
break;
case "sizeFull" :
if(this.options.fullScreen && this.options[key].cssClass !== value.cssClass) {
this._removeUiClass();
}
this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed.
this._refreshSize();
break;
case "autohide" :
this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed.
this._updateAutohide();
break;
case "loop" :
this._loop(value);
break;
case "nativeVideoControls" :
this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed.
this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls);
this._restrictNativeVideoControls();
this._updateNativeVideoControls();
break;
case "noFullScreen" :
this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed.
this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); // Need to check again as noFullScreen can depend on this flag and the restrict() can override it.
this.status.noFullScreen = this._uaBlocklist(this.options.noFullScreen);
this._restrictNativeVideoControls();
this._updateButtons();
break;
case "noVolume" :
this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed.
this.status.noVolume = this._uaBlocklist(this.options.noVolume);
this._updateVolume();
this._updateMute();
break;
case "emulateHtml" :
if(this.options[key] !== value) { // To avoid multiple event handlers being created, if true already.
this.options[key] = value;
if(value) {
this._emulateHtmlBridge();
} else {
this._destroyHtmlBridge();
}
}
break;
}
return this;
},
// End of: (Options code adapted from ui.widget.js)
_refreshSize: function() {
this._setSize(); // update status and jPlayer element size
this._addUiClass(); // update the ui class
this._updateSize(); // update internal sizes
this._updateButtons();
this._updateAutohide();
this._trigger($.jPlayer.event.resize);
},
_setSize: function() {
// Determine the current size from the options
if(this.options.fullScreen) {
this.status.width = this.options.sizeFull.width;
this.status.height = this.options.sizeFull.height;
this.status.cssClass = this.options.sizeFull.cssClass;
} else {
this.status.width = this.options.size.width;
this.status.height = this.options.size.height;
this.status.cssClass = this.options.size.cssClass;
}
// Set the size of the jPlayer area.
this.element.css({'width': this.status.width, 'height': this.status.height});
},
_addUiClass: function() {
if(this.ancestorJq.length) {
this.ancestorJq.addClass(this.status.cssClass);
}
},
_removeUiClass: function() {
if(this.ancestorJq.length) {
this.ancestorJq.removeClass(this.status.cssClass);
}
},
_updateSize: function() {
// The poster uses show/hide so can simply resize it.
this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height});
// Video html or flash resized if necessary at this time, or if native video controls being used.
if(!this.status.waitForPlay && this.html.active && this.status.video || this.html.video.available && this.html.used && this.status.nativeVideoControls) {
this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height});
}
else if(!this.status.waitForPlay && this.flash.active && this.status.video) {
this.internal.flash.jq.css({'width': this.status.width, 'height': this.status.height});
}
},
_updateAutohide: function() {
var self = this,
event = "mousemove.jPlayer",
namespace = ".jPlayerAutohide",
eventType = event + namespace,
handler = function() {
self.css.jq.gui.fadeIn(self.options.autohide.fadeIn, function() {
clearTimeout(self.internal.autohideId);
self.internal.autohideId = setTimeout( function() {
self.css.jq.gui.fadeOut(self.options.autohide.fadeOut);
}, self.options.autohide.hold);
});
};
if(this.css.jq.gui.length) {
// End animations first so that its callback is executed now.
// Otherwise an in progress fadeIn animation still has the callback to fadeOut again.
this.css.jq.gui.stop(true, true);
// Removes the fadeOut operation from the fadeIn callback.
clearTimeout(this.internal.autohideId);
this.element.unbind(namespace);
this.css.jq.gui.unbind(namespace);
if(!this.status.nativeVideoControls) {
if(this.options.fullScreen && this.options.autohide.full || !this.options.fullScreen && this.options.autohide.restored) {
this.element.bind(eventType, handler);
this.css.jq.gui.bind(eventType, handler);
this.css.jq.gui.hide();
} else {
this.css.jq.gui.show();
}
} else {
this.css.jq.gui.hide();
}
}
},
fullScreen: function() {
this._setOption("fullScreen", true);
},
restoreScreen: function() {
this._setOption("fullScreen", false);
},
_html_initMedia: function() {
this.htmlElement.media.src = this.status.src;
if(this.options.preload !== 'none') {
this._html_load(); // See function for comments
}
this._trigger($.jPlayer.event.timeupdate); // The flash generates this event for its solution.
},
_html_setAudio: function(media) {
var self = this;
// Always finds a format due to checks in setMedia()
$.each(this.formats, function(priority, format) {
if(self.html.support[format] && media[format]) {
self.status.src = media[format];
self.status.format[format] = true;
self.status.formatType = format;
return false;
}
});
this.htmlElement.media = this.htmlElement.audio;
this._html_initMedia();
},
_html_setVideo: function(media) {
var self = this;
// Always finds a format due to checks in setMedia()
$.each(this.formats, function(priority, format) {
if(self.html.support[format] && media[format]) {
self.status.src = media[format];
self.status.format[format] = true;
self.status.formatType = format;
return false;
}
});
if(this.status.nativeVideoControls) {
this.htmlElement.video.poster = this._validString(media.poster) ? media.poster : "";
}
this.htmlElement.media = this.htmlElement.video;
this._html_initMedia();
},
_html_resetMedia: function() {
if(this.htmlElement.media) {
if(this.htmlElement.media.id === this.internal.video.id && !this.status.nativeVideoControls) {
this.internal.video.jq.css({'width':'0px', 'height':'0px'});
}
this.htmlElement.media.pause();
}
},
_html_clearMedia: function() {
if(this.htmlElement.media) {
this.htmlElement.media.src = "";
this.htmlElement.media.load(); // Stops an old, "in progress" download from continuing the download. Triggers the loadstart, error and emptied events, due to the empty src. Also an abort event if a download was in progress.
}
},
_html_load: function() {
// This function remains to allow the early HTML5 browsers to work, such as Firefox 3.6
// A change in the W3C spec for the media.load() command means that this is no longer necessary.
// This command should be removed and actually causes minor undesirable effects on some browsers. Such as loading the whole file and not only the metadata.
if(this.status.waitForLoad) {
this.status.waitForLoad = false;
this.htmlElement.media.load();
}
clearTimeout(this.internal.htmlDlyCmdId);
},
_html_play: function(time) {
var self = this;
this._html_load(); // Loads if required and clears any delayed commands.
this.htmlElement.media.play(); // Before currentTime attempt otherwise Firefox 4 Beta never loads.
if(!isNaN(time)) {
try {
this.htmlElement.media.currentTime = time;
} catch(err) {
this.internal.htmlDlyCmdId = setTimeout(function() {
self.play(time);
}, 100);
return; // Cancel execution and wait for the delayed command.
}
}
this._html_checkWaitForPlay();
},
_html_pause: function(time) {
var self = this;
if(time > 0) { // We do not want the stop() command, which does pause(0), causing a load operation.
this._html_load(); // Loads if required and clears any delayed commands.
} else {
clearTimeout(this.internal.htmlDlyCmdId);
}
// Order of these commands is important for Safari (Win) and IE9. Pause then change currentTime.
this.htmlElement.media.pause();
if(!isNaN(time)) {
try {
this.htmlElement.media.currentTime = time;
} catch(err) {
this.internal.htmlDlyCmdId = setTimeout(function() {
self.pause(time);
}, 100);
return; // Cancel execution and wait for the delayed command.
}
}
if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button.
this._html_checkWaitForPlay();
}
},
_html_playHead: function(percent) {
var self = this;
this._html_load(); // Loads if required and clears any delayed commands.
try {
if((typeof this.htmlElement.media.seekable === "object") && (this.htmlElement.media.seekable.length > 0)) {
this.htmlElement.media.currentTime = percent * this.htmlElement.media.seekable.end(this.htmlElement.media.seekable.length-1) / 100;
} else if(this.htmlElement.media.duration > 0 && !isNaN(this.htmlElement.media.duration)) {
this.htmlElement.media.currentTime = percent * this.htmlElement.media.duration / 100;
} else {
throw "e";
}
} catch(err) {
this.internal.htmlDlyCmdId = setTimeout(function() {
self.playHead(percent);
}, 100);
return; // Cancel execution and wait for the delayed command.
}
if(!this.status.waitForLoad) {
this._html_checkWaitForPlay();
}
},
_html_checkWaitForPlay: function() {
if(this.status.waitForPlay) {
this.status.waitForPlay = false;
if(this.css.jq.videoPlay.length) {
this.css.jq.videoPlay.hide();
}
if(this.status.video) {
this.internal.poster.jq.hide();
this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height});
}
}
},
_html_volume: function(v) {
if(this.html.audio.available) {
this.htmlElement.audio.volume = v;
}
if(this.html.video.available) {
this.htmlElement.video.volume = v;
}
},
_html_mute: function(m) {
if(this.html.audio.available) {
this.htmlElement.audio.muted = m;
}
if(this.html.video.available) {
this.htmlElement.video.muted = m;
}
},
_flash_setAudio: function(media) {
var self = this;
try {
// Always finds a format due to checks in setMedia()
$.each(this.formats, function(priority, format) {
if(self.flash.support[format] && media[format]) {
switch (format) {
case "m4a" :
case "fla" :
self._getMovie().fl_setAudio_m4a(media[format]);
break;
case "mp3" :
self._getMovie().fl_setAudio_mp3(media[format]);
break;
case "rtmpa":
self._getMovie().fl_setAudio_rtmp(media[format]);
break;
}
self.status.src = media[format];
self.status.format[format] = true;
self.status.formatType = format;
return false;
}
});
if(this.options.preload === 'auto') {
this._flash_load();
this.status.waitForLoad = false;
}
} catch(err) { this._flashError(err); }
},
_flash_setVideo: function(media) {
var self = this;
try {
// Always finds a format due to checks in setMedia()
$.each(this.formats, function(priority, format) {
if(self.flash.support[format] && media[format]) {
switch (format) {
case "m4v" :
case "flv" :
self._getMovie().fl_setVideo_m4v(media[format]);
break;
case "rtmpv":
self._getMovie().fl_setVideo_rtmp(media[format]);
break;
}
self.status.src = media[format];
self.status.format[format] = true;
self.status.formatType = format;
return false;
}
});
if(this.options.preload === 'auto') {
this._flash_load();
this.status.waitForLoad = false;
}
} catch(err) { this._flashError(err); }
},
_flash_resetMedia: function() {
this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); // Must do via CSS as setting attr() to zero causes a jQuery error in IE.
this._flash_pause(NaN);
},
_flash_clearMedia: function() {
try {
this._getMovie().fl_clearMedia();
} catch(err) { this._flashError(err); }
},
_flash_load: function() {
try {
this._getMovie().fl_load();
} catch(err) { this._flashError(err); }
this.status.waitForLoad = false;
},
_flash_play: function(time) {
try {
this._getMovie().fl_play(time);
} catch(err) { this._flashError(err); }
this.status.waitForLoad = false;
this._flash_checkWaitForPlay();
},
_flash_pause: function(time) {
try {
this._getMovie().fl_pause(time);
} catch(err) { this._flashError(err); }
if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button.
this.status.waitForLoad = false;
this._flash_checkWaitForPlay();
}
},
_flash_playHead: function(p) {
try {
this._getMovie().fl_play_head(p);
} catch(err) { this._flashError(err); }
if(!this.status.waitForLoad) {
this._flash_checkWaitForPlay();
}
},
_flash_checkWaitForPlay: function() {
if(this.status.waitForPlay) {
this.status.waitForPlay = false;
if(this.css.jq.videoPlay.length) {
this.css.jq.videoPlay.hide();
}
if(this.status.video) {
this.internal.poster.jq.hide();
this.internal.flash.jq.css({'width': this.status.width, 'height': this.status.height});
}
}
},
_flash_volume: function(v) {
try {
this._getMovie().fl_volume(v);
} catch(err) { this._flashError(err); }
},
_flash_mute: function(m) {
try {
this._getMovie().fl_mute(m);
} catch(err) { this._flashError(err); }
},
_getMovie: function() {
return document[this.internal.flash.id];
},
_checkForFlash: function (version) {
// Function checkForFlash adapted from FlashReplace by Robert Nyman
// http://code.google.com/p/flashreplace/
var flashIsInstalled = false;
var flash;
if(window.ActiveXObject){
try{
flash = new ActiveXObject(("ShockwaveFlash.ShockwaveFlash." + version));
flashIsInstalled = true;
}
catch(e){
// Throws an error if the version isn't available
}
}
else if(navigator.plugins && navigator.mimeTypes.length > 0){
flash = navigator.plugins["Shockwave Flash"];
if(flash){
var flashVersion = navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/, "$1");
if(flashVersion >= version){
flashIsInstalled = true;
}
}
}
return flashIsInstalled;
},
_validString: function(url) {
return (url && typeof url === "string"); // Empty strings return false
},
_limitValue: function(value, min, max) {
return (value < min) ? min : ((value > max) ? max : value);
},
_urlNotSetError: function(context) {
this._error( {
type: $.jPlayer.error.URL_NOT_SET,
context: context,
message: $.jPlayer.errorMsg.URL_NOT_SET,
hint: $.jPlayer.errorHint.URL_NOT_SET
});
},
_flashError: function(error) {
var errorType;
if(!this.internal.ready) {
errorType = "FLASH";
} else {
errorType = "FLASH_DISABLED";
}
this._error( {
type: $.jPlayer.error[errorType],
context: this.internal.flash.swf,
message: $.jPlayer.errorMsg[errorType] + error.message,
hint: $.jPlayer.errorHint[errorType]
});
// Allow the audio player to recover if display:none and then shown again, or with position:fixed on Firefox.
// This really only affects audio in a media player, as an audio player could easily move the jPlayer element away from such issues.
this.internal.flash.jq.css({'width':'1px', 'height':'1px'});
},
_error: function(error) {
this._trigger($.jPlayer.event.error, error);
if(this.options.errorAlerts) {
this._alert("Error!" + (error.message ? "\n\n" + error.message : "") + (error.hint ? "\n\n" + error.hint : "") + "\n\nContext: " + error.context);
}
},
_warning: function(warning) {
this._trigger($.jPlayer.event.warning, undefined, warning);
if(this.options.warningAlerts) {
this._alert("Warning!" + (warning.message ? "\n\n" + warning.message : "") + (warning.hint ? "\n\n" + warning.hint : "") + "\n\nContext: " + warning.context);
}
},
_alert: function(message) {
alert("jPlayer " + this.version.script + " : id='" + this.internal.self.id +"' : " + message);
},
_emulateHtmlBridge: function() {
var self = this;
// Emulate methods on jPlayer's DOM element.
$.each( $.jPlayer.emulateMethods.split(/\s+/g), function(i, name) {
self.internal.domNode[name] = function(arg) {
self[name](arg);
};
});
// Bubble jPlayer events to its DOM element.
$.each($.jPlayer.event, function(eventName,eventType) {
var nativeEvent = true;
$.each( $.jPlayer.reservedEvent.split(/\s+/g), function(i, name) {
if(name === eventName) {
nativeEvent = false;
return false;
}
});
if(nativeEvent) {
self.element.bind(eventType + ".jPlayer.jPlayerHtml", function() { // With .jPlayer & .jPlayerHtml namespaces.
self._emulateHtmlUpdate();
var domEvent = document.createEvent("Event");
domEvent.initEvent(eventName, false, true);
self.internal.domNode.dispatchEvent(domEvent);
});
}
// The error event would require a special case
});
// IE9 has a readyState property on all elements. The document should have it, but all (except media) elements inherit it in IE9. This conflicts with Popcorn, which polls the readyState.
},
_emulateHtmlUpdate: function() {
var self = this;
$.each( $.jPlayer.emulateStatus.split(/\s+/g), function(i, name) {
self.internal.domNode[name] = self.status[name];
});
$.each( $.jPlayer.emulateOptions.split(/\s+/g), function(i, name) {
self.internal.domNode[name] = self.options[name];
});
},
_destroyHtmlBridge: function() {
var self = this;
// Bridge event handlers are also removed by destroy() through .jPlayer namespace.
this.element.unbind(".jPlayerHtml"); // Remove all event handlers created by the jPlayer bridge. So you can change the emulateHtml option.
// Remove the methods and properties
var emulated = $.jPlayer.emulateMethods + " " + $.jPlayer.emulateStatus + " " + $.jPlayer.emulateOptions;
$.each( emulated.split(/\s+/g), function(i, name) {
delete self.internal.domNode[name];
});
}
};
$.jPlayer.error = {
FLASH: "e_flash",
FLASH_DISABLED: "e_flash_disabled",
NO_SOLUTION: "e_no_solution",
NO_SUPPORT: "e_no_support",
URL: "e_url",
URL_NOT_SET: "e_url_not_set",
VERSION: "e_version"
};
$.jPlayer.errorMsg = {
FLASH: "jPlayer's Flash fallback is not configured correctly, or a command was issued before the jPlayer Ready event. Details: ", // Used in: _flashError()
FLASH_DISABLED: "jPlayer's Flash fallback has been disabled by the browser due to the CSS rules you have used. Details: ", // Used in: _flashError()
NO_SOLUTION: "No solution can be found by jPlayer in this browser. Neither HTML nor Flash can be used.", // Used in: _init()
NO_SUPPORT: "It is not possible to play any media format provided in setMedia() on this browser using your current options.", // Used in: setMedia()
URL: "Media URL could not be loaded.", // Used in: jPlayerFlashEvent() and _addHtmlEventListeners()
URL_NOT_SET: "Attempt to issue media playback commands, while no media url is set.", // Used in: load(), play(), pause(), stop() and playHead()
VERSION: "jPlayer " + $.jPlayer.prototype.version.script + " needs Jplayer.swf version " + $.jPlayer.prototype.version.needFlash + " but found " // Used in: jPlayerReady()
};
$.jPlayer.errorHint = {
FLASH: "Check your swfPath option and that Jplayer.swf is there.",
FLASH_DISABLED: "Check that you have not display:none; the jPlayer entity or any ancestor.",
NO_SOLUTION: "Review the jPlayer options: support and supplied.",
NO_SUPPORT: "Video or audio formats defined in the supplied option are missing.",
URL: "Check media URL is valid.",
URL_NOT_SET: "Use setMedia() to set the media URL.",
VERSION: "Update jPlayer files."
};
$.jPlayer.warning = {
CSS_SELECTOR_COUNT: "e_css_selector_count",
CSS_SELECTOR_METHOD: "e_css_selector_method",
CSS_SELECTOR_STRING: "e_css_selector_string",
OPTION_KEY: "e_option_key"
};
$.jPlayer.warningMsg = {
CSS_SELECTOR_COUNT: "The number of css selectors found did not equal one: ",
CSS_SELECTOR_METHOD: "The methodName given in jPlayer('cssSelector') is not a valid jPlayer method.",
CSS_SELECTOR_STRING: "The methodCssSelector given in jPlayer('cssSelector') is not a String or is empty.",
OPTION_KEY: "The option requested in jPlayer('option') is undefined."
};
$.jPlayer.warningHint = {
CSS_SELECTOR_COUNT: "Check your css selector and the ancestor.",
CSS_SELECTOR_METHOD: "Check your method name.",
CSS_SELECTOR_STRING: "Check your css selector is a string.",
OPTION_KEY: "Check your option name."
};
})(jQuery);
| JavaScript |
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
| JavaScript |
/*
Uniform v1.7.5
Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC
http://pixelmatrixdesign.com
Requires jQuery 1.4 or newer
Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this
Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/>
and his noSelect plugin. <http://github.com/mathiasbynens/noSelect-jQuery-Plugin>
Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin
License:
MIT License - http://www.opensource.org/licenses/mit-license.php
Enjoy!
*/
(function($) {
$.uniform = {
options: {
selectClass: 'selector',
radioClass: 'radio',
checkboxClass: 'checker',
fileClass: 'uploader',
filenameClass: 'filename',
fileBtnClass: 'action',
fileDefaultText: 'No file selected',
fileBtnText: 'Choose File',
checkedClass: 'checked',
focusClass: 'focus',
disabledClass: 'disabled',
buttonClass: 'button',
activeClass: 'active',
hoverClass: 'hover',
useID: true,
idPrefix: 'uniform',
resetSelector: false,
autoHide: true
},
elements: []
};
if($.browser.msie && $.browser.version < 7){
$.support.selectOpacity = false;
}else{
$.support.selectOpacity = true;
}
$.fn.uniform = function(options) {
options = $.extend($.uniform.options, options);
var el = this;
//code for specifying a reset button
if(options.resetSelector != false){
$(options.resetSelector).mouseup(function(){
function resetThis(){
$.uniform.update(el);
}
setTimeout(resetThis, 10);
});
}
function doInput(elem){
var $el = $(elem);
$el.addClass($el.attr("type"));
storeElement(elem);
}
function doTextarea(elem){
$(elem).addClass("uniform");
storeElement(elem);
}
function doButton(elem){
var $el = $(elem);
var divTag = $("<div>"),
spanTag = $("<span>");
divTag.addClass(options.buttonClass);
if(options.useID && $el.attr("id")) divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
var btnText;
if($el.is("a") || $el.is("button")){
btnText = $el.html();
}else if($el.is(":submit") || $el.is(":reset") || $el.is("input[type=button]")){
btnText = $el.attr("value");
}
btnText = btnText == "" ? $el.is(":reset") ? "Reset" : "Submit" : btnText;
spanTag.html(btnText);
$el.css("opacity", 0);
$el.wrap(divTag);
$el.wrap(spanTag);
//redefine variables
divTag = $el.closest("div");
spanTag = $el.closest("span");
if($el.is(":disabled")) divTag.addClass(options.disabledClass);
divTag.bind({
"mouseenter.uniform": function(){
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function(){
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function(){
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(e){
if($(e.target).is("span") || $(e.target).is("div")){
if(elem[0].dispatchEvent){
var ev = document.createEvent('MouseEvents');
ev.initEvent( 'click', true, true );
elem[0].dispatchEvent(ev);
}else{
elem[0].click();
}
}
}
});
elem.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
}
});
$.uniform.noSelect(divTag);
storeElement(elem);
}
function doSelect(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.selectClass);
if(options.useID && elem.attr("id")){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
var selected = elem.find(":selected:first");
if(selected.length == 0){
selected = elem.find("option:first");
}
spanTag.html(selected.html());
elem.css('opacity', 0);
elem.wrap(divTag);
elem.before(spanTag);
//redefine variables
divTag = elem.parent("div");
spanTag = elem.siblings("span");
elem.bind({
"change.uniform": function() {
spanTag.html(elem.find(":selected").html());
divTag.removeClass(options.activeClass);
},
"focus.uniform": function() {
divTag.addClass(options.focusClass);
},
"blur.uniform": function() {
divTag.removeClass(options.focusClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"keyup.uniform": function(){
spanTag.html(elem.find(":selected").html());
}
});
//handle disabled state
if($(elem).is(":disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(spanTag);
storeElement(elem);
}
function doCheckbox(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.checkboxClass);
//assign the id of the element
if(options.useID && elem.attr("id")){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).is(":checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span.
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).is(":checked")){
//box is checked by default, check our box
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).is(":disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doRadio(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.radioClass);
if(options.useID && elem.attr("id")){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).is(":checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span
var classes = options.radioClass.split(" ")[0];
$("." + classes + " span." + options.checkedClass + ":has([name='" + $(elem).attr('name') + "'])").removeClass(options.checkedClass);
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchend.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform touchbegin.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform touchend.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).is(":checked")){
//box is checked by default, check span
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).is(":disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doFile(elem){
//sanitize input
var $el = $(elem);
var divTag = $('<div />'),
filenameTag = $('<span>'+options.fileDefaultText+'</span>'),
btnTag = $('<span>'+options.fileBtnText+'</span>');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.fileClass);
filenameTag.addClass(options.filenameClass);
btnTag.addClass(options.fileBtnClass);
if(options.useID && $el.attr("id")){
divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
}
//wrap with the proper elements
$el.wrap(divTag);
$el.after(btnTag);
$el.after(filenameTag);
//redefine variables
divTag = $el.closest("div");
filenameTag = $el.siblings("."+options.filenameClass);
btnTag = $el.siblings("."+options.fileBtnClass);
//set the size
if(!$el.attr("size")){
var divWidth = divTag.width();
//$el.css("width", divWidth);
$el.attr("size", divWidth/10);
}
//actions
var setFilename = function()
{
var filename = $el.val();
if (filename === '')
{
filename = options.fileDefaultText;
}
else
{
filename = filename.split(/[\/\\]+/);
filename = filename[(filename.length-1)];
}
filenameTag.text(filename);
};
// Account for input saved across refreshes
setFilename();
$el
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"mousedown.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
// IE7 doesn't fire onChange until blur or second fire.
if ($.browser.msie){
// IE considers browser chrome blocking I/O, so it
// suspends tiemouts until after the file has been selected.
$el.bind('click.uniform.ie7', function() {
setTimeout(setFilename, 0);
});
}else{
// All other browsers behave properly
$el.bind('change.uniform', setFilename);
}
//handle defaults
if($el.is(":disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(filenameTag);
$.uniform.noSelect(btnTag);
storeElement(elem);
}
$.uniform.restore = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
$(elem).each(function(){
if($(this).is(":checkbox")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is("select")){
//remove sibling span
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is(":radio")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is(":file")){
//remove sibling spans
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is("button, :submit, :reset, a, input[type='button']")){
//unwrap from span and div
$(this).unwrap().unwrap();
}
//unbind events
$(this).unbind(".uniform");
//reset inline style
$(this).css("opacity", "1");
//remove item from list of uniformed elements
var index = $.inArray($(elem), $.uniform.elements);
$.uniform.elements.splice(index, 1);
});
};
function storeElement(elem){
//store this element in our global array
elem = $(elem).get();
if(elem.length > 1){
$.each(elem, function(i, val){
$.uniform.elements.push(val);
});
}else{
$.uniform.elements.push(elem);
}
}
//noSelect v1.0
$.uniform.noSelect = function(elem) {
function f() {
return false;
};
$(elem).each(function() {
this.onselectstart = this.ondragstart = f; // Webkit & IE
$(this)
.mousedown(f) // Webkit & Opera
.css({ MozUserSelect: 'none' }); // Firefox
});
};
$.uniform.update = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
//sanitize input
elem = $(elem);
elem.each(function(){
//do to each item in the selector
//function to reset all classes
var $e = $(this);
if($e.is("select")){
//element is a select
var spanTag = $e.siblings("span");
var divTag = $e.parent("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
//reset current selected text
spanTag.html($e.find(":selected").html());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":checkbox")){
//element is a checkbox
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":radio")){
//element is a radio
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":file")){
var divTag = $e.parent("div");
var filenameTag = $e.siblings("."+options.filenameClass);
btnTag = $e.siblings(options.fileBtnClass);
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
filenameTag.text($e.val());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":submit") || $e.is(":reset") || $e.is("button") || $e.is("a") || elem.is("input[type=button]")){
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}
});
};
return this.each(function() {
if($.support.selectOpacity){
var elem = $(this);
if(elem.is("select")){
//element is a select
if(!this.multiple){
//element is not a multi-select
if(elem.attr("size") == undefined || elem.attr("size") <= 1){
doSelect(elem);
}
}
}else if(elem.is(":checkbox")){
//element is a checkbox
doCheckbox(elem);
}else if(elem.is(":radio")){
//element is a radio
doRadio(elem);
}else if(elem.is(":file")){
//element is a file upload
doFile(elem);
}else if(elem.is(":text, :password, input[type='email']")){
doInput(elem);
}else if(elem.is("textarea")){
doTextarea(elem);
}else if(elem.is("a") || elem.is(":submit") || elem.is(":reset") || elem.is("button") || elem.is("input[type=button]")){
doButton(elem);
}
}
});
};
})(jQuery);
| JavaScript |
$(document).ready(function(){
var title_ms=$('#title_ms').val();
var liked=$('#liked').val();
var share_success=$('#share_success').val();
var email_er = $('#email_er').val();
var mes_er = $('#mes_er').val();
var send_success = $('#send_success').val();
var send_error = $('#send_error').val();
$("#check_like").click(function(){
var id = $(this).attr('rel');
$.ajax({
url: root + "contest/like",
type: "POST",
data: {
id : id
},
success: function(data){
if(data!='false'){
$("#count_like").html(data);
}else{
$.fancybox('<div style="padding:0px;width:200px;text-align:center;background:#fff"><div class="title">'+title_ms+'</div><p style="padding:10px">'+liked+'</p></div>',{
'autoScale':false,
'padding':0
});
}
}
});
return false;
});
$("#like_mo").click(function(){
var id = $(this).attr('rel');
var $this=$(this);
$.ajax({
url: root + "contest/like_mo",
type: "POST",
data: {
id : id
},
success: function(data){
if(data!='false'){
$this.html(data);
$this.attr('id','');
}else{
$.fancybox('<div style="padding:0px;width:200px;text-align:center;background:#fff"><div class="title">'+title_ms+'</div><p style="padding:10px">'+liked+'</p></div>',{
'autoScale':false,
'padding':0
});
}
}
});
return false;
});
$(".check_like2").click(function(){
var id = $(this).attr('rel');
var $this=$(this)
$.ajax({
url: root + "contest/like",
type: "POST",
data: {
id : id
},
success: function(data){
if(data!='false'){
$this.parent().find('.check_like2').html(data);
}else{
$.fancybox('<div style="padding:0px;width:200px;text-align:center;background:#fff"><div class="title">'+title_ms+'</div><p style="padding:10px">'+liked+'</p></div>',{
'autoScale':false,
'padding':0
});
}
}
});
return false;
});
$(".check_like").click(function(){
var id = $(this).attr('rel');
var $this=$(this)
$.ajax({
url: root + "contest/like_mo",
type: "POST",
data: {
id : id
},
success: function(data){
if(data!='false'){
$this.parent().find('.check_like').html(data);
}else{
$.fancybox('<div style="padding:0px;width:200px;text-align:center;background:#fff"><div class="title">'+title_ms+'</div><p style="padding:10px">'+liked+'</p></div>',{
'autoScale':false,
'padding':0
});
}
}
});
return false;
});
$(".comment_like").click(function(){
var id = $(this).attr('id');
$.ajax({
url: root + "contest/comment_like",
type: "POST",
data: {
id : id
},
success: function(data){
if(data!='false'){
$("#like_"+ id).html(data);
}else{
$.fancybox('<div style="padding:0px;width:200px;text-align:center"><div class="title">'+title_ms+'</div><p style="padding:10px">'+liked+'</p></div>',{
'autoScale':false,
'padding':0
});
}
}
});
return false;
});
$("#share_fb, #share_twitter").live('click',function(){
var $this=$(this);
var id= $('#ids').val();
var url = $('#urls').val();
var img = $('#imgs').val();
var title = $('#titles').val();
var des = $('#des_invite').val();
$.ajax({
url: root + "contest/share",
type: "POST",
data: {
id : id
},
success: function(data){
if(data!='false'){
$("#count_share").html(data);
}
if($this.is('#share_fb')){
share_facebook(url,title,des,img);
}else{
share_twitter(url,title);
}
$.fancybox('<div style="padding:0px;width:200px;text-align:center;background:#fff"><div class="title">'+title_ms+'</div><p style="padding:10px">'+share_success+'</p></div>',{
'autoScale':false,
'padding':0
});
}
});
return false;
});
// set radius button
$('.searchicon').click(function(){
$('#search').submit();
});
$('#typesort').bind('change', function(){
var url=$(this).val();
window.location=url;
})
function share_facebook(u,t,s,img) {
var url="http://www.facebook.com/sharer.php?s=100&p[title]="+encodeURIComponent(t)+"&p[url]="+encodeURIComponent(u)+"&p[summary]="+encodeURIComponent(s)+"&p[images][0]="+encodeURIComponent(img);
window.open(url);
return false;
}
function share_twitter(url,title) {
window.open("http://twitter.com/home?status="+ title + encodeURIComponent(url));
}
});
function invite()
{
var mes_invite=$('#mes_invite').val();
FB.ui({
method: 'apprequests',
message: mes_invite
}, function (response) {
if (response && response.to) {
}
});
return false;
}
function invite2(link,img,title)
{
var title_invite_contest=$('#title_invite_contest').val();
var des_invite=$('#des_invite').val();
FB.ui({
method: 'apprequests',
message: title_invite_contest
}, function (response) {
if (response && response.to) {
var id=String(response.to);
//var _link = root+_link1;
$.each(id.split(','), function(key, value) {
FB.api('/'+value+'/feed', 'post', {
//message: link,
picture: img,
caption: decodeURIComponent(title),
name: decodeURIComponent(title),
link:link,
description:des_invite
}, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Post ID: ' + response.id);
}
});
});
}
});
return false;
}
$(document).ready(function(){
$('a.back').click(function(){
window.history.back();
return false;
});
});
| 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 |
//Copyright (c) 2009 The Chromium Authors. All rights reserved.
//Use of this source code is governed by a BSD-style license that can be
//found in the LICENSE file.
// Various functions for helping debug WebGL apps.
WebGLDebugUtils = function() {
/**
* Wrapped logging function.
* @param {string} msg Message to log.
*/
var log = function(msg) {
if (window.console && window.console.log) {
window.console.log(msg);
}
};
/**
* Which arguements are enums.
* @type {!Object.<number, string>}
*/
var glValidEnumContexts = {
// Generic setters and getters
'enable': { 0:true },
'disable': { 0:true },
'getParameter': { 0:true },
// Rendering
'drawArrays': { 0:true },
'drawElements': { 0:true, 2:true },
// Shaders
'createShader': { 0:true },
'getShaderParameter': { 1:true },
'getProgramParameter': { 1:true },
// Vertex attributes
'getVertexAttrib': { 1:true },
'vertexAttribPointer': { 2:true },
// Textures
'bindTexture': { 0:true },
'activeTexture': { 0:true },
'getTexParameter': { 0:true, 1:true },
'texParameterf': { 0:true, 1:true },
'texParameteri': { 0:true, 1:true, 2:true },
'texImage2D': { 0:true, 2:true, 6:true, 7:true },
'texSubImage2D': { 0:true, 6:true, 7:true },
'copyTexImage2D': { 0:true, 2:true },
'copyTexSubImage2D': { 0:true },
'generateMipmap': { 0:true },
// Buffer objects
'bindBuffer': { 0:true },
'bufferData': { 0:true, 2:true },
'bufferSubData': { 0:true },
'getBufferParameter': { 0:true, 1:true },
// Renderbuffers and framebuffers
'pixelStorei': { 0:true, 1:true },
'readPixels': { 4:true, 5:true },
'bindRenderbuffer': { 0:true },
'bindFramebuffer': { 0:true },
'checkFramebufferStatus': { 0:true },
'framebufferRenderbuffer': { 0:true, 1:true, 2:true },
'framebufferTexture2D': { 0:true, 1:true, 2:true },
'getFramebufferAttachmentParameter': { 0:true, 1:true, 2:true },
'getRenderbufferParameter': { 0:true, 1:true },
'renderbufferStorage': { 0:true, 1:true },
// Frame buffer operations (clear, blend, depth test, stencil)
'clear': { 0:true },
'depthFunc': { 0:true },
'blendFunc': { 0:true, 1:true },
'blendFuncSeparate': { 0:true, 1:true, 2:true, 3:true },
'blendEquation': { 0:true },
'blendEquationSeparate': { 0:true, 1:true },
'stencilFunc': { 0:true },
'stencilFuncSeparate': { 0:true, 1:true },
'stencilMaskSeparate': { 0:true },
'stencilOp': { 0:true, 1:true, 2:true },
'stencilOpSeparate': { 0:true, 1:true, 2:true, 3:true },
// Culling
'cullFace': { 0:true },
'frontFace': { 0:true },
};
/**
* Map of numbers to names.
* @type {Object}
*/
var glEnums = null;
/**
* Initializes this module. Safe to call more than once.
* @param {!WebGLRenderingContext} ctx A WebGL context. If
* you have more than one context it doesn't matter which one
* you pass in, it is only used to pull out constants.
*/
function init(ctx) {
if (glEnums == null) {
glEnums = { };
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'number') {
glEnums[ctx[propertyName]] = propertyName;
}
}
}
}
/**
* Checks the utils have been initialized.
*/
function checkInit() {
if (glEnums == null) {
throw 'WebGLDebugUtils.init(ctx) not called';
}
}
/**
* Returns true or false if value matches any WebGL enum
* @param {*} value Value to check if it might be an enum.
* @return {boolean} True if value matches one of the WebGL defined enums
*/
function mightBeEnum(value) {
checkInit();
return (glEnums[value] !== undefined);
}
/**
* Gets an string version of an WebGL enum.
*
* Example:
* var str = WebGLDebugUtil.glEnumToString(ctx.getError());
*
* @param {number} value Value to return an enum for
* @return {string} The string version of the enum.
*/
function glEnumToString(value) {
checkInit();
var name = glEnums[value];
return (name !== undefined) ? name :
("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")");
}
/**
* Returns the string version of a WebGL argument.
* Attempts to convert enum arguments to strings.
* @param {string} functionName the name of the WebGL function.
* @param {number} argumentIndx the index of the argument.
* @param {*} value The value of the argument.
* @return {string} The value as a string.
*/
function glFunctionArgToString(functionName, argumentIndex, value) {
var funcInfo = glValidEnumContexts[functionName];
if (funcInfo !== undefined) {
if (funcInfo[argumentIndex]) {
return glEnumToString(value);
}
}
return value.toString();
}
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not gl.NO_ERROR.
*
* @param {!WebGLRenderingContext} ctx The webgl context to
* wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc
* The function to call when gl.getError returns an
* error. If not specified the default function calls
* console.log with a message.
*/
function makeDebugContext(ctx, opt_onErrorFunc) {
init(ctx);
opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
for (var ii = 0; ii < args.length; ++ii) {
argStr += ((ii == 0) ? '' : ', ') +
glFunctionArgToString(functionName, ii, args[ii]);
}
log("WebGL error "+ glEnumToString(err) + " in "+ functionName +
"(" + argStr + ")");
};
// Holds booleans for each GL error so after we get the error ourselves
// we can still return it to the client app.
var glErrorShadow = { };
// Makes a function that calls a WebGL function and then calls getError.
function makeErrorWrapper(ctx, functionName) {
return function() {
var result = ctx[functionName].apply(ctx, arguments);
var err = ctx.getError();
if (err != 0) {
glErrorShadow[err] = true;
opt_onErrorFunc(err, functionName, arguments);
}
return result;
};
}
// Make a an object that has a copy of every property of the WebGL context
// but wraps all functions.
var wrapper = {};
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
wrapper[propertyName] = makeErrorWrapper(ctx, propertyName);
} else {
wrapper[propertyName] = ctx[propertyName];
}
}
// Override the getError function with one that returns our saved results.
wrapper.getError = function() {
for (var err in glErrorShadow) {
if (glErrorShadow[err]) {
glErrorShadow[err] = false;
return err;
}
}
return ctx.NO_ERROR;
};
return wrapper;
}
function resetToInitialState(ctx) {
var numAttribs = ctx.getParameter(ctx.MAX_VERTEX_ATTRIBS);
var tmp = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, tmp);
for (var ii = 0; ii < numAttribs; ++ii) {
ctx.disableVertexAttribArray(ii);
ctx.vertexAttribPointer(ii, 4, ctx.FLOAT, false, 0, 0);
ctx.vertexAttrib1f(ii, 0);
}
ctx.deleteBuffer(tmp);
var numTextureUnits = ctx.getParameter(ctx.MAX_TEXTURE_IMAGE_UNITS);
for (var ii = 0; ii < numTextureUnits; ++ii) {
ctx.activeTexture(ctx.TEXTURE0 + ii);
ctx.bindTexture(ctx.TEXTURE_CUBE_MAP, null);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
ctx.activeTexture(ctx.TEXTURE0);
ctx.useProgram(null);
ctx.bindBuffer(ctx.ARRAY_BUFFER, null);
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);
ctx.bindFramebuffer(ctx.FRAMEBUFFER, null);
ctx.bindRenderbuffer(ctx.RENDERBUFFER, null);
ctx.disable(ctx.BLEND);
ctx.disable(ctx.CULL_FACE);
ctx.disable(ctx.DEPTH_TEST);
ctx.disable(ctx.DITHER);
ctx.disable(ctx.SCISSOR_TEST);
ctx.blendColor(0, 0, 0, 0);
ctx.blendEquation(ctx.FUNC_ADD);
ctx.blendFunc(ctx.ONE, ctx.ZERO);
ctx.clearColor(0, 0, 0, 0);
ctx.clearDepth(1);
ctx.clearStencil(-1);
ctx.colorMask(true, true, true, true);
ctx.cullFace(ctx.BACK);
ctx.depthFunc(ctx.LESS);
ctx.depthMask(true);
ctx.depthRange(0, 1);
ctx.frontFace(ctx.CCW);
ctx.hint(ctx.GENERATE_MIPMAP_HINT, ctx.DONT_CARE);
ctx.lineWidth(1);
ctx.pixelStorei(ctx.PACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_FLIP_Y_WEBGL, false);
ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
// TODO: Delete this IF.
if (ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL) {
ctx.pixelStorei(ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL, ctx.BROWSER_DEFAULT_WEBGL);
}
ctx.polygonOffset(0, 0);
ctx.sampleCoverage(1, false);
ctx.scissor(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.stencilFunc(ctx.ALWAYS, 0, 0xFFFFFFFF);
ctx.stencilMask(0xFFFFFFFF);
ctx.stencilOp(ctx.KEEP, ctx.KEEP, ctx.KEEP);
ctx.viewport(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
// TODO: This should NOT be needed but Firefox fails with 'hint'
while(ctx.getError());
}
function makeLostContextSimulatingContext(ctx) {
var wrapper_ = {};
var contextId_ = 1;
var contextLost_ = false;
var resourceId_ = 0;
var resourceDb_ = [];
var onLost_ = undefined;
var onRestored_ = undefined;
var nextOnRestored_ = undefined;
// Holds booleans for each GL error so can simulate errors.
var glErrorShadow_ = { };
function isWebGLObject(obj) {
//return false;
return (obj instanceof WebGLBuffer ||
obj instanceof WebGLFramebuffer ||
obj instanceof WebGLProgram ||
obj instanceof WebGLRenderbuffer ||
obj instanceof WebGLShader ||
obj instanceof WebGLTexture);
}
function checkResources(args) {
for (var ii = 0; ii < args.length; ++ii) {
var arg = args[ii];
if (isWebGLObject(arg)) {
return arg.__webglDebugContextLostId__ == contextId_;
}
}
return true;
}
function clearErrors() {
var k = Object.keys(glErrorShadow_);
for (var ii = 0; ii < k.length; ++ii) {
delete glErrorShdow_[k];
}
}
// Makes a function that simulates WebGL when out of context.
function makeLostContextWrapper(ctx, functionName) {
var f = ctx[functionName];
return function() {
// Only call the functions if the context is not lost.
if (!contextLost_) {
if (!checkResources(arguments)) {
glErrorShadow_[ctx.INVALID_OPERATION] = true;
return;
}
var result = f.apply(ctx, arguments);
return result;
}
};
}
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
wrapper_[propertyName] = makeLostContextWrapper(ctx, propertyName);
} else {
wrapper_[propertyName] = ctx[propertyName];
}
}
function makeWebGLContextEvent(statusMessage) {
return {statusMessage: statusMessage};
}
function freeResources() {
for (var ii = 0; ii < resourceDb_.length; ++ii) {
var resource = resourceDb_[ii];
if (resource instanceof WebGLBuffer) {
ctx.deleteBuffer(resource);
} else if (resource instanceof WebctxFramebuffer) {
ctx.deleteFramebuffer(resource);
} else if (resource instanceof WebctxProgram) {
ctx.deleteProgram(resource);
} else if (resource instanceof WebctxRenderbuffer) {
ctx.deleteRenderbuffer(resource);
} else if (resource instanceof WebctxShader) {
ctx.deleteShader(resource);
} else if (resource instanceof WebctxTexture) {
ctx.deleteTexture(resource);
}
}
}
wrapper_.loseContext = function() {
if (!contextLost_) {
contextLost_ = true;
++contextId_;
while (ctx.getError());
clearErrors();
glErrorShadow_[ctx.CONTEXT_LOST_WEBGL] = true;
setTimeout(function() {
if (onLost_) {
onLost_(makeWebGLContextEvent("context lost"));
}
}, 0);
}
};
wrapper_.restoreContext = function() {
if (contextLost_) {
if (onRestored_) {
setTimeout(function() {
freeResources();
resetToInitialState(ctx);
contextLost_ = false;
if (onRestored_) {
var callback = onRestored_;
onRestored_ = nextOnRestored_;
nextOnRestored_ = undefined;
callback(makeWebGLContextEvent("context restored"));
}
}, 0);
} else {
throw "You can not restore the context without a listener"
}
}
};
// Wrap a few functions specially.
wrapper_.getError = function() {
if (!contextLost_) {
var err;
while (err = ctx.getError()) {
glErrorShadow_[err] = true;
}
}
for (var err in glErrorShadow_) {
if (glErrorShadow_[err]) {
delete glErrorShadow_[err];
return err;
}
}
return ctx.NO_ERROR;
};
var creationFunctions = [
"createBuffer",
"createFramebuffer",
"createProgram",
"createRenderbuffer",
"createShader",
"createTexture"
];
for (var ii = 0; ii < creationFunctions.length; ++ii) {
var functionName = creationFunctions[ii];
wrapper_[functionName] = function(f) {
return function() {
if (contextLost_) {
return null;
}
var obj = f.apply(ctx, arguments);
obj.__webglDebugContextLostId__ = contextId_;
resourceDb_.push(obj);
return obj;
};
}(ctx[functionName]);
}
var functionsThatShouldReturnNull = [
"getActiveAttrib",
"getActiveUniform",
"getBufferParameter",
"getContextAttributes",
"getAttachedShaders",
"getFramebufferAttachmentParameter",
"getParameter",
"getProgramParameter",
"getProgramInfoLog",
"getRenderbufferParameter",
"getShaderParameter",
"getShaderInfoLog",
"getShaderSource",
"getTexParameter",
"getUniform",
"getUniformLocation",
"getVertexAttrib"
];
for (var ii = 0; ii < functionsThatShouldReturnNull.length; ++ii) {
var functionName = functionsThatShouldReturnNull[ii];
wrapper_[functionName] = function(f) {
return function() {
if (contextLost_) {
return null;
}
return f.apply(ctx, arguments);
}
}(wrapper_[functionName]);
}
var isFunctions = [
"isBuffer",
"isEnabled",
"isFramebuffer",
"isProgram",
"isRenderbuffer",
"isShader",
"isTexture"
];
for (var ii = 0; ii < isFunctions.length; ++ii) {
var functionName = isFunctions[ii];
wrapper_[functionName] = function(f) {
return function() {
if (contextLost_) {
return false;
}
return f.apply(ctx, arguments);
}
}(wrapper_[functionName]);
}
wrapper_.checkFramebufferStatus = function(f) {
return function() {
if (contextLost_) {
return ctx.FRAMEBUFFER_UNSUPPORTED;
}
return f.apply(ctx, arguments);
};
}(wrapper_.checkFramebufferStatus);
wrapper_.getAttribLocation = function(f) {
return function() {
if (contextLost_) {
return -1;
}
return f.apply(ctx, arguments);
};
}(wrapper_.getAttribLocation);
wrapper_.getVertexAttribOffset = function(f) {
return function() {
if (contextLost_) {
return 0;
}
return f.apply(ctx, arguments);
};
}(wrapper_.getVertexAttribOffset);
wrapper_.isContextLost = function() {
return contextLost_;
};
function wrapEvent(listener) {
if (typeof(listener) == "function") {
return listener;
} else {
return function(info) {
listener.handleEvent(info);
}
}
}
wrapper_.registerOnContextLostListener = function(listener) {
onLost_ = wrapEvent(listener);
};
wrapper_.registerOnContextRestoredListener = function(listener) {
if (contextLost_) {
nextOnRestored_ = wrapEvent(listener);
} else {
onRestored_ = wrapEvent(listener);
}
}
return wrapper_;
}
return {
/**
* Initializes this module. Safe to call more than once.
* @param {!WebGLRenderingContext} ctx A WebGL context. If
* you have more than one context it doesn't matter which one
* you pass in, it is only used to pull out constants.
*/
'init': init,
/**
* Returns true or false if value matches any WebGL enum
* @param {*} value Value to check if it might be an enum.
* @return {boolean} True if value matches one of the WebGL defined enums
*/
'mightBeEnum': mightBeEnum,
/**
* Gets an string version of an WebGL enum.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glEnumToString(ctx.getError());
*
* @param {number} value Value to return an enum for
* @return {string} The string version of the enum.
*/
'glEnumToString': glEnumToString,
/**
* Converts the argument of a WebGL function to a string.
* Attempts to convert enum arguments to strings.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glFunctionArgToString('bindTexture', 0, gl.TEXTURE_2D);
*
* would return 'TEXTURE_2D'
*
* @param {string} functionName the name of the WebGL function.
* @param {number} argumentIndx the index of the argument.
* @param {*} value The value of the argument.
* @return {string} The value as a string.
*/
'glFunctionArgToString': glFunctionArgToString,
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not NO_ERROR.
*
* You can supply your own function if you want. For example, if you'd like
* an exception thrown on any GL error you could do this
*
* function throwOnGLError(err, funcName, args) {
* throw WebGLDebugUtils.glEnumToString(err) + " was caused by call to" +
* funcName;
* };
*
* ctx = WebGLDebugUtils.makeDebugContext(
* canvas.getContext("webgl"), throwOnGLError);
*
* @param {!WebGLRenderingContext} ctx The webgl context to wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc The function
* to call when gl.getError returns an error. If not specified the default
* function calls console.log with a message.
*/
'makeDebugContext': makeDebugContext,
/**
* Given a WebGL context returns a wrapped context that adds 4
* functions.
*
* ctx.loseContext:
* simulates a lost context event.
*
* ctx.restoreContext:
* simulates the context being restored.
*
* ctx.registerOnContextLostListener(listener):
* lets you register a listener for context lost. Use instead
* of addEventListener('webglcontextlostevent', listener);
*
* ctx.registerOnContextRestoredListener(listener):
* lets you register a listener for context restored. Use
* instead of addEventListener('webglcontextrestored',
* listener);
*
* @param {!WebGLRenderingContext} ctx The webgl context to wrap.
*/
'makeLostContextSimulatingContext': makeLostContextSimulatingContext,
/**
* Resets a context to the initial state.
* @param {!WebGLRenderingContext} ctx The webgl context to
* reset.
*/
'resetToInitialState': resetToInitialState
};
}();
| JavaScript |
// cuon-utils.js (c) 2012 kanda and matsuda
/**
* Create a program object and make current
* @param gl GL context
* @param vshader a vertex shader program (string)
* @param fshader a fragment shader program (string)
* @return true, if the program object was created and successfully made current
*/
function initShaders(gl, vshader, fshader) {
var program = createProgram(gl, vshader, fshader);
if (!program) {
console.log('Failed to create program');
return false;
}
gl.useProgram(program);
gl.program = program;
return true;
}
/**
* Create the linked program object
* @param gl GL context
* @param vshader a vertex shader program (string)
* @param fshader a fragment shader program (string)
* @return created program object, or null if the creation has failed
*/
function createProgram(gl, vshader, fshader) {
// Create shader object
var vertexShader = loadShader(gl, gl.VERTEX_SHADER, vshader);
var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fshader);
if (!vertexShader || !fragmentShader) {
return null;
}
// Create a program object
var program = gl.createProgram();
if (!program) {
return null;
}
// Attach the shader objects
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// Link the program object
gl.linkProgram(program);
// Check the result of linking
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var error = gl.getProgramInfoLog(program);
console.log('Failed to link program: ' + error);
gl.deleteProgram(program);
gl.deleteShader(fragmentShader);
gl.deleteShader(vertexShader);
return null;
}
return program;
}
/**
* Create a shader object
* @param gl GL context
* @param type the type of the shader object to be created
* @param source shader program (string)
* @return created shader object, or null if the creation has failed.
*/
function loadShader(gl, type, source) {
// Create shader object
var shader = gl.createShader(type);
if (shader == null) {
console.log('unable to create shader');
return null;
}
// Set the shader program
gl.shaderSource(shader, source);
// Compile the shader
gl.compileShader(shader);
// Check the result of compilation
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
var error = gl.getShaderInfoLog(shader);
console.log('Failed to compile shader: ' + error);
gl.deleteShader(shader);
return null;
}
return shader;
}
/**
* Initialize and get the rendering for WebGL
* @param canvas <cavnas> element
* @param opt_debug flag to initialize the context for debugging
* @return the rendering context for WebGL
*/
function getWebGLContext(canvas, opt_debug) {
// Get the rendering context for WebGL
var gl = WebGLUtils.setupWebGL(canvas);
if (!gl) return null;
// if opt_debug is explicitly false, create the context for debugging
if (arguments.length < 2 || opt_debug) {
gl = WebGLDebugUtils.makeDebugContext(gl);
}
return gl;
}
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.